PyalgoTrade 繪圖(七)

PyAlgoTrade使得繪製策略執行變得很是簡單python

from pyalgotrade import strategy from pyalgotrade.technical import ma from pyalgotrade.technical import cross 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 onEnterCanceled(self, position): self.__position = None def onExitOk(self, position): self.__position = None def onExitCanceled(self, position): # If the exit was canceled, re-submit it. self.__position.exitMarket() 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 yahoofeed
from pyalgotrade.stratanalyzer import returns
import sma_crossover

# Load the yahoo feed from the CSV file
feed = yahoofeed.Feed()
feed.addBarsFromCSV("orcl", "orcl-2000.csv")

# Evaluate the strategy with the feed's bars.
myStrategy = sma_crossover.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())

# Plot the strategy.
plt.plot()

代碼正在作3件事情:lua

  • 從CSV文件加載Feed。
  • 使用Feed提供的欄和附帶的StrategyPlotter來運行策略。
  • 制定策略
    以下樣子:



做者:readilen
連接:http://www.jianshu.com/p/b90f58c6a54c
來源:簡書
著做權歸做者全部。商業轉載請聯繫做者得到受權,非商業轉載請註明出處。spa

相關文章
相關標籤/搜索