Python 数据分析(PYDA)第三版(五)(3)https://developer.aliyun.com/article/1482393
当您从高频率转换为低频率时,pandas 会确定子周期,取决于超级周期“属于”哪里。例如,在A-JUN频率中,月份Aug-2011实际上是2012周期的一部分:
In [168]: p = pd.Period("Aug-2011", "M") In [169]: p.asfreq("A-JUN") Out[169]: Period('2012', 'A-JUN')
整个PeriodIndex对象或时间序列也可以使用相同的语义进行类似转换:
In [170]: periods = pd.period_range("2006", "2009", freq="A-DEC") In [171]: ts = pd.Series(np.random.standard_normal(len(periods)), index=periods) In [172]: ts Out[172]: 2006 1.607578 2007 0.200381 2008 -0.834068 2009 -0.302988 Freq: A-DEC, dtype: float64 In [173]: ts.asfreq("M", how="start") Out[173]: 2006-01 1.607578 2007-01 0.200381 2008-01 -0.834068 2009-01 -0.302988 Freq: M, dtype: float64
在这里,年度周期被替换为对应于每个年度周期中第一个月的月度周期。如果我们希望每年的最后一个工作日,可以使用"B"频率并指示我们想要周期的结束:
In [174]: ts.asfreq("B", how="end") Out[174]: 2006-12-29 1.607578 2007-12-31 0.200381 2008-12-31 -0.834068 2009-12-31 -0.302988 Freq: B, dtype: float64
季度周期频率
季度数据在会计、金融和其他领域中很常见。许多季度数据是相对于财年结束报告的,通常是一年中的 12 个月的最后一个日历日或工作日。因此,期间 2012Q4 根据财年结束日期的不同具有不同的含义。pandas 支持所有 12 种可能的季度频率,从 Q-JAN 到 Q-DEC:
In [175]: p = pd.Period("2012Q4", freq="Q-JAN") In [176]: p Out[176]: Period('2012Q4', 'Q-JAN')
在财年结束于一月的情况下,2012Q4 从 2011 年 11 月到 2012 年 1 月,您可以通过转换为每日频率来检查:
In [177]: p.asfreq("D", how="start") Out[177]: Period('2011-11-01', 'D') In [178]: p.asfreq("D", how="end") Out[178]: Period('2012-01-31', 'D')
参见 Figure 11.2 进行说明。
Figure 11.2: 不同的季度频率约定
因此,可以进行方便的期间算术;例如,要获取季度倒数第二个工作日下午 4 点的时间戳,可以执行以下操作:
In [179]: p4pm = (p.asfreq("B", how="end") - 1).asfreq("T", how="start") + 16 * 6 0 In [180]: p4pm Out[180]: Period('2012-01-30 16:00', 'T') In [181]: p4pm.to_timestamp() Out[181]: Timestamp('2012-01-30 16:00:00')
to_timestamp 方法默认返回期间开始的 Timestamp。
您可以使用 pandas.period_range 生成季度范围。算术也是相同的:
In [182]: periods = pd.period_range("2011Q3", "2012Q4", freq="Q-JAN") In [183]: ts = pd.Series(np.arange(len(periods)), index=periods) In [184]: ts Out[184]: 2011Q3 0 2011Q4 1 2012Q1 2 2012Q2 3 2012Q3 4 2012Q4 5 Freq: Q-JAN, dtype: int64 In [185]: new_periods = (periods.asfreq("B", "end") - 1).asfreq("H", "start") + 1 6 In [186]: ts.index = new_periods.to_timestamp() In [187]: ts Out[187]: 2010-10-28 16:00:00 0 2011-01-28 16:00:00 1 2011-04-28 16:00:00 2 2011-07-28 16:00:00 3 2011-10-28 16:00:00 4 2012-01-30 16:00:00 5 dtype: int64
将时间戳转换为期间(以及相反)
通过 to_period 方法,以时间戳索引的 Series 和 DataFrame 对象可以转换为期间:
In [188]: dates = pd.date_range("2000-01-01", periods=3, freq="M") In [189]: ts = pd.Series(np.random.standard_normal(3), index=dates) In [190]: ts Out[190]: 2000-01-31 1.663261 2000-02-29 -0.996206 2000-03-31 1.521760 Freq: M, dtype: float64 In [191]: pts = ts.to_period() In [192]: pts Out[192]: 2000-01 1.663261 2000-02 -0.996206 2000-03 1.521760 Freq: M, dtype: float64
由于期间指的是不重叠的时间跨度,因此给定频率的时间戳只能属于一个期间。虽然新的 PeriodIndex 的频率默认情况下是根据时间戳推断的,但您可以指定任何支持的频率(大多数列在 Table 11.4 中列出的频率都受支持)。在结果中有重复期间也没有问题:
In [193]: dates = pd.date_range("2000-01-29", periods=6) In [194]: ts2 = pd.Series(np.random.standard_normal(6), index=dates) In [195]: ts2 Out[195]: 2000-01-29 0.244175 2000-01-30 0.423331 2000-01-31 -0.654040 2000-02-01 2.089154 2000-02-02 -0.060220 2000-02-03 -0.167933 Freq: D, dtype: float64 In [196]: ts2.to_period("M") Out[196]: 2000-01 0.244175 2000-01 0.423331 2000-01 -0.654040 2000-02 2.089154 2000-02 -0.060220 2000-02 -0.167933 Freq: M, dtype: float64
要转换回时间戳,请使用 to_timestamp 方法,该方法返回一个 DatetimeIndex:
In [197]: pts = ts2.to_period() In [198]: pts Out[198]: 2000-01-29 0.244175 2000-01-30 0.423331 2000-01-31 -0.654040 2000-02-01 2.089154 2000-02-02 -0.060220 2000-02-03 -0.167933 Freq: D, dtype: float64 In [199]: pts.to_timestamp(how="end") Out[199]: 2000-01-29 23:59:59.999999999 0.244175 2000-01-30 23:59:59.999999999 0.423331 2000-01-31 23:59:59.999999999 -0.654040 2000-02-01 23:59:59.999999999 2.089154 2000-02-02 23:59:59.999999999 -0.060220 2000-02-03 23:59:59.999999999 -0.167933 Freq: D, dtype: float64
从数组创建 PeriodIndex
固定频率数据集有时会存储在跨多列的时间跨度信息中。例如,在这个宏观经济数据集中,年份和季度在不同的列中:
In [200]: data = pd.read_csv("examples/macrodata.csv") In [201]: data.head(5) Out[201]: year quarter realgdp realcons realinv realgovt realdpi cpi 0 1959 1 2710.349 1707.4 286.898 470.045 1886.9 28.98 \ 1 1959 2 2778.801 1733.7 310.859 481.301 1919.7 29.15 2 1959 3 2775.488 1751.8 289.226 491.260 1916.4 29.35 3 1959 4 2785.204 1753.7 299.356 484.052 1931.3 29.37 4 1960 1 2847.699 1770.5 331.722 462.199 1955.5 29.54 m1 tbilrate unemp pop infl realint 0 139.7 2.82 5.8 177.146 0.00 0.00 1 141.7 3.08 5.1 177.830 2.34 0.74 2 140.5 3.82 5.3 178.657 2.74 1.09 3 140.0 4.33 5.6 179.386 0.27 4.06 4 139.6 3.50 5.2 180.007 2.31 1.19 In [202]: data["year"] Out[202]: 0 1959 1 1959 2 1959 3 1959 4 1960 ... 198 2008 199 2008 200 2009 201 2009 202 2009 Name: year, Length: 203, dtype: int64 In [203]: data["quarter"] Out[203]: 0 1 1 2 2 3 3 4 4 1 .. 198 3 199 4 200 1 201 2 202 3 Name: quarter, Length: 203, dtype: int64
通过将这些数组传递给 PeriodIndex 并指定频率,可以将它们组合成 DataFrame 的索引:
In [204]: index = pd.PeriodIndex(year=data["year"], quarter=data["quarter"], .....: freq="Q-DEC") In [205]: index Out[205]: PeriodIndex(['1959Q1', '1959Q2', '1959Q3', '1959Q4', '1960Q1', '1960Q2', '1960Q3', '1960Q4', '1961Q1', '1961Q2', ... '2007Q2', '2007Q3', '2007Q4', '2008Q1', '2008Q2', '2008Q3', '2008Q4', '2009Q1', '2009Q2', '2009Q3'], dtype='period[Q-DEC]', length=203) In [206]: data.index = index In [207]: data["infl"] Out[207]: 1959Q1 0.00 1959Q2 2.34 1959Q3 2.74 1959Q4 0.27 1960Q1 2.31 ... 2008Q3 -3.16 2008Q4 -8.79 2009Q1 0.94 2009Q2 3.37 2009Q3 3.56 Freq: Q-DEC, Name: infl, Length: 203, dtype: float64
11.6 重新采样和频率转换
重新采样 指的是将时间序列从一种频率转换为另一种频率的过程。将高频数据聚合到低频称为下采样,而将低频转换为高频称为上采样。并非所有重新采样都属于这两类;例如,将 W-WED(每周三)转换为 W-FRI 既不是上采样也不是下采样。
pandas 对象配备有一个 resample 方法,这是所有频率转换的工作函数。resample 具有类似于 groupby 的 API;您调用 resample 来对数据进行分组,然后调用聚合函数:
In [208]: dates = pd.date_range("2000-01-01", periods=100) In [209]: ts = pd.Series(np.random.standard_normal(len(dates)), index=dates) In [210]: ts Out[210]: 2000-01-01 0.631634 2000-01-02 -1.594313 2000-01-03 -1.519937 2000-01-04 1.108752 2000-01-05 1.255853 ... 2000-04-05 -0.423776 2000-04-06 0.789740 2000-04-07 0.937568 2000-04-08 -2.253294 2000-04-09 -1.772919 Freq: D, Length: 100, dtype: float64 In [211]: ts.resample("M").mean() Out[211]: 2000-01-31 -0.165893 2000-02-29 0.078606 2000-03-31 0.223811 2000-04-30 -0.063643 Freq: M, dtype: float64 In [212]: ts.resample("M", kind="period").mean() Out[212]: 2000-01 -0.165893 2000-02 0.078606 2000-03 0.223811 2000-04 -0.063643 Freq: M, dtype: float64
resample 是一个灵活的方法,可用于处理大型时间序列。以下部分的示例说明了其语义和用法。Table 11.5 总结了一些选项。
Table 11.5: resample 方法参数
| 参数 | 描述 |
rule |
字符串、DateOffset 或时间增量,指示所需的重新采样频率(例如,’M’、’5min’ 或 Second(15)) |
axis |
要重新采样的轴;默认 axis=0 |
fill_method |
在上采样时如何插值,例如 "ffill" 或 "bfill";默认情况下不进行插值 |
closed |
在下采样时,每个间隔的哪一端是闭合的(包含的),"right" 或 "left" |
label |
在下采样时,如何标记聚合结果,使用 "right" 或 "left" 边界(例如,9:30 到 9:35 五分钟间隔可以标记为 9:30 或 9:35) |
limit |
在向前或向后填充时,要填充的最大周期数 |
kind |
聚合到期间("period")或时间戳("timestamp");默认为时间序列具有的索引类型 |
convention |
在重新采样周期时,用于将低频周期转换为高频的约定("start"或"end");默认为"start" |
origin |
用于确定重新采样箱边缘的“基准”时间戳;也可以是"epoch"、"start"、"start_day"、"end"或"end_day"之一;有关完整详细信息,请参阅resample文档字符串 |
offset |
添加到原点的偏移时间间隔;默认为None |
下采样
下采样是将数据聚合到常规、较低的频率。您正在聚合的数据不需要经常固定;所需频率定义了用于将时间序列切片成块以进行聚合的箱边缘。例如,要转换为每月,"M"或"BM",您需要将数据切割成一个月的间隔。每个间隔被称为半开放;数据点只能属于一个间隔,间隔的并集必须构成整个时间范围。在使用resample对数据进行下采样时,有几件事需要考虑:
- 每个间隔的哪一侧是关闭的
- 如何为每个聚合的箱子打标签,可以是间隔的开始或结束
为了说明,让我们看一些一分钟频率的数据:
In [213]: dates = pd.date_range("2000-01-01", periods=12, freq="T") In [214]: ts = pd.Series(np.arange(len(dates)), index=dates) In [215]: ts Out[215]: 2000-01-01 00:00:00 0 2000-01-01 00:01:00 1 2000-01-01 00:02:00 2 2000-01-01 00:03:00 3 2000-01-01 00:04:00 4 2000-01-01 00:05:00 5 2000-01-01 00:06:00 6 2000-01-01 00:07:00 7 2000-01-01 00:08:00 8 2000-01-01 00:09:00 9 2000-01-01 00:10:00 10 2000-01-01 00:11:00 11 Freq: T, dtype: int64
假设您想要通过将每组的总和来将这些数据聚合成五分钟的块或条:
In [216]: ts.resample("5min").sum() Out[216]: 2000-01-01 00:00:00 10 2000-01-01 00:05:00 35 2000-01-01 00:10:00 21 Freq: 5T, dtype: int64
您传递的频率定义了以五分钟为增量的箱边缘。对于这个频率,默认情况下左箱边缘是包含的,因此00:00值包含在00:00到00:05间隔中,而00:05值不包含在该间隔中。¹
In [217]: ts.resample("5min", closed="right").sum() Out[217]: 1999-12-31 23:55:00 0 2000-01-01 00:00:00 15 2000-01-01 00:05:00 40 2000-01-01 00:10:00 11 Freq: 5T, dtype: int64
生成的时间序列由每个箱子左侧的时间戳标记。通过传递label="right",您可以使用右侧箱子边缘对它们进行标记:
In [218]: ts.resample("5min", closed="right", label="right").sum() Out[218]: 2000-01-01 00:00:00 0 2000-01-01 00:05:00 15 2000-01-01 00:10:00 40 2000-01-01 00:15:00 11 Freq: 5T, dtype: int64
请参见图 11.3,以了解将分钟频率数据重新采样为五分钟频率的示例。
图 11.3:五分钟重新采样示例,显示了闭合、标签约定
最后,您可能希望将结果索引向前移动一定量,例如从右边减去一秒,以便更清楚地了解时间戳所指的间隔。要执行此操作,请向结果索引添加一个偏移量:
In [219]: from pandas.tseries.frequencies import to_offset In [220]: result = ts.resample("5min", closed="right", label="right").sum() In [221]: result.index = result.index + to_offset("-1s") In [222]: result Out[222]: 1999-12-31 23:59:59 0 2000-01-01 00:04:59 15 2000-01-01 00:09:59 40 2000-01-01 00:14:59 11 Freq: 5T, dtype: int64
开盘-最高-最低-收盘(OHLC)重新采样
在金融领域,聚合时间序列的一种流行方式是为每个桶计算四个值:第一个(开盘)、最后一个(收盘)、最大值(最高)和最小值(最低)。通过使用ohlc聚合函数,您将获得一个包含这四个聚合值的列的 DataFrame,这四个值可以在单个函数调用中高效计算:
In [223]: ts = pd.Series(np.random.permutation(np.arange(len(dates))), index=date s) In [224]: ts.resample("5min").ohlc() Out[224]: open high low close 2000-01-01 00:00:00 8 8 1 5 2000-01-01 00:05:00 6 11 2 2 2000-01-01 00:10:00 0 7 0 7
上采样和插值
上采样是将数据从较低频率转换为较高频率,不需要聚合。让我们考虑一个包含一些周数据的 DataFrame:
In [225]: frame = pd.DataFrame(np.random.standard_normal((2, 4)), .....: index=pd.date_range("2000-01-01", periods=2, .....: freq="W-WED"), .....: columns=["Colorado", "Texas", "New York", "Ohio"]) In [226]: frame Out[226]: Colorado Texas New York Ohio 2000-01-05 -0.896431 0.927238 0.482284 -0.867130 2000-01-12 0.493841 -0.155434 1.397286 1.507055
当您使用聚合函数处理这些数据时,每组只有一个值,缺失值会导致间隙。我们使用asfreq方法将其转换为更高的频率,而不进行任何聚合:
In [227]: df_daily = frame.resample("D").asfreq() In [228]: df_daily Out[228]: Colorado Texas New York Ohio 2000-01-05 -0.896431 0.927238 0.482284 -0.867130 2000-01-06 NaN NaN NaN NaN 2000-01-07 NaN NaN NaN NaN 2000-01-08 NaN NaN NaN NaN 2000-01-09 NaN NaN NaN NaN 2000-01-10 NaN NaN NaN NaN 2000-01-11 NaN NaN NaN NaN 2000-01-12 0.493841 -0.155434 1.397286 1.507055
假设您希望在非星期三填充每周值。与fillna和reindex方法中可用的填充或插值方法相同,对于重新采样也是可用的:
In [229]: frame.resample("D").ffill() Out[229]: Colorado Texas New York Ohio 2000-01-05 -0.896431 0.927238 0.482284 -0.867130 2000-01-06 -0.896431 0.927238 0.482284 -0.867130 2000-01-07 -0.896431 0.927238 0.482284 -0.867130 2000-01-08 -0.896431 0.927238 0.482284 -0.867130 2000-01-09 -0.896431 0.927238 0.482284 -0.867130 2000-01-10 -0.896431 0.927238 0.482284 -0.867130 2000-01-11 -0.896431 0.927238 0.482284 -0.867130 2000-01-12 0.493841 -0.155434 1.397286 1.507055
您也可以选择仅填充一定数量的周期,以限制使用观察值的范围:
In [230]: frame.resample("D").ffill(limit=2) Out[230]: Colorado Texas New York Ohio 2000-01-05 -0.896431 0.927238 0.482284 -0.867130 2000-01-06 -0.896431 0.927238 0.482284 -0.867130 2000-01-07 -0.896431 0.927238 0.482284 -0.867130 2000-01-08 NaN NaN NaN NaN 2000-01-09 NaN NaN NaN NaN 2000-01-10 NaN NaN NaN NaN 2000-01-11 NaN NaN NaN NaN 2000-01-12 0.493841 -0.155434 1.397286 1.507055
值得注意的是,新的日期索引不一定与旧的完全重合:
In [231]: frame.resample("W-THU").ffill() Out[231]: Colorado Texas New York Ohio 2000-01-06 -0.896431 0.927238 0.482284 -0.867130 2000-01-13 0.493841 -0.155434 1.397286 1.507055
使用周期重新采样
按周期索引的数据重新采样类似于时间戳:
In [232]: frame = pd.DataFrame(np.random.standard_normal((24, 4)), .....: index=pd.period_range("1-2000", "12-2001", .....: freq="M"), .....: columns=["Colorado", "Texas", "New York", "Ohio"]) In [233]: frame.head() Out[233]: Colorado Texas New York Ohio 2000-01 -1.179442 0.443171 1.395676 -0.529658 2000-02 0.787358 0.248845 0.743239 1.267746 2000-03 1.302395 -0.272154 -0.051532 -0.467740 2000-04 -1.040816 0.426419 0.312945 -1.115689 2000-05 1.234297 -1.893094 -1.661605 -0.005477 In [234]: annual_frame = frame.resample("A-DEC").mean() In [235]: annual_frame Out[235]: Colorado Texas New York Ohio 2000 0.487329 0.104466 0.020495 -0.273945 2001 0.203125 0.162429 0.056146 -0.103794
上采样更加微妙,因为在重新采样之前,您必须决定将值放在新频率的时间跨度的哪一端。convention参数默认为"start",但也可以是"end":
# Q-DEC: Quarterly, year ending in December In [236]: annual_frame.resample("Q-DEC").ffill() Out[236]: Colorado Texas New York Ohio 2000Q1 0.487329 0.104466 0.020495 -0.273945 2000Q2 0.487329 0.104466 0.020495 -0.273945 2000Q3 0.487329 0.104466 0.020495 -0.273945 2000Q4 0.487329 0.104466 0.020495 -0.273945 2001Q1 0.203125 0.162429 0.056146 -0.103794 2001Q2 0.203125 0.162429 0.056146 -0.103794 2001Q3 0.203125 0.162429 0.056146 -0.103794 2001Q4 0.203125 0.162429 0.056146 -0.103794 In [237]: annual_frame.resample("Q-DEC", convention="end").asfreq() Out[237]: Colorado Texas New York Ohio 2000Q4 0.487329 0.104466 0.020495 -0.273945 2001Q1 NaN NaN NaN NaN 2001Q2 NaN NaN NaN NaN 2001Q3 NaN NaN NaN NaN 2001Q4 0.203125 0.162429 0.056146 -0.103794
由于周期指的是时间跨度,因此有关上采样和下采样的规则更为严格:
- 在下采样中,目标频率必须是源频率的子周期。
- 在上采样中,目标频率必须是源频率的超周期。
如果这些规则不满足,将会引发异常。这主要影响季度、年度和每周频率;例如,由Q-MAR定义的时间跨度只与A-MAR、A-JUN、A-SEP和A-DEC对齐:
In [238]: annual_frame.resample("Q-MAR").ffill() Out[238]: Colorado Texas New York Ohio 2000Q4 0.487329 0.104466 0.020495 -0.273945 2001Q1 0.487329 0.104466 0.020495 -0.273945 2001Q2 0.487329 0.104466 0.020495 -0.273945 2001Q3 0.487329 0.104466 0.020495 -0.273945 2001Q4 0.203125 0.162429 0.056146 -0.103794 2002Q1 0.203125 0.162429 0.056146 -0.103794 2002Q2 0.203125 0.162429 0.056146 -0.103794 2002Q3 0.203125 0.162429 0.056146 -0.103794
分组时间重采样
对于时间序列数据,resample方法在时间间隔化的基础上是一个组操作。这里是一个小例子表:
In [239]: N = 15 In [240]: times = pd.date_range("2017-05-20 00:00", freq="1min", periods=N) In [241]: df = pd.DataFrame({"time": times, .....: "value": np.arange(N)}) In [242]: df Out[242]: time value 0 2017-05-20 00:00:00 0 1 2017-05-20 00:01:00 1 2 2017-05-20 00:02:00 2 3 2017-05-20 00:03:00 3 4 2017-05-20 00:04:00 4 5 2017-05-20 00:05:00 5 6 2017-05-20 00:06:00 6 7 2017-05-20 00:07:00 7 8 2017-05-20 00:08:00 8 9 2017-05-20 00:09:00 9 10 2017-05-20 00:10:00 10 11 2017-05-20 00:11:00 11 12 2017-05-20 00:12:00 12 13 2017-05-20 00:13:00 13 14 2017-05-20 00:14:00 14
在这里,我们可以按"time"索引,然后重采样:
In [243]: df.set_index("time").resample("5min").count() Out[243]: value time 2017-05-20 00:00:00 5 2017-05-20 00:05:00 5 2017-05-20 00:10:00 5
假设一个 DataFrame 包含多个时间序列,由额外的分组键列标记:
In [244]: df2 = pd.DataFrame({"time": times.repeat(3), .....: "key": np.tile(["a", "b", "c"], N), .....: "value": np.arange(N * 3.)}) In [245]: df2.head(7) Out[245]: time key value 0 2017-05-20 00:00:00 a 0.0 1 2017-05-20 00:00:00 b 1.0 2 2017-05-20 00:00:00 c 2.0 3 2017-05-20 00:01:00 a 3.0 4 2017-05-20 00:01:00 b 4.0 5 2017-05-20 00:01:00 c 5.0 6 2017-05-20 00:02:00 a 6.0
为了对每个"key"值执行相同的重采样,我们引入pandas.Grouper对象:
In [246]: time_key = pd.Grouper(freq="5min")
然后我们可以设置时间索引,按"key"和time_key分组,并进行聚合:
In [247]: resampled = (df2.set_index("time") .....: .groupby(["key", time_key]) .....: .sum()) In [248]: resampled Out[248]: value key time a 2017-05-20 00:00:00 30.0 2017-05-20 00:05:00 105.0 2017-05-20 00:10:00 180.0 b 2017-05-20 00:00:00 35.0 2017-05-20 00:05:00 110.0 2017-05-20 00:10:00 185.0 c 2017-05-20 00:00:00 40.0 2017-05-20 00:05:00 115.0 2017-05-20 00:10:00 190.0 In [249]: resampled.reset_index() Out[249]: key time value 0 a 2017-05-20 00:00:00 30.0 1 a 2017-05-20 00:05:00 105.0 2 a 2017-05-20 00:10:00 180.0 3 b 2017-05-20 00:00:00 35.0 4 b 2017-05-20 00:05:00 110.0 5 b 2017-05-20 00:10:00 185.0 6 c 2017-05-20 00:00:00 40.0 7 c 2017-05-20 00:05:00 115.0 8 c 2017-05-20 00:10:00 190.0
使用pandas.Grouper的一个限制是时间必须是 Series 或 DataFrame 的索引。
11.7 移动窗口函数
用于时间序列操作的一类重要的数组转换是在滑动窗口上评估统计数据和其他函数,或者使用指数衰减权重。这对于平滑嘈杂或有缺失数据的数据很有用。我将这些称为移动窗口函数,尽管它们包括没有固定长度窗口的函数,比如指数加权移动平均。与其他统计函数一样,这些函数也会自动排除缺失数据。
在深入研究之前,我们可以加载一些时间序列数据并将其重采样为工作日频率:
In [250]: close_px_all = pd.read_csv("examples/stock_px.csv", .....: parse_dates=True, index_col=0) In [251]: close_px = close_px_all[["AAPL", "MSFT", "XOM"]] In [252]: close_px = close_px.resample("B").ffill()
我现在介绍rolling运算符,它的行为类似于resample和groupby。它可以与一个window(表示为一定数量的周期)一起在 Series 或 DataFrame 上调用(请参见 Apple 价格与 250 日移动平均创建的图):
In [253]: close_px["AAPL"].plot() Out[253]: <Axes: > In [254]: close_px["AAPL"].rolling(250).mean().plot()
图 11.4:苹果价格与 250 日移动平均值
表达式rolling(250)在行为上类似于groupby,但不是分组,而是创建一个对象,使得可以在 250 天滑动窗口上进行分组。因此,这里是苹果股价的 250 日移动窗口平均值。
默认情况下,滚动函数要求窗口中的所有值都不是 NA。这种行为可以更改以考虑缺失数据,特别是在时间序列开始时将少于window周期的数据(请参见苹果 250 日每日回报标准差):
In [255]: plt.figure() Out[255]: <Figure size 1000x600 with 0 Axes> In [256]: std250 = close_px["AAPL"].pct_change().rolling(250, min_periods=10).std () In [257]: std250[5:12] Out[257]: 2003-01-09 NaN 2003-01-10 NaN 2003-01-13 NaN 2003-01-14 NaN 2003-01-15 NaN 2003-01-16 0.009628 2003-01-17 0.013818 Freq: B, Name: AAPL, dtype: float64 In [258]: std250.plot()
图 11.5:苹果 250 日每日回报标准差
要计算扩展窗口均值,请使用expanding运算符,而不是rolling。扩展均值从与滚动窗口相同的时间窗口开始,并增加窗口的大小,直到包含整个系列。std250时间序列上的扩展窗口均值如下所示:
In [259]: expanding_mean = std250.expanding().mean()
在 DataFrame 上调用移动窗口函数会将转换应用于每一列(请参见股价 60 日移动平均(对数 y 轴)):
In [261]: plt.style.use('grayscale') In [262]: close_px.rolling(60).mean().plot(logy=True)
图 11.6:股价 60 日移动平均(对数 y 轴)
rolling函数还接受一个字符串,指示固定大小的时间偏移rolling()在移动窗口函数中,而不是一组周期。使用这种表示法对于不规则的时间序列很有用。这些是您可以传递给resample的相同字符串。例如,我们可以这样计算 20 天的滚动均值:
In [263]: close_px.rolling("20D").mean() Out[263]: AAPL MSFT XOM 2003-01-02 7.400000 21.110000 29.220000 2003-01-03 7.425000 21.125000 29.230000 2003-01-06 7.433333 21.256667 29.473333 2003-01-07 7.432500 21.425000 29.342500 2003-01-08 7.402000 21.402000 29.240000 ... ... ... ... 2011-10-10 389.351429 25.602143 72.527857 2011-10-11 388.505000 25.674286 72.835000 2011-10-12 388.531429 25.810000 73.400714 2011-10-13 388.826429 25.961429 73.905000 2011-10-14 391.038000 26.048667 74.185333 [2292 rows x 3 columns]
指数加权函数
使用固定窗口大小和等权观测值的替代方法是指定一个恒定的衰减因子,以赋予更多权重给最近的观测值。有几种指定衰减因子的方法。一种流行的方法是使用跨度,使结果与窗口大小等于跨度的简单移动窗口函数可比较。
由于指数加权统计对最近的观察结果赋予更大的权重,与等权重版本相比,它更快地“适应”变化。
pandas 有ewm运算符(代表指数加权移动),与rolling和expanding配合使用。以下是一个示例,比较了苹果公司股价的 30 天移动平均值与指数加权(EW)移动平均值(span=60)(请参阅简单移动平均与指数加权):
In [265]: aapl_px = close_px["AAPL"]["2006":"2007"] In [266]: ma30 = aapl_px.rolling(30, min_periods=20).mean() In [267]: ewma30 = aapl_px.ewm(span=30).mean() In [268]: aapl_px.plot(style="k-", label="Price") Out[268]: <Axes: > In [269]: ma30.plot(style="k--", label="Simple Moving Avg") Out[269]: <Axes: > In [270]: ewma30.plot(style="k-", label="EW MA") Out[270]: <Axes: > In [271]: plt.legend()
图 11.7:简单移动平均与指数加权
二进制移动窗口函数
一些统计运算符,如相关性和协方差,需要在两个时间序列上操作。例如,金融分析师通常对股票与标普 500 等基准指数的相关性感兴趣。为了查看这一点,我们首先计算所有感兴趣时间序列的百分比变化:
In [273]: spx_px = close_px_all["SPX"] In [274]: spx_rets = spx_px.pct_change() In [275]: returns = close_px.pct_change()
在我们调用rolling之后,corr聚合函数可以计算与spx_rets的滚动相关性(请参阅苹果公司六个月回报与标普 500 的相关性以查看结果图):
In [276]: corr = returns["AAPL"].rolling(125, min_periods=100).corr(spx_rets) In [277]: corr.plot()
图 11.8:苹果公司六个月回报与标普 500 的相关性
假设您想要计算 S&P 500 指数与多只股票的滚动相关性。您可以像我们上面为苹果公司所做的那样编写一个循环来计算每只股票的相关性,但如果每只股票是单个 DataFrame 中的一列,我们可以通过在 DataFrame 上调用rolling并传递spx_rets Series 来一次性计算所有滚动相关性。
请参阅与标普 500 的六个月回报相关性以查看结果图:
In [279]: corr = returns.rolling(125, min_periods=100).corr(spx_rets) In [280]: corr.plot()
图 11.9:与标普 500 的六个月回报相关性
用户定义的移动窗口函数
rolling和相关方法上的apply方法提供了一种方法,可以在移动窗口上应用自己创建的数组函数。唯一的要求是函数从数组的每个部分产生一个单一值(一个减少)。例如,虽然我们可以使用rolling(...).quantile(q)计算样本分位数,但我们可能对特定值在样本中的百分位数感兴趣。scipy.stats.percentileofscore函数正是这样做的(请参阅 2%苹果公司回报在一年窗口内的百分位数以查看结果图):
In [282]: from scipy.stats import percentileofscore In [283]: def score_at_2percent(x): .....: return percentileofscore(x, 0.02) In [284]: result = returns["AAPL"].rolling(250).apply(score_at_2percent) In [285]: result.plot()
图 11.10:2%苹果公司回报在一年窗口内的百分位数
如果您尚未安装 SciPy,可以使用 conda 或 pip 进行安装:
conda install scipy
11.8 结论
时间序列数据需要不同类型的分析和数据转换工具,与我们在之前章节中探讨过的其他类型数据不同。
在接下来的章节中,我们将展示如何开始使用建模库,如 statsmodels 和 scikit-learn。
- 对于
closed和label的默认值选择可能对一些用户来说有点奇怪。默认值为closed="left",除了一组特定的值("M"、"A"、"Q"、"BM"、"BQ"和"W")默认为closed="right"。选择默认值是为了使结果更直观,但值得知道默认值并不总是一个或另一个。