I wrote a python script to get the daily USD/CAD current exchange rate from the Bank of Canada and output it into a .beancount file that can be include in my main file. I need this to properly report transactions to the CRA using the CAD value at the date of the transaction and maybe this will be helpful to other people.
The first time you run the script, it will get all the data starting from 2021-01-01. Subsequently, it will just query for new exchange rates since the last run and append them to the file. So if you manually edit a price, it will no get overwritten when you the script again. import requests, json, os.path import datetime priceFilename = "BofC_CADprices.beancount" if os.path.exists(priceFilename): priceFile = open(priceFilename, "r+") currentPrices = priceFile.readlines() last_line = currentPrices[-1:][0].split(' ')[0] last_date = datetime.datetime.strptime(last_line, '%Y-%m-%d').date() next_date = last_date + datetime.timedelta(days=1) else: priceFile = open(priceFilename, "w") next_date = datetime.datetime.strptime('2021-01-01', '%Y-%m-%d').date() end_date = datetime.date.today() - datetime.timedelta(days=1) # Note that output format of dates should be %Y-%m-%d. Default is this, so it # works, but maybe should use strptime to explicity set format url = requests.get("https://www.bankofcanada.ca/valet/observations/FXUSDCAD/json?start_date={}&end_date={}".format(next_date,end_date)) data = json.loads(url.text) rates = data['observations'] for r in rates: priceFile.write('{} price USD {} CAD;\n'.format(r['d'],r['FXUSDCAD']['v'])) priceFile.close() -- You received this message because you are subscribed to the Google Groups "Beancount" group. To unsubscribe from this group and stop receiving emails from it, send an email to beancount+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/beancount/a9fa28f2-2132-4dba-9c91-ad92ce8760dan%40googlegroups.com.