[Python] pyalgotrade 第一篇

        如果你有不錯的想法,想進行股票投資,但是不知道這個方法的績效會怎麼樣?可以透過歷史的資料模擬交易,就可以得到一個參考的績效,也就知道大概的報酬率了,這樣就叫做回測,篩選出適合你的投資策略。如果你熟悉Python,那恭喜你,現在有很多回測的平台可以使用,省略掉要寫很多的交易規則、買進賣出的股市交易的邏輯,可以專注於策略或資金管理的開發上,本篇就來教學Pyalgotrade的入門範例,並以yahoo finance 台灣50作為範例,下載範例程式


  1. 安裝pyalgotrade
    • pip install pyalgotrade
  2. 準備台灣50歷史資料
  3. 改寫yahoofeed.py
          因為下載下來的資料,有些日期的資料是null,直接執行會造成錯誤,所以這邊先                  改寫處理資料的部分,簡單地加個try/except即可:

def parseBar(self, csvRowDict):
    try:
        dateTime = self.__parseDate(csvRowDict["Date"])
        close = float(csvRowDict["Close"])
        open_ = float(csvRowDict["Open"])
        high = float(csvRowDict["High"])
        low = float(csvRowDict["Low"])
        volume = float(csvRowDict["Volume"])
        adjClose = float(csvRowDict["Adj Close"])

        if self.__sanitize:
            open_, high, low, close = common.sanitize_ohlc(open_, high, low, close)

        return self.__barClass(dateTime, open_, high, low, close, volume, adjClose, self.__frequency)
    except Exception as e :
        print(e)
        return None
           
         4. 範例



from pyalgotrade import strategy

from jccsc.barfeed import yahoofeed


class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        super(MyStrategy, self).__init__(feed)
        self.__instrument = instrument

    def onBars(self, bars):
        bar = bars[self.__instrument]
        self.info("{:.2f}, {:.2f}, {:.2f}, {:.2f}, {:.2f}, {:.2f}"
               .format(bar.getOpen(), 
               bar.getHigh(), 
               bar.getLow(),
               bar.getClose(), 
               bar.getVolume(),
               bar.getAdjClose()))

    def onEnterOk(self, position):
        self.info("onEnterOk")

    def onEnterCanceled(self, position):
        self.info("onEnterCanceled")

    # Called when the exit order for a position was filled.
    def onExitOk(self, position):
        self.info("onExitOk")

    # Called when the exit order for a position was canceled.
    def onExitCanceled(self, position):
        self.info("onExitCanceled")

    """Base class for strategies. """
    def onStart(self):
        self.info("onStart")
        self.info("Open,High,Low,Close,Volume,AdjClose")

    def onFinish(self, bars):
        self.info("onFinish")

    def onIdle(self):
        self.info("onIdle")


# Load the bar feed from the CSV file
feed = yahoofeed.Feed()
feed.addBarsFromCSV("0050", "../data/0050.TW.csv")

# Evaluate the strategy with the feed's bars.
myStrategy = MyStrategy(feed, "0050")
myStrategy.run()




建立MyStrategy,並繼承了strategy.BacktestingStrategy ,在將改寫過的yahoofeed讀取台灣50歷史資料,代入MyStrategy,執行run(),就會開始觸發每一天的事件,透過了onStart、onBars、onFinish 等等的method,而onBars是最重要的地方,bars就是當天的資料,我們之後必須透過這個地方撰寫交易策略,而這個範例會把每一天的資料顯示出來,以後的範例會在提供策略、交易的寫法。


執行結果



範例程式





留言

  1. 感謝大大的分享,找時間來測試
    太讚了 佛心來的

    回覆刪除
    回覆
    1. 謝謝巧克力,希望對你有幫助!!

      刪除

張貼留言

這個網誌中的熱門文章

[Python] 使用 Pyinstaller打包成執行檔

[Python] Websocket Example

[Linux] SSH筆記