Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Volatility calculation #7

Open
roehst opened this issue Aug 21, 2024 · 1 comment
Open

Volatility calculation #7

roehst opened this issue Aug 21, 2024 · 1 comment

Comments

@roehst
Copy link

roehst commented Aug 21, 2024

Hi bro

defmodule Xirr do
  defmodule Volatility do
    def calculate_volatility(daily_prices) do
      # pairs of prices using zip
      pairs = Enum.zip(daily_prices, Enum.drop(daily_prices, 1))

      # pct change for each pair
      pct_changes = Enum.map(pairs, fn {a, b} -> (b - a) / a end)

      # standard deviation of pct changes
      mean = Enum.sum(pct_changes) / Enum.count(pct_changes)

      # sum of squared differences
      variance = Enum.sum(Enum.map(pct_changes, fn x -> (x - mean) * (x - mean) end))

      # standard deviation
      stddev = :math.sqrt(variance / (Enum.count(pct_changes) - 1))

      # annualize
      stddev * :math.sqrt(252)
    end
  end
end
@tubedude
Copy link
Owner

I'm accepting PR. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants