python 量化交易 2 resample 转换周K月K
resample是pandas库里的一个方法函数,主要作用就是用来转换时间序列的频次,同时还可以做统计汇总的工作
如转换日K为周K的方法,所谓日K得数据构成就是当天的开盘价、收盘价、最高价、最低价,周K就是一周内的这四个数据
方法说明:https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.resample.html
import pandas as pd # 设置行列不忽略 pd.set_option('display.max_rows',100000) pd.set_option('display.max_column',10) # resample的使用 # 转换周期:日K转换周K,先用过get_price方法获取日K df2 = get_price('000001.XSHG', count=20, end_date='2021-12-16', frequency='daily', panel=False) #加一个显示周几的字段(0为周一) df2['weekday'] = df2.index.weekday #获取周K(当周的):开盘价(当周第一天)、收盘价(当周最后一天)、最高价(当周)、最低价(当周) #先定义一下df_week为pandas下的DataFrame对象 df_week = pd.DataFrame() # 通过resample的first\last获取本周的开盘价和收盘价,通过max和min获取最高价和最低价 df_week['open'] = df2['open'].resample('W').first() df_week['close'] = df2['close'].resample('W').last() df_week['high'] = df2['high'].resample('W').max() df_week['low'] = df2['low'].resample('W').min() # 汇总统计:统计月成交量,成交额(sum) df_week['volume(sum)'] = df2['volume'].resample('W').sum() df_week['money(sum)'] = df2['money'].resample('W').sum() print(df_week)
如果需要改成月K
# 首先修改时间周期为开始时间和结束时间为一年 df2 = get_price('000001.XSHG', start_date='2021-01-01, end_date='2021-12-31', frequency='daily', panel=False) df_week = pd.DataFrame() # 修改所有的resample值为M,如果改为年K值就是Y df_week['open'] = df2['open'].resample('M').first() df_week['close'] = df2['close'].resample('M').last() df_week['high'] = df2['high'].resample('M').max() df_week['low'] = df2['low'].resample('M').min() df_week['volume(sum)'] = df2['volume'].resample('M').sum() df_week['money(sum)'] = df2['money'].resample('M').sum() print(df_week)