从外部txt文件读取股票代码列表

2024-09-26 17:50:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个从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'])

enter image description here

我想从外部文件读取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'])

…出了什么问题: enter image description here

tickers.txt:

["aapl", "goog", "amzn", "BAC", "BA"]

有什么想法吗? 提前谢谢


Tags: import脚本datadownloadasstartlistgoog
3条回答

您应该在tickers.txt文件中以纯文本形式显示标记,而不是像编写Python list那样结构化。否则,它假定每个股票代码都包含引号和括号

aapl, goog, amzn, BAC, BA

通常我会告诉您拆分,但是从错误消息(which you should paste as text, not an image in the future)的外观来看,它似乎已经能够拆分逗号分隔的值字符串。但一般来说,我建议您使用.split(",")手动拆分它,然后使用.strip()确保没有错误的空白附加到您的代码

fh.read()返回字符串,而不是字符串列表

下面是应该可以工作的代码:

import yfinance as yf

with open("tickers.txt") as fh: # No need to specify the mode as READ is the default mode
    ticker_list = fh.read().splitlines()

data = yf.download(tickers_list, start="2017-01-01", end="2017-04-30")

print(data['Adj Close'])

问题的原因是yf.download希望第一个参数是一个列表,但从文件中读取的是一个字符串。如果更改标记文件,使其以空格分隔或每行一个标记,则可以使用

with open("tickers.txt") as fh:
    tickers_list = fh.read().split()

当然,您可以用其他字符分隔标记符,只要您将其指定为split

相关问题 更多 >

    热门问题