0

Let's say I want to import tickers from yahoo finance and want to create a function for the same. How can I create it a way that I can name the variable of the said ticker within the function?

For example:

def function(x, y):
    x = pdr.get_data_yahoo(y, start, end)
    return x

Here I want to take x input as the name that the we want to assign to the variable and y as the ticker. Which would be in a 'AAPL' format.

For example:

function(aapl, 'AAPL')

Is there any way to achieve this so I can quickly import a historical data and assign it to a variable?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 2
    Why not remove `x` as parameter from `function` and call it like `aapl = function('AAPL')`? – mkrieger1 May 25 '21 at 12:03
  • Python variables don't work like that. Either `aapl = function('AAPL')` or, if you really need something dynamic, use a `dict` like `keyname = 'aapl'; d[keyname] = function('AAPL')`. – chepner May 25 '21 at 12:03
  • What if i wanted to not just do aapl ? i want to take any ticker as an input. and change the name of the variable accordingly. – Heisencode May 25 '21 at 12:04
  • See: https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables – mkrieger1 May 25 '21 at 12:05
  • so that means i would have to manualy create dicts for several tickers and that is the only solution? – Heisencode May 25 '21 at 12:06

1 Answers1

0

Function below will return what you want without local variable x:

def function(y):
    return pdr.get_data_yahoo(y, start, end)

If you want to create a variable in local scope with a given name it is generally not possible. Function locals() returns local scope as dict, but updates are implementation dependent, you will not create local variable by modifying this dict, so avoid the approach. If you need key value assignment use dict like:

def function(x, y):
    d = {x: pdr.get_data_yahoo(y, start, end)} # or just return d
    return d
Jacek Błocki
  • 452
  • 3
  • 9
  • This works as i would just have to do this and then assign the function to a variable outside the function- ie - aapl = function(y) – Heisencode May 25 '21 at 12:24