PageRenderTime 26ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/statsmodels/sandbox/examples/thirdparty/findow_0.py

http://github.com/statsmodels/statsmodels
Python | 81 lines | 53 code | 2 blank | 26 comment | 0 complexity | baf0c35a7ff492be45eadf5bcb6a045f MD5 | raw file
Possible License(s): BSD-3-Clause
  1. # -*- coding: utf-8 -*-
  2. """A quick look at volatility of stock returns for 2009
  3. Just an exercise to find my way around the pandas methods.
  4. Shows the daily rate of return, the square of it (volatility) and
  5. a 5 day moving average of the volatility.
  6. No guarantee for correctness.
  7. Assumes no missing values.
  8. colors of lines in graphs are not great
  9. uses DataMatrix and WidePanel to hold data downloaded from yahoo using matplotlib.
  10. I haven't figured out storage, so the download happens at each run
  11. of the script.
  12. getquotes is from pandas\examples\finance.py
  13. Created on Sat Jan 30 16:30:18 2010
  14. Author: josef-pktd
  15. """
  16. import numpy as np
  17. import matplotlib.finance as fin
  18. import matplotlib.pyplot as plt
  19. import datetime as dt
  20. import pandas as pa
  21. def getquotes(symbol, start, end):
  22. quotes = fin.quotes_historical_yahoo(symbol, start, end)
  23. dates, open, close, high, low, volume = zip(*quotes)
  24. data = {
  25. 'open' : open,
  26. 'close' : close,
  27. 'high' : high,
  28. 'low' : low,
  29. 'volume' : volume
  30. }
  31. dates = pa.Index([dt.datetime.fromordinal(int(d)) for d in dates])
  32. return pa.DataMatrix(data, index=dates)
  33. start_date = dt.datetime(2009, 1, 1)
  34. end_date = dt.datetime(2010, 1, 1)
  35. mysym = ['msft', 'ibm', 'goog']
  36. indexsym = ['gspc', 'dji']
  37. # download data
  38. dmall = {}
  39. for sy in mysym:
  40. dmall[sy] = getquotes(sy, start_date, end_date)
  41. # combine into WidePanel
  42. pawp = pa.WidePanel.fromDict(dmall)
  43. print pawp.values.shape
  44. # select closing prices
  45. paclose = pawp.getMinorXS('close')
  46. # take log and first difference over time
  47. paclose_ratereturn = paclose.apply(np.log).diff()
  48. plt.figure()
  49. paclose_ratereturn.plot()
  50. plt.title('daily rate of return')
  51. # square the returns
  52. paclose_ratereturn_vol = paclose_ratereturn.apply(lambda x:np.power(x,2))
  53. plt.figure()
  54. plt.title('volatility (with 5 day moving average')
  55. paclose_ratereturn_vol.plot()
  56. # use convolution to get moving average
  57. paclose_ratereturn_vol_mov = paclose_ratereturn_vol.apply(
  58. lambda x:np.convolve(x,np.ones(5)/5.,'same'))
  59. paclose_ratereturn_vol_mov.plot()
  60. #plt.show()