Search code examples
pythonpandasnumpycurrencyforex

Forex_python in custom function for Pandas dataframe


I am trying to build a custom function which can be applied to a pandas dataframe and convert an amount of some currency into the amount in my local currency (DKK) according to the exchange rate of the last day of the previous month (With base in the Pstng Date). So for instance, if the posting date is 2016-03-12, I want to convert the amount according to the exchange rate of 2016-02-28.

I am using the forex-python library with the convert function - Here's my dataframe:

df = pd.DataFrame({
    'Crcy': ['DKK','CAD','GBP','USD'],
    'Pstng Date': ['2017-01-12','2015-12-15','2016-06-06','2017-08-12'],
    'Amount': [100,5000,40,50]
})

And here is my function:

from forex_python.converter import CurrencyRates
c = CurrencyRates()

def convert_rates2(amount,currency,PstngDate):
    if currency != 'DKK':
        return c.convert(base_cur=currency,dest_cur='DKK',amount=amount \
                         ,date_obj=PstngDate - datetime.timedelta(PstngDate.strftime('%d')))
    else:
        return amount

The way I am trying to apply it to the df:

df['Amount, DKK'] = np.vectorize(convert_rates2)(
    amount=df['Amount'],
    currency=df['Crcy'],
    PstngDate=df['Pstng Date']
)

However, I get the following error:

AttributeError: 'str' object has no attribute 'strftime'

Does anyone have an idea of how to approach this? Different approaches are very welcome as well.


Solution

  • You could try something like this:

    from datetime import datetime, timedelta
    
    def convert_rates2(amount,currency,PstngDate):
        PstngDate = datetime.strptime(PstngDate, '%Y-%m-%d')
        if currency != 'DKK':
            return c.convert(base_cur=currency,dest_cur='DKK',amount=amount \
                         ,date_obj=PstngDate - timedelta(PstngDate.day))
        else:
            return amount
    

    This would give this result:

    df['Amount, DKK'] = np.vectorize(convert_rates2)(
        amount=df['Amount'],
        currency=df['Crcy'],
        PstngDate=df['Pstng Date']
    )
    
    
    df
    Out[56]: 
       Amount Crcy  Pstng Date  Amount, DKK
    0     100  DKK  2017-01-12          100
    1    5000  CAD  2015-12-15        26375
    2      40  GBP  2016-06-06          390
    3      50  USD  2017-08-12          317