复制《Learn Algorithmic Trading》代码遇DataReader属性错误求助
AttributeError When Running Code from Learn Algorithmic Trading (Donadio & Ghosh)
Let's break down the errors you're seeing and fix them step by step:
First, the Root Cause of the AttributeError
Your code has a variable name collision that's breaking the DataReader call:
- You start by importing
datafrompandas_datareader(this is a module). - Inside the
tryblock, you assigndata = pd.read_pickle(...)— this overwrites thedatamodule with a pandas DataFrame object. - When the
FileNotFoundErrortriggers and you try to calldata.DataReader(), you're actually trying to access a method on a DataFrame, which doesn't exist. That's why you getAttributeError: 'DataFrame' object has no attribute 'DataReader'.
Additional Issues in the Original Code
- You're using
pd.read_pickle()but never imported pandas withimport pandas as pd— this would throw an error once the variable collision is fixed. - There's a typo in your
SYMBOLSlist:JPNUSD=Xshould beJPYUSD=X(the correct Yahoo Finance ticker for Japanese Yen vs USD). - Minor typo:
TRADING_INSTRAMENTshould beTRADING_INSTRUMENT.
Fixed Code
Here's the corrected version that addresses all these issues:
import pandas as pd from pandas_datareader import data # Fetch daily data for 4 years, for 7 major currency pairs TRADING_INSTRUMENT = 'CADUSD=X' SYMBOLS = ['AUDUSD=X', 'GBPUSD=X', 'CADUSD=X', 'CHFUSD=X', 'EURUSD=X', 'JPYUSD=X', 'NZDUSD=X'] START_DATE = '2014-01-01' END_DATE = '2018-01-01' # DataSeries for each currency symbols_data = {} for symbol in SYMBOLS: SRC_DATA_FILENAME = symbol + '_data.pkl' try: # Use a different variable name (df) to avoid overwriting the data module df = pd.read_pickle(SRC_DATA_FILENAME) except FileNotFoundError: # Now we're correctly calling DataReader from the pandas_datareader data module df = data.DataReader(symbol, 'yahoo', START_DATE, END_DATE) df.to_pickle(SRC_DATA_FILENAME) symbols_data[symbol] = df
If You Still Have Issues with Yahoo Finance Data
Over time, Yahoo has changed its API, so pandas_datareader's Yahoo backend might not work reliably. If you hit more errors fetching data, switch to the yfinance library (a popular, maintained replacement):
- Install it first:
pip install yfinance
- Modify the data-fetching part of the code:
import pandas as pd import yfinance as yf # ... keep the rest of your variables the same ... for symbol in SYMBOLS: SRC_DATA_FILENAME = symbol + '_data.pkl' try: df = pd.read_pickle(SRC_DATA_FILENAME) except FileNotFoundError: # Use yfinance's download method instead df = yf.download(symbol, start=START_DATE, end=END_DATE) df.to_pickle(SRC_DATA_FILENAME) symbols_data[symbol] = df
This should resolve both the AttributeError and any potential data-fetching issues with Yahoo Finance.
内容的提问来源于stack exchange,提问作者Cinji18
相关产品推荐
相关产品推荐

