加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

从零实现”搭积木式实现策略“的回测系统partVI

(2018-10-29 13:42:57)
分类: python从零实现AI量化投资系统

本篇我们将对比经典量化回测框架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。

代码在github上开源ailabx

https://note.youdao.com/yws/public/resource/624f4972c4f89ff3aaa41a5251b17d9c/xmlnote/E21A03876FCA476F8ED330062407C379/12867

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有