python回测量化交易策略收益率
本篇我們將對(duì)比經(jīng)典量化回測(cè)框架pyalgotrade與ailabx,二者同時(shí)實(shí)現(xiàn)均線策略。
“積木式”實(shí)現(xiàn)策略示例
“買入并持有”策略: 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(),])
另外,傳統(tǒng)量化平臺(tái)本質(zhì)上是用戶思路的自動(dòng)化,“自動(dòng)化”只是量化的初級(jí)階段。
“智能化”才是量化的核心與終級(jí)目標(biāo)。
基于機(jī)器學(xué)習(xí)、深度學(xué)習(xí)、強(qiáng)化學(xué)習(xí)等人工智能前沿工具,機(jī)器自動(dòng)發(fā)現(xiàn)數(shù)據(jù)中的模式,并優(yōu)化相應(yīng)的策略,是這個(gè)我們這個(gè)平臺(tái)的核心目標(biāo)。
開(kāi)發(fā)環(huán)境與安裝部署
anaconda python3.6
直接git或者下載源碼包,安裝相關(guān)依賴,然后運(yùn)行main.py即可。
git clone?https://github.com/ailabx/ailabx.git
cd ailabx
pip install requirements.txt
python main.py
?
先看pyalgotrade的代碼實(shí)現(xiàn):
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()再來(lái)看ailax積木式框架的實(shí)現(xiàn):
''' @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只是做了一些配置。規(guī)則是通過(guò)兩句表達(dá)式來(lái)給出,相當(dāng)簡(jiǎn)潔:
long_expr = 'cross_up(close,ma(close,20))' flat_expr = 'cross_down(close,ma(close,20))'m項(xiàng)目在github上開(kāi)源,歡迎star。
代碼在github上開(kāi)源ailabx
總結(jié)
以上是生活随笔為你收集整理的python回测量化交易策略收益率的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Opencv dnn实现人类性别检测和年
- 下一篇: PyQt5在对话框中打开外部链接的方法