三日定律:
三日定律其实是来源与乔治·道格拉斯·泰勒的“预约法”,在后来它就被演变成了LSS三日周期法。泰勒说,市场波动最开始就是从内部开始驱动的,有内部消息者或者聪明人最先买进,逐步带动了市场的上扬后,到了第三天的话,市场走势虽然还是在向上运行,但是聪明的投资者已经开始趁势卖出兑现了,这其实就是泰勒定义的真个市场波动程序。
通常一只股票出现了连续上天相同的走势,第一天会哟与市场里先知先觉的玩家所发动的,而后知后觉的人会在第二天进行跟进,然而到了第三天的话,连哪些原本不知不觉的人都开始经常了,显然这就已经说明了走势接近尾声了。这其实也就是股市中的常说的那句俗语“三天不追涨,五天不杀跌。”“三日没有新高现,只卖不买没商量”的缘由。
K线形态引用自:http://www.yingjia360.com/kxtj/2017-12-21/41751.html
照着上面的理论, 笔者的理解为,股市砖家认为,三天的连续的走势,到了第四天会反转,得出策略:上涨三日卖出,下跌三日买入
上代码:
#出现三日定律,全仓买入,全仓卖出
import tushare as ts
import pandas as pd
import datetime # For datetime objects
import os.path # To manage paths
import sys # To find out the script name (in argv[0])
# Import the backtrader platform
import backtrader as bt
import talib as talib
import numpy as np
class MyStrategy(bt.Strategy):
# 策略参数
params = dict(
printlog=False
)
def __init__(self):
self.star = dict()
self.cdl3inside = dict()
# 定义全局变量
self.count = 0
for data in self.datas:
# 转为tabib要求的数据格式
opens = np.array(data.open.array)
highs = np.array(data.high.array)
lows = np.array(data.low.array)
closes = np.array(data.close.array)
# 三日定律形态
cdl3insideRes = talib.CDL3INSIDE(opens, highs, lows, closes)
# 数据放入self中
print('三日定律,100是三天连续上涨,-100是三天连续下跌')
print(cdl3insideRes)
self.cdl3inside[data._id] = cdl3insideRes
def next(self):
# 得到当前的账户价值
total_value = self.broker.getcash()
for data in self.datas:
pos = self.getposition(data).size
# 三日连跌
if total_value > 0 and self.cdl3inside[data._id][self.count] == -100:
p_value = total_value * 0.9 / 10
size = ((int(total_value / self.data.close[0]))) - ((int(total_value / self.data.close[0])) % 100) - 100
if(size > 100 ):
self.buy(data=data, size=size)
print('出现底部三日定律,全仓买入,买入数量' + str(size) )
#三日连跌
if pos > 0 and self.cdl3inside[data._id][self.count] == 100:
# 全部卖出
# 跟踪订单避免重复
self.sell(data=data, size=pos)
print('出现三日定律,卖出数量' + str(pos))
#自增处理
self.count = self.count + 1
def log(self, txt, dt=None, doprint=False):
if self.params.printlog or doprint:
dt = dt or self.datas[0].datetime.date(0)
print(f'{dt.isoformat()},{txt}')
# 记录交易执行情况(可省略,默认不输出结果)
def notify_order(self, order):
# 如果order为submitted/accepted,返回空
if order.status in [order.Submitted, order.Accepted]:
return
# 如果order为buy/sell executed,报告价格结果
if order.status in [order.Completed]:
if order.isbuy():
self.log(f'买入:\n价格:{order.executed.price:.2f},\
成本:{order.executed.value:.2f},\
数量:{order.executed.size:.2f},\
手续费:{order.executed.comm:.2f}')
self.buyprice = order.executed.price
self.buycomm = order.executed.comm
else:
self.log(f'卖出:\n价格:{order.executed.price:.2f},\
成本: {order.executed.value:.2f},\
数量:{order.executed.size:.2f},\
手续费{order.executed.comm:.2f}')
self.bar_executed = len(self)
# 如果指令取消/交易失败, 报告结果
elif order.status in [order.Canceled, order.Margin, order.Rejected]:
self.log('交易失败')
self.order = None
# 记录交易收益情况(可省略,默认不输出结果)
def notify_trade(self, trade):
if not trade.isclosed:
return
self.log(f'策略收益:\n毛收益 {trade.pnl:.2f}, 净收益 {trade.pnlcomm:.2f}')
pro = ts.pro_api('cbb257058b7cb228769b4949437c27c27e5132e882747dc80f01a5a5')
def ts_get_daily_stock(code, start_dt, end_dt):
start_dt = start_dt.replace("'", "", 3);
end_dt = end_dt.replace("'", "", 3);
# start_dt = '20190101'
# end_dt=''
print(code, start_dt, end_dt)
data = pro.daily(ts_code=code, start_date=start_dt, end_date=end_dt)
data['trade_date'] = pd.to_datetime(data['trade_date'])
data['trade_date'] = pd.to_datetime(data['trade_date'])
data = data.sort_values(by='trade_date')
data.index = data['trade_date']
data['openinterest'] = 0
data['volume'] = data['vol']
data = data[
['open', 'close', 'high', 'low', 'volume']
]
return data
# 读取选股的结果
df = pd.read_csv('stock_alpha.csv')
df.columns = ['ts_code', 'name', 'alpha', 'start_dt', 'end_dt']
min_a = df.sort_values(by='alpha')
min_a = min_a.iloc[:10, :]
code = []
code = min_a['ts_code'] # 股票代码
start_dts = []
start_dts = min_a['start_dt'] # 股票代码起始时间
end_dts = []
end_dts = min_a['end_dt'] # 股票代码结束时间
for i in range(len(code)):
data = ts_get_daily_stock(code.iloc[i], start_dts.iloc[i], end_dts.iloc[i]) # 字段分别为股票代码、开始日期、结束日期
data.to_csv(code.iloc[i] + '.csv')
cerebro = bt.Cerebro()
for i in range(len(code)): # 循环获取股票历史数据
dataframe = pd.read_csv(code.iloc[i] + '.csv', index_col=0, parse_dates=True)
dataframe['openinterest'] = 0
data = bt.feeds.PandasData(dataname=dataframe,
fromdate=datetime.datetime(2020, 2, 20),
todate=datetime.datetime(2022, 4, 5)
)
cerebro.adddata(data)
# 回测设置
startcash = 100000.0
cerebro.broker.setcash(startcash)
# 设置佣金为千分之一
cerebro.broker.setcommission(commission=0.001)
# 添加策略
cerebro.addstrategy(MyStrategy, printlog=True)
cerebro.run()
# 获取回测结束后的总资金
portvalue = cerebro.broker.getvalue()
pnl = portvalue - startcash
# 打印结果
print(f'总资金: {round(portvalue,2)}')
print(f'净收益: {round(pnl,2)}')
cerebro.plot()
执行结论:
总资金: 128617.2
净收益: 28617.2
数据源同上一章
三日定律函数:
talib.CDL3INSIDE(opens, highs, lows, closes)
-100三天连跌
100三天连涨