Skip to content

Instantly share code, notes, and snippets.

@liuyigh
Forked from johntyree/history_vol.py
Last active October 2, 2015 16:41
Show Gist options
  • Save liuyigh/6706fdd81c60e405832b to your computer and use it in GitHub Desktop.
Save liuyigh/6706fdd81c60e405832b 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')['Adj 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment