Assigning Values to Dynamic Variables

1

I'm trying to write a code that downloads the historical stock price series of yahoo finance , then I need to separate the data. I want each variable to get the name of the action.

For example: I am downloading the data from Petrobras, so I wanted it to look like this: Volume_PETR4, Minimo_PETR4 and etc ...
But I am not able to assign the values to these variables, here is what I have done so far.

def desmenbrando_dados(acao,date1,date2, nome):
    pegando_acoes(acao,date1,date2,nome)
    globals()['volume_%s' % nome] = []
    globals()['minimo_%s' % nome] = []
    globals()['maximo_%s' % nome] = []
    globals()['abertura_%s' % nome] = []
    globals()['fechamento_%s' % nome] = []
    globals()['volume_teste'] = []
    for i in serie:
        vol = int(i['Volume'])
        volume_%s.append(vol) 
        maxi = float(i['High'])
        maximo_%s.append(maxi)
        mini = float(i['Low'])
        minimo_%s.append(mini)
        openn = float(i['Open'])
        abertura_%s.append(openn)
        close = float(i['Close']) 
        fechamento_%s.append(close)
    
asked by anonymous 02.11.2015 / 22:02

1 answer

1

In Python, the separation of what is given (text strings, for example) and what is code is very rigid - which sets it apart from PHP, Perl and Shel Script.

So you can create dynamic variable names, as you do - but notice that the name is passed in a string: globals()['volume_%s' % nome] = [] (The % operator with two strings creates another string that is used as a key in the global dictionary)

So volume_%s.append(vol) is simply wrong. Coincidentally, this is not a syntax error: the language will try to use the % operator with the variables volume_ and s , and you should see NameError (why volume_ with nothing does not exist).

So, to make it work what you want, you would just access the variables in the same way you created them, like keys in the global dictionary. To not have to repeat globals() on each line, you can assign this dictionary to a short variable:

g =  globals()
g['volume_%s' % nome] = []
...
for i in serie:
    g['volume_%s'% nome].append(int(i['Volume'])) 

And that's the answer to your question. Now a good practice advice, which must have become very visible at this point: You should use variables for names that you know when you are coding and have fixed function - and use dictionaries for names that you will receive dynamically.

In this case, for example, you gain nothing in saving your data in the global dictionary (the dictionary that is returned by globals() ) and any dictionary you create yourself. (You actually get a chance to overwrite some other variable unexpectedly with direct writing in globals() and have a very difficult debugging bug.)

With a 'common' dictionary you can even store all your data in a dictionary where there is a key for each name, and it is easier to view and view your data: and only adapt the view (or output to file) after:

dados = {}
def desmenbrando_dados(acao,date1,date2, nome):
    dados_locais = dados[nome] = {}
    dados_locais['volume'] = []
    ...
    for i in serie: 
        vol = int(i['Volume'])
        dados_locais['volume'].append(vol) 

Ready - data for all series will be available in the dictionary - this global yes - fixed-name "data". Better yet, you can make the function return the dados_locais dictionary and dispense with the use of dados globally: whites desmembrando_dados is responsible for consolidating the complete dictionary of each company. In short, there are several possibilities - but none in which you're going to take any benefit from dynamically creating the names of the variables themselves - for the simple fact that you would have to write the same code back to read the data from those dynamic variables. p>     

03.11.2015 / 17:03