1 Star 0 Fork 3

Lotcsy/判读趋势后的日内反转与趋势并行策略-基于Joinquant回测平台编写

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
判断趋势后的日内反转与趋势并行策略code.txt 33.61 KB
一键复制 编辑 原始数据 按行查看 历史
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
'''
策略说明:
沪深300指数期货或者中证500指数期货
开盘前判断趋势,判断为震荡行情实行反转策略,若为趋势则实行趋势策略。
趋势判断方法:
是否存在趋势:1、ADX指标在四日内有三日上升。2、当前ADX比昨日大。3、ADX>30
判断趋势方向:PDI>MDI则存在正向趋势,PDI<MDI则存在负向趋势
若为反转策略:
开盘前判定是否连续三日上涨或者下跌
以波动率乘一个固定值作为幅度,以百分之一为例
连续三日上涨则今天开盘前以上一日收盘价负百分之一挂多单,连续三日下跌则今天开盘前以上一日收盘价正百分之一挂空单
不存在明显trend则每日以上一日收盘价的正百分之一挂空单,负百分之一挂多单
若某一单成交,则立马撤销另外一单,并在这一单的基础上挂止盈限价单,同时确定止损线,突破止损线则挂市价单
若成交为空单,在此基础上挂负百分之一限价多单,突破正百分之一时挂市价空单
若成交为多单,在此基础上挂涨百分之一限价空单,突破负百分之一时挂市价多单
14点55对全部进行平仓保证多空相等
每日开盘前判定,如若多空单数大于等于2,只平仓,否则只开仓
开盘前挂单若在9点30成交,则以9点30开盘价对应幅度挂止盈单
若开盘前挂单在开盘后一段时间成交,则以挂单价格对应幅度挂止盈单
若为趋势策略(以正向趋势为例):
开盘前15分钟翻红则挂市价多单。
若15分钟未成交,则不再进行订单。
14点55进行平仓
'''
def initialize(context):
# 设定沪深300作为基准
g.index= '000905.XSHG'
set_benchmark(g.index)
# True为开启动态复权模式,使用真实价格交易
set_option('use_real_price', True)
# 设定成交量比例
set_option('order_volume_ratio', 1)
# 关闭订单提醒
# log.set_level('order', 'error')
# 设定期货保证金比例
set_option('futures_margin_rate', 0.12)
# 设定操作金融期货
set_subportfolios([SubPortfolioConfig(cash=context.portfolio.cash, type='index_futures')])
# 金融期货close_today_commission可不用设定,平今仓默认0.0023
set_order_cost(OrderCost(open_commission=0.000023, close_commission=0.000023, close_today_commission=0.0023), type='index_futures')
#滑点3跳(上下各3跳)
set_slippage(StepRelatedSlippage(6))
g.adx=[0,0,0,0,0,0]
g.up_trend=0
g.momen=0
g.rev=0
## 开盘前
def before_trading_start(context):
#期货代码
g.security = get_stock_index_futrue_code(context,symbol='IC',month='current_month')
#计算是否存在明显趋势
g.index_trend = if_momen(context,g.index)
#计算波动率
g.vol = std(g.index,20)
#根据波动率选择上浮下浮幅度
g.up = 1 + g.vol*0.05
g.down = 1 - g.vol*0.05
#当前已有持仓
long_closeable_amount = context.portfolio.long_positions[g.security].closeable_amount
short_closeable_amount = context.portfolio.short_positions[g.security].closeable_amount
#当天操作数清零
g.count=0
#根据波动率判断是否存在某种趋势
#g.long_trend = if_long()
if g.index_trend == 1 or g.index_trend == -1:
if long_closeable_amount+short_closeable_amount>1:
g.begin = 1
else:
g.begin = 0
elif g.index_trend == 0:
g.trend = if_trend(g.security)
#存在上升趋势,开始时只挂多单
if g.trend ==1:
if long_closeable_amount+short_closeable_amount>1:
g.begin = 1
only_up.Close_first_order(context)
else:
g.begin = 0
only_up.Open_first_order(context)
#存在下降趋势,开始时只挂空单
elif g.trend == -1:
if long_closeable_amount+short_closeable_amount>1:
g.begin = 1
only_down.Close_first_order(context)
else:
g.begin = 0
only_down.Open_first_order(context)
#不存在趋势,开始时挂多空单
else:
if long_closeable_amount+short_closeable_amount>1:
g.begin = 1
Close.first_order(context)
else:
g.begin=0
Open.first_order(context)
## 开盘后
def handle_data(context,data):
#执行顺上涨趋势策略
if g.index_trend == 1:
if g.begin ==0:
long_trend.Open_on_order(context)
Open.last_order(context)
elif g.begin == 1:
long_trend.Close_on_order(context)
Close.last_order(context)
#执行顺下降趋势策略
if g.index_trend == -1:
if g.begin ==0:
long_trend.Open_on_order(context)
Open.last_order(context)
elif g.begin == 1:
long_trend.Close_on_order(context)
Close.last_order(context)
#执行反转策略
elif g.index_trend == 0:
#无趋势
if g.trend == 0:
#只平仓
if g.begin == 1:
# 2点55分之后全部平仓
Close.last_order(context)
#盘中运行
Close.on_order(context)
#只开仓
else:
Open.last_order(context)
Open.on_order(context)
#上升趋势
elif g.trend == 1:
if g.begin == 1:
# 2点55分之后全部平仓
Close.last_order(context)
#盘中运行
only_up.Close_on_order(context)
else:
Open.last_order(context)
only_up.Open_on_order(context)
#下降趋势
elif g.trend == -1:
if g.begin == 1:
# 2点55分之后全部平仓
Close.last_order(context)
#盘中运行
only_down.Close_on_order(context)
else:
Open.last_order(context)
only_down.Open_on_order(context)
## 测算是否存在趋势函数
def if_momen(context,index):
security=[index]
pdi,mdi,adx,adxr = DMI(security,context.previous_date)
g.adx.append(adx[index])
adx_up=0
for i in range(4):
if g.adx[-(i+1)]>g.adx[-(i+2)]:
adx_up+=1
if g.adx[-1]>30 and g.adx[-1]>g.adx[-2] and adx_up>2:
if pdi[index]>mdi[index]:
index_trend=1#存在上升趋势
elif pdi[index]<mdi[index]:
index_trend=-1#存在下降趋势
else:
index_trend=0
g.rev+=1
return index_trend
## 获取昨日收盘价的正负百分之一
def Line_begin(security):
# 历史数据
hist = attribute_history(security, 3, '1d', ['close'], df=False)
# 昨日收盘价
Close_price = hist['close'][-1]
Line_up_one = num_five(g.up*Close_price)#涨1%
Line_down_one = num_five(g.down*Close_price)#跌1%
# 返回结果
return Line_up_one,Line_down_one
##对任意个数寻找最近5的倍数
def num_five(num):
if num%5 >=3:
number = (num//5)*5+5
else:
number = (num//5)*5
return number
##计算波动率
def std(security,k):
hist = attribute_history(security, k+1, '1d', ['close'], df=False)
Close_price = []
log_price = []
return_price = []
for i in range(k+1):
Close_price.append(hist['close'][-(i+1)])
for i in range(k+1):
log_price.append(math.log(Close_price[i]))
for i in range(k):
return_price.append(log_price[i]-log_price[i+1])
std = np.std(return_price,ddof=1)
std_year = std*((250)**(1/2))
return std_year
#根据波动率判断是否执行顺趋势策略
def if_long():
if g.vol > 0.15:
long = 1
else:
long= 0
return long
## 根据波动率判断是否存在趋势行情:
def if_trend(security):
hist = attribute_history(security, 3, '1d', ['open','close'], df=False)
Close_price_1 = hist['close'][-1]
Close_price_2 = hist['close'][-2]
Close_price_3 = hist['close'][-3]
open_price_1 = hist['open'][-1]
open_price_2 = hist['open'][-2]
open_price_3 = hist['open'][-3]
return_1 = Close_price_1/open_price_1
return_2 = Close_price_2/open_price_2
return_3 = Close_price_3/open_price_3
return_num = [return_1, return_2, return_3]
num_over = 0
for i in return_num:
if i >1:
num_over +=1
#连续三天上涨
if num_over>=3:
trend = 1
#连续三天下跌
elif num_over == 0:
trend = -1
else:
trend = 0
return trend
## 顺上升趋势策略
class long_trend(object):
def Open_on_order(context):
if (context.current_dt.hour == 9) and (context.current_dt.minute <= 45) and (g.count ==0):
current_data = get_current_data()
open_price = num_five(current_data[g.security].day_open)+5
current_data = get_current_data()
current_price=current_data[g.security].last_price
if current_price > open_price and g.count==0:
order(g.security,1,side='long')
g.count=1
def Close_on_order(context):
if (context.current_dt.hour == 9) and (context.current_dt.minute <= 45) and (g.count ==0):
current_data = get_current_data()
open_price = num_five(current_data[g.security].day_open)+5
current_data = get_current_data()
current_price=current_data[g.security].last_price
if current_price > open_price and g.count==0:
order(g.security,-1,side='short')
g.count=1
## 顺下降趋势策略
class short_trend(object):
def Open_on_order(context):
if (context.current_dt.hour == 9) and (context.current_dt.minute <= 45) and (g.count ==0):
current_data = get_current_data()
open_price = num_five(current_data[g.security].day_open)-5
current_data = get_current_data()
current_price=current_data[g.security].last_price
if current_price < open_price and g.count==0:
order(g.security,1,side='short')
g.count=1
def Close_on_order(context):
if (context.current_dt.hour == 9) and (context.current_dt.minute <= 45) and (g.count ==0):
current_data = get_current_data()
open_price = num_five(current_data[g.security].day_open)-5
current_data = get_current_data()
current_price=current_data[g.security].last_price
if current_price < open_price and g.count==0:
order(g.security,-1,side='long')
g.count=1
## 只开仓
class Open(object):
## 开盘挂单
def first_order(context):
# 获取2条线
g.Line_up_one, g.Line_down_one = Line_begin(g.security)
# 挂空仓
order(g.security, 1, LimitOrderStyle(g.Line_up_one), side='short')
# 挂多仓
order(g.security, 1 , LimitOrderStyle(g.Line_down_one), side='long')
## 14点55分之后全部平仓
def last_order(context):
if (context.current_dt.hour == 14) and (context.current_dt.minute == 55):
# 取消还未执行的全部订单
orders = get_open_orders()
for i in orders.values():
cancel_order(i)
#获取当前所有多空仓
long_closeable_amount = context.portfolio.long_positions[g.security].closeable_amount
short_closeable_amount = context.portfolio.short_positions[g.security].closeable_amount
#观察是否需要进行平仓
if long_closeable_amount < short_closeable_amount:
order(g.security, 1, side='long')
elif long_closeable_amount > short_closeable_amount:
order(g.security, 1 , side = 'short')
## 盘中运行
def on_order(context):
#时间不超过14点55
if (context.current_dt.hour >= 14) and (context.current_dt.minute >= 55):
return
else:
#还未交易订单数清零
trade=0
#计算还未交易订单数
orders = get_open_orders()
for i in orders.values():
trade+=1
# 获取标的的最新价
current_data = get_current_data()
current_price=current_data[g.security].last_price
#所挂订单小于2,表示所挂某订单已交易
if (trade < 2) and (g.count==0):
#挂单成立,取消所有其他单
orders = get_open_orders()
for i in orders.values():
cancel_order(i)
#已完成一个订单
g.count=1
#挂新订单
#如果九点半就成交,则以开盘价的正负百分之一
if (context.current_dt.hour == 9) and (context.current_dt.minute == 30):
long_closeable_amount = context.portfolio.long_positions[g.security].closeable_amount
short_closeable_amount = context.portfolio.short_positions[g.security].closeable_amount
if long_closeable_amount > short_closeable_amount:
g.Line_up_1 = num_five(g.up*current_price)
g.Line_down_1 = g.down*current_price
order(g.security,1,LimitOrderStyle(g.Line_up_1),side='short')
elif long_closeable_amount < short_closeable_amount:
g.Line_down_1 = num_five(g.down*current_price)
g.Line_up_1 = g.up*current_price
order(g.security,1,LimitOrderStyle(g.Line_down_1),side='long')
#如果不是九点半成交,则以所成交限价单的正负百分之一
else:
long_closeable_amount = context.portfolio.long_positions[g.security].closeable_amount
short_closeable_amount = context.portfolio.short_positions[g.security].closeable_amount
if long_closeable_amount > short_closeable_amount:
g.Line_up_1 = num_five(g.up*g.Line_down_one)
g.Line_down_1 = g.down*g.Line_down_one
order(g.security,1,LimitOrderStyle(g.Line_up_1),side='short')
elif long_closeable_amount < short_closeable_amount:
g.Line_down_1 = num_five(g.down*g.Line_up_one)
g.Line_up_1 = g.up*g.Line_up_one
order(g.security,1,LimitOrderStyle(g.Line_down_1),side='long')
#若当天还只成交过一个订单,则每分钟判断是否止损
if g.count==1 and trade==1 and ((context.current_dt.hour != 9) or (context.current_dt.minute != 30)):
#止损
if (current_price <= g.Line_down_1) or (current_price >= g.Line_up_1):
#取消还未成交所有订单
orders = get_open_orders()
for i in orders.values():
cancel_order(i)
order_target(g.security,1, side='short')
order_target(g.security,1, side='long')
#已完成两个订单
g.count=2
## 只平仓
class Close(object):
## 开盘挂单
def first_order(context):
# 获取2条线
g.Line_up_one, g.Line_down_one = Line_begin(g.security)
# 挂空仓
order(g.security, -1, LimitOrderStyle(g.Line_up_one), side='long')
# 挂多仓
order(g.security, -1, LimitOrderStyle(g.Line_down_one), side='short')
## 14点55分之后全部平仓
def last_order(context):
if (context.current_dt.hour == 14) and (context.current_dt.minute == 55):
# 取消还未执行的全部订单
orders = get_open_orders()
for i in orders.values():
cancel_order(i)
#获取当前所有多空仓
long_closeable_amount = context.portfolio.long_positions[g.security].closeable_amount
short_closeable_amount = context.portfolio.short_positions[g.security].closeable_amount
#观察是否需要进行平仓
if long_closeable_amount < short_closeable_amount and g.count==1:
order(g.security, -1, side='short')
elif long_closeable_amount > short_closeable_amount and g.count==1:
order(g.security, -1 , side ='long')
## 盘中运行
def on_order(context):
#时间不超过14点55
if (context.current_dt.hour >= 14) and (context.current_dt.minute >= 55):
return
else:
# 获取标的的最新价
trade=0
current_data = get_current_data()
current_price=current_data[g.security].last_price
#还未成交订单数
orders = get_open_orders()
for i in orders.values():
trade+=1
if (trade < 2) and (g.count==0):
#挂单成交,取消所有其他单
orders = get_open_orders()
# 循环,撤销订单
for i in orders.values():
cancel_order(i)
g.count=1
if(context.current_dt.hour == 9) and (context.current_dt.minute == 30):
long_closeable_amount = context.portfolio.long_positions[g.security].closeable_amount
short_closeable_amount = context.portfolio.short_positions[g.security].closeable_amount
if long_closeable_amount > short_closeable_amount:
g.Line_up_1 = num_five(g.up*current_price)
g.Line_down_1 = g.down*current_price
order(g.security,-1,LimitOrderStyle(g.Line_up_1),side='long')
elif long_closeable_amount < short_closeable_amount:
g.Line_down_1 = num_five(g.down*current_price)
g.Line_up_1 = g.up*current_price
order(g.security,-1,LimitOrderStyle(g.Line_down_1),side='short')
else:
long_closeable_amount = context.portfolio.long_positions[g.security].closeable_amount
short_closeable_amount = context.portfolio.short_positions[g.security].closeable_amount
if long_closeable_amount > short_closeable_amount:
g.Line_up_1 = num_five(g.up*g.Line_down_one)
g.Line_down_1 = g.down*g.Line_down_one
order(g.security,-1,LimitOrderStyle(g.Line_up_1),side='long')
elif long_closeable_amount < short_closeable_amount:
g.Line_down_1 = num_five(g.down*g.Line_up_one)
g.Line_up_1 = g.up*g.Line_up_one
order(g.security,-1,LimitOrderStyle(g.Line_down_1),side='short')
# 挂多仓
if g.count==1 and trade==1 and ((context.current_dt.hour != 9) or (context.current_dt.minute != 30)):
#价格上涨百分之一或下跌百分之一
if (current_price <= g.Line_down_1) or (current_price >= g.Line_up_1):
orders = get_open_orders()
for i in orders.values():
cancel_order(i)
order_target(g.security,0 ,side='long')
order_target(g.security,0 ,side='short')
g.count=2
## 连续三天上涨
class only_up(object):
def Open_first_order(context):
g.Line_up_one, g.Line_down_one = Line_begin(g.security)
order(g.security, 1 ,LimitOrderStyle(g.Line_down_one) , side='long')
def Close_first_order(context):
g.Line_up_one, g.Line_down_one = Line_begin(g.security)
order(g.security, -1 ,LimitOrderStyle(g.Line_down_one) , side='short')
def Open_on_order(context):
if (context.current_dt.hour >= 14) and (context.current_dt.minute >= 55):
return
else:
#还未交易订单数清零
trade=0
#计算还未交易订单数
orders = get_open_orders()
for i in orders.values():
trade+=1
# 获取标的的最新价
current_data = get_current_data()
current_price=current_data[g.security].last_price
#多空仓不相等表示所挂订单已交易
if (trade < 1) and (g.count==0):
#已完成一个订单
g.count=1
#挂新订单
#如果九点半就成交,则以开盘价的正负百分之一
if (context.current_dt.hour == 9) and (context.current_dt.minute == 30):
g.Line_up_1 = num_five(g.up*current_price)
g.Line_down_1 = g.down*current_price
order(g.security,1,LimitOrderStyle(g.Line_up_1),side='short')
#如果不是九点半成交,则以所成交限价单的正负百分之一
else:
g.Line_up_1 = num_five(g.up*g.Line_down_one)
g.Line_down_1 = g.down*g.Line_down_one
order(g.security,1,LimitOrderStyle(g.Line_up_1),side='short')
#若当天还只成交过一个订单,则每分钟判断是否止损
if g.count==1 and trade==1 and ((context.current_dt.hour != 9) or (context.current_dt.minute != 30)):
if current_price <= g.Line_down_1:
orders = get_open_orders()
for i in orders.values():
cancel_order(i)
order(g.security,1, side='short')
#已完成两个订单
g.count=2
def Close_on_order(context):
if (context.current_dt.hour >= 14) and (context.current_dt.minute >= 55):
return
else:
#还未交易订单数清零
trade=0
#计算还未交易订单数
orders = get_open_orders()
for i in orders.values():
trade+=1
# 获取标的的最新价
current_data = get_current_data()
current_price=current_data[g.security].last_price
#多空仓不相等表示所挂订单已交易
if (trade < 1) and (g.count==0):
#已完成一个订单
g.count=1
#挂新订单
#如果九点半就成交,则以开盘价的正负百分之一
if (context.current_dt.hour == 9) and (context.current_dt.minute == 30):
g.Line_up_1 = num_five(g.up*current_price)
g.Line_down_1 = g.down*current_price
order(g.security,-1,LimitOrderStyle(g.Line_up_1),side='long')
#如果不是九点半成交,则以所成交限价单的正负百分之一
else:
g.Line_up_1 = num_five(g.up*g.Line_down_one)
g.Line_down_1 = g.down*g.Line_down_one
order(g.security,-1,LimitOrderStyle(g.Line_up_1),side='long')
#若当天还只成交过一个订单,则每分钟判断是否止损
if g.count==1 and trade==1 and ((context.current_dt.hour != 9) or (context.current_dt.minute != 30)):
if current_price <= g.Line_down_1:
orders = get_open_orders()
for i in orders.values():
cancel_order(i)
order(g.security,-1, side='long')
#已完成两个订单
g.count=2
class only_down(object):
def Open_first_order(context):
g.Line_up_one, g.Line_down_one = Line_begin(g.security)
order(g.security, 1 ,LimitOrderStyle(g.Line_up_one) , side='short')
def Close_first_order(context):
g.Line_up_one, g.Line_down_one = Line_begin(g.security)
order(g.security, -1 ,LimitOrderStyle(g.Line_up_one) , side='long')
def Open_on_order(context):
if (context.current_dt.hour >= 14) and (context.current_dt.minute >= 55):
return
else:
#还未交易订单数清零
trade=0
#计算还未交易订单数
orders = get_open_orders()
for i in orders.values():
trade+=1
# 获取标的的最新价
current_data = get_current_data()
current_price=current_data[g.security].last_price
#多空仓不相等表示所挂订单已交易
if (trade < 1) and (g.count==0):
#挂单成立,取消所有其他单
orders = get_open_orders()
for i in orders.values():
cancel_order(i)
#已完成一个订单
g.count=1
#挂新订单
#如果九点半就成交,则以开盘价的正负百分之一
if (context.current_dt.hour == 9) and (context.current_dt.minute == 30):
g.Line_down_1 = num_five(g.down*current_price)
g.Line_up_1 = g.up*current_price
order(g.security,1,LimitOrderStyle(g.Line_down_1),side='long')
#如果不是九点半成交,则以所成交限价单的正负百分之一
else:
g.Line_down_1 = num_five(g.down*g.Line_up_one)
g.Line_up_1 = g.up*g.Line_up_one
order(g.security,1,LimitOrderStyle(g.Line_down_1),side='long')
#若当天还只成交过一个订单,则每分钟判断是否止损
if g.count==1 and trade==1 and ((context.current_dt.hour != 9) or (context.current_dt.minute != 30)):
if current_price >= g.Line_up_1:
orders = get_open_orders()
for i in orders.values():
cancel_order(i)
order(g.security,1, side='long')
#已完成两个订单
g.count=2
def Close_on_order(context):
if (context.current_dt.hour >= 14) and (context.current_dt.minute >= 55):
return
else:
#还未交易订单数清零
trade=0
#计算还未交易订单数
orders = get_open_orders()
for i in orders.values():
trade+=1
# 获取标的的最新价
current_data = get_current_data()
current_price=current_data[g.security].last_price
#多空仓不相等表示所挂订单已交易
if (trade < 1) and (g.count==0):
#挂单成立,取消所有其他单
orders = get_open_orders()
for i in orders.values():
cancel_order(i)
#已完成一个订单
g.count=1
#挂新订单
#如果九点半就成交,则以开盘价的正负百分之一
if (context.current_dt.hour == 9) and (context.current_dt.minute == 30):
g.Line_down_1 = num_five(g.down*current_price)
g.Line_up_1 = g.up*current_price
order(g.security,-1,LimitOrderStyle(g.Line_down_1),side='short')
#如果不是九点半成交,则以所成交限价单的正负百分之一
else:
g.Line_down_1 = num_five(g.down*g.Line_up_one)
g.Line_up_1 = g.up*g.Line_up_one
order(g.security,-1,LimitOrderStyle(g.Line_down_1),side='short')
#若当天还只成交过一个订单,则每分钟判断是否止损
if g.count==1 and trade==1 and ((context.current_dt.hour != 9) or (context.current_dt.minute != 30)):
if current_price >= g.Line_up_1:
orders = get_open_orders()
for i in orders.values():
cancel_order(i)
order(g.security,-1, side='short')
#已完成两个订单
g.count=2
#计算PDI,MDI,ADX
def DMI(security_list, check_date, N=14, MM=6):
'''
计算公式:
MTR = 最高价-最低价和最高价-1日前的收盘价的绝对值的较大值和1日前的收盘价-最低价的绝对值的较大值的N日指数平滑移动平均
HD = 最高价-1日前的最高价
LD = 1日前的最低价-最低价
DMP = 如果HD>0并且HD>LD,返回HD,否则返回0的N日指数平滑移动平均
DMM = 如果LD>0并且LD>HD,返回LD,否则返回0的N日指数平滑移动平均
输出PDI = DMP*100/MTR
输出MDI = DMM*100/MTR
输出ADX = MDI-PDI的绝对值/(MDI+PDI)*100的MM日指数平滑移动平均
输出ADXR = ADX的MM日指数平滑移动平均
输入:
security_list:股票列表
check_date:要查询数据的日期
N:统计的天数 N
MM:统计的天数 MM
输出:
PDI, MDI, ADX, ADXR的值
输出结果类型:
字典(dict):键(key)为股票代码,值(value)为数据。
'''
import talib
import numpy as np
import six
# 修复传入为单只股票的情况
if isinstance(security_list, six.string_types):
security_list = [security_list]
# 计算 PDI, MDI, ADX, ADXR
dmi_pdi = {}
dmi_mdi = {}
dmi_adx = {}
dmi_adxr = {}
for stock in security_list:
security_data = get_price(stock, end_date=check_date, frequency='1d', fields=[
'high', 'low', 'close'], skip_paused=True, count=N * 20)
nan_count = list(np.isnan(security_data['close'])).count(True)
if nan_count == len(security_data['close']):
log.info("股票 %s 输入数据全是 NaN,该股票可能已退市、未上市或刚上市,返回 NaN 值数据。" % stock)
dmi_pdi[stock] = np.nan
dmi_mdi[stock] = np.nan
dmi_adx[stock] = np.nan
dmi_adxr[stock] = np.nan
else:
if nan_count > 0:
security_data.fillna(method="bfill", inplace=True)
close_DMI = security_data['close']
high_DMI = security_data['high']
low_DMI = security_data['low']
maxList = []
dmpList = []
dmmList = []
# 获取 mtr
temp = -N * 5
while temp < 0:
m = max(high_DMI[temp] - low_DMI[temp], abs(high_DMI[temp] -
close_DMI[temp - 1]), abs(close_DMI[temp - 1] - low_DMI[temp]))
maxList.append(m)
temp += 1
mtr = talib.EMA(np.array(maxList), N)
# 获取dmp 和 dmm
temp = -N * 5
while temp < 0:
m = 0
hd = high_DMI[temp] - high_DMI[temp - 1]
ld = low_DMI[temp - 1] - low_DMI[temp]
if hd > 0 and hd > ld:
m = hd
else:
m = 0
dmpList.append(m)
if ld > 0 and ld > hd:
m = ld
else:
m = 0
dmmList.append(m)
temp += 1
dmpList, dmmList = np.nan_to_num(np.array(dmpList)), np.nan_to_num(np.array(dmmList))
dmp = talib.EMA(dmpList, N)
dmm = talib.EMA(dmmList, N)
# 获取 mdi 和 pdi
pdi = dmp * 100 / mtr
mdi = dmm * 100 / mtr
# 获取adx 和 adxr
adxList = abs(mdi - pdi) / (mdi + pdi) * 100
adx = talib.EMA(adxList, MM)
adxr = talib.EMA(adx, MM)
dmi_pdi[stock] = pdi[-1]
dmi_mdi[stock] = mdi[-1]
dmi_adx[stock] = adx[-1]
dmi_adxr[stock] = adxr[-1]
return dmi_pdi, dmi_mdi, dmi_adx, dmi_adxr
## 获取当天时间正在交易的股指期货合约
def get_stock_index_futrue_code(context,symbol,month='current_month'):
'''
获取当天时间正在交易的股指期货合约。其中:
symbol:
'IF' #沪深300指数期货
'IC' #中证500股指期货
'IH' #上证50股指期货
month:
'current_month' #当月
'next_month' #隔月
'next_quarter' #下季
'skip_quarter' #隔季
'''
display_name_dict = {'IF':'沪深300指数期货','IC':'中证500股指期货','IH':'上证50股指期货'}
month_dict = {'current_month':0, 'next_month':1, 'next_quarter':2, 'skip_quarter':3}
display_name = display_name_dict[symbol]
n = month_dict[month]
dt = context.current_dt.date()
a = get_all_securities(types=['futures'], date=dt)
try:
df = a[(a.display_name == display_name) & (a.start_date <= dt) & (a.end_date >= dt)]
if (len(df)>4) and (month in ('next_quarter','skip_quarter')):
return df.index[n+1]
else:
return df.index[n]
except:
return 'WARRING: 无此合约'
# 获取金融期货合约到期日
def get_CCFX_end_date(fature_code):
return get_security_info(fature_code).end_date
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/lotcsy/day-trend-and-adverse.git
git@gitee.com:lotcsy/day-trend-and-adverse.git
lotcsy
day-trend-and-adverse
判读趋势后的日内反转与趋势并行策略-基于Joinquant回测平台编写
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385