在PyAlgoTrade教程中使用交易策略时的导入错误

1 投票
1 回答
1829 浏览
提问于 2025-04-18 00:41

我在运行一个用Python写的简单交易策略时,遇到了一个导入错误,使用的是Pyalgotrade这个库。

from pyalgotrade.tools import yahoofinance
yahoofinance.download_daily_bars('orcl', 2000, 'orcl-2000.csv')

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


class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        strategy.BacktestingStrategy.__init__(self, 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()

错误信息如下所示。

>>>Traceback (most recent call last):
   File "/Users/johnhenry/Desktop/pyalgotrade2.py", line 1, in <module>
    from pyalgotrade import strategy
   File "/Users/johnhenry/Desktop/pyalgotrade.py", line 1, in <module>
    from pyalgotrade import strategy
   ImportError: cannot import name strategy

我确定我已经安装了这个叫做pyalgotrade的库。

1 个回答

0

你把自己的程序命名为 pyalgotrade.py

File "/Users/johnhenry/Desktop/pyalgotrade.py"

所以Python会认为你指的就是这个文件。你需要把你的程序改个名字,删除任何可能存在的 pyalgotrade.pycpyalgotrade.pyo 文件,然后重新启动你的解释器。

撰写回答