Home > Software engineering >  Python: Save variables-names and use them later in a loop
Python: Save variables-names and use them later in a loop

Time:11-03

I downloaded DataFrames (depending on how many assets are in the variable "assets") and created for each one its own variable by using globals().

Now, I require a loop to pick up each created variable, to perform other tasks with these variables.

Before this, I need to "save" the created variables, maybe in some kind of dictionary?

start = "2019-01-01"
end = "2020-01-01"
assets = ["FB" , "AMZN" , "AAPL" , "NFLX" , "GOOG"]

i = 0
while (i < len(assets)):
    try:
        globals()["Stock_%s" %assets[i]] = pd.DataFrame(web.DataReader(assets[i] , "yahoo" , start , end))
        i  = 1     
    except: 
        break
        print("Error")

The created DataFrames are called:

Stock_FB
Stock_AMZN
etc..

Any help would be appreciated.

CodePudding user response:

Creating variables by assigning to globals() is not only unnecessarily difficult in itself, it makes iterating over the result afterward also unnecessarily difficult. Avoid it altogether; instead of:

i = 0
while (i < len(assets)):
    try:
        globals()["Stock_%s" %assets[i]] = pd.DataFrame(web.DataReader(assets[i] , "yahoo" , start , end))
        i  = 1     
    except: 
        break
        print("Error")

do:

stocks = {
    asset: pd.DataFrame(web.DataReader(asset, "yahoo", start, end))
    for asset in assets
}

Now if you want to do something with each of the dataframes you've created you can do:

for stock_data in stocks.values():
    # do something with 'stock_data'

If you need to do something with the symbol (FB, etc) do:

for symbol, stock_data in stocks.items():
    # do something with 'symbol' and 'stock_data'
  • Related