如何在Python中正确导入yfinance?获取股价数据时遇属性错误
解决yfinance调用
get_historical_price_data报错的问题 问题原因
你混淆了两个不同的Python库:yfinance 和 yahoofinancials。get_historical_price_data 是yahoofinancials库的专属方法,并非yfinance库的接口,所以用yf.get_historical_price_data调用会触发属性不存在的错误。另外你虽然安装了yahoofinancials,但没有正确导入和使用它。
两种解决方案
方案1:正确使用yahoofinancials库
修改导入与调用代码,注意必须指定目标股票代码:
import sys !{sys.executable} -m pip install yahoofinancials from yahoofinancials import YahooFinancials # 示例:获取苹果公司(AAPL)的日度历史数据 stock_code = "AAPL" yahoo_fin = YahooFinancials(stock_code) data = yahoo_fin.get_historical_price_data(start_date=start_date, end_date=end_date, time_interval='daily')
方案2:改用yfinance库的原生方法
如果想直接用yfinance获取数据,使用它自带的history方法即可:
import sys !{sys.executable} -m pip install yfinance import yfinance as yf # 示例:获取苹果公司(AAPL)的历史数据 data = yf.Ticker("AAPL").history(start=start_date, end=end_date)
内容的提问来源于stack exchange,提问作者john martinez
相关产品推荐
相关产品推荐

