: | : | :期货程序化 | :期货程序化研究 | :期货量化学习 | :期货量化 |
返回列表 发帖

[Python源码] 海龟交易系统的Python完全版

[Python源码] 海龟交易系统的Python完全版

为方便对比,这里把java、python两种语言代码同时贴出,回测时间及初始资金均使用页面默认的20140104-20150104,100000.0软妹币。
turtle_java

  1. public class TurtleOriginalStrategy implements IHStrategy {
  2.   Core talibCore;

  3. //定义全局变量
  4.   static int tradedayNum = 0;
  5.   static double unit = 0;
  6.   static double atr = 0;
  7.   static String tradingSignal = "start";
  8.   static String preTradingSignal = "";
  9.   static int units_hold_max = 4;
  10.   static int units_hold = 0;
  11.   static double quantity = 0;
  12.   static double max_add = 0;
  13.   static double firstOpenPrice = 0;
  14.   
  15.   //计算最大最小值
  16.   public double[] getExtremem(double[] arrayHighPriceResult, double[] arrayLowPriceResult) {
  17.       DescriptiveStatistics forMax = new DescriptiveStatistics();
  18.       for (int i = 0; i < arrayHighPriceResult.length-1; i++) {
  19.           forMax.addValue(arrayHighPriceResult[i]);
  20.       }
  21.       double maxResult = forMax.getMax();
  22.       
  23.       DescriptiveStatistics forMin = new DescriptiveStatistics();
  24.       for (int i = 0; i < arrayLowPriceResult.length-1; i++) {
  25.           forMin.addValue(arrayLowPriceResult[i]);
  26.       }
  27.       double minResult = forMin.getMin();
  28.       
  29.       double[] forExtremum = new double[2];
  30.       forExtremum[0] = maxResult;
  31.       forExtremum[1] = minResult;
  32.       return forExtremum;
  33.   }
  34.   //计算Atr以及单位
  35.   public double[] getAtrAndUnit(double[] atrArrayResult, MInteger atrLengthResult, double portfolioValueResult) {
  36.       double atr = atrArrayResult[atrLengthResult.value-1];
  37.       double unit = Math.floor(portfolioValueResult * .01 / atr);
  38.       double[] atrAndUnit = new double[2];
  39.       atrAndUnit[0] = atr;
  40.       atrAndUnit[1] = unit;
  41.       return atrAndUnit;
  42.   }
  43.   //计算止损线价位
  44.   public double getStopPrice(double firstOpenPriceResult, int units_hold_result, double atrResult) {
  45.       double stopPrice =  firstOpenPriceResult - 2*atrResult + (units_hold_result-1)*0.5*atrResult;
  46.       return stopPrice;
  47.   }
  48.   
  49.   

  50.   @Override
  51.   public void init(IHInformer informer, IHInitializers initializers) {
  52.    
  53.     talibCore = new Core();
  54.    
  55.    
  56.     int openObserveTime = 55;
  57.     int closeObserveTime = 20;
  58.     int atrTime = 20;
  59.     MInteger atrBegin = new MInteger();
  60.     MInteger atrLength = new MInteger();

  61.    
  62.     String stockId = "CSI300.INDX";
  63.     initializers.instruments((universe) -> universe.add(stockId));
  64.    
  65.    
  66.     initializers.events().statistics((stats, info, trans) -> {

  67.         //获取组合总价值,包含市场价值与剩余资金
  68.         double portfolioValue = info.portfolio().getPortfolioValue();
  69.         
  70.         
  71.         double[] highPrice = stats.get(stockId).history(openObserveTime+1, HPeriod.Day).getHighPrice();
  72.         double[] lowPriceForAtr = stats.get(stockId).history(openObserveTime+1, HPeriod.Day).getLowPrice();
  73.         double[] lowPriceForExtremem = stats.get(stockId).history(closeObserveTime+1, HPeriod.Day).getLowPrice();
  74.         double[] closePrice = stats.get(stockId).history(openObserveTime+2, HPeriod.Day).getClosingPrice();
  75.         
  76.         double closePriceForAtr[] = new double[closePrice.length-1];
  77.         for (int i = 0; i < closePrice.length-1; i++) {
  78.             closePriceForAtr[i] = closePrice[i];
  79.         }
  80.         
  81.       
  82.         double[] atrArray = new double[openObserveTime];
  83.         //Talib计算N即ATR
  84.         RetCode retCode = talibCore.atr(0, openObserveTime-1, highPrice, lowPriceForAtr, closePriceForAtr, atrTime, atrBegin, atrLength, atrArray);
  85.         
  86.         
  87.         double max = getExtremem(highPrice, lowPriceForExtremem)[0];
  88.         double min = getExtremem(highPrice, lowPriceForExtremem)[1];
  89.         
  90.         
  91.         double atr = atrArray[atrLength.value-1];
  92.         
  93.         informer.info(lowPriceForExtremem[lowPriceForExtremem.length - 1]);
  94.         informer.info("#######");
  95.         informer.info(max);
  96.         informer.info(min);
  97.         informer.info(atr);
  98.         informer.info("#######");
  99.         
  100.         if (tradingSignal != "start") {
  101.             if (units_hold != 0) {
  102.             max_add += 0.5 * getAtrAndUnit(atrArray, atrLength, portfolioValue)[0];
  103.             }
  104.         } else {
  105.             max_add = stats.get(stockId).getLastPrice();
  106.         }
  107.         
  108.         informer.info(units_hold);
  109.         
  110.         double curPosition = info.position(stockId).getNonClosedTradeQuantity();
  111.         double availableCash = info.portfolio().getAvailableCash();
  112.         double marketValue = info.portfolio().getMarketValue();
  113.         
  114.         
  115.         if (curPosition > 0 & stats.get(stockId).getLastPrice() < getStopPrice(firstOpenPrice, units_hold, atr)) {
  116.             tradingSignal = "stop";
  117.         } else {
  118.             if (curPosition > 0 & stats.get(stockId).getLastPrice() < min) {
  119.                 tradingSignal = "exit";
  120.             } else {
  121.                 if (stats.get(stockId).getLastPrice() > max_add & units_hold != 0 & units_hold < units_hold_max & availableCash > stats.get(stockId).getLastPrice()*unit) {
  122.                     tradingSignal = "entry_add";
  123.                 } else {
  124.                     if (stats.get(stockId).getLastPrice() > max & units_hold == 0) {
  125.                         max_add = stats.get(stockId).getLastPrice();
  126.                         tradingSignal = "entry";
  127.                     }
  128.                 }
  129.             }
  130.         }
  131.         
  132.         //informer.info(tradingSignal);
  133.         
  134.         atr = getAtrAndUnit(atrArray, atrLength, portfolioValue)[0];
  135.         if (tradedayNum % 5 == 0) {
  136.             unit = getAtrAndUnit(atrArray, atrLength, portfolioValue)[1];
  137.         }
  138.         tradedayNum += 1;
  139.         
  140.         double quantity = unit;
  141.         
  142.         
  143.         if (tradingSignal != preTradingSignal | (units_hold < units_hold_max & units_hold > 1) | tradingSignal == "stop") {
  144.             
  145.             
  146.             if (tradingSignal == "entry") {
  147.                 quantity = unit;
  148.                 if (availableCash > stats.get(stockId).getLastPrice()*quantity) {
  149.                     trans.buy(stockId).shares(quantity).commit();
  150.                     firstOpenPrice = stats.get(stockId).getLastPrice();
  151.                     units_hold = 1;
  152.                     informer.info("entrybuy" + quantity);
  153.                 }
  154.             }
  155.             if (tradingSignal == "entry_add") {
  156.                 quantity = unit;
  157.                 trans.buy(stockId).shares(quantity).commit();
  158.                 units_hold += 1;
  159.                 informer.info("entry_addbuy" + quantity);
  160.             }
  161.             
  162.             
  163.             if (tradingSignal == "stop") {
  164.                 if (/*curPosition marketValue*/ units_hold > 0) {
  165.                     trans.sell(stockId).shares(quantity).commit();
  166.                     units_hold -= 1;
  167.                     informer.info("stop" + quantity);
  168.                 }
  169.             }
  170.             if (tradingSignal == "exit") {
  171.                 if (curPosition > 0) {
  172.                     trans.sell(stockId).shares(curPosition).commit();
  173.                     units_hold = 0;
  174.                     informer.info("exitsell" + curPosition);
  175.                 }
  176.             }
  177.             
  178.         }
  179.         
  180.         preTradingSignal = tradingSignal;
  181.    
  182.     });
  183.       
  184.   }
  185. }
复制代码



turtle_python

  1. import numpy as np
  2. import talib
  3. import math

  4. def getExtremem(arrayHighPriceResult, arrayLowPriceResult):
  5.     np_arrayHighPriceResult = np.array(arrayHighPriceResult[:-1])
  6.     np_arrayLowPriceResult = np.array(arrayLowPriceResult[:-1])
  7.     maxResult = np_arrayHighPriceResult.max()
  8.     minResult = np_arrayLowPriceResult.min()
  9.     return [maxResult, minResult]
  10.    
  11. def getAtrAndUnit(atrArrayResult, atrLengthResult, portfolioValueResult):
  12.     atr = atrArrayResult[atrLengthResult-1]
  13.     unit = math.floor(portfolioValueResult * .01 / atr)
  14.     return [atr, unit]
  15.    
  16. def getStopPrice(firstOpenPriceResult, units_hold_result, atrResult):
  17.     stopPrice =  firstOpenPriceResult - 2*atrResult + (units_hold_result-1)*0.5*atrResult
  18.     return stopPrice


  19. def init(context):
  20.     context.tradedayNum = 0
  21.     context.unit = 0
  22.     context.atr = 0
  23.     context.tradingSignal = 'start'
  24.     context.preTradingSignal = ''
  25.     context.units_hold_max = 4
  26.     context.units_hold = 0
  27.     context.quantity = 0
  28.     context.max_add = 0
  29.     context.firstOpenPrice = 0
  30.     context.s = 'CSI300.INDX'
  31.     update_universe([context.s])
  32.     context.openObserveTime = 55;
  33.     context.closeObserveTime = 20;
  34.     context.atrTime = 20;

  35. def handle_bar(context, bar_dict):
  36.     portfolioValue = context.portfolio.portfolio_value
  37.     highPrice = history(context.openObserveTime+1, '1d', 'high')[context.s]
  38.     lowPriceForAtr = history(context.openObserveTime+1, '1d', 'low')[context.s]
  39.     lowPriceForExtremem = history(context.closeObserveTime+1, '1d', 'low')[context.s]
  40.     closePrice = history(context.openObserveTime+2, '1d', 'close')[context.s]
  41.     closePriceForAtr = closePrice[:-1]
  42.    
  43.     atrArray = talib.ATR(highPrice.values, lowPriceForAtr.values, closePriceForAtr.values, timeperiod=context.atrTime)
  44.    
  45.     maxx = getExtremem(highPrice.values, lowPriceForExtremem.values)[0]
  46.     minn = getExtremem(highPrice.values, lowPriceForExtremem.values)[1]
  47.     atr = atrArray[-2]
  48.    

  49.     if (context.tradingSignal != 'start'):
  50.         if (context.units_hold != 0):
  51.             context.max_add += 0.5 * getAtrAndUnit(atrArray, atrArray.size, portfolioValue)[0]
  52.     else:
  53.         context.max_add = bar_dict[context.s].last
  54.         
  55.    
  56.     curPosition = context.portfolio.positions[context.s].quantity
  57.     availableCash = context.portfolio.cash
  58.     marketValue = context.portfolio.market_value
  59.    
  60.    
  61.     if (curPosition > 0 and bar_dict[context.s].last < minn):
  62.         context.tradingSignal = 'exit'
  63.     else:
  64.         if (curPosition > 0 and bar_dict[context.s].last < getStopPrice(context.firstOpenPrice, context.units_hold, atr)):
  65.             context.tradingSignal = 'stop'
  66.         else:
  67.             if (bar_dict[context.s].last > context.max_add and context.units_hold != 0 and context.units_hold < context.units_hold_max and availableCash > bar_dict[context.s].last*context.unit):
  68.                 context.tradingSignal = 'entry_add'
  69.             else:
  70.                 if (bar_dict[context.s].last > maxx and context.units_hold == 0):
  71.                     context.max_add = bar_dict[context.s].last
  72.                     context.tradingSignal = 'entry'
  73.                     
  74.                
  75.     atr = getAtrAndUnit(atrArray, atrArray.size, portfolioValue)[0]
  76.     if context.tradedayNum % 5 == 0:
  77.         context.unit = getAtrAndUnit(atrArray, atrArray.size, portfolioValue)[1]
  78.     context.tradedayNum += 1
  79.     context.quantity = context.unit
  80.    
  81.    
  82.    
  83.     if (context.tradingSignal != context.preTradingSignal or (context.units_hold < context.units_hold_max and context.units_hold > 1) or context.tradingSignal == 'stop'):
  84.         
  85.         if context.tradingSignal == 'entry':
  86.             context.quantity = context.unit
  87.             if availableCash > bar_dict[context.s].last*context.quantity:
  88.                 order_shares(context.s, context.quantity)
  89.                 context.firstOpenPrice = bar_dict[context.s].last
  90.                 context.units_hold = 1
  91.                
  92.                
  93.         if context.tradingSignal == 'entry_add':
  94.             context.quantity = context.unit
  95.             order_shares(context.s, context.quantity)
  96.             context.units_hold += 1
  97.             
  98.             
  99.         if context.tradingSignal == 'stop':
  100.             if (context.units_hold > 0):
  101.                 order_shares(context.s, -context.quantity)
  102.                 context.units_hold -= 1
  103.                
  104.                
  105.         if context.tradingSignal == 'exit':
  106.             if curPosition > 0:
  107.                 order_shares(context.s, -curPosition)
  108.                 context.units_hold = 0

  109.     context.preTradingSignal = context.tradingSignal
复制代码

论坛官方微信、群(期货热点、量化探讨、开户与绑定实盘)
 
期货论坛 - 版权/免责声明   1.本站发布源码(包括函数、指标、策略等)均属开放源码,用意在于让使用者学习程序化语法撰写,使用者可以任意修改语法內容并调整参数。仅限用于个人学习使用,请勿转载、滥用,严禁私自连接实盘账户交易
  2.本站发布资讯(包括文章、视频、历史记录、教材、评论、资讯、交易方案等)均系转载自网络主流媒体,内容仅为作者当日个人观点,本网转载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。本网不对该类信息或数据做任何保证。不对您构成任何投资建议,不能依靠信息而取代自身独立判断,不对因使用本篇文章所诉信息或观点等导致的损失承担任何责任。
  3.本站发布资源(包括书籍、杂志、文档、软件等)均从互联网搜索而来,仅供个人免费交流学习,不可用作商业用途,本站不对显示的内容承担任何责任。请在下载后24小时内删除。如果喜欢,请购买正版,谢谢合作!
  4.龙听期货论坛原创文章属本网版权作品,转载须注明来源“龙听期货论坛”,违者本网将保留追究其相关法律责任的权力。本论坛除发布原创文章外,亦致力于优秀财经文章的交流分享,部分文章推送时若未能及时与原作者取得联系并涉及版权问题时,请及时联系删除。联系方式:http://www.qhlt.cn/thread-262-1-1.html
如何访问权限为100/255贴子:/thread-37840-1-1.html;注册后仍无法回复:/thread-23-1-1.html;微信/QQ群:/thread-262-1-1.html;网盘链接失效解决办法:/thread-93307-1-1.html

如何访问权限为100/255贴子:/thread-37840-1-1.html;注册后仍无法回复:/thread-23-1-1.html;微信/QQ群:/thread-262-1-1.html;网盘链接失效解决办法:/thread-93307-1-1.html

TOP

下载 学习 谢谢大大

TOP

谢谢楼主的无私奉献

TOP

返回列表