本篇我们将对比经典量化回测框架pyalgotrade与ailabx,二者同时实现均线策略。
先看pyalgotrade的代码实现:
from pyalgotrade import strategy
from pyalgotrade.technical import ma
from pyalgotrade.technical import cross
from pyalgotrade.tools import quandl
class SMACrossOver(strategy.BacktestingStrategy):
def __init__(self, feed, instrument, smaPeriod):
super(SMACrossOver, self).__init__(feed)
self.__instrument = instrument
self.__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.__sma
def onEnterOk(self, position):
execInfo = position.getEntryOrder().getExecutionInfo()
self.info("BUY at %.2f" % (execInfo.getPrice()))
def onEnterCanceled(self, position):
self.__position = None
def onExitOk(self, position):
execInfo = position.getExitOrder().getExecutionInfo()
self.info("SELL at $%.2f" % (execInfo.getPrice()))
self.__position = None
def 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_crossover
data = 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 EnvUtils
utils =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。