Search code examples
pythonpandascryptocurrency

How to add on to parameter names in functions?


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.


Solution

  • 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]