Source

jaraco.financial / jaraco / financial / ofx.py

Full commit
Jason R. Coombs 226d04a 

Jason R. Coombs 4073c86 





Jason R. Coombs c8b9284 
Jason R. Coombs 8d1ced7 

Jason R. Coombs f49d987 
Jason R. Coombs 226d04a 
Jason R. Coombs 549fda3 
Jason R. Coombs 4073c86 
Jason R. Coombs 226d04a 
Jason R. Coombs c8b9284 
Jason R. Coombs 884fb5e 
Jason R. Coombs 549fda3 
Jason R. Coombs f49d987 
Jason R. Coombs 4073c86 
Jason R. Coombs 8d1ced7 
Jason R. Coombs f49d987 
Jason R. Coombs 8d1ced7 

Jason R. Coombs 4073c86 
Jason R. Coombs 1055a30 








Jason R. Coombs 2aed0f4 
Jason R. Coombs 1055a30 

Jason R. Coombs 2d5e02d 
Jason R. Coombs 2aed0f4 

Jason R. Coombs 1055a30 







Jason R. Coombs 2aed0f4 
Jason R. Coombs 1055a30 



Jason R. Coombs 4073c86 










Jason R. Coombs e49df4e 
Jason R. Coombs 4073c86 





Jason R. Coombs 8d1ced7 




Jason R. Coombs 130b68e 





Jason R. Coombs 8d1ced7 




Jason R. Coombs c836508 















Jason R. Coombs 549fda3 












Jason R. Coombs 8d1ced7 
Jason R. Coombs 4073c86 

Jason R. Coombs 549fda3 
Jason R. Coombs 4073c86 

Jason R. Coombs 814eb3b 
Jason R. Coombs 39574dc 
Jason R. Coombs 4073c86 


Jason R. Coombs 549fda3 
Jason R. Coombs 4073c86 
Jason R. Coombs 814eb3b 
Jason R. Coombs 39574dc 
Jason R. Coombs 4073c86 













Jason R. Coombs c836508 
Jason R. Coombs e49df4e 
Jason R. Coombs c836508 
Jason R. Coombs 4073c86 
Jason R. Coombs e49df4e 
Jason R. Coombs 4073c86 


Jason R. Coombs e49df4e 
Jason R. Coombs 8f9c701 
Jason R. Coombs 4073c86 

Jason R. Coombs 8f9c701 
Jason R. Coombs 4073c86 









Jason R. Coombs e49df4e 
Jason R. Coombs 4073c86 








Jason R. Coombs e49df4e 
Jason R. Coombs a17367d 
Jason R. Coombs 4073c86 















Jason R. Coombs 0425247 
Jason R. Coombs 4073c86 























Jason R. Coombs 8f9c701 
Jason R. Coombs 4073c86 



Jason R. Coombs c836508 
Jason R. Coombs 8f9c701 
Jason R. Coombs 4073c86 


Jason R. Coombs e49df4e 
Jason R. Coombs 4073c86 



Jason R. Coombs c836508 
Jason R. Coombs e49df4e 
Jason R. Coombs 4073c86 


Jason R. Coombs 0425247 
Jason R. Coombs 4073c86 


Jason R. Coombs c836508 
Jason R. Coombs e49df4e 
Jason R. Coombs 4073c86 


Jason R. Coombs e49df4e 
Jason R. Coombs 4073c86 


Jason R. Coombs c836508 
Jason R. Coombs 0425247 
Jason R. Coombs 4073c86 


Jason R. Coombs e49df4e 
Jason R. Coombs 4073c86 





Jason R. Coombs 5c6836a 

Jason R. Coombs 4073c86 

Jason R. Coombs aef754a 










Jason R. Coombs 4073c86 
Jason R. Coombs c8b9284 





Jason R. Coombs f49d987 















Jason R. Coombs 5d7362e 




Jason R. Coombs a5e89cc 
Jason R. Coombs 5d7362e 
Jason R. Coombs a5e89cc 
Jason R. Coombs 5d7362e 
Jason R. Coombs a5e89cc 
Jason R. Coombs 5d7362e 
Jason R. Coombs 8f9c701 

Jason R. Coombs a5e89cc 


Jason R. Coombs 5d7362e 

Jason R. Coombs aabc7fe 







Jason R. Coombs 5d7362e 
Jason R. Coombs f49d987 















Jason R. Coombs 8a67581 
Jason R. Coombs 8213961 
Jason R. Coombs f49d987 
Jason R. Coombs aabc7fe 
Jason R. Coombs 5d7362e 

Jason R. Coombs f49d987 


Jason R. Coombs 5d7362e 


Jason R. Coombs f49d987 










Jason R. Coombs 8a67581 
Jason R. Coombs 226d04a 




Jason R. Coombs 1b2eae4 
Jason R. Coombs 613933b 
Jason R. Coombs 1b2eae4 


Jason R. Coombs a653f59 


Jason R. Coombs f49d987 
Jason R. Coombs 4073c86 
Jason R. Coombs 613933b 


Jason R. Coombs f49d987 

Jason R. Coombs 8d1ced7 
Jason R. Coombs f49d987 
Jason R. Coombs 8a67581 
Jason R. Coombs 4073c86 

Jason R. Coombs 613933b 

Jason R. Coombs 1055a30 
Jason R. Coombs 8a67581 
Jason R. Coombs 4073c86 
Jason R. Coombs 0425247 
Jason R. Coombs 4073c86 
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
from __future__ import absolute_import, unicode_literals, print_function

import urllib2
import uuid
import argparse
import getpass
import itertools
import collections
import datetime
import contextlib
import logging
import inspect
import json
import re

import path
import dateutil.parser
import keyring
import pkg_resources
import jaraco.util.string as jstring
from jaraco.util.string import local_format as lf
import jaraco.util.logging
import jaraco.util.meta

log = logging.getLogger(__name__)

def load_sites():
	"""
	Locate all setuptools entry points by the name 'financial_institutions'
	and initialize them.
	Any third-party library may register an entry point by adding the
	following to their setup.py::

		entry_points = {
			'financial_institutions': {
				'institution set=mylib.mymodule:institutions',
			},
		},

	Where `institutions` is a dictionary mapping institution name to
	institution details.
	"""

	group = 'financial_institutions'
	entry_points = pkg_resources.iter_entry_points(group=group)
	for ep in entry_points:
		try:
			log.info('Loading %s', ep.name)
			detail = ep.load()
			sites.update(detail)
		except Exception:
			log.exception("Error initializing institution %s." % ep)

sites = dict()

def _field(tag, value):
	return lf('<{tag}>{value}')

def _tag(tag, *contents):
	start_tag = lf('<{tag}>')
	end_tag = lf('</{tag}>')
	lines = itertools.chain([start_tag], contents, [end_tag])
	return '\r\n'.join(lines)

def _date():
	return datetime.datetime.utcnow().strftime("%Y%m%d%H%M%S")

def _genuuid():
	return uuid.uuid4().hex

AppInfo = collections.namedtuple('AppInfo', 'id version')

@contextlib.contextmanager
def url_context(*args, **kwargs):
	"""
	Context wrapper around urlopen
	"""
	try:
		response = urllib2.urlopen(*args, **kwargs)
	except urllib2.HTTPError as err:
		with open('err.txt', 'wb') as err_f:
			err_f.write(err.read())
		raise
	try:
		yield response
	finally:
		response.close()

def sign_on_message(config):
	fidata = [_field("ORG", config["fiorg"])]
	if 'fid' in config:
		fidata += [_field("FID", config["fid"])]
	return _tag("SIGNONMSGSRQV1",
		_tag("SONRQ",
			_field("DTCLIENT", _date()),
			_field("USERID", config["user"]),
			_field("USERPASS", config["password"]),
			_field("LANGUAGE", "ENG"),
			_tag("FI", *fidata),
			_field("APPID", config["appid"]),
			_field("APPVER", config["appver"]),
		),
	)

def get_version_id():
	"""
	OFX seems to like version ids that look like NNNN, so generate something
	like that from our version.
	"""
	ver = pkg_resources.require('jaraco.financial')[0].version
	ver_id = ''.join(re.findall('\d+', ver))
	# first pad right to three digits (so last two digits are minor/patch ver)
	ver_id = '{:0<3s}'.format(ver_id)
	# now pad left to four digits (so first two digits are major ver)
	ver_id = '{:0>4s}'.format(ver_id)
	assert len(ver_id) == 4
	return ver_id

class OFXClient(object):
	"""
	Encapsulate an ofx client, config is a dict containing configuration.
	"""

	# pyofx is appears to be work for many institutions
	pyofx = AppInfo('PyOFX', '0100')
	# if you have problems, fake quicken with one of these app ids
	quicken_2009 = AppInfo('QWIN', '1800')
	quicken_older = AppInfo('QWIN', '1200')
	money_sunset = AppInfo('Money Plus', '1700')

	app = pyofx

	def __init__(self, config, user, password):
		self.password = password
		self.user = user
		self.config = config
		self.cookie = 3
		config["user"] = user
		config["password"] = password
		config.setdefault('appid', self.app.id)
		config.setdefault('appver', self.app.version)

	def _cookie(self):
		self.cookie += 1
		return str(self.cookie)

	def sign_on(self):
		"""Generate signon message"""
		return sign_on_message(self.config)

	def _acctreq(self, dtstart):
		req = _tag("ACCTINFORQ", _field("DTACCTUP", dtstart))
		return self._message("SIGNUP", "ACCTINFO", req)

	# this is from _ccreq below and reading page 176 of the latest OFX doc.
	def _bareq(self, bankid, acctid, dtstart, accttype):
		req = _tag("STMTRQ",
			_tag("BANKACCTFROM",
				_field("BANKID", bankid),
				_field("ACCTID", acctid),
				_field("ACCTTYPE", accttype),
			),
			_tag("INCTRAN",
				_field("DTSTART", dtstart),
				_field("INCLUDE", "Y"),
			),
		)
		return self._message("BANK", "STMT", req)

	def _ccreq(self, acctid, dtstart):
		req = _tag("CCSTMTRQ",
			_tag("CCACCTFROM", _field("ACCTID", acctid)),
			_tag("INCTRAN",
				_field("DTSTART", dtstart),
				_field("INCLUDE", "Y"),
			),
		)
		return self._message("CREDITCARD", "CCSTMT", req)

	def _invstreq(self, brokerid, acctid, dtstart):
		dtnow = _date()
		req = _tag("INVSTMTRQ",
			_tag("INVACCTFROM",
				_field("BROKERID", brokerid),
				_field("ACCTID", acctid),
			),
			_tag("INCTRAN",
				_field("DTSTART", dtstart),
				_field("INCLUDE", "Y"),
			),
			_field("INCOO", "Y"),
			_tag("INCPOS",
				_field("DTASOF", dtnow),
				_field("INCLUDE", "Y"),
			),
			_field("INCBAL", "Y"),
		)
		return self._message("INVSTMT", "INVSTMT", req)

	def _message(self, msgType, trnType, request):
		return _tag(msgType + "MSGSRQV1",
			_tag(trnType + "TRNRQ",
				_field("TRNUID", _genuuid()),
				_field("CLTCOOKIE", self._cookie()),
				request,
			),
		)

	def _header(self):
		return '\r\n'.join([
			"OFXHEADER:100",
			"DATA:OFXSGML",
			"VERSION:102",
			"SECURITY:NONE",
			"ENCODING:USASCII",
			"CHARSET:1252",
			"COMPRESSION:NONE",
			"OLDFILEUID:NONE",
			"NEWFILEUID:" + _genuuid(),
			"",
		])

	def baQuery(self, bankid, acctid, dtstart, accttype):
		"""Bank account statement request"""
		return '\r\n'.join([
			self._header(),
			_tag("OFX",
				self.sign_on(),
				self._bareq(bankid, acctid, dtstart, accttype),
			),
		])

	def ccQuery(self, acctid, dtstart):
		"""CC Statement request"""
		return '\r\n'.join([
			self._header(),
			_tag("OFX",
				self.sign_on(),
				self._ccreq(acctid, dtstart),
			),
		])

	def acctQuery(self, dtstart):
		return '\r\n'.join([
			self._header(),
			_tag("OFX",
				self.sign_on(),
				self._acctreq(dtstart),
			),
		])

	def invstQuery(self, brokerid, acctid, dtstart):
		return '\r\n'.join([
			self._header(),
			_tag("OFX",
				self.sign_on(),
				self._invstreq(brokerid, acctid, dtstart),
			),
		])

	def doQuery(self, query, name):
		headers = {
			"Content-type": "application/x-ofx",
			"Accept": "*/*, application/x-ofx",
		}
		request = urllib2.Request(
			self.config["url"],
			data = query,
			headers = headers,
		)

		url = self.config["url"]
		log.debug(lf("URL is {url}; query is {query}"))

		with url_context(request) as response:
			payload = response.read()
			content_type = response.headers.getheader('Content-type')
			if content_type != 'application/x-ofx':
				log.warning(lf('Unexpected content type {content_type}'))

		with file(name, "w") as outfile:
			outfile.write(payload)

class DateAction(argparse.Action):
	def __call__(self, parser, namespace, values, option_string=None):
		value = values
		value = dateutil.parser.parse(value)
		setattr(namespace, self.dest, value)

# todo: move the following class to jaraco.util
class Command(object):
	__metaclass__ = jaraco.util.meta.LeafClassesMeta

	@classmethod
	def add_subparsers(cls, parser):
		subparsers = parser.add_subparsers()
		[cmd_class.add_parser(subparsers) for cmd_class in cls._leaf_classes]

	@classmethod
	def add_parser(cls, subparsers):
		cmd_string = jstring.words(cls.__name__).lowered().dash_separated()
		parser = subparsers.add_parser(cmd_string)
		parser.set_defaults(action=cls)
		return parser

	@staticmethod
	def download(site, account, dt_start, creds, account_type=None):
		config = sites[site]
		client = OFXClient(config, *creds)

		caps = sites[site]['caps']
		if "CCSTMT" in caps:
			query = client.ccQuery(account, dt_start)
		elif "INVSTMT" in caps:
			query = client.invstQuery(sites[site]["fiorg"], account, dt_start)
		elif "BASTMT" in caps:
			bank_id = config["bankid"]
			query = client.baQuery(bank_id, account, dt_start, account_type)
		filename = '{site} {account} {dtnow}.ofx'.format(
			dtnow = datetime.datetime.now().strftime('%Y-%m-%d'),
			**vars())
		client.doQuery(query, filename)

	@staticmethod
	def _get_password(site, username):
		password = keyring.get_password(site, username)
		if password is None:
			password = getpass.getpass(lf("Password for {site}:{username}: "))
			keyring.set_password(site, username, password)
		return password


class Query(Command):
	@classmethod
	def add_parser(cls, subparsers):
		parser = super(Query, cls).add_parser(subparsers)
		parser.add_argument('site', help="One of {0}".format(', '.join(sites)))
		parser.add_argument('-u', '--username', default=getpass.getuser())
		parser.add_argument('-a', '--account')
		parser.add_argument('-t', '--account-type',
			help="Required if retrieving bank statement, should be CHECKING, SAVINGS, ...",
		)
		default_start = datetime.datetime.now() - datetime.timedelta(days=31)
		parser.add_argument('-d', '--start-date', default=default_start,
			action=DateAction)
		return parser

	@classmethod
	def run(cls, args):
		creds = args.username, cls._get_password(args.site, args.username)
		if not args.account:
			# download account info
			config = sites[args.site]
			client = OFXClient(config, *creds)
			query = client.acctQuery("19700101000000")
			client.doQuery(query, args.site + "_acct.ofx")
		else:
			dt_start = args.start_date.strftime("%Y%m%d")
			cls.download(args.site, args.account, dt_start, creds,
				args.account_type)

class DownloadAll(Command):
	@classmethod
	def add_parser(cls, subparsers):
		parser = super(DownloadAll, cls).add_parser(subparsers)
		default_start = datetime.datetime.now() - datetime.timedelta(days=31)
		parser.add_argument('-d', '--start-date', default=default_start,
			action=DateAction)
		return parser

	@classmethod
	def run(cls, args):
		root = path.path('~/Documents/Financial').expanduser()
		accounts = root / 'accounts.json'
		with open(accounts) as f:
			accounts = json.load(f)
		print('Found', len(accounts), 'accounts')
		for account in accounts:
			log.info('Downloading %(institution)s' % account)
			username = account.get('username', getpass.getuser())
			site = account['institution']
			creds = username, cls._get_password(site, username)
			acct_type = account.get('type', '').upper() or None
			dt_start = args.start_date.strftime("%Y%m%d")
			cls.download(site, account['account'], dt_start, creds, acct_type)

def get_args():
	"""
	Parse command-line arguments, including the Command and its arguments.
	"""
	usage = inspect.getdoc(handle_command_line)
	parser = argparse.ArgumentParser(usage=usage)
	jaraco.util.logging.add_arguments(parser)
	Command.add_subparsers(parser)
	return parser.parse_args()

def handle_command_line():
	args = get_args()
	jaraco.util.logging.setup(args)
	load_sites()
	args.action.run(args)

if __name__ == "__main__":
	handle_command_line()