import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
close_px_all = pd.read_csv('stock_px.csv',parse_dates=True,index_col=0)
close_px = close_px_all[['AAPL','MSFT','XOM']]
close_px = close_px.resample('B').ffill()
print(close_px.head())
AAPL MSFT XOM
2003-01-02 7.40 21.11 29.22
2003-01-03 7.45 21.14 29.24
2003-01-06 7.45 21.52 29.96
2003-01-07 7.43 21.93 28.95
2003-01-08 7.28 21.31 28.83
一、直接使用plot进行绘图
close_px['AAPL'].plot(figsize=(10,3))
<matplotlib.axes._subplots.AxesSubplot at 0x65d922a470>
close_px.plot(figsize=(10,3))
<matplotlib.axes._subplots.AxesSubplot at 0x65d4f28208>
close_px.loc['2009'].plot(figsize=(10,3))
<matplotlib.axes._subplots.AxesSubplot at 0x65d91ad4a8>
close_px['AAPL'].loc['2011-01':'2011-03'].plot(figsize=(10,3))
<matplotlib.axes._subplots.AxesSubplot at 0x65d9417f28>
appl_q = close_px['AAPL'].resample('Q-DEC').ffill()
appl_q.loc['2009'].plot()
<matplotlib.axes._subplots.AxesSubplot at 0x65d94f6d30>
二、移动窗口函数
- rolling方法,移动窗口函数,其中参数window指定窗口的大小;
- rolling方法后,可以接mean、count、sum、max、min、median、std等聚合函数;
close_px['AAPL'].plot(figsize=(10,3))
close_px['AAPL'].rolling(window=250).mean().plot()
<matplotlib.axes._subplots.AxesSubplot at 0x65da992ba8>
close_px['AAPL'].plot(figsize=(10,3))
close_px['AAPL'].rolling(window=250,min_periods=10).std().plot()
<matplotlib.axes._subplots.AxesSubplot at 0x65da91d9b0>
三、指数加权函数
-
yt+1^=αyt+(1−α)yt^
,其中
yt^
表示t时刻指数加权的预测值,
yt
表示t时刻的观测值,
α
是平滑常数。
- 在函数ewm中
α=2span+1
,其中span是用户需要指定的参数。
fig,axes = plt.subplots(nrows=2,ncols=1,sharex=True,sharey=True,figsize=(12,7))
aapl_px = close_px.AAPL['2005':'2009']
ma60 = aapl_px.rolling(window=60,min_periods=50).mean()
ewma60 = aapl_px.ewm(span=60).mean()
aapl_px.plot(style='k-',ax=axes[0])
ma60.plot(style='k--',ax=axes[0])
aapl_px.plot(style='k-',ax=axes[1])
ewma60.plot(style='k--',ax=axes[1])
axes[0].set_title('Simple MA')
axes[1].set_title('Exponentially-weighted MA')
<matplotlib.text.Text at 0x65dacf1860>
四、二元移动窗口函数
- pct_change方法:
yt^=yt−yt−1yt−1
,其中
yt
是t时刻的原始值,
yt^
是t时刻pct_change()的返回值。其含义是,当前数据相较前一个数据变化的幅度。
spx_px = close_px_all['SPX']
spx_rets = spx_px/spx_px.shift(1)-1
returns = close_px.pct_change()
corr = returns['AAPL'].rolling(window=125,min_periods=100).corr(spx_rets)
corr.plot(figsize=(10,3))
<matplotlib.axes._subplots.AxesSubplot at 0x65dbb3d4a8>
corrs = returns.rolling(window=125,min_periods=100).corr(spx_rets)
corrs.plot(figsize=(10,3))
<matplotlib.axes._subplots.AxesSubplot at 0x65dcc3f8d0>
五、用户定义的移动窗口函数
- 通过rolling().apply()方法,可以在移动窗口上使用自己定义的函数。
from scipy.stats import percentileofscore
score_at_2percent = lambda x:percentileofscore(x,0.02)
result = returns['AAPL'].rolling(window=250).apply(score_at_2percent)
result.plot(figsize=(10,3))
<matplotlib.axes._subplots.AxesSubplot at 0x65dd73fe10>