1

I am trying to create a stock trading algorithm with python and pandas, in which I am making a function that I can pass a list of tickers and it will calculate a dataframe for each of the tickers passed. I want the name of each dataframe to be like df_ + "ticker name". So if I pass aapl and msft it will create two dataframes one called df_aapl and one called df_msft. In the function I have a variable called df_name which holds the value of 'df'+ tickername concatenated together. How do I rename the dataframe once it is created to the value of the df_name variable i.e. "df_appl" instead of "df_name". The line that says df_name = df is what needs fixed.

As a side note, call me dumb, but I cannot figure out how to rename a dataframe without making a copy. So help with that would be appreciated too.

def calcTickerData(ticker):
    df_name = 'df' + ticker

#get dataframe for ticker from alphavantage
    ts = TimeSeries(key = av_api_key, output_format ='pandas')
    df, meta_data = ts.get_daily(symbol = ticker, outputsize = 'compact')

#rename dataframe
    df_name = df
    return df_name
calcTickerData('AAPL')
Brandon Frenchak
  • 486
  • 4
  • 12

1 Answers1

0

You can use 'exec'

x='Foo'    
exec("%s = %s" % (x,'Bar'))

This will return

Foo = 'Bar'

This same concept can be extrapolated into your case. However, there might be better ways than to dynamically create variables, and this should only be used if you're sure this is the best option.