我有一个从Yahoo Finance检索财务数据的简单python脚本:
import yfinance as yf
tickers_list = ["aapl", "goog", "amzn", "BAC", "BA"] # example list
data = yf.download(tickers_list, start="2017-01-01", end="2017-04-30")
print(data['Adj Close'])
我想从外部文件读取tickers\u列表,但如果我创建这样的脚本:
import yfinance as yf
fh = open("tickers.txt") # No need to specify the mode as READ is the default mode
tickers_list = fh.read()
data = yf.download(tickers_list, start="2017-01-01", end="2017-04-30")
print(data['Adj Close'])
tickers.txt:
["aapl", "goog", "amzn", "BAC", "BA"]
有什么想法吗? 提前谢谢
您应该在
tickers.txt
文件中以纯文本形式显示标记,而不是像编写Pythonlist
那样结构化。否则,它假定每个股票代码都包含引号和括号通常我会告诉您拆分,但是从错误消息(which you should paste as text, not an image in the future)的外观来看,它似乎已经能够拆分逗号分隔的值字符串。但一般来说,我建议您使用
.split(",")
手动拆分它,然后使用.strip()
确保没有错误的空白附加到您的代码fh.read()
返回字符串,而不是字符串列表下面是应该可以工作的代码:
问题的原因是
yf.download
希望第一个参数是一个列表,但从文件中读取的是一个字符串。如果更改标记文件,使其以空格分隔或每行一个标记,则可以使用当然,您可以用其他字符分隔标记符,只要您将其指定为
split
相关问题 更多 >
编程相关推荐