Historical exchange rate between currencies using Ecbxrate
up vote
1
down vote
favorite
I tried writing a simple python script using the python module ecbxrate
that outputs to a CSV file a table with the daily exchange rate between EUR and USD since 2013.
Below is my code, it works, gives the correct output. I tried using methods rather than a long script. I specifically wanted to use Ecbxrate.
import ecbxrate
import datetime
import pandas as pd
from sqlite3 import Error
ecb_path = 'sqlite:///D://test/db/ecb.sqlite3' #path where ecb historical database is stored
outfile = 'Downloads/Exchnage_rate.csv' # CSV table name and path
store = ecbxrate.ExchangeRateStore(ecb_path)
""" We can initialise it one time also from command line but i kept it as a part of script in case there is any issue it can re initialise as per given path"""
"""This initialise the ecb data if does not exist else update if it does, we can sechdule the script to be run after 3pm to get lastest exchange rate of the day
and then it shall first update with lastest exchange rate data before writing it to file.Also I tried printing exceptions, we can follow the uniform error handling method as per standards/requirement """
def get_data():
try:
store.last_updated()
except Error as e:
print("Error with ecb database", e)
except:
try:
store.initialise()
except Error as e:
print('Error while initialising',e)
except:
print('unknown error , check initialise process')
else:
if store.last_updated() != datetime.datetime.today().date(): #if latest data doesn't exist
try:
store.update()
except Error as e:
print('Error while updating', e)
except:
print('unknown error while updating')
"""else:
print('latest data already') """
"""#Else part is not needed because all excpetions already handleded, we can do it in case need to log the process for success."""
""" This gets the data from updated ECB database from given date range between given currencies"""
def get_exchange_rate(start_date, end_Date, from_curr, to_cuur):
daterange = pd.date_range(start_date, end_Date)
data = [store.get_rate(from_curr, to_cuur,single_date.strftime("%Y-%m-%d")) for single_date in daterange] #calling for all days in between
#return (pd.DataFrame(data))
d = pd.DataFrame(data)
d.insert(1, 'currency_from', from_curr)
d.insert(2,'currency_to', to_cuur)
d.rename(columns={d.columns[0]: "Date", d.columns[3]: "Exchange_Rate" },inplace=True)
d.to_csv(outfile, index=False) # putting it in csv of given path and name
def main():
get_data()
get_exchange_rate('2013-1-1', datetime.datetime.today().date(),'EUR', 'USD')
main()
Could you please review and let me know if it can be written better. Few doubts I have are:
- Should I pass
ecb_path
as parameter toget_data()
andget_exchange_Rate()
? I am not sure about the best approach. - Are nested
try
except
blocks Pythonic in this case? Can I handle it better? - Should I write a different method to write output to csv file?
- Is
for
loop efficient in this case, to get data for bigger date range? - Should I add a check in case the output file is not created or given path is wrong?
python performance beginner python-3.x error-handling
add a comment |
up vote
1
down vote
favorite
I tried writing a simple python script using the python module ecbxrate
that outputs to a CSV file a table with the daily exchange rate between EUR and USD since 2013.
Below is my code, it works, gives the correct output. I tried using methods rather than a long script. I specifically wanted to use Ecbxrate.
import ecbxrate
import datetime
import pandas as pd
from sqlite3 import Error
ecb_path = 'sqlite:///D://test/db/ecb.sqlite3' #path where ecb historical database is stored
outfile = 'Downloads/Exchnage_rate.csv' # CSV table name and path
store = ecbxrate.ExchangeRateStore(ecb_path)
""" We can initialise it one time also from command line but i kept it as a part of script in case there is any issue it can re initialise as per given path"""
"""This initialise the ecb data if does not exist else update if it does, we can sechdule the script to be run after 3pm to get lastest exchange rate of the day
and then it shall first update with lastest exchange rate data before writing it to file.Also I tried printing exceptions, we can follow the uniform error handling method as per standards/requirement """
def get_data():
try:
store.last_updated()
except Error as e:
print("Error with ecb database", e)
except:
try:
store.initialise()
except Error as e:
print('Error while initialising',e)
except:
print('unknown error , check initialise process')
else:
if store.last_updated() != datetime.datetime.today().date(): #if latest data doesn't exist
try:
store.update()
except Error as e:
print('Error while updating', e)
except:
print('unknown error while updating')
"""else:
print('latest data already') """
"""#Else part is not needed because all excpetions already handleded, we can do it in case need to log the process for success."""
""" This gets the data from updated ECB database from given date range between given currencies"""
def get_exchange_rate(start_date, end_Date, from_curr, to_cuur):
daterange = pd.date_range(start_date, end_Date)
data = [store.get_rate(from_curr, to_cuur,single_date.strftime("%Y-%m-%d")) for single_date in daterange] #calling for all days in between
#return (pd.DataFrame(data))
d = pd.DataFrame(data)
d.insert(1, 'currency_from', from_curr)
d.insert(2,'currency_to', to_cuur)
d.rename(columns={d.columns[0]: "Date", d.columns[3]: "Exchange_Rate" },inplace=True)
d.to_csv(outfile, index=False) # putting it in csv of given path and name
def main():
get_data()
get_exchange_rate('2013-1-1', datetime.datetime.today().date(),'EUR', 'USD')
main()
Could you please review and let me know if it can be written better. Few doubts I have are:
- Should I pass
ecb_path
as parameter toget_data()
andget_exchange_Rate()
? I am not sure about the best approach. - Are nested
try
except
blocks Pythonic in this case? Can I handle it better? - Should I write a different method to write output to csv file?
- Is
for
loop efficient in this case, to get data for bigger date range? - Should I add a check in case the output file is not created or given path is wrong?
python performance beginner python-3.x error-handling
add a comment |
up vote
1
down vote
favorite
up vote
1
down vote
favorite
I tried writing a simple python script using the python module ecbxrate
that outputs to a CSV file a table with the daily exchange rate between EUR and USD since 2013.
Below is my code, it works, gives the correct output. I tried using methods rather than a long script. I specifically wanted to use Ecbxrate.
import ecbxrate
import datetime
import pandas as pd
from sqlite3 import Error
ecb_path = 'sqlite:///D://test/db/ecb.sqlite3' #path where ecb historical database is stored
outfile = 'Downloads/Exchnage_rate.csv' # CSV table name and path
store = ecbxrate.ExchangeRateStore(ecb_path)
""" We can initialise it one time also from command line but i kept it as a part of script in case there is any issue it can re initialise as per given path"""
"""This initialise the ecb data if does not exist else update if it does, we can sechdule the script to be run after 3pm to get lastest exchange rate of the day
and then it shall first update with lastest exchange rate data before writing it to file.Also I tried printing exceptions, we can follow the uniform error handling method as per standards/requirement """
def get_data():
try:
store.last_updated()
except Error as e:
print("Error with ecb database", e)
except:
try:
store.initialise()
except Error as e:
print('Error while initialising',e)
except:
print('unknown error , check initialise process')
else:
if store.last_updated() != datetime.datetime.today().date(): #if latest data doesn't exist
try:
store.update()
except Error as e:
print('Error while updating', e)
except:
print('unknown error while updating')
"""else:
print('latest data already') """
"""#Else part is not needed because all excpetions already handleded, we can do it in case need to log the process for success."""
""" This gets the data from updated ECB database from given date range between given currencies"""
def get_exchange_rate(start_date, end_Date, from_curr, to_cuur):
daterange = pd.date_range(start_date, end_Date)
data = [store.get_rate(from_curr, to_cuur,single_date.strftime("%Y-%m-%d")) for single_date in daterange] #calling for all days in between
#return (pd.DataFrame(data))
d = pd.DataFrame(data)
d.insert(1, 'currency_from', from_curr)
d.insert(2,'currency_to', to_cuur)
d.rename(columns={d.columns[0]: "Date", d.columns[3]: "Exchange_Rate" },inplace=True)
d.to_csv(outfile, index=False) # putting it in csv of given path and name
def main():
get_data()
get_exchange_rate('2013-1-1', datetime.datetime.today().date(),'EUR', 'USD')
main()
Could you please review and let me know if it can be written better. Few doubts I have are:
- Should I pass
ecb_path
as parameter toget_data()
andget_exchange_Rate()
? I am not sure about the best approach. - Are nested
try
except
blocks Pythonic in this case? Can I handle it better? - Should I write a different method to write output to csv file?
- Is
for
loop efficient in this case, to get data for bigger date range? - Should I add a check in case the output file is not created or given path is wrong?
python performance beginner python-3.x error-handling
I tried writing a simple python script using the python module ecbxrate
that outputs to a CSV file a table with the daily exchange rate between EUR and USD since 2013.
Below is my code, it works, gives the correct output. I tried using methods rather than a long script. I specifically wanted to use Ecbxrate.
import ecbxrate
import datetime
import pandas as pd
from sqlite3 import Error
ecb_path = 'sqlite:///D://test/db/ecb.sqlite3' #path where ecb historical database is stored
outfile = 'Downloads/Exchnage_rate.csv' # CSV table name and path
store = ecbxrate.ExchangeRateStore(ecb_path)
""" We can initialise it one time also from command line but i kept it as a part of script in case there is any issue it can re initialise as per given path"""
"""This initialise the ecb data if does not exist else update if it does, we can sechdule the script to be run after 3pm to get lastest exchange rate of the day
and then it shall first update with lastest exchange rate data before writing it to file.Also I tried printing exceptions, we can follow the uniform error handling method as per standards/requirement """
def get_data():
try:
store.last_updated()
except Error as e:
print("Error with ecb database", e)
except:
try:
store.initialise()
except Error as e:
print('Error while initialising',e)
except:
print('unknown error , check initialise process')
else:
if store.last_updated() != datetime.datetime.today().date(): #if latest data doesn't exist
try:
store.update()
except Error as e:
print('Error while updating', e)
except:
print('unknown error while updating')
"""else:
print('latest data already') """
"""#Else part is not needed because all excpetions already handleded, we can do it in case need to log the process for success."""
""" This gets the data from updated ECB database from given date range between given currencies"""
def get_exchange_rate(start_date, end_Date, from_curr, to_cuur):
daterange = pd.date_range(start_date, end_Date)
data = [store.get_rate(from_curr, to_cuur,single_date.strftime("%Y-%m-%d")) for single_date in daterange] #calling for all days in between
#return (pd.DataFrame(data))
d = pd.DataFrame(data)
d.insert(1, 'currency_from', from_curr)
d.insert(2,'currency_to', to_cuur)
d.rename(columns={d.columns[0]: "Date", d.columns[3]: "Exchange_Rate" },inplace=True)
d.to_csv(outfile, index=False) # putting it in csv of given path and name
def main():
get_data()
get_exchange_rate('2013-1-1', datetime.datetime.today().date(),'EUR', 'USD')
main()
Could you please review and let me know if it can be written better. Few doubts I have are:
- Should I pass
ecb_path
as parameter toget_data()
andget_exchange_Rate()
? I am not sure about the best approach. - Are nested
try
except
blocks Pythonic in this case? Can I handle it better? - Should I write a different method to write output to csv file?
- Is
for
loop efficient in this case, to get data for bigger date range? - Should I add a check in case the output file is not created or given path is wrong?
python performance beginner python-3.x error-handling
python performance beginner python-3.x error-handling
edited 16 hours ago
Graipher
22.8k53384
22.8k53384
asked yesterday
BlackCurrant
283
283
add a comment |
add a comment |
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f209099%2fhistorical-exchange-rate-between-currencies-using-ecbxrate%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown