美文网首页
股票量化分析入门——PyAlgoTrade 安装运行

股票量化分析入门——PyAlgoTrade 安装运行

作者: coolwind | 来源:发表于2018-06-07 14:06 被阅读96次

    本文记录了在Mac 10.13环境下安装配置 Python 下的回归工具 PyAlgoTrade 的过程。

    运行环境

    • python 2.7
    • pyenv
    • Mac Os 10.13

    包安装

    PyAlgoTrade

    pip install pyalgotrade

    matplotlib

    python -mpip install -U pip
    python -mpip install -U matplotlib

    pandas

    pip install pandas

    pandas-datareader

    pip install pandas-datareader

    运行效果

    stocktradeplot.jpg

    示例代码

    #coding=utf-8
    
    #mac is Moving Average Crossover
    
    from pyalgotrade import strategy,plotter
    from pyalgotrade.bar import Frequency
    from pyalgotrade.barfeed.csvfeed import GenericBarFeed
    from pyalgotrade.technical import ma
    from pyalgotrade.stratanalyzer import returns
    import datetime as dt
    import pandas_datareader.data as web
    import numpy as np
    
    class MyStrategy(strategy.BacktestingStrategy):
        def __init__(self,feed,instrument,smaPeriod1,smaPeriod2):
            strategy.BacktestingStrategy.__init__(self,feed,10000)
            self.__instrument = instrument
            self.__sma1=ma.EMA(feed[instrument].getPriceDataSeries(),smaPeriod1)
            self.__sma2=ma.EMA(feed[instrument].getPriceDataSeries(),smaPeriod2)
            self.__shortPos = None
            self.__longPos = None
    
        def getSMA(self):
            return self.__sma1,self.__sma2
    
        def onEnterCanceled(self,position):
            if self.__shortPos == position:
                self.__shortPos = None
            elif self.__longPos == position:
                self.__longPos = None
            else:
                assert False
    
        def onExitOk(self,position):
            if self.__shortPos == position:
                self.__shortPos = None
            elif self.__longPos == position:
                self.__longPos = None
            else:
                assert False
    
        def onExitCanceled(self,position):
            position.exitMarket()
    
        def enterLongSignal(self,bar):
            return self.__sma1[-1] > self.__sma2[-1]
    
        def exitLongSignal(self):
            return self.__sma1[-1] < self.__sma2[-1]
    
        def exitShortSignal(self):
            return self.__sma1[-1] > self.__sma2[-1]
    
        def enterShortSignal(self):
            return self.__sma1[-1] < self.__sma2[-1]
    
        def onBars(self,bars):
            if self.__sma1[-1] is None or self.__sma2[-1] is None:
                return
    
            bar = bars[self.__instrument]
            if self.__longPos is not None:
                if self.exitLongSignal():
                    self.__longPos.exitMarket()
            elif self.__shortPos is not None:
                if self.exitShortSignal():
                    self.__shortPos.exitMarket()
            else:
                if self.enterLongSignal(bar):
                    shares = int(self.getBroker().getCash() /
                                 bars[self.__instrument].getPrice() * 0.9)
                    self.__longPos = self.enterLong(self.__instrument,shares,True)
    
    def run_strategy(smaPeriod1,smaPeriod2):
        feed = GenericBarFeed(Frequency.DAY,None,None)
        feed.addBarsFromCSV("s000001","s000001.csv")
    
        myStrategy = MyStrategy(feed,'s000001',smaPeriod1,smaPeriod2)
        retAnalyzer = returns.Returns()
        myStrategy.attachAnalyzer(retAnalyzer)
    
        plt = plotter.StrategyPlotter(myStrategy)
        plt.getInstrumentSubplot('s000001').addDataSeries('SMA1',myStrategy.getSMA()[0])
        plt.getInstrumentSubplot('s000001').addDataSeries('SMA2',myStrategy.getSMA()[1])
        plt.getOrCreateSubplot('returns').addDataSeries('returns',retAnalyzer.getReturns())
    
        myStrategy.run()
        plt.plot()
        return myStrategy.getBroker().getEquity()
    
    run_strategy(10,20)
    

    至此,完成了所有插件的安装。并成功运行了第一个示例。可以开始慢慢研究 PyAlgoTrade 的各类API了。

    样例数据

    Date Time,Open,High,Close,Low,Volume,amount
    2000-12-29 00:00:00,23.99,24.33,24.22,23.99,180120,5070815
    2000-12-28 00:00:00,24.08,24.3,23.99,23.95,334011,9359495
    2000-12-27 00:00:00,24.59,24.62,24.13,24.06,569336,16169689
    2000-12-26 00:00:00,23.86,24.46,24.43,23.78,591466,16671897
    2000-12-25 00:00:00,23.9,24.13,23.84,23.73,418610,11613743
    2000-12-22 00:00:00,24.33,24.59,24.04,23.82,448530,12625467
    2000-12-21 00:00:00,24.77,24.92,24.43,24.37,487400,13966501
    2000-12-20 00:00:00,24.42,24.68,24.51,24.28,813306,23171987
    2000-12-19 00:00:00,24.14,24.28,23.72,23.66,356910,9930823
    2000-12-18 00:00:00,23.82,24.14,24.13,23.43,835629,23146962
    

    问题解决

    matplotlib

    https://matplotlib.org/users/installing.html#macos
    在我的安装过程中一直报错,提示如下的错误

    >>> import matplotlib.pyplot as plt
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "//anaconda/lib/python2.7/site-packages/matplotlib-1.3.1-py2.7-macosx-10.5-x86_64.egg/matplotlib/pyplot.py", line 98, in <module>
        _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
      File "//anaconda/lib/python2.7/site-packages/matplotlib-1.3.1-py2.7-macosx-10.5-x86_64.egg/matplotlib/backends/__init__.py", line 28, in pylab_setup
        globals(),locals(),[backend_name],0)
      File "//anaconda/lib/python2.7/site-packages/matplotlib-1.3.1-py2.7-macosx-10.5-x86_64.egg/matplotlib/backends/backend_macosx.py", line 21, in <module>
        from matplotlib.backends import _macosx
    **RuntimeError**: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the other backends.
    

    最终使用如下的方式解决。
    在 ~/.matplotlib路径下创建一个文件 matplotlibrc 并加入如下的代码 backend: TkAgg

    pandas_datareader

    碰到以下的错误

    import pandas_datareader.data as web
      File "/Users/apple/.pyenv/versions/stock2.7/lib/python2.7/site-packages/pandas_datareader/__init__.py", line 2, in <module>
        from .data import (DataReader, Options, get_components_yahoo,
      File "/Users/apple/.pyenv/versions/stock2.7/lib/python2.7/site-packages/pandas_datareader/data.py", line 14, in <module>
        from pandas_datareader.fred import FredReader
      File "/Users/apple/.pyenv/versions/stock2.7/lib/python2.7/site-packages/pandas_datareader/fred.py", line 1, in <module>
        from pandas.core.common import is_list_like
    ImportError: cannot import name is_list_like
    

    这是因为 is_list_like 已经被迁移到了 pandas.api.types 之下,需要修改 fred.py 文件,错误信息中可以找到文件的位置。然后将 from pandas.core.common import is_list_like 替换为 from pandas.api.types import is_list_like,之后就可以正常工作了。

    相关文章

      网友评论

          本文标题:股票量化分析入门——PyAlgoTrade 安装运行

          本文链接:https://www.haomeiwen.com/subject/huowsftx.html