I am trying to download stock data from yfinance. I have a ticker list called ticker_list_1 with a bunch of symbols. The structure is:
array(['A', 'AAP', 'AAPL', 'ABB', 'ABBV', 'ABC', 'ABEV', 'ABMD', 'ABNB',....
Now I am using the following code to download the data:
i = 0
xrz_data = {}
for i, len in enumerate (ticker_list_1):
data = yf.download(ticker_list_1[i], start ="2019-01-01", end="2022-10-20")
xrz_data[i] = data
i=i 1
The problem I am having is that once downloaded the data is saved as xrz_data. I can access a specific dataset through the code xrz_data[I]
with the corresponding number. However I want to be able to access the data through xrz_data[tickername].
How can I achieve this ?
I have tried using xrz_data[i].values = data
which gives me the error KeyError: 0
EDIT: Here is the current output of the for loop:
{0: Open High Low Close Adj Close \
Date
2018-12-31 66.339996 67.480003 66.339996 67.459999 65.660202
2019-01-02 66.500000 66.570000 65.300003 65.690002 63.937435
2019-01-03 65.529999 65.779999 62.000000 63.270000 61.582008
2019-01-04 64.089996 65.949997 64.089996 65.459999 63.713589
2019-01-07 65.639999 67.430000 65.610001 66.849998 65.066483
... ... ... ... ... ...
2022-10-13 123.000000 128.830002 122.349998 127.900002 127.900002
2022-10-14 129.000000 130.220001 125.470001 125.699997 125.699997
2022-10-17 127.379997 131.089996 127.379997 130.559998 130.559998
2022-10-18 133.919998 134.679993 131.199997 132.300003 132.300003
2022-10-19 130.110001 130.270004 127.239998 128.960007 128.960007
[959 rows x 6 columns],
1: Open High Low Close Adj Close \
Date
2018-12-31 156.050003 157.679993 154.990005 157.460007 149.844055
2019-01-02 156.160004 159.919998 153.820007 157.919998 150.281815
........
My desired output would be:
AAP: Open High Low Close Adj Close \
Date
2018-12-31 156.050003 157.679993 154.990005 157.460007 149.844055
2019-01-02 156.160004 159.919998 153.820007 157.919998 150.281815
........
CodePudding user response:
In my opinion there is no need to use a reserved keyword or methode name len
and enumerate()
- Simply iterate your list and use the name of the ticker:
xrz_data = {}
for ticker in ticker_list_1:
data = yf.download(ticker, start ="2019-01-01", end="2022-10-20")
xrz_data.update(data)
CodePudding user response:
I was able to figure it out. With the following code I am able to download the data and access specific tickers through f.e. xrz_data['AAPL‘]
i = 0
xrz_data = {}
for ticker in ticker_list_1:
data = yf.download(ticker, start ="2019-01-01", end="2022-10-20")
xrz_data[ticker] = data