Pandas时间序列:移动窗口及绘图

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)) # 整个DataFrame
<matplotlib.axes._subplots.AxesSubplot at 0x65d4f28208>

这里写图片描述

close_px.loc['2009'].plot(figsize=(10,3)) # 索引2009的数据进行绘图
<matplotlib.axes._subplots.AxesSubplot at 0x65d91ad4a8>

这里写图片描述

close_px['AAPL'].loc['2011-01':'2011-03'].plot(figsize=(10,3)) # 索引2011-01到2011-03进行绘图
<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))
# min_periods指窗口中非NA值至少要有10个
close_px['AAPL'].rolling(window=250,min_periods=10).std().plot()
<matplotlib.axes._subplots.AxesSubplot at 0x65da91d9b0>

这里写图片描述

三、指数加权函数

  • y t + 1 ^ = α y t + ( 1 α ) y t ^ ,其中 y t ^ 表示t时刻指数加权的预测值, y t 表示t时刻的观测值, α 是平滑常数。
  • 在函数ewm中 α = 2 s p a n + 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方法: y t ^ = y t y t 1 y t 1 ,其中 y t 是t时刻的原始值, y t ^ 是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>

这里写图片描述

猜你喜欢

转载自blog.csdn.net/bqw18744018044/article/details/80964477
今日推荐