本篇我们将对比经典量化回测框架pyalgotrade与ailabx,二者同时实现均线策略。
“积木式”实现策略示例
“买入并持有”策略: buy_and_hold = Strategy([ RunOnce(),
PrintBar(),SelectAll(),WeighEqually(),
])
“均线交叉策略”:
long_expr = 'cross_up(ma(close,5),ma(close,10))'
flat_expr = 'cross_down(ma(close,5),ma(close,10))'
ma_cross = Strategy([
SelectByExpr(long_expr=long_expr,flat_expr=flat_expr),WeighEqually(),
])
另外,传统量化平台本质上是用户思路的自动化,“自动化”只是量化的初级阶段。
“智能化”才是量化的核心与终级目标。
基于机器学习、深度学习、强化学习等人工智能前沿工具,机器自动发现数据中的模式,并优化相应的策略,是这个我们这个平台的核心目标。
开发环境与安装部署
anaconda python3.6
直接git或者下载源码包,安装相关依赖,然后运行main.py即可。
git clone https://github.com/ailabx/ailabx.git
cd ailabx
pip install requirements.txt
python main.py
先看pyalgotrade的代码实现:
from pyalgotrade import strategy
from pyalgotrade.technical import ma
from pyalgotrade.technical import cross
from pyalgotrade.tools import quandlclass SMACrossOver(strategy.BacktestingStrategy):def __init__(self, feed, instrument, smaPeriod):super(SMACrossOver, self).__init__(feed)self.__instrument = instrumentself.__position = None# We'll use adjusted close values instead of regular close values.self.setUseAdjustedValues(True)self.__prices = feed[instrument].getPriceDataSeries()self.__sma = ma.SMA(self.__prices, smaPeriod)def getSMA(self):return self.__smadef onEnterOk(self, position):execInfo = position.getEntryOrder().getExecutionInfo()self.info("BUY at %.2f" % (execInfo.getPrice()))def onEnterCanceled(self, position):self.__position = Nonedef onExitOk(self, position):execInfo = position.getExitOrder().getExecutionInfo()self.info("SELL at $%.2f" % (execInfo.getPrice()))self.__position = Nonedef onBars(self, bars):# If a position was not opened, check if we should enter a long position.if self.__position is None:if cross.cross_above(self.__prices, self.__sma) > 0:shares = int(self.getBroker().getCash() * 0.9 / bars[self.__instrument].getPrice())# Enter a buy market order. The order is good till canceled.self.__position = self.enterLong(self.__instrument, shares, True)# Check if we have to exit the position.elif not self.__position.exitActive() and cross.cross_below(self.__prices, self.__sma) > 0:self.__position.exitMarket()from pyalgotrade import plotter
from pyalgotrade.barfeed import quandlfeed
from pyalgotrade.stratanalyzer import returns
#import sma_crossoverdata = quandl.build_feed("WIKI", ['ORCL'], 2000, 2000, ".")
# Load the bar feed from the CSV file
feed = quandlfeed.Feed()
feed.addBarsFromCSV("orcl", "WIKI-ORCL-2000-quandl.csv")# Evaluate the strategy with the feed's bars.
myStrategy = SMACrossOver(feed, "orcl", 20)# Attach a returns analyzers to the strategy.
returnsAnalyzer = returns.Returns()
myStrategy.attachAnalyzer(returnsAnalyzer)# Attach the plotter to the strategy.
plt = plotter.StrategyPlotter(myStrategy)
# Include the SMA in the instrument's subplot to get it displayed along with the closing prices.
plt.getInstrumentSubplot("orcl").addDataSeries("SMA", myStrategy.getSMA())
# Plot the simple returns on each bar.
plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())# Run the strategy.
myStrategy.run()
myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult())from pyalgotrade.stratanalyzer import returns, sharpe, drawdown, trades
sharpe_ratio = sharpe.SharpeRatio()
myStrategy.attachAnalyzer(sharpe_ratio)#print('sharpe:',sharpe_ratio.getSharpeRatio(0))# Plot the strategy.
plt.plot()
再来看ailax积木式框架的实现:
'''
@author: 魏佳斌
@license: (C) Copyright 2018-2025, ailabx.com.@contact: 86820609@qq.com
@file: test_trading_env.py
@time: 2018-10-17 10:29
@desc:'''
import unittest,os
from quant.engine.trading_env import TradingEnv
from quant.engine.datafeed import DataFeed
from quant.engine.algos import *class TestTradingEnv(unittest.TestCase):def test_run_step(self):path = os.path.abspath(os.path.join(os.getcwd(), "../../data"))feed = DataFeed(data_path=path)feed.download_or_get_data(['ORCL',], 2000, 2000)long_expr = 'cross_up(close,ma(close,20))'flat_expr = 'cross_down(close,ma(close,20))'ma_cross = Strategy([SelectByExpr(long_expr=long_expr,flat_expr=flat_expr),WeighEqually(),Constraint({'max_weight':0.9})],name='均线交叉策略')env = TradingEnv(strategy=ma_cross,feed=feed)env.run_strategy()stra_stats = env.get_statistics()stats = [stra_stats]from quant.engine.trading_env import EnvUtilsutils =EnvUtils(stats=stats)utils.show_stats()
客观讲,ailabx只是做了一些配置。规则是通过两句表达式来给出,相当简洁:
long_expr = 'cross_up(close,ma(close,20))'
flat_expr = 'cross_down(close,ma(close,20))'m
项目在github上开源,欢迎star。
代码在github上开源ailabx