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:




  1. Should I pass ecb_path as parameter to get_data() and get_exchange_Rate()? I am not sure about the best approach.

  2. Are nested try except blocks Pythonic in this case? Can I handle it better?

  3. Should I write a different method to write output to csv file?

  4. Is for loop efficient in this case, to get data for bigger date range?

  5. Should I add a check in case the output file is not created or given path is wrong?










share|improve this question




























    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:




    1. Should I pass ecb_path as parameter to get_data() and get_exchange_Rate()? I am not sure about the best approach.

    2. Are nested try except blocks Pythonic in this case? Can I handle it better?

    3. Should I write a different method to write output to csv file?

    4. Is for loop efficient in this case, to get data for bigger date range?

    5. Should I add a check in case the output file is not created or given path is wrong?










    share|improve this question


























      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:




      1. Should I pass ecb_path as parameter to get_data() and get_exchange_Rate()? I am not sure about the best approach.

      2. Are nested try except blocks Pythonic in this case? Can I handle it better?

      3. Should I write a different method to write output to csv file?

      4. Is for loop efficient in this case, to get data for bigger date range?

      5. Should I add a check in case the output file is not created or given path is wrong?










      share|improve this question















      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:




      1. Should I pass ecb_path as parameter to get_data() and get_exchange_Rate()? I am not sure about the best approach.

      2. Are nested try except blocks Pythonic in this case? Can I handle it better?

      3. Should I write a different method to write output to csv file?

      4. Is for loop efficient in this case, to get data for bigger date range?

      5. 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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 16 hours ago









      Graipher

      22.8k53384




      22.8k53384










      asked yesterday









      BlackCurrant

      283




      283



























          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          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






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          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.




          draft saved


          draft discarded














          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





















































          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







          Popular posts from this blog

          Morgemoulin

          Scott Moir

          Souastre