用 pandas 扩展窗口函数

Python 中的时间序列数据处理

Stefan Jansen

Founder & Lead Data Scientist at Applied Artificial Intelligence

pandas 中的扩展窗口

  • 从滚动窗口到扩展窗口
  • 计算至当前日期的区间指标
  • 新时间序列反映全部历史值
  • 适用于运行收益率、运行最小/最大值
  • pandas 提供两种方式:
    • .expanding() —— 与 .rolling() 类似
    • .cumsum().cumprod()cummin()/max()
Python 中的时间序列数据处理

基本思路

df = pd.DataFrame({'data': range(5)})

df['expanding sum'] = df.data.expanding().sum()
df['cumulative sum'] = df.data.cumsum()
df
   data  expanding sum  cumulative sum
0     0            0.0               0
1     1            1.0               1
2     2            3.0               3
3     3            6.0               6
4     4           10.0              10
Python 中的时间序列数据处理

获取标普 500 数据

data = pd.read_csv('sp500.csv', parse_dates=['date'], index_col='date')
DatetimeIndex: 2519 entries, 2007-05-24 to 2017-05-24
Data columns (total 1 columns):
SP500    2519 non-null float64

ch3_2_v2 - 使用 Pandas 的扩展窗口函数.013.png

Python 中的时间序列数据处理

如何计算运行收益

  • 单期收益 r_t:本期价格/上期价格减 1:

    $$r_t = \frac{P_t}{P_{t-1}} - 1$$

    • 多期收益:各期 (1 + r_t) 的乘积减 1:

    $$R_T = (1 + r_1)(1 + r_2)...(1 + r_T) - 1$$

    • 计算单期收益:.pct_change()
    • 基本运算:.add().sub().mul().div()
    • 累乘:.cumprod()
Python 中的时间序列数据处理

运行收益示例

pr = data.SP500.pct_change() # period return

pr_plus_one = pr.add(1)
cumulative_return = pr_plus_one.cumprod().sub(1)
cumulative_return.mul(100).plot()

ch3_2_v2 - 使用 Pandas 的扩展窗口函数.021.png

Python 中的时间序列数据处理

获取运行最小值与最大值

data['running_min'] = data.SP500.expanding().min()

data['running_max'] = data.SP500.expanding().max()
data.plot()

ch3_2_v2 - 使用 Pandas 的扩展窗口函数.023.png

Python 中的时间序列数据处理

滚动年化收益率

def multi_period_return(period_returns):
    return np.prod(period_returns + 1) - 1

pr = data.SP500.pct_change() # period return
r = pr.rolling('360D').apply(multi_period_return)
data['Rolling 1yr Return'] = r.mul(100)
data.plot(subplots=True)
Python 中的时间序列数据处理

滚动年化收益率

data['Rolling 1yr Return'] = r.mul(100)

data.plot(subplots=True)

ch3_2_v2 - 使用 Pandas 的扩展窗口函数.027.png

Python 中的时间序列数据处理

Vamos praticar!

Python 中的时间序列数据处理

Preparing Video For Download...