NewInPython
NewInPython

Reputation: 247

How do I get forex rates historically from a range of dates in python?

Im able to get the rates in real time and of a particular time in the year. But how can I just ask for a range of dates and the currency value for that day through

 from forex_python.converter import CurrencyRates
    ...: import datetime
    ...: 
    ...: c = CurrencyRates()
    ...: 
    ...: dt = datetime.datetime(2020, 3, 27, 11, 21, 13, 114505)
    ...: 
    ...: print(c.get_rate('CAD', 'USD', dt))
0.7072353585464853

My objective is to have a table that has

Rate   DateTime                Currency
0.702   08-01-2007 1:15pm      CAD - USD
0.712   08-01-2007 1:16pm      CAD - USD

and so on.Keep an interval by minute. How can I do it?

Upvotes: 0

Views: 2781

Answers (1)

Vivek Kalyanarangan
Vivek Kalyanarangan

Reputation: 9081

Use -

from forex_python.converter import CurrencyRates
c = CurrencyRates()

df['DateTime'] = pd.to_datetime(df['DateTime'], format='%d-%m-%Y %I:%M%p')
df['Rate_'] = df.apply(lambda x: c.get_rate(x['Currency'].split('-')[0].strip(), x['Currency'].split('-')[1].strip(), x['DateTime']), axis=1)

Output

                Rate            DateTime   Currency              Rate_
0 0.7020000000000001 2007-01-08 13:15:00  CAD - USD 0.8510666143174977
1 0.7120000000000001 2007-01-08 13:16:00  CAD - USD 0.8510666143174977

Update

Based on OP's updated query:

df = pd.DataFrame(pd.date_range(start='8/16/2021 10:00:00', end='8/16/2021 11:00:00', freq='1min'), columns=['DateTime'])

def get_rate(x):
    try:
        op = c.get_rate('CAD', 'USD', x)
    except Exception as re:
        print(re)
        op=None
    return op

df['Rate'] = df['DateTime'].apply(get_rate)

I have shown this only on 1 hour data. You can modify the start and end dates accordingly

Upvotes: 1

Related Questions