日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

python搭积木_从零实现”搭积木式实现策略“的回测系统 part VI

發(fā)布時間:2023/11/27 生活经验 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python搭积木_从零实现”搭积木式实现策略“的回测系统 part VI 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

本篇我們將對比經(jīng)典量化回測框架pyalgotrade與ailabx,二者同時實現(xiàn)均線策略。

先看pyalgotrade的代碼實現(xiàn):

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積木式框架的實現(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 EnvUtils

utils =EnvUtils(stats=stats)

utils.show_stats()

客觀講,ailabx只是做了一些配置。規(guī)則是通過兩句表達(dá)式來給出,相當(dāng)簡潔:

long_expr = 'cross_up(close,ma(close,20))'

flat_expr = 'cross_down(close,ma(close,20))'

m

項目在github上開源,歡迎star。

總結(jié)

以上是生活随笔為你收集整理的python搭积木_从零实现”搭积木式实现策略“的回测系统 part VI的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。