我有一个循环(运行大约 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()
解决方案:您可以创建一个交易品种列表并将该列表提供给 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()
您也可以使用
stockdex
获取最新的价格数据。
pip install stockdex -U
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