pandas金融时间序列处理
(2018-04-11 10:29:52)
标签:
ai金融 |
分类: python从零实现AI量化投资系统 |
pandas本身就是为金融时间序列而生,它的思考借鉴自R语言的Dataframe。
可以这么说,python有了numpy,基本就和matlab的矩阵运算功能对齐了;而有了pandas,数据类型和操作方便性上,已超过了matlab。
pandas的功能非常强大,可以简单认为,就是一个内存里的excel,而且是加上VBA编程功能的excel。
重建索引:reindex
金融的时间序列,有一个常见的现象,就是某支股票会在某些时间段停牌,这时是没有交易数据的。但对于回测这样的应用,这个时间段的数据不能为0吧,正常的逻辑,需要使用停牌前的数据,也就是需要数据向后填充。
pandas的reindex函数,可以对index重建,缺失值是使用NA填充,可以自行指定,比如0.0
import pandas as pd import unittest class TestPandas(unittest.TestCase): def test_reindex(self): df = pd.Series([4.5, 7.2, -5.3, 3.6], index=['d', 'b', 'a', 'c']) print(df) df_fillNA = df.reindex(['a', 'b', 'c', 'd', 'e']) print(df_fillNA) df_fill0 = df.reindex(['a', 'b', 'c', 'd', 'e'],fill_value=0.0) print(df_fill0)
打印出来的结果如下:
d
b
a
c
dtype: float64
a
b
c
d
e
dtype: float64
a
b
c
d
e
dtype: float64
插值功能:
上前文提到,时间序列,比如股票的交易数据不能默认填充为Na或0.0,而是需要使用前一期或后一期的数据来填充。可以使用method这个参数。ffill为向前(时间小的往大的填充)
def test_fill(self): raw = pd.Series(['blue', 'red', 'yellow'], index=[0, 2, 4]) print(raw) ffill = raw.reindex(range(6), method='ffill') print('ffill:',ffill) bfill = raw.reindex(range(6), method='bfill') print('bfill',bfill)
这里会有一个问题就是,起点缺失的问题,比如bfill的最后一个日期,没有数据,那还是使用默认值Na。
0
2
4
dtype: object
ffill:
0
1
2
3
4
5
dtype: object
bfill
0
1
2
3
4
5
一个实际应用的例子:
对金融时间序列做填充,比如万科,2015年12月18号开始停牌,到2016年7月4号才复牌。这中间的数据,都使用2015年12月8号的。
def get_symbol_dataframe(self,symbol):
if symbol not in self.all_symbol_dfs.keys():
logger.debug('symbol未发现,从服务器获取。')
df_get = query_data.query_symbol_dataframe(symbol, start_date=self.start_date,
end_date=self.end_date)
print('raw',df_get)
if self.trade_days is not None:
df_get = df_get.reindex(self.trade_days,method='ffill',fill_value=0.0)
self.all_symbol_dfs[symbol] = df_get
df = self.all_symbol_dfs[symbol]
return df
填充前:
2015-12-14
2015-12-15
2015-12-16
2015-12-17
2015-12-18
2016-07-04
2016-07-05
2016-07-06
2016-07-07
填充后:
2015-12-15
2015-12-16
2015-12-17
2015-12-18
2015-12-21
2015-12-22
2015-12-23
2015-12-24
2015-12-25
2015-12-28
2015-12-29
2015-12-30
2015-12-31
2016-01-04
原文出自: