PyalgoTrade 计算权重平滑平均价(三)

本节介绍如何使用收盘价的SMA价格的策略

from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.technical import ma


class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        super(MyStrategy, self).__init__(feed)
        # We want a 15 period SMA over the closing prices.
        self.__sma = ma.SMA(feed[instrument].getCloseDataSeries(), 15)
        self.__instrument = instrument

    def onBars(self, bars):
        bar = bars[self.__instrument]
        self.info("%s %s" % (bar.getClose(), self.__sma[-1]))

# 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 = MyStrategy(feed, "orcl")
myStrategy.run()

这与前面的例子非常相似,只是:

  • 用收盘价格数据系列中初始化SMA过滤器。
  • 打印当前的SMA值以及收盘价。
    如果您运行脚本,您应该看到收盘价格和相应的SMA值,但在这种情况下,前14个SMA值为空。那是因为我们需要至少15个值来求取SMA:
    2000-01-03 00:00:00 strategy [INFO] 118.12 None
    2000-01-04 00:00:00 strategy [INFO] 107.69 None
    2000-01-05 00:00:00 strategy [INFO] 102.0 None
    2000-01-06 00:00:00 strategy [INFO] 96.0 None
    2000-01-07 00:00:00 strategy [INFO] 103.37 None
    2000-01-10 00:00:00 strategy [INFO] 115.75 None
    2000-01-11 00:00:00 strategy [INFO] 112.37 None
    2000-01-12 00:00:00 strategy [INFO] 105.62 None
    2000-01-13 00:00:00 strategy [INFO] 105.06 None
    2000-01-14 00:00:00 strategy [INFO] 106.81 None
    2000-01-18 00:00:00 strategy [INFO] 111.25 None
    2000-01-19 00:00:00 strategy [INFO] 57.13 None
    2000-01-20 00:00:00 strategy [INFO] 59.25 None
    2000-01-21 00:00:00 strategy [INFO] 59.69 None
    2000-01-24 00:00:00 strategy [INFO] 54.19 94.2866666667
    2000-01-25 00:00:00 strategy [INFO] 56.44 90.1746666667
    .
    .
    .
    2000-12-27 00:00:00 strategy [INFO] 30.69 29.9866666667
    2000-12-28 00:00:00 strategy [INFO] 31.06 30.0446666667
    2000-12-29 00:00:00 strategy [INFO] 29.06 30.0946666667



作者:readilen
链接:http://www.jianshu.com/p/7a9e2635bfa1
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

posted @ 2017-09-21 16:21  zl306222525  阅读(284)  评论(0编辑  收藏  举报