pythonpandasstockalpha-vantage

How do I apply my function which returns a pandas dataframe, to a range of inputs so it returns individual dataframes?


I am using the alpha_vantage API in python which returns a Pandas dataframe table.

I have written a function, below, which takes a stock name, resets the index of the dataframe and renames it. How do I apply this function to a few inputs so it brings back individual dataframes for them? At the moment, I have to do this manually and run the function individually for each input.

Would it work if I create a pandas series with the list of stocks, and apply the function to the series?

def get_stock(ticker):
    stock, meta_data = ts.get_daily_adjusted(symbol=ticker, outputsize='compact')
    ticker = pd.DataFrame(stock)
    ticker = ticker.reset_index()
    return ticker

To make this dataframe available outside of the function, I was running it as below:

example = get_stock('XX')

example is therefore the returned dataframe variable.

Thanks!


Solution

  • You could use the globals variable to create different variables:

    def get_stock(ticker):
        ...
    
    for symbol in [list_of_symbols]:
        globals()[symbol + '_df'] = get_stock(symbol)
    

    Of course you could use any other name for the dataframes.