Skip to content

Instantly share code, notes, and snippets.

@johntyree
Last active February 26, 2020 04:24
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save johntyree/4587049 to your computer and use it in GitHub Desktop.
Save johntyree/4587049 to your computer and use it in GitHub Desktop.
Calculate annualized volatility from historical data.
#/usr/bin/env python
from pandas import np
from pandas.io.data import DataReader
def historical_volatility(sym, days):
"Return the annualized stddev of daily log returns of `sym`."
try:
quotes = DataReader(sym, 'yahoo')['Close'][-days:]
except Exception, e:
print "Error getting data for symbol '{}'.\n".format(sym), e
return None, None
logreturns = np.log(quotes / quotes.shift(1))
return np.sqrt(252*logreturns.var())
if __name__ == "__main__":
print historical_volatility('GOOG', 30)
@humanely
Copy link

Why have you multiplied var with 252 in line 15?

@verawatk
Copy link

verawatk commented Sep 2, 2016

the reason for multiplying with 252 is to convert daily volatility to annualised volatility.

@drussellmrichie
Copy link

drussellmrichie commented Sep 7, 2017

When I run this, I get a syntax error?

File "volatility_test.py", line 11
    except Exception, e:
                    ^
SyntaxError: invalid syntax

@ilyakatz
Copy link

So what is 252 represent? Number of days that trading is open in a year?

@johntyree
Copy link
Author

I barely remember writing this, but yes, on average it's around 252 trading days a year.

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