股票日线数据转换为周线、月线

pandas
新手专区
标签: #<Tag:0x00007fcf66715038> #<Tag:0x00007fcf66714ed0>

(神龙斗士) #1

通过股票日线数据,可以转换为周线、月线、季线、年线等任意数据。参考代码如下:

克隆策略
In [12]:
df=D.history_data(['000001.SZA', '000002.SZA', '600000.SHA'], start_date='2015-01-01', fields=['open', 'high', 'low', 'close', 'volume', 'amount'])
df.set_index('date', inplace=True)


def resample(df):
    # https://pandas-docs.github.io/pandas-docs-travis/timeseries.html#offset-aliases
    # 周 W、月 M、季度 Q、10天 10D、2周 2W
    period = 'W'

    weekly_df = df.resample(period, how='last')
    weekly_df['open'] = df['open'].resample(period, how='first')
    weekly_df['high'] = df['high'].resample(period, how='max')
    weekly_df['low'] = df['low'].resample(period, how='min')
    weekly_df['close'] = df['close'].resample(period, how='last')
    weekly_df['volume'] = df['volume'].resample(period, how='sum')
    weekly_df['amount'] = df['amount'].resample(period, how='sum')
    # 去除空的数据(没有交易的周)
    weekly_df = weekly_df[weekly_df.instrument.notnull()]
    weekly_df.reset_index(inplace=True)
    return weekly_df

weekly_df = df.groupby('instrument').apply(resample)
weekly_df.reset_index(drop=True, inplace=True)
weekly_df.head()
Out[12]:
date instrument open high low close volume amount
0 2015-12-31 000001.SZA 1136.148560 1504.896484 799.744995 1031.069092 36620106011 5.306051e+11
1 2016-12-31 000001.SZA 1031.928955 1034.508789 810.064270 953.300110 12636100947 1.225585e+11
2 2017-12-31 000001.SZA 954.347656 1007.774414 931.300842 936.538757 3731449546 3.450330e+10
3 2015-12-31 000002.SZA 1774.230591 3113.541504 1421.603760 3113.541504 55976109983 8.080087e+11
4 2016-12-31 000002.SZA 3113.541504 3850.691650 2133.470459 2728.679688 17826139968 4.027525e+11

更多 周期


策略研究常用功能
(江旭奇) #2

代码很规整:grinning:


(hightemplarr) #3

刚看了下链接的文档,确实挺有用的。谢谢大神了:sunglasses:


(iQuant) #4

如果要保证转化为的数据的索引为交易日历,可以参考下例:

克隆策略

转换成周线数据,并且保持日期索引为交易日历

In [90]:
df = D.history_data(['000001.SZA'],'2017-01-01','2018-01-01',['close','open'])  # 暂且以收盘价和开盘价为例

index_  = df.reset_index().resample('W',how='first',on='date').set_index('date').index  # 先获取日期索引
close_column = df.set_index('date')['close'].resample('W',label='left', how='last') # 再分别计算数据
open_column =  df.set_index('date')['open'].resample('W',label='left', how='first')
instrument_column = df.set_index('date')['instrument'].resample('W',label='left', how='first')

weekly_df = pd.DataFrame({'open':list(open_column),'close':list(close_column), # 按日期索引合并为数据框,并去除缺失值
                         'instrument':list(instrument_column)
                         },index=index_).dropna()
In [93]:
 weekly_df.head()
Out[93]:
close instrument open
date
2017-01-03 956.442871 000001.SZA 954.347656
2017-01-09 959.585571 000001.SZA 956.442871
2017-01-16 965.871094 000001.SZA 958.538025
2017-01-23 977.394470 000001.SZA 965.871094
2017-02-03 970.061401 000001.SZA 978.442078