0
def priceusd(df):
    return df['closeprice'][-1]*btcusdtclose[-1]

This function gives the price of a certain asset in USD by multiplying its price in Bitcoin by Bitcoins price in USD using a dataframe as a parameter.

What I want to do is just allow the name of the asset to be the parameter instead of the dataframe where the price data is coming from. All my dataframes have been named assetbtc. for example ethbtc or neobtc. I want to just be able to pass eth into the function and return ethbtc['closeprice'][-1]*btcusdtclose[-1].

For example,

def priceusd(eth):
    return ethbtc['close'][-1]*btcusdtclose[-1]

I tried this and it didnt work, but you can see what I am trying to do

def priceusd(assetname):  '{}btc'.format(assetname)['close'][-1]*btcusdtclose[-1].

Thank you very much.

johnchase
  • 13,155
  • 6
  • 38
  • 64
mikecaro2
  • 35
  • 1
  • 4
  • You need to evaluate the code as a string. https://stackoverflow.com/questions/9383740/what-does-pythons-eval-do – xyzjayne Jul 18 '18 at 17:58
  • 2
    Make a dictionary with strings for keys and DataFrames as values then in the function lookup the DataFrame using the string that was passed. – wwii Jul 18 '18 at 18:03

2 Answers2

2

It's not necessary to use eval in a situation like this. As @wwii says, store the DataFrames in a dictionary so that you can easily retrieve them by name.

E.g.

coins_to_btc = {
    'eth': ethbtc,
    'neo': neobtc,
}

Then,

def priceusd(name):
    df = coins_to_btc[name]

    return df['close'][-1]*btcusdtclose[-1]
Oliver Evans
  • 1,405
  • 14
  • 17
1

You should be getting the dataframe you want from whatever contains it instead of trying to use a str as the dataframe. I mean you should use the str you formed to fetch the dataframe from where it is.

For example assuming you have placed the priceusd function inside the same module that contains all your created data frames like:

abtc = df1()
bbtc = df2()
cbtc = df3() 
# and so on...

def priceusd(asset):
    asset_container = priceusd.__module__
    asset_name = f'{asset}btc'
    df = getattr(asset_container, asset_name)
    # now do whatever you want with your df (dataframe) 

You can replace the code for getting the asset_container if the structure of your code is different from the one I assumed. But you should generally get my point...

Seyi Shoboyejo
  • 489
  • 4
  • 11