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