pandas提供了一套标准的时间序列处理工具和算法,使得咱们能够很是高效的处理时间序列,好比切片、聚合、重采样等等。html
本节咱们讨论如下三种时间序列:python
Python的时间序列处理是一个很重要的话题,尤为在金融领域有着很是重要的应用。本节只作简单的介绍,若是之后有须要的话再深刻学习。本文参考的Working with Time Series对python原生的日期时间处理模块datetime
,numpy日期时间处理模块datetime64
,以及第三方日期时间处理模块dateutil
等都作了介绍,咱们这里跳过这些,直接进入pandas的时间序列。git
import numpy as np
import pandas as pd
当你使用时间戳做为数据索引的时候,pandas的时间序列工具就变得是非有用。github
index = pd.DatetimeIndex(['2014-07-04', '2014-08-04',
'2015-07-04', '2015-08-04'])
data = pd.Series([0, 1, 2, 3], index=index)
data
#> 2014-07-04 0
#> 2014-08-04 1
#> 2015-07-04 2
#> 2015-08-04 3
#> dtype: int64
data['2014-07-04':'2015-07-04']
#> 2014-07-04 0
#> 2014-08-04 1
#> 2015-07-04 2
#> dtype: int64
data['2015']
#> 2015-07-04 2
#> 2015-08-04 3
#> dtype: int64
对于时间戳,pandas提供了Timestamp
类型。它基于numpy.datetime64
数据类型,与与之相关的索引类型是DatetimeIndex
。算法
对于时间时期,pandas提供了Period
类型,它是基于numpy.datetime64
编码的固定频率间隔。与之相关的索引类型是PeriodIndex
。markdown
对于时间差,pandas提供了Timedelta
类型,一样基于numpy.datetime64
。与之相关的索引结构是TimedeltaIndex
。数据结构
最基本的时间/日期是时间戳Timestamp
和DatetimeIndex
。可是咱们能够直接使用pd.to_datetime()
函数来直接解析不一样的格式。传入单个日期给pd.to_datetime()
返回一个Timestamp
,传入一系列日期默认返回DatetimeIndex
。app
dates = pd.to_datetime([datetime(2015, 7, 3), '4th of July, 2015',
'2015-Jul-6', '07-07-2015', '20150708'])
dates
#> DatetimeIndex(['2015-07-03', '2015-07-04', '2015-07-06', '2015-07-07',
#> '2015-07-08'],
#> dtype='datetime64[ns]', freq=None)
当一个日期减去另外一个日期的时候,TimedeltaIndex
就会被建立:函数
dates - dates[0]
#> TimedeltaIndex(['0 days', '1 days', '3 days', '4 days', '5 days'], dtype='timedelta64[ns]', freq=None)
为了方便地建立按期的日期序列,pandas提供了一些函数:pd.date_range()
建立时间戳,pd.period_range()
建立时期,pd.timedelta_range()
建立时间差。默认状况下频率间隔是一天。工具
pd.date_range('2015-07-03', '2015-07-10')
#> DatetimeIndex(['2015-07-03', '2015-07-04', '2015-07-05', '2015-07-06',
#> '2015-07-07', '2015-07-08', '2015-07-09', '2015-07-10'],
#> dtype='datetime64[ns]', freq='D')
另外能够不指定终点,而是提供一个时期数:
pd.date_range('2015-07-03', periods=8)
#> DatetimeIndex(['2015-07-03', '2015-07-04', '2015-07-05', '2015-07-06',
#> '2015-07-07', '2015-07-08', '2015-07-09', '2015-07-10'],
#> dtype='datetime64[ns]', freq='D')
频率间隔能够经过freq
参数设置,默认是D
:
pd.date_range('2015-07-03', periods=8, freq='H')
#> DatetimeIndex(['2015-07-03 00:00:00', '2015-07-03 01:00:00',
#> '2015-07-03 02:00:00', '2015-07-03 03:00:00',
#> '2015-07-03 04:00:00', '2015-07-03 05:00:00',
#> '2015-07-03 06:00:00', '2015-07-03 07:00:00'],
#> dtype='datetime64[ns]', freq='H')
相似的
pd.period_range('2015-07', periods=8, freq='M')
#> PeriodIndex(['2015-07', '2015-08', '2015-09', '2015-10', '2015-11', '2015-12',
#> '2016-01', '2016-02'],
#> dtype='period[M]', freq='M')
pd.timedelta_range(0, periods=10, freq='H')
#> TimedeltaIndex(['00:00:00', '01:00:00', '02:00:00', '03:00:00', '04:00:00',
#> '05:00:00', '06:00:00', '07:00:00', '08:00:00', '09:00:00'],
#> dtype='timedelta64[ns]', freq='H')
以上这些时间序列处理工具最基础的概念是频率和时间偏移。下表总结了主要的代码表示:
代码 | 描述 | 代码 | 描述 |
---|---|---|---|
D |
日历天 | L |
厘秒 |
W |
星期 | U |
毫秒 |
M |
月末 | N |
纳秒 |
Q |
季度末 | B |
工做日 |
A |
年底 | BM |
工做月末 |
H |
小时 | BQ |
工做季末 |
T |
分钟 | BA |
工做年底 |
S |
秒 | BH |
工做时 |
上面的月,季度以及周期性频率都被标记为这一时期的终点,若是想变成起始点能够加S
后缀。
代码 | 描述 | 代码 | 描述 |
---|---|---|---|
MS |
月初 | BMS |
工做月初 |
QS |
季度初 | BQS |
工做季初 |
AS |
年初 | BAS |
工做年初 |
另外,还能够经过加后缀的方法改变季度或年的月份等。
Q-JAN
, BQ-FEB
, BQS-APR
等等;A-JAN
, BA-FEB
, BAS-APR
等等。
相似的,星期也能够分解成周一,周二…
W-SUN
, W-MON
, W-WED
等等
以上这些代码还能够与数字结合来表示频率, 例如咱们要表示2小时30分的频率:
pd.timedelta_range(0, periods=9, freq="2H30T")
#> TimedeltaIndex(['00:00:00', '02:30:00', '05:00:00', '07:30:00', '10:00:00',
#> '12:30:00', '15:00:00', '17:30:00', '20:00:00'],
#> dtype='timedelta64[ns]', freq='150T')
以上这些代码表示的含义还能够经过pd.tseries.offsets
模块表示:
from pandas.tseries.offsets import BDay
pd.date_range('2015-07-01', periods=5, freq=BDay())
#> DatetimeIndex(['2015-07-01', '2015-07-02', '2015-07-03', '2015-07-06',
#> '2015-07-07'],
#> dtype='datetime64[ns]', freq='B')
更加详细的讨论能够看DateOffset。
咱们以一些真实的金融数据为例讲解,pandas-datareader
(可经过conda install pandas-datareader
来安装, 若是)包包含谷歌,雅虎等公司的金融数据。
from pandas_datareader import data
goog = data.DataReader('GOOG', start='2004', end='2016',
data_source='google')
goog.head()
#> Open High Low Close Volume
#> Date
#> 2004-08-19 49.96 51.98 47.93 50.12 NaN
#> 2004-08-20 50.69 54.49 50.20 54.10 NaN
#> 2004-08-23 55.32 56.68 54.47 54.65 NaN
#> 2004-08-24 55.56 55.74 51.73 52.38 NaN
#> 2004-08-25 52.43 53.95 51.89 52.95 NaN
简单起见,咱们只是用收盘价格
goog = goog['Close']
为了更好的说明问题,咱们能够利用matplotlib对数据进行可视化,关于matplotlib能够经过Python for Data Analysis这本书进行学习,也能够经过官网的gallary进行学习,我我的当时是在官网看了大量的实例,有什么需求直接去官网找例子,都很方便。本系列学习笔记不会包含数据可视化部分。
import matplotlib.pyplot as plt
goog.plot()
重采样(resampling)指的是将时间序列从一个频率转换到另外一个频率的处理过程。将高频数据聚合到低频称为降采样(downsampling),将低频数据转换到高频则称为升采样(upsampling)。除此之外还存在一种采样方式既不是升采样,也不是降采样,好比W-WED
转换成W-FRI
。
能够经过resample()
函数来实现,也能够经过更简单的方式asfreq()
函数来实现。二者基本的不一样点在于resample()
是一种数据聚合方式asfreq()
是一种数据选取方式。
goog.plot(alpha=0.5, style='-')
goog.resample('BA').mean().plot(style=':')
goog.asfreq('BA').plot(style='--');
plt.legend(['input', 'resample', 'asfreq'],
loc='upper left')
resample()
的处理过程是取全年的数据的平均值,而asfreq()
是选取年底的时间点的数据。
对于升采样来讲,resample()
与asfreq()
是等效的。对于空置采样点都会用NaN
来进行填充。就像pd.fillna()
方法,asfreq()
接受一个参数method
可指定缺失值的填充方法。ffill
表示与前面的值保持一致,bfill
表示与后面的值保持一致等等。
fig, ax = plt.subplots(2, sharex=True)
data = goog.iloc[:10]
data.asfreq('D').plot(ax=ax[0], marker='o')
data.asfreq('D', method='bfill').plot(ax=ax[1], style='-o')
data.asfreq('D', method='ffill').plot(ax=ax[1], style='--o')
ax[1].legend(["back-fill", "forward-fill"])
另外一个与时间序列相关的操做是数据在时间轴的移动。pandas提供了两个相关的函数:shift()
和tshift()
,二者的不一样是shift()
移动的是数据,tshift()
移动的是时间轴(索引)。
fig, ax = plt.subplots(3, sharey=True)
# apply a frequency to the data
goog = goog.asfreq('D', method='pad')
goog.plot(ax=ax[0])
goog.shift(900).plot(ax=ax[1])
goog.tshift(900).plot(ax=ax[2])
# legends and annotations
local_max = pd.to_datetime('2007-11-05')
offset = pd.Timedelta(900, 'D')
ax[0].legend(['input'], loc=2)
ax[0].get_xticklabels()[2].set(weight='heavy', color='red')
ax[0].axvline(local_max, alpha=0.3, color='red')
ax[1].legend(['shift(900)'], loc=2)
ax[1].get_xticklabels()[2].set(weight='heavy', color='red')
ax[1].axvline(local_max + offset, alpha=0.3, color='red')
ax[2].legend(['tshift(900)'], loc=2)
ax[2].get_xticklabels()[1].set(weight='heavy', color='red')
ax[2].axvline(local_max + offset, alpha=0.3, color='red')
时移一个重要做用即便计算一段时间内的差异,好比计算谷歌股票一年的投资回报率:
ROI = 100 * (goog.tshift(-365) / goog - 1)
ROI.plot()
plt.ylabel('% Return on Investment')
滚动统计是时间序列的又一重要的操做。能够经过Series
和DataFrame
的rolling()
方法实现,返回相似于groupby
的操做,一样也有许多数据聚合的操做。
rolling = goog.rolling(365, center=True)
data = pd.DataFrame({'input': goog,
'one-year rolling_mean': rolling.mean(),
'one-year rolling_std': rolling.std()})
ax = data.plot(style=['-', '--', ':'])
ax.lines[0].set_alpha(0.3)