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

@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%

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/523617.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C++中list的一些内置函数

引言 这里记录一些list常用的内置函数&#xff0c;方便日后查看。 内置函数 Lst1.assign() 给list赋值 Lst1.back() 返回最后一个元素 Lst1.begin() 返回指向第一个元素的迭代器 Lst1.clear() 删除所有元素 Lst1.empty() 如果list是空的则返回true Lst1.end() 返回末尾的迭代…

Hadoop精华问答 | NameNode是什么?

戳蓝字“CSDN云计算”关注我们哦&#xff01;2006年项目成立的一开始,“Hadoop”这个单词只代表了两个组件——HDFS和MapReduce。到现在的13个年头,这个单词代表的是“核心”&#xff0c;今天我们就来看看关于Hadoop的精华问答。1Q&#xff1a;NameNode是什么&#xff1f;A&…

01_SpringCoud 整合SpringCoud alibaba Nacos

SpringCoud 核心 整合SpringCoud alibaba Nacos 文章目录一、快速构建一个SpringBoot项目二、添加依赖2.1 SpringMVC2.2 nacos客户端2.3 lombok(可以省略)2.4 actuator监控(图形化)2.5 SpringCloud和spring-cloud-alibaba三、添加注解(无)四、写配置信息五、下载和运行nacos5.1…

python怎么读写_python怎么读写文件

python怎么读写文件&#xff1f;读取操作# 一次性读取整个文件内容with open(致橡树.txt, r, encodingutf-8) as f:print(f.read())# 通过for-in循环逐行读取with open(致橡树.txt, moder) as f:for line in f:print(line, end)time.sleep(0.5)print()# 读取文件按行读取到列表…

C++线程处理函数的返回值

引言 关于线程处理函数&#xff0c;常见的可能是返回值为void类型&#xff0c;那线程处理函数是否能定义自己想要的返回值类型呢&#xff0c;这里请看下面的说明。 C线程返回值 应用环境1、传统的方式获取线程返回值2、使用C Promise和future方式3、promise和future介绍 应…

华为在欧注册HUAWEI ARK OS商标或为海外版操作系统命名;联通电信正探索合并?汽车共享品牌car2go近宣布退出中国……...

关注并标星星CSDN云计算极客头条&#xff1a;速递、最新、绝对有料。这里有企业新动、这里有业界要闻&#xff0c;打起十二分精神&#xff0c;紧跟fashion你可以的&#xff01;每周三次&#xff0c;打卡即read更快、更全了解泛云圈精彩newsgo go go 一加 7 Pro &#xff…

04_SpringCloud 整合Ribbon细粒度配置自定义

SpringCloud 整合Ribbon细粒度配置自定义 文章目录Ribbon内置负载均衡规则&#xff0c;细粒度配置自定义1. 需求分析2. java代码配置2.1. 创建一个类2.2. 然后创建一个类3. 配置文件配置Ribbon内置负载均衡规则&#xff0c;细粒度配置自定义 默认的ZoneAvoidanceRule在没有Zon…

ip访问次数统计 nginx_PHP实现IP访问限制及提交次数的方法详解

一、原理提交次数是肯定要往数据库里写次数这个数据的&#xff0c;比如用户登陆&#xff0c;当用户出错时就忘数据库写入出错次数1&#xff0c;并且出错时间&#xff0c;再出错写2&#xff0c;当满比如5次时提示不允许再登陆&#xff0c;请明天再试&#xff0c;然后用DateDiff计…

C++容器deque的用法

目录 1.deque容器概念 2.deque对象的构造 2.1deque对象的默认构造 2.2deque对象的带参数构造 3.deque头部和末尾的添加移除操作 4.deque的数据存取 5.deque与迭代器 6.deque的赋值 7.deque的大小 8.deque的插入 9.deque的删除 1.deque容器概念 deque容器概念 deque是…

AI时代,中国技术创新如何弯道超车?

2019 年 5 月 26 日 - 27 日&#xff0c;杭州国际博览中心&#xff0c;由工信部人才交流中心指导&#xff0c;CSDN 和数字经济人才发展中心主办的 CTA 核心技术及应用峰会圆满落下帷幕。本次大会聚焦机器学习、知识图谱等 AI 领域的热门技术&#xff0c;关注技术在行业中的实践…

JBOSS7启动与关闭

1.启动 进入Jboss的bin目录下 通过以下命令启动jboss ./standalone.sh启动没有问题&#xff0c;但是当你按你ctrl C退出后&#xff0c;jboss服务也关闭了&#xff0c;所以我们要使用后台启动方式&#xff1a; nohup ./standalone.sh&查看Jboss启动进程&#xff1a; tai…

容器云常见安全威胁与防范 | 技术干货

戳蓝字“CSDN云计算”关注我们哦&#xff01;技术头条&#xff1a;干货、简洁、多维全面。更多云计算精华知识尽在眼前&#xff0c;get要点、solve难题&#xff0c;统统不在话下&#xff01;除了应对常见云平台和传统数据中心常见的安全威胁&#xff0c;容器云平台还存在一些自…

开启灯光就是近光吗_有用!科目三灯光模拟操作大全

科三考试第一项就是灯光模拟考试&#xff0c;要求考生在5秒之内根据相关语音播报完成相应操作。不少学员在这一项中出错&#xff0c;以至于科三考试还没开出几米就挂了&#xff01;今天通妹特地整理了灯光操作相关技巧&#xff0c;希望大家顺利通过科三第一关&#xff01;语音提…

vmware安装问题:Microsoft Runtime DLL安装程序未能完成安装

文章目录一、vmware安装问题&#xff1a;Microsoft Runtime DLL安装程序未能完成安装1.1 在输入%temp%1.2. 找到{ADC3121A-3EBA-4016-AF64-00B8FE017080}~setup结尾是~setup1.3. 打开该文件夹选择安装程序即可正常安装。一、vmware安装问题&#xff1a;Microsoft Runtime DLL安…

雾计算精华问答 | 雾计算与云计算的区别?

物联网对于数据的处理能力要求很高&#xff0c;怎么能够从庞大的数据海中挖掘一些有价值的信息对于物联网的发展至关重要&#xff0c;因此云计算&#xff0c;雾计算&#xff0c;边缘计算等等都将发挥其左右。今天先让我们来了解一下雾计算吧。1Q&#xff1a;雾计算是如何构成的…

【解决】-bash: ftp: command not found

今天在centos上使用ftp命令连接本机的FTP服务器&#xff08;本机FTP服务使用Vsftpd搭建&#xff09;&#xff0c;出现如下的错误提示&#xff1a;-bash: ftp: command not found 查询相关资料&#xff0c;发现很有可能是FTP命令没有安装。 通过yum方式安装FTP命令: yum insta…

kodi pvr 不能安装_「保姆级教程」家庭影音多媒体中心第5节—KODI18安装/设置IPTV...

一、本章前言&#xff1a;上一章节万晓博SEO带领大学习安装了kodi18播放群晖NAS或者本地视频教程&#xff0c;本节课我们讲讲如何使用kodi播放器看IPTV央视/地方卫视频道&#xff0c;我们遐想下&#xff0c;如果我们使用kodi播放IPTV&#xff0c;这样既可以播放群晖nas或者本地…

使用云原生buildpacks将你的代码转换成Docker Image | 技术干货

戳蓝字“CSDN云计算”关注我们哦&#xff01;技术头条&#xff1a;干货、简洁、多维全面。更多云计算精华知识尽在眼前&#xff0c;get要点、solve难题&#xff0c;统统不在话下&#xff01;七年前buildpack技术开源之时&#xff0c;我们就看到了这项技术将大大简化应用的发布过…

从当前元素继续寻找_169. 多数元素

169. 多数元素给定一个大小为 n 的数组&#xff0c;找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。你可以假设数组是非空的&#xff0c;并且给定的数组总是存在多数元素。示例1&#xff1a;输入: [3,2,3] 输出: 3示例2&#xff1a;输入: [2,2,1,1,1…

Windiws环境安装轻量级文件服务器ftpserver

Windiws环境安装轻量级文件服务器ftpserver 文章目录1. 在线下载&#xff1a;2. 解压3. 以管理员身份运行4. 启动5. 浏览器验证6. 输入账号和口令7. 创建测试文件8. 验证效果图1. 在线下载&#xff1a; 点击即可下载&#xff1a;http://learning.happymmall.com/ftpserver/FTP…