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%
python海龟交易源码_海龟交易系统的Python完全版 | RiceQuant米筐量化社区 交易策略论坛...相关推荐
- python海龟代码大全_海龟交易系统的Python完全版 | RiceQuant米筐量化社区 交易策略论坛...
@zhaoyang-chen 海龟的Python版出炉. 为方便对比,这里把java.python两种语言代码同时贴出,回测时间及初始资金均使用页面默认的20140104-20150104,10000 ...
- python 深度学习源码_「深度学习」用TensorFlow实现人脸识别(附源码,快速get技能)...
本文将会带你使用python码一个卷积神经网络模型,实现人脸识别,操作难度比较低,动手跟着做吧,让你的电脑认出你那帅气的脸. 由于代码篇幅较长,而且最重要的缩进都没了,建议直接打开源码或者点击分享-& ...
- python 网格交易源码_网格交易策略(难度:中级)
什么是网格交易策略 网格交易又名渔网交易,就是跌买涨卖.它适合震荡市,震荡市就是行情价围着一个数字上下浮动的,这个数字就是设置的价格中轴线. 设定中枢价格后,对投资标的进行机械式操作,下跌时,进行分档 ...
- python 网格交易源码_网格交易法策略源码
网格交易法的源码 //+------------------------------------------------------------------+ //| Grid1.1.mq4 | // ...
- python自动交易源码_【硬核福利】量化交易神器talib中28个技术指标的Python实现(附全部源码)...
内容首发 乐学偶得(http://lexueoude.com) 公众号: 乐学Fintech 用代码理解分析解决金融问题 之前跟大家分享过用Python调用talib实现技术指标分析,但是许多小伙伴有 ...
- python如何查看源码_查看“Python-2020-fall”的源代码
因为以下原因,您没有权限编辑本页: 您所请求的操作仅限于该用户组的用户使用:用户 您可以查看与复制此页面的源代码.== Python程序设计课程主页(2020年秋季学期) == Teacher: [h ...
- python支付程序源码_支付宝推出新活动,Python脚本能让你赚的更多!(附源码)...
写在前面 近期,马云大哥又在支付宝推出新活动了,不对,马云已经辞职了.不好意思哈,小编忘了. 但是呢,这个活动可是实实在在存在的哦~ 据说,只要你的手速够快,就能够赚去更多的余额宝体验金哦~ 下面,小 ...
- python12306源码_春运了,Python大神分享爬取12306车票信息的例子,附抢票源码
爬虫:爬虫的根本就是得到一个网页的源代码数据.更深入一些,就会出现和网页进行POST交互从而获取服务器接收POST请求后返回的数据!总结:爬虫就是由计算机自动与服务器交互获取数据的工具.(爬虫请注意网 ...
- python爬虫技术源码_实战|手把手教你用Python爬虫(附详细源码)
大家好,我是J哥,专注原创,致力于用浅显易懂的语言分享爬虫.数据分析及可视化等干货,希望人人都能学到新知识.最近J哥做了个爬虫小项目,感觉还挺适合新手入门的,于是迫不及待想分享给大家. 什么是爬虫? ...
- python股票分析源码_用python开发股票自动技术分析的软件
一.配置环境 python是个强大的工具,还有很多插件包可以用,所以完全可以考虑用python来编程实现股票的自动技术分析. 第一步就是实现股票历史数据的获取,这个有安装包TuShare可以用.首先是 ...
最新文章
- CentOS6.5 升级 Python 2.7 版本
- 一个游戏大量合服代表什么_[游戏服务器从入门到关门]4.分区分服、连服、合服...
- boost::multiprecision模块mpfi相关的测试程序
- 【code】Splay 模板
- 让JavaScript像C#一样支持Region
- AttributeError: module 'pip' has no attribute 'main'
- LINQ IN ACTION读书笔记:LINQ 使用连接 1、组连接 2、内连接 3、左外连接 4、交叉连接 使用和区别...
- c语言中{的作用,C语言中Static和Const关键字的作用
- 钱晓捷第五版习题4 题4.8 bufx bufy bufz 为三个有符号十六进制数编写一个比较相等关系的程序如果这三个数都不相等则显示0,其中两个相等显示1 ,三个都相等则显示2
- SAT数学解题方法总结
- LeetCode - 加一
- java语言基础(七):Collection、泛型、案例:斗地主
- protoc protoc-gen-go安装
- rust纯黑_你可能不知道:黑波斯的黑色毛发其实有6种不同的类型
- python辗转相除法算法_辗转相除法的算法
- 为什么我选择csdn写blog
- Java猿社区—ShardingSphere之广播表与绑定表
- 独具目光的郭研(转载)
- 一说这些,总有那么些人骂我“沙雕”
- 6种让机器人实现避障的方法
热门文章
- 联想“重组症”:一系列的动作能否解决创新难题?
- 全新的SharePoint 2019
- 互联网科普-什么是淘宝
- 富士通Fujitsu DPK2180T 打印机驱动
- linux——alsa中多个声卡设备时打开某一指定声卡的PCM设备
- Struts中动态ActionForm与静态ActionForm有什么区别?_
- android xml 工具下载,安卓xml文件编辑器
- arduino并口屏_Arduino教程 12864绘图功能库的使用(并口通信,仅适用ST7920)
- 高通8926和高通410的参数对比
- python使用win32*模块模拟人工操作——城通网盘下载器(一)