从 YahooFinance 获取价格数据会导致:AttributeError 'nonetype' 对象没有属性 'text'

问题描述 投票:0回答:2

我有一个循环(运行大约 200 次)来从 YahooFinance 获取之前的收盘价。该循环在某个点随机停止,并显示以下错误消息:

WARNING:root:Some characters could not be decoded, and were replaced with REPLACEMENT CHARACTER.
[...]
AttributeError 'nonetype' object has no attribute 'text'

每次运行脚本时,它都会在不同的点停止。这是脚本:

from yahoofinancials import YahooFinancials
import csv

with open('instruments.csv', 'r') as csvfile:
    instruments = csv.reader(csvfile, delimiter=',', quoting = csv.QUOTE_NONNUMERIC, quotechar='"')
    for instrument in instruments:
        symbol = instrument[0]
        yahoo_financials = YahooFinancials(symbol)
        price = yahoo_financials.get_prev_close_price()
python error-handling yahoo-finance nonetype
2个回答
0
投票

解决方案:您可以创建一个交易品种列表并将该列表提供给 YahooFincials api,然后执行请求,而不是循环遍历每个交易品种并请求价格。看起来这个包可以完美地处理这个问题,尽管需要一些时间。 这是doc的摘录:

from yahoofinancials import YahooFinancials
tech_stocks = ['AAPL', 'MSFT', 'INTC']
yahoo_financials_tech = YahooFinancials(tech_stocks)
tech_stock_price_data = yahoo_financials_tech.get_prev_close_price()

0
投票

您也可以使用

stockdex
获取最新的价格数据。

  1. 安装包:
    pip install stockdex -U
  2. 重构代码:
from stockdex import Ticker
import csv

with open('instruments.csv', 'r') as csvfile:
    instruments = csv.reader(csvfile, delimiter=',', quoting = csv.QUOTE_NONNUMERIC, quotechar='"')
    for instrument in instruments:
        symbol = instrument[0]
        ticker = Ticker(ticker="AAPL")
        price = ticker.price().iloc[-1]["close"]  # you can change it to high, low or open as desired

© www.soinside.com 2019 - 2024. All rights reserved.