'Cannot get a file to be read into a list of stock tickers and then get yfinance data for each

I am trying to read a csv file into a dataframe and then iterate over each ticker to get some yahoo finance data, but I struggle with matching the right data type read from the CSV file. The problem is that yfinance needs a str for the ticker parameter data = yf.download("AAPL', start ="2019-01-01", end="2022-04-20") and I cannot convert the df row item into str.

This is my code:


combined = yf.download("SPY", start ="2019-01-01", end="2019-01-02")
  

for index, row in stockslist.iterrows():
            
    data = yf.download([index,row["ticker"].to_string], start ="2019-01-01", end="2022-04-20") 

and this is the csv file

enter image description here

The question is basically about this part of the code " [index,row["ticker"].to_string] " . I cannot get to pass each row of the dataframe as a ticker argument to finance. The error I get is "TypeError: expected string or bytes-like object "



Solution 1:[1]

The download function doesn't understand [index,row["ticker"].to_string] parameter. Like where does it come from ?

you have to give the context of it. Like building an array with the values from the CSV then you pass the array[i].value to the download function.

A quick example with fictional code :

#initiate the array with the ticker list
array_ticker = ['APPL''MSFT''...'] 

#reads array + download
for i=0 in range(array_ticker.size):      
     data = yf.download(array_ticker[i], start ="2019-01-01", end="2022-04-20")
     i=i+1

UPDATE :

If you want to keep the dataframe as you are using now, I just did a simple code to help you to sort your issue :

import pandas as pd

d = {'ticker': ['APPL', 'MSFT', 'GAV']}
ticker_list = pd.DataFrame(data=d) #creating the dataframe
print(ticker_list) #print the whole dataframe
print('--------')
print(ticker_list.iloc[1]['ticker']) #print the 2nd value of the column ticker

Same topic : How to iterate over rows in a DataFrame in Pandas

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1