Home > database >  Read ticker list from an external txt file
Read ticker list from an external txt file

Time:10-13

I've this simple python script that retrieve financial data from Yahoo Finance:

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

I'd like to read tickers_list from an external file but if I create a script like this:

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'])

...anything goes wrong: enter image description here

tickers.txt:

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

Any idea? Thanks in advance

CodePudding user response:

fh.read() returns a string, not a list of strings

Here is code that should work:

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'])

CodePudding user response:

The reason for the problem is that yf.download expects the 1st arg to be a list but what you read from the file is a string. If you change your tickers file so that they are space-separated or one per line, then you can read them with

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

Of course, you can have the tickers be separated by some other character as long as you specify that to split.

CodePudding user response:

You should just have the tickers as plain text in your tickers.txt file, not structured as you would write a Python list. Otherwise, it assumes each ticker literallly includes the quotes and the brackets.

aapl, goog, amzn, BAC, BA

Normally I would then tell you to split, but from the look of your error message (which you should paste as text, not an image in the future) it appears that it is already able to split a string of comma separated values. In general though, I would recommend that you split it yourself manually with .split(",") and then use .strip() to ensure there are no errant whitespaces attached to your tickers.

  • Related