Reputation: 1604
Situation:
Trying to get hand of for loops to and importing data from the web using python. I found a library online that can extract currency rates for most currencies.
Im stuck at creating a function that will loop through a range of dates and extract for each day the value and store in its appropriate cell.
Objective:
Create a DataFrame
with base value CAD and several converted currencies every day for the past two years.
What I tried:
from forex_python.converter import CurrencyRates
from datetime import .datetime, timedelta
import pandas as pd
c = CurrencyRates()
# 4. store information into a dataframe
den = "CAD" # base currency
cols = ["date", "CAD", "MXN", "DKK", "INR", "SGD", "JPY"] # currencies to convert to
df = pd.DataFrame(columns=cols) # create df structure
sDate = datetime.datetime(2018, 1, 1, 16, 30, 30, 000000) # start date
eDate = datetime.today() - timedelta(1) # end date
amount = 1 # amount to convert
"""Loop through each day between the start to end date (once a day at the same time) and extract
the rate for each currency and store the data in their respective column"""
c.convert('CAD','MXN',1000,date_obj)
The following is an example c.convert('CAD','MXN',1,date_obj)
is an example of getting the CAD to MXN exchange rate using the date stored in the date_obj
variable
Upvotes: 0
Views: 1527
Reputation: 2417
Try this
from forex_python import converter
import datetime
import pandas as pd
rrc = converter.CurrencyRates()
keys= [*rrc.get_rates('CAD').keys(),]
numdays = 365 * 2
base = datetime.datetime(2019, 7,12)
date_list = [base - datetime.timedelta(days=x) for x in range(0, numdays)]
df = pd.DataFrame(columns =keys + ['date'])
def append_data(t) :
global df
try :
dic = rrc.get_rates('CAD',t)
dic['date'] = t
r = pd.DataFrame(dic, index = [0])
df = df.append(r, ignore_index= True)
except :
pass
for i,t in enumerate(date_list[::-1]):
append_data(t)
In this exemple , I just get all the currencies , so you could just crop it by specifying your actual columns, for example, if you want [AUD, USD]
, you could just do
df = df.loc[:,['AUD', 'USD', 'date']]
I don't believe the API provides a way to do it directly, other than iterates over the two of them, which might actually be slower.
Upvotes: 2