1.1创建Strategy模块
此模块用于策略开发,产生交易信号。
1.2创建周期选股策略
什么为周期?简单来说,就是周四买入,周一卖出。这就是一个周期。
1.3生成交易信号
明确哪个交易日买入 哪个交易日卖出,用1和-1 标注。帮助之后计算持仓的信息。
import finance.Stock as st
import numpy as np#用来创建交易策略、生成交易信号
def week_period_strategy(stock_code, timefrequency, startdate, enddate):#获取数据data = st.get_single_price(stock_code, startdate, enddate,timefrequency)print(data)#创建周期字段data['weekday'] = data.index.weekday#周四交易:买入(0:不操作 1:买入)data['buy_signal'] = np.where((data['weekday']==3),1,0)#周一交易:卖出(0:不操作 1:卖出)data['sell_signal'] = np.where((data['weekday']==0),-1,0)return dataif __name__ == '__main__':data = week_period_strategy(stock_code='000001.XSHE', timefrequency='daily', startdate='2021-02-01', enddate='2021-03-01')print(data)
考虑到不能够隔天重复呢买入,我们需要模拟一个情况
2.2模拟重复买入:周五再次买入
def week_period_strategy(stock_code, timefrequency, startdate, enddate):#获取数据data = st.get_single_price(stock_code, timefrequency, startdate, enddate)print(data)#创建周期字段data['weekday'] = data.index.weekday#周四交易:买入(0:不操作 1:买入)data['buy_signal'] = np.where((data['weekday']==3),1,0) #周一交易:卖出(0:不操作 1:卖出)data['sell_signal'] = np.where((data['weekday']==0),-1,0)#模拟重复买入:周五再次买入data['buy_signal'] = np.where((data['weekday']==3) | (data['weekday']==4),1,0) return data
出现了三次:连着2天买入,一次在卖出。
当我有2天连续买入,但实际上,只有一个买入信号时,怎么去合并。我们的合并思路应该是什么么?
我们的策略是:
只保留第一次出现的“1”,接下来不管出现多少个‘1’,都不视作卖出。
怎么实现呢?我们注意到要删除的这个“1”的特性:
要被删除的这个”1“ 上一行还是”1“,我们只需将这种情况改为0即可
import finance.Stock as st
import numpy as np#用来创建交易策略、生成交易信号
def week_period_strategy(stock_code, timefrequency, startdate, enddate):#获取数据data = st.get_single_price(stock_code, startdate, enddate,timefrequency)print(data)#创建周期字段data['weekday'] = data.index.weekday#周四交易:买入(0:不操作 1:买入)data['buy_signal'] = np.where((data['weekday']==3),1,0)#周一交易:卖出(0:不操作 1:卖出)data['sell_signal'] = np.where((data['weekday']==0),-1,0)# 模拟重复买入:周五再次买入data['buy_signal'] = np.where((data['weekday'] == 3) | (data['weekday'] == 4), 1, 0)# 合并信号 很快的观察出买和卖data['signal'] = data['buy_signal'] + data['sell_signal']return dataif __name__ == '__main__':data = week_period_strategy(stock_code='000001.XSHE', timefrequency='daily', startdate='2021-02-01', enddate='2021-03-01')# 整合信号data['buy_signal'] = np.where((data['buy_signal'] == 1) & (data['buy_signal'].shift(1) == 1), 0, data['buy_signal'])data['sell_signal'] = np.where((data['sell_signal'] == -1) & (data['sell_signal'].shift(1) == -1), 0,data['sell_signal'])print(data)
到目前位置,我们就是实现了最简单的周一买,周四卖的选股策略。