@zhaoyang-chen 海龟的Python版出炉。

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

turtle_java

public class TurtleOriginalStrategy implements IHStrategy {

Core talibCore;

//定义全局变量

static int tradedayNum = 0;

static double unit = 0;

static double atr = 0;

static String tradingSignal = "start";

static String preTradingSignal = "";

static int units_hold_max = 4;

static int units_hold = 0;

static double quantity = 0;

static double max_add = 0;

static double firstOpenPrice = 0;

//计算最大最小值

public double[] getExtremem(double[] arrayHighPriceResult, double[] arrayLowPriceResult) {

DescriptiveStatistics forMax = new DescriptiveStatistics();

for (int i = 0; i < arrayHighPriceResult.length-1; i++) {

forMax.addValue(arrayHighPriceResult[i]);

}

double maxResult = forMax.getMax();

DescriptiveStatistics forMin = new DescriptiveStatistics();

for (int i = 0; i < arrayLowPriceResult.length-1; i++) {

forMin.addValue(arrayLowPriceResult[i]);

}

double minResult = forMin.getMin();

double[] forExtremum = new double[2];

forExtremum[0] = maxResult;

forExtremum[1] = minResult;

return forExtremum;

}

//计算Atr以及单位

public double[] getAtrAndUnit(double[] atrArrayResult, MInteger atrLengthResult, double portfolioValueResult) {

double atr = atrArrayResult[atrLengthResult.value-1];

double unit = Math.floor(portfolioValueResult * .01 / atr);

double[] atrAndUnit = new double[2];

atrAndUnit[0] = atr;

atrAndUnit[1] = unit;

return atrAndUnit;

}

//计算止损线价位

public double getStopPrice(double firstOpenPriceResult, int units_hold_result, double atrResult) {

double stopPrice = firstOpenPriceResult - 2*atrResult + (units_hold_result-1)*0.5*atrResult;

return stopPrice;

}

@Override

public void init(IHInformer informer, IHInitializers initializers) {

talibCore = new Core();

int openObserveTime = 55;

int closeObserveTime = 20;

int atrTime = 20;

MInteger atrBegin = new MInteger();

MInteger atrLength = new MInteger();

String stockId = "CSI300.INDX";

initializers.instruments((universe) -> universe.add(stockId));

initializers.events().statistics((stats, info, trans) -> {

//获取组合总价值,包含市场价值与剩余资金

double portfolioValue = info.portfolio().getPortfolioValue();

double[] highPrice = stats.get(stockId).history(openObserveTime+1, HPeriod.Day).getHighPrice();

double[] lowPriceForAtr = stats.get(stockId).history(openObserveTime+1, HPeriod.Day).getLowPrice();

double[] lowPriceForExtremem = stats.get(stockId).history(closeObserveTime+1, HPeriod.Day).getLowPrice();

double[] closePrice = stats.get(stockId).history(openObserveTime+2, HPeriod.Day).getClosingPrice();

double closePriceForAtr[] = new double[closePrice.length-1];

for (int i = 0; i < closePrice.length-1; i++) {

closePriceForAtr[i] = closePrice[i];

}

double[] atrArray = new double[openObserveTime];

//Talib计算N即ATR

RetCode retCode = talibCore.atr(0, openObserveTime-1, highPrice, lowPriceForAtr, closePriceForAtr, atrTime, atrBegin, atrLength, atrArray);

double max = getExtremem(highPrice, lowPriceForExtremem)[0];

double min = getExtremem(highPrice, lowPriceForExtremem)[1];

double atr = atrArray[atrLength.value-1];

informer.info(lowPriceForExtremem[lowPriceForExtremem.length - 1]);

informer.info("#######");

informer.info(max);

informer.info(min);

informer.info(atr);

informer.info("#######");

if (tradingSignal != "start") {

if (units_hold != 0) {

max_add += 0.5 * getAtrAndUnit(atrArray, atrLength, portfolioValue)[0];

}

} else {

max_add = stats.get(stockId).getLastPrice();

}

informer.info(units_hold);

double curPosition = info.position(stockId).getNonClosedTradeQuantity();

double availableCash = info.portfolio().getAvailableCash();

double marketValue = info.portfolio().getMarketValue();

if (curPosition > 0 & stats.get(stockId).getLastPrice() < getStopPrice(firstOpenPrice, units_hold, atr)) {

tradingSignal = "stop";

} else {

if (curPosition > 0 & stats.get(stockId).getLastPrice() < min) {

tradingSignal = "exit";

} else {

if (stats.get(stockId).getLastPrice() > max_add & units_hold != 0 & units_hold < units_hold_max & availableCash > stats.get(stockId).getLastPrice()*unit) {

tradingSignal = "entry_add";

} else {

if (stats.get(stockId).getLastPrice() > max & units_hold == 0) {

max_add = stats.get(stockId).getLastPrice();

tradingSignal = "entry";

}

}

}

}

//informer.info(tradingSignal);

atr = getAtrAndUnit(atrArray, atrLength, portfolioValue)[0];

if (tradedayNum % 5 == 0) {

unit = getAtrAndUnit(atrArray, atrLength, portfolioValue)[1];

}

tradedayNum += 1;

double quantity = unit;

if (tradingSignal != preTradingSignal | (units_hold < units_hold_max & units_hold > 1) | tradingSignal == "stop") {

if (tradingSignal == "entry") {

quantity = unit;

if (availableCash > stats.get(stockId).getLastPrice()*quantity) {

trans.buy(stockId).shares(quantity).commit();

firstOpenPrice = stats.get(stockId).getLastPrice();

units_hold = 1;

informer.info("entrybuy" + quantity);

}

}

if (tradingSignal == "entry_add") {

quantity = unit;

trans.buy(stockId).shares(quantity).commit();

units_hold += 1;

informer.info("entry_addbuy" + quantity);

}

if (tradingSignal == "stop") {

if (/*curPosition marketValue*/ units_hold > 0) {

trans.sell(stockId).shares(quantity).commit();

units_hold -= 1;

informer.info("stop" + quantity);

}

}

if (tradingSignal == "exit") {

if (curPosition > 0) {

trans.sell(stockId).shares(curPosition).commit();

units_hold = 0;

informer.info("exitsell" + curPosition);

}

}

}

preTradingSignal = tradingSignal;

});

}

}

结果:

turtle_python

import numpy as np

import talib

import math

def getExtremem(arrayHighPriceResult, arrayLowPriceResult):

np_arrayHighPriceResult = np.array(arrayHighPriceResult[:-1])

np_arrayLowPriceResult = np.array(arrayLowPriceResult[:-1])

maxResult = np_arrayHighPriceResult.max()

minResult = np_arrayLowPriceResult.min()

return [maxResult, minResult]

def getAtrAndUnit(atrArrayResult, atrLengthResult, portfolioValueResult):

atr = atrArrayResult[atrLengthResult-1]

unit = math.floor(portfolioValueResult * .01 / atr)

return [atr, unit]

def getStopPrice(firstOpenPriceResult, units_hold_result, atrResult):

stopPrice = firstOpenPriceResult - 2*atrResult + (units_hold_result-1)*0.5*atrResult

return stopPrice

def init(context):

context.tradedayNum = 0

context.unit = 0

context.atr = 0

context.tradingSignal = 'start'

context.preTradingSignal = ''

context.units_hold_max = 4

context.units_hold = 0

context.quantity = 0

context.max_add = 0

context.firstOpenPrice = 0

context.s = 'CSI300.INDX'

update_universe([context.s])

context.openObserveTime = 55;

context.closeObserveTime = 20;

context.atrTime = 20;

def handle_bar(context, bar_dict):

portfolioValue = context.portfolio.portfolio_value

highPrice = history(context.openObserveTime+1, '1d', 'high')[context.s]

lowPriceForAtr = history(context.openObserveTime+1, '1d', 'low')[context.s]

lowPriceForExtremem = history(context.closeObserveTime+1, '1d', 'low')[context.s]

closePrice = history(context.openObserveTime+2, '1d', 'close')[context.s]

closePriceForAtr = closePrice[:-1]

atrArray = talib.ATR(highPrice.values, lowPriceForAtr.values, closePriceForAtr.values, timeperiod=context.atrTime)

maxx = getExtremem(highPrice.values, lowPriceForExtremem.values)[0]

minn = getExtremem(highPrice.values, lowPriceForExtremem.values)[1]

atr = atrArray[-2]

if (context.tradingSignal != 'start'):

if (context.units_hold != 0):

context.max_add += 0.5 * getAtrAndUnit(atrArray, atrArray.size, portfolioValue)[0]

else:

context.max_add = bar_dict[context.s].last

curPosition = context.portfolio.positions[context.s].quantity

availableCash = context.portfolio.cash

marketValue = context.portfolio.market_value

if (curPosition > 0 and bar_dict[context.s].last < minn):

context.tradingSignal = 'exit'

else:

if (curPosition > 0 and bar_dict[context.s].last < getStopPrice(context.firstOpenPrice, context.units_hold, atr)):

context.tradingSignal = 'stop'

else:

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):

context.tradingSignal = 'entry_add'

else:

if (bar_dict[context.s].last > maxx and context.units_hold == 0):

context.max_add = bar_dict[context.s].last

context.tradingSignal = 'entry'

atr = getAtrAndUnit(atrArray, atrArray.size, portfolioValue)[0]

if context.tradedayNum % 5 == 0:

context.unit = getAtrAndUnit(atrArray, atrArray.size, portfolioValue)[1]

context.tradedayNum += 1

context.quantity = context.unit

if (context.tradingSignal != context.preTradingSignal or (context.units_hold < context.units_hold_max and context.units_hold > 1) or context.tradingSignal == 'stop'):

if context.tradingSignal == 'entry':

context.quantity = context.unit

if availableCash > bar_dict[context.s].last*context.quantity:

order_shares(context.s, context.quantity)

context.firstOpenPrice = bar_dict[context.s].last

context.units_hold = 1

if context.tradingSignal == 'entry_add':

context.quantity = context.unit

order_shares(context.s, context.quantity)

context.units_hold += 1

if context.tradingSignal == 'stop':

if (context.units_hold > 0):

order_shares(context.s, -context.quantity)

context.units_hold -= 1

if context.tradingSignal == 'exit':

if curPosition > 0:

order_shares(context.s, -curPosition)

context.units_hold = 0

context.preTradingSignal = context.tradingSignal

结果:

PLUS:

1.没用到python的一些黑法术的情况下java代码190行,python代码120行。

2.java编译小猫耳朵猛抖8下,python编译小猫耳朵猛抖了13下。

回测收益回测年化收益基准收益AlphaBetaSharpe最大回撤

31.685%32.190%56.904%0.03660.45372.5366-3.720%

Created with Highstock 4.2.4缩放1月3月6月1年全部从2014-01-06到2014-12-31累计收益2014-022014-042014-062014-082014-102014-12-10.00%-5.00%0%5.00%10.00%15.00%20.00%25.00%30.00%35.00%40.00%45.00%50.00%55.00%60.00%65.00%

python海龟代码大全_海龟交易系统的Python完全版 | RiceQuant米筐量化社区 交易策略论坛...相关推荐

  1. python turtle代码大全_通过构建简单的骰子游戏学习如何使用Python编程

    Python是一种通用的编程语言,可以用于创建桌面应用程序.3D图形.视频游戏,甚至是网站.它是一种很棒的第一编程语言,因为它很容易学习,而且比复杂的语言(如C.C++或Java)更简单.Python ...

  2. python常用代码大全-大神整理的python资源大全

    * Python号星际旅行船 著名Python社区,代码.文档.高人这里都有. * faqts.com的Python程序设计知识数据库 Python程序设计知识库,都是与Python有关的程序设计问题 ...

  3. python画画代码大全_太赞了,微软正式推出 Python 零基础教程!

    公众号关注 "GitHubDaily"设为 "星标",每天带你逛 GitHub!Python 可以说是当今世界最火的编程语言之一了.数据科学家和人工智能从业者们 ...

  4. python优雅代码大全_代码这样写更优雅(Python版)

    Python 这门语言最大的优点之一就是语法简洁,好的代码就像伪代码一样,干净.整洁.一目了然.但有时候我们写代码,特别是 Python 初学者,往往还是按照其它语言的思维习惯来写,那样的写法不仅运行 ...

  5. python爬虫百度贴吧代码大全_零基础写python爬虫之抓取百度贴吧代码分享

    这里就不给大家废话了,直接上代码,代码的解释都在注释里面,看不懂的也别来问我,好好学学基础知识去! # -*- coding: utf-8 -*- #------------------------- ...

  6. 动漫的python语言代码大全_下载动漫壁纸-Python代码

    本帖最后由 我心她有丶 于 2020-4-16 19:28 编辑 前段时间在论坛找到一个下载动漫壁纸的软件,还挺好用的,这几天突然用一下,下载不出图片,下载的一片白,然后分析了下他的软件,得到了一个地 ...

  7. python turtle代码大全_分享给大家几段有趣的代码,学会python画画可以不用自己动手啦

    前言 Python 是一门简单易学且功能强大的编程语言,无需繁琐的配置,掌握基本语法,了解基本库函数,就可以通过调用海量的现有工具包编写自己的程序,轻松实现批量自动化操作,可以极大提高办公和学习效率. ...

  8. 动漫的python语言代码大全_使用Python来看看动漫中的你

    百度人工智能运用世界领先的对抗生成网络,结合人脸检测.头发分割.人像分割等技术,为用户量身定制千人千面的二次元动漫形象,并且可通过参数设置,生成戴口罩的二次元动漫人像. 先来一组图看看效果 八种口罩任 ...

  9. python考试代码复制_笨办法学Python 习题 26: 恭喜你,现在可以考试了! 错误代码下载链接...

    你已经差不多完成这本书的前半部分了,不过后半部分才是更有趣的.你将学到逻辑,并通过条件判断实现有用的功能. 在你继续学习之前,你有一道试题要做.这道试题很难,因为它需要你修正别人写的代码.当你成为程序 ...

最新文章

  1. c++ 重载 重写_Java | 深入理解方法调用的本质(含重载与重写区别)
  2. Fragment 源码解析
  3. linux拒绝tcp链接,Linux 内核 TCP SACK 拒绝服务问题
  4. 医疗器械软件安全性级别判定
  5. 【C语言】switch中无break的情况
  6. hdfs安全模式退出_浅谈HDFS(二)之NameNode与SecondaryNameNode
  7. 能使曲线变平滑的一维滤波器_双边滤波器的原理及实现
  8. Spark Streaming之Kafka的Receiver和Direct方式
  9. Pytorch出现Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
  10. 洛谷P3152 正整数序列
  11. 手机计算机快速切换功能,群控系统快速切换多部手机
  12. R语言统计—配对t检验样本量计算
  13. 虚拟机设置共享文件夹之后看不见文件(失败合集+成功分享)
  14. Hadoop之——重新格式化HDFS的方案
  15. AMD Software Adrenalin Edition 23.5.1驱动发布,快速获取驱动
  16. Flutter实战之go_router路由组件入门指南
  17. php 如何将image图片转化为字符串
  18. 写给所有默默支持我们这些IT人的另一半------携手看夕阳
  19. python制作翻译小软件_如何基于Python制作有道翻译小工具
  20. 朴素贝叶斯(演示结果与SVM进行对比)

热门文章

  1. 小可评测:来自peluso的性价比 peluso251 电子管麦克风使用评价
  2. Blake算法的流程
  3. 哪家代运营公司比较好?天猫代运营公司十大排名任你挑选。
  4. 震撼的视觉感,裸眼3d成为企业宣传最优选择
  5. 百度地图根据经纬度获取实际位置纠偏
  6. 名画100 燕肃《画选两幅》
  7. 教你如何最大程度降低提审ipa到苹果市场被拒概率及提高通过率(最近我上包的一个实例)...
  8. 在arch linux下安装百度网盘
  9. 浅谈Redis如何实现一致性
  10. 向日葵远程连接linux断开,win10与ubuntu18.04的向日葵远程连接问题