0

I currently have the following code whereby I used exec() to help create variable names in the for loop. Any idea how I can call up the variables outside of the for loop? I tried stock_{i} but didnt work.

stocks = ['GS', 'FB']

date0 = '2019-12-31'

date1 = '2019-01-01'

def get_stock_prices(stk, start, end):  
    ts = TimeSeries(key = api_key, output_format = 'pandas')
    data, meta_data = ts.get_daily(stk, outputsize = 'full')
    adj_data = data.loc[start:end]
    print(adj_data)

for i in stocks:

    exec(f'stock_{i} = get_stock_prices(i, date0, date1)')
Gav
  • 3
  • 3
  • 4
    The fact that they're difficult to refer to should indicate that creating variables this way is not helpful at all. – khelwood Aug 27 '20 at 08:12
  • What do you mean 'call up' – Safwan Samsudeen Aug 27 '20 at 08:12
  • 1
    "I currently have the following code whereby I used exec() to help create variable names in the for loop. " Don't do that. Use *a container object*, like a `list` or a `dict`. In this case, you probably just want a `list`. In this case, you would use `globals()`, which simply returns the `dict` which is the global namespace.... so you end up working with a container anyway. But this is why you shouldn't create dynamic variables likethis – juanpa.arrivillaga Aug 27 '20 at 08:16

0 Answers0