Assigning values to dynamic variables

Asked

Viewed 1,698 times

1

I’m trying to write a code that downloads the historical stock price series from yahoo Finance, then I need to separate the data. I want each variable to be named after 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..
However 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)
  • 1

    I believe you cannot use the character "%" in a variable.

  • is there any need to do it this way? I recommend that you create a class or even a dictionary to handle it.

  • 1

    @jsbueno thank you very much for the help, you have not only answered my doubt and also gave me better ideas

1 answer

2


In Python, the separation of what is given (text strings, for example) and what is code is very rigid - what differentiates it 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)

Thus volume_%s.append(vol) is simply wrong. By coincidence it is not a syntax error: the language will try to use the operator % with the variables volume_ and s, and you should see a NameError (why the variable volume_ with nothing there is no).

So to make it work what you want, it would just be to access the variables in the same way that you created them, as keys in the global dictionary. So I don’t have to keep repeating globals() in each row, 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 piece of good practice advice, which should have become very visible by now: You should use variables for names that you know when you’re coding and have a fixed function - and use dictionaries for names that you’ll receive dynamically.

In this case, for example, you gain nothing by storing your data in the global dictionary (the dictionary that is returned by globals()) and some dictionary of your own. (In fact, you get yes: the chance to over-write some other variable unexpectedly with direct writing on globals() and have a very difficult bug to debug).

With a 'common" dictionary you can even save all your data in a dictionary where there is a key for each name, and it is easier to view and see your data: and only adjust 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 - the data of all series will be available in the dictionary -this global yes - fixed name "data". Better yet, you can make the function return the dictionary dados_locais and dispense with the use of dados entirely global: who calls the desmembrando_dados is responsible for consolidating the complete dictionary of each company. In short, it has several possibilities - but none where you will get any benefit from creating the names of the variables themselves dynamically - for the simple fact that you would have to write the same code back to read the data of these dynamic variables.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.