================================================================================
总体回测前
================================================================================#总体回测前要做的事情
def initialize(context):set_params()        #1设置策参数set_variables()     #2设置中间变量set_backtest()      #3设置回测条件#1
#设置策略参数
def set_params():g.security = '000063.XSHE'# 系统1入市的trailing dateg.short_in_date = 20# 系统2入市的trailing dateg.long_in_date = 55# 系统1 exiting market trailing dateg.short_out_date = 10# 系统2 exiting market trailing dateg.long_out_date = 20# g.dollars_per_share是标的股票每波动一个最小单位,1手股票的总价格变化量。# 在国内最小变化量是0.01元,所以就是0.01×100=1g.dollars_per_share = 1# 可承受的最大损失率g.loss = 0.1# 若超过最大损失率,则调整率为:g.adjust = 0.8# 计算N值的天数g.number_days = 20# 最大允许单元g.unit_limit = 4# 系统1所配金额占总金额比例g.ratio = 0.8#2
#设置中间变量
def set_variables():# 初始单元g.unit = 1000# A list storing info of Ng.N = []# Record the number of days for this trading systemg.days = 0# 系统1的突破价格g.break_price1 = 0# 系统2的突破价格g.break_price2 = 0# 系统1建的仓数g.sys1 = 0# 系统2建的仓数g.sys2 = 0# 系统1执行且系统2不执行g.system1 = True#3
#设置回测条件
def set_backtest():# 作为判断策略好坏和一系列风险值计算的基准set_benchmark(g.security)set_option('use_real_price',True) #用真实价格交易log.set_level('order','error') # 设置报错等级================================================================================
每天开盘前
================================================================================
'''
#每天开盘前要做的事情
def before_trading_start(context):set_slip_fee(context) #4 根据不同的时间段设置滑点与手续费
def set_slip_fee(context):# 将滑点设置为0set_slippage(FixedSlippage(0)) # 根据不同的时间段设置手续费dt=context.current_dtif dt>datetime.datetime(2013,1, 1):set_commission(PerTrade(buy_cost=0.0003, sell_cost=0.0013, min_cost=5)) elif dt>datetime.datetime(2011,1, 1):set_commission(PerTrade(buy_cost=0.001, sell_cost=0.002, min_cost=5))elif dt>datetime.datetime(2009,1, 1):set_commission(PerTrade(buy_cost=0.002, sell_cost=0.003, min_cost=5))else:set_commission(PerTrade(buy_cost=0.003, sell_cost=0.004, min_cost=5))================================================================================
每天交易时
================================================================================
# 按分钟回测
def handle_data(context, data):dt = context.current_dt # 当前日期current_price = data[g.security].price # 当前价格Nif dt.hour==9 and dt.minute==30:g.days += 1calculate_N() #计算N的值if g.days > g.number_days:# 当前持有的股票和现金的总价值value = context.portfolio.portfolio_value# 可花费的现金cash = context.portfolio.cash if g.sys1 == 0 and g.sys2 == 0:# 若损失率大于g.loss,则调整(减小)可持有现金和总价值if value < (1-g.loss)*context.portfolio.starting_cash:cash *= g.adjustvalue *= g.adjust# 计算美元波动的价格dollar_volatility = g.dollars_per_share*(g.N)[-1]# 依本策略,计算买卖的单位g.unit = value*0.01/dollar_volatility# 系统1的操作g.system1 = Trueif g.sys1 == 0:market_in(current_price, g.ratio*cash, g.short_in_date)else:stop_loss(current_price)market_add(current_price, g.ratio*cash, g.short_in_date)    market_out(current_price, g.short_out_date)# 系统2的操作g.system1 == Falseif g.sys2==0:market_in(current_price, (1-g.ratio)*cash, g.long_in_date)else:stop_loss(current_price)market_add(current_price, (1-g.ratio)*cash, g.long_in_date)market_out(current_price, g.long_out_date)   #5
# 计算当前N的值
# 输入:none
# 输出:N的值的更新列表-list类型
def calculate_N():# 如果交易天数小于等于20天if g.days <= g.number_days:price = attribute_history(g.security, g.days, '1d',('high','low','pre_close'))lst = []for i in range(0, g.days):h_l = price['high'][i]-price['low'][i]h_c = price['high'][i]-price['pre_close'][i]c_l = price['pre_close'][i]-price['low'][i]# 计算 True RangeTrue_Range = max(h_l, h_c, c_l)lst.append(True_Range)# 计算前g.days(小于等于20)天的True_Range平均值,即当前N的值:current_N = np.mean(np.array(lst))(g.N).append(current_N)# 如果交易天数超过20天else:price = attribute_history(g.security, 1, '1d',('high','low','pre_close'))h_l = price['high'][0]-price['low'][0]h_c = price['high'][0]-price['pre_close'][0]c_l = price['pre_close'][0]-price['low'][0]# Calculate the True RangeTrue_Range = max(h_l, h_c, c_l)# 计算前g.number_days(大于20)天的True_Range平均值,即当前N的值:current_N = (True_Range + (g.number_days-1)*(g.N)[-1])/g.number_days(g.N).append(current_N)#6
# 入市:决定系统1、系统2是否应该入市,更新系统1和系统2的突破价格
# 海龟将所有资金分为2部分:一部分资金按系统1执行,一部分资金按系统2执行
# 输入:当前价格-float, 现金-float, 天数-int
# 输出:none
def market_in(current_price, cash, in_date):# Get the price for the past "in_date" daysprice = attribute_history(g.security, in_date, '1d', ('close'))# Build position if current price is higher than highest in pastif current_price > max(price['close']):# 计算可以买该股票的股数num_of_shares = cash/current_priceif num_of_shares >= g.unit:print ("买入")print (current_price)print (max(price['close']))if g.system1 == True:if g.sys1 < int(g.unit_limit*g.unit):order(g.security, int(g.unit))g.sys1 += int(g.unit)g.break_price1 = current_priceelse:if g.sys2 < int(g.unit_limit*g.unit):order(g.security, int(g.unit))g.sys2 += int(g.unit)g.break_price2 = current_price#7
# 加仓函数
# 输入:当前价格-float, 现金-float, 天数-int
# 输出:none
def market_add(current_price, cash, in_date):if g.system1 == True:break_price=g.break_price1else:break_price=g.break_price2# 每上涨0.5N,加仓一个单元if current_price >= break_price + 0.5*(g.N)[-1]: num_of_shares = cash/current_price# 加仓if num_of_shares >= g.unit: print ("加仓")print (g.sys1)print (g.sys2)print (current_price)print (break_price + 0.5*(g.N)[-1])if g.system1 == True:if g.sys1 < int(g.unit_limit*g.unit):order(g.security, int(g.unit))g.sys1 += int(g.unit)g.break_price1 = current_priceelse:if g.sys2 < int(g.unit_limit*g.unit):order(g.security, int(g.unit))g.sys2 += int(g.unit)g.break_price2 = current_price#8
# 离场函数
# 输入:当前价格-float, 天数-int
# 输出:none
def market_out(current_price, out_date):# Function for leaving the marketprice = attribute_history(g.security, out_date, '1d', ('close'))# 若当前价格低于前out_date天的收盘价的最小值, 则卖掉所有持仓if current_price < min(price['close']):print ("离场")print (current_price)print (min(price['close']))if g.system1 == True:if g.sys1>0:order(g.security, -g.sys1)g.sys1 = 0else:if g.sys2>0:order(g.security, -g.sys2)g.sys2 = 0#9
# 止损函数
# 输入:当前价格-float
# 输出:none
def stop_loss(current_price):# 损失大于2N,卖出股票if g.system1 == True:break_price = g.break_price1else:break_price = g.break_price2# If the price has decreased by 2N, then clear all positionif current_price < (break_price - 2*(g.N)[-1]):print ("止损")print (current_price)print (break_price - 2*(g.N)[-1])if g.system1 == True:order(g.security, -g.sys1)g.sys1 = 0  else:order(g.security, -g.sys2)g.sys2 = 0================================================================================
每天收盘后
================================================================================
'''
# 每日收盘后要做的事情(本策略中不需要)
def after_trading_end(context):return
################################################################################

聚宽量化交易-入门篇(海龟交易法则)相关推荐

  1. 聚宽量化交易策略基本框架

    JoinQuant-TWist 策略编写的基本框架及其实现 回测的含义及其实现 初步学习解决代码错误 周期循环的开始时间 自测与自学 通过前文对量化交易有了一个基本认识之后,我们开始学习做量化交易.毕 ...

  2. 分享聚宽量化交易执行选股策略的执行过程

    分享聚宽量化交易执行选股策略的执行过程: 首先就是需要用不同的函数处理不同的数据,比如上市数据,要用run_query()函数处理,财务与估值数据要用get_fundamentals()函数处理.以及 ...

  3. 聚宽量化是干什么的?

    聚宽是一家量化交易平台,为投资者提供做量化交易的工具与服务,帮助投资者更好地做量化交易.也就是说,在聚宽量化交易平台,"大型收割机"已经为你准备好了,不需要你自己造了,你只需要学会 ...

  4. python双均线策略,当五日均线位于十日均线上方则买入,反之卖出。(聚宽量化平台使用)

    ''' ** python双均线策略,当五日均线位于十日均线上方则买入,反之卖出.(聚宽量化平台使用) ** ''' 初始化函数,设定要操作的股票.基准等等 def initialize(contex ...

  5. 基于聚宽量化交易平台实现量化交易策略

    一.入门量化策略 JoinQuant聚宽API文档:https://www.joinquant.com/help/api/help?name=api 1.策略内容 设置股票池为沪深300的所有成分股 ...

  6. python聚宽量化_今天开始使用聚宽的系统学习python量化交易

    今天开始使用聚宽的系统学习python量化交易 满满的成就感,终于在两个月时间里稍微懂一点程序是怎么了,虽然学习的进度比较慢,但是还是学会了一些东西 # 统计a中元素出现的次数 a = [1,2,3, ...

  7. python聚宽量化_Python量化交易之四_聚宽数据

    介绍 之前测试过一些免费API,比如tushare现在只能下载两年半数据,163有的股票数据无法下载,pandas_reader速度很慢,并且只能下载A股的各股数据,对基金和指数支持不佳.这两天尝试了 ...

  8. python聚宽量化_聚宽量化交易Portfolio与Context对象学习笔记

    聚宽的API文档对Portfolio,Context对象的描述理解不清晰,自己动手输出了Portfolio,Context对象的详细属性.(遇到不理解不明白的地方,自己动手实践输出) Portfoli ...

  9. [68 量化交易] JoinQuent聚宽量化平台代码解析

    # -*- coding: utf-8 -*- # @Time : 2022/11/4 12:38 # @Author : xxxd39 # @FileName: JoinQuantLearn001. ...

最新文章

  1. Adobe Reader 文档无法签名_手把手教你如何利用PDF阅读器压缩PDF文档
  2. c语言扫雷游戏代码_C语言游戏详解---扫雷游戏
  3. Android手机WIFI与电脑间共享文件
  4. java api接口怎么写_Java 如何设计 API 接口,实现统一格式返回?
  5. 解决: This application has no explicit mapping for /error, so you are seeing this as a fallback.
  6. fatal error LNK1104: 无法打开***.exe的错误
  7. WinCE驱动之Touch Panel(开发详解)
  8. 金山打字通计算机英语,金山打字通英文版
  9. GIS投影、坐标系、坐标系转换
  10. BLDC (无刷直流电机) 六步式控制方法
  11. 采用LocalDateTime获取指定时间段
  12. 卷积神经网络结构相关
  13. 华为p4不是鸿蒙吗怎么又改为安卓_鸿蒙系统是不是就是改版的安卓系统?
  14. java后端判断图片尺寸(GB,MB,KB形式),图片色彩(黑白照或彩色照片),图片构图(横图竖图方图)
  15. tomcat 配置域名和ssl证书
  16. hdu 5238 Calculator
  17. 神鬼世界更新完了为什么显示与服务器断开连接,全新服务器构架 神鬼世界6月23日数据互通公告...
  18. 刚生了宝宝后需要及时办理的6个证件
  19. mysql免安装版安装教程
  20. Python安装Pycrypto

热门文章

  1. 高通ar android,Android版高通AR Vuforia QCAR SDK学习笔记
  2. Gym实战-冰面滑行
  3. 如何快速摆脱焦虑困扰,重建内心平静?分享一份无需药物的指南,让你重拾自信并远离焦虑!
  4. vue-element-表格 Excel 【导出】功能
  5. 万字详解,吃透 MongoDB!
  6. Android桌面Widget
  7. 夺命雷公狗---无限极分类NO2
  8. 算法导论第三版2.2答案
  9. 快鹿集团被罚15亿 黄家骝及韦炎平以集资诈骗罪被判无期
  10. 千宗版权案缠身 三年亏掉21亿 资本会为喜马拉雅买单吗?