Skip to content

Instantly share code, notes, and snippets.

@e2thenegpii
Last active November 17, 2018 18:12
Show Gist options
  • Save e2thenegpii/616d20bfcaacb830eb198cd4c3d05574 to your computer and use it in GitHub Desktop.
Save e2thenegpii/616d20bfcaacb830eb198cd4c3d05574 to your computer and use it in GitHub Desktop.
small script to take price data from tdameritrade and put it into a gnucash mysql database intended to run on a mysql server without gnucash installed
#!/usr/bin/env python
#pip install piecash requests pandas_market_calendars MySQL
import argparse
import piecash
import requests
import datetime
import decimal
import pandas_market_calendars as mcal
import numpy as np
url = 'https://api.tdameritrade.com/v1/marketdata/quotes'
def main():
parser = argparse.ArgumentParser()
parser.add_argument('username')
parser.add_argument('password', type=argparse.FileType())
parser.add_argument('uri')
parser.add_argument('apikey')
args = parser.parse_args()
today = datetime.date.today()
# Check that today is not a banking holiday and is not a weekend
if np.datetime64(today) not in mcal.get_calendar('NYSE').holidays().holidays and today.weekday() >= 0 and today.weekday() <= 4:
db_uri = 'mysql://{0}:{1}@{2}'.format(args.username, args.password.read().strip(), args.uri)
with piecash.open_book(uri_conn=db_uri, readonly=False, do_backup=False, open_if_lock=True) as book:
# Assuming there is only one currency in the book...
currency, = [x for x in book.commodities if x.namespace == 'CURRENCY' and x.mnemonic == 'USD']
r = requests.get(url, params={'apikey': args.apikey, 'symbol':','.join(x.mnemonic for x in book.commodities if x.namespace != 'CURRENCY')})
symdata = r.json() if r.ok else {}
for symbol, data in symdata.iteritems():
# The commodity must be present in the book because we only looked up prices on commodities that were already in the book
commodity, = [x for x in book.commodities if x.mnemonic == symbol]
# Only add a price if it is not already present
if not [x for x in book.prices if x.date == today and x.commodity == commodity]:
if data['assetType'] == 'ETF':
value = decimal.Decimal(str(data['lastPrice']))
elif data['assetType'] == 'MUTUAL_FUND':
value = decimal.Decimal(str(data['closePrice']))
book.prices.append(piecash.Price(commodity=commodity,
currency=currency,
date=today,
source='tdameritrade',
type='last',
value=value))
book.save()
if __name__ == '__main__':
main()
@e2thenegpii
Copy link
Author

I am so not responsible if you break your database using this code...

@e2thenegpii
Copy link
Author

Crontab:
00 18 * * * cd /usr/local/lib/tdameritrade_updater && /usr/local/lib/tdameritrade_updater/bin/python /usr/local/lib/tdameritrade_updater/tdameritrade.py gnucash /usr/local/lib/tdameritrade_updater/gnucash_pass localhost/gnucash <TD_AMERITRADE API KEY>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment