forked from jbms/beancount-import
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstockplanconnect.py
620 lines (567 loc) · 25.2 KB
/
stockplanconnect.py
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
"""Stockplanconnect release/trade transaction source.
Data format
===========
To use, first download PDF release and trade confirmations into a directory on
the filesystem either manually or using the `finance_dl.stockplanconnect`
module.
You might have a directory structure like:
financial/
documents/
stockplanconnect/
%Y-%m-%d.Restricted_Units.Trade_Confirmations.Confirmation.pdf
%Y-%m-%d.Restricted_Units.Trade_Confirmations.Confirmation.<N>.pdf
%Y-%m-%d.Restricted_Units.Trade_Confirmations.Release_Confirmation.pdf
%Y-%m-%d.Restricted_Units.Trade_Confirmations.Release_Confirmation.<N>.pdf
where `<N>` is a base-10 number. Only filenames with these patterns are
recognized.
Specifying the source to beancount_import
=========================================
Within your Python script for invoking beancount_import, you might use an
expression like the following to specify the Stockplanconnect source:
dict(
module='beancount_import.source.stockplanconnect',
payee='My Company',
directory=os.path.join(journal_dir,
'documents', 'stockplanconnect'),
income_account='Income:MyCompany:Equity',
capital_gains_account='Income:Morgan-Stanley:Capital-Gains',
fees_account='Income:Expenses:Financial:Investment-Fees:Morgan-Stanley',
asset_account='Assets:Investment:Morgan-Stanley:MyCompany',
)
Optionally, you may also specify a `tax_accounts` key with value like:
tax_accounts=collections.OrderedDict([
('Federal Tax', 'Income:Expenses:Taxes:TY{year:04d}:Federal:Income'),
('State Tax', 'Income:Expenses:Taxes:TY{year:04d}:California:Income'),
('Medicare Tax', 'Income:Expenses:Taxes:TY{year:04d}:Federal:Medicare'),
]),
However, if you are also importing payroll statements that include the tax
breakdown as well, it works better to leave `tax_accounts` unspecified.
"""
from typing import Union, Optional, List, Set, Dict, Tuple, Any
import datetime
import os
import re
import collections
from beancount.core.data import Open, Transaction, Posting, Amount, Pad, Balance, Directive, EMPTY_SET, Entries
from beancount.core.amount import sub as amount_sub
from beancount.core.position import CostSpec
from beancount.core.number import D, ZERO
from beancount.core.number import MISSING
from beancount_import.posting_date import POSTING_DATE_KEY
from beancount_import.amount_parsing import parse_amount
from beancount_import.matching import FIXME_ACCOUNT
from beancount_import.source import ImportResult, Source, InvalidSourceReference, SourceResults, AssociatedData, LogFunction
from .stockplanconnect_statement import Release, TradeConfirmation, get_document_type
AWARD_NOTE_KEY = 'stock_award_note'
AWARD_ID_KEY = 'stock_award_id'
TRADE_REFERENCE_NUMBER_KEY = 'trade_ref_number'
def load_documents(directory: str, log_status: LogFunction):
releases = []
trades = []
for name in sorted(os.listdir(directory)):
path = os.path.join(directory, name)
class_type = get_document_type(path)
if class_type is None: continue
log_status('stockplanconnect_source: loading %s' % name)
doc = class_type(path)
if class_type is Release:
releases.append(doc)
else:
trades.append(doc)
return releases, trades
class StockplanconnectSource(Source):
def __init__(self,
directory: str,
income_account: str,
asset_account: str,
capital_gains_account: str,
fees_account: str,
payee: str,
tax_accounts: Optional[Dict[str, str]] = None,
**kwargs):
super().__init__(**kwargs)
self.directory = directory
self.releases, self.trades = load_documents(directory, self.log_status)
self.income_account = income_account
self.asset_account = asset_account
self.asset_cash_account = asset_account + ':Cash'
self.fees_account = fees_account
self.capital_gains_account = capital_gains_account
self.tax_accounts = tax_accounts
self.payee = payee
def check_for_duplicates(documents, get_key):
result = dict()
documents_without_duplicates = []
for x in documents:
key = get_key(x)
if key in result:
# raise RuntimeError('Duplicate document found: existing=%r, new=%r' %
# (result[key].path, x.path))
continue
documents_without_duplicates.append(x)
result[key] = x
return result, documents_without_duplicates
# Maps (income_account, release_date) pair to release object
self.release_dates, self.releases = check_for_duplicates(
self.releases, self.get_release_key)
self.release_stock_posting_keys = set(
self.get_stock_posting_key(r) for r in self.releases
if r.net_release_shares is not None)
self.trade_keys, self.trades = check_for_duplicates(
self.trades, self.get_trade_key)
self.expected_trade_transfers = {(t.settlement_date,
t.reference_number): t
for t in self.trades}
self.expected_release_transfers = {(r.settlement_date or r.release_date,
r.award_id): r
for r in self.releases}
self.income_accounts = set(
self.get_income_account(r) for r in self.releases)
self.managed_accounts = set(self.income_accounts)
self.managed_accounts.add(self.asset_cash_account)
self.stock_accounts = set(
self.asset_account + ':' + r.symbol for r in self.releases)
self.managed_accounts.update(self.stock_accounts)
def get_income_account(self, r: Release):
return '%s:%s:%s' % (self.income_account, r.award_id, r.symbol)
def get_stock_account(self, x: Union[Release, TradeConfirmation]):
return self.asset_account + ':' + x.symbol
def get_stock_posting_key(self, r: Release):
stock_account = '%s:%s' % (self.asset_account, r.symbol)
return (stock_account, r.release_date, r.award_id)
def get_release_key(self, r: Release):
return (self.get_income_account(r), r.release_date)
def get_trade_key(self, r: TradeConfirmation):
return (self.get_stock_account(r), r.trade_date, r.reference_number)
def _preprocess_entries(self, entries: Entries):
seen_releases = dict(
) # type: Dict[Tuple[str, Optional[datetime.date]], List[Tuple[Transaction, Posting]]]
seen_release_stock_postings = dict(
) # type: Dict[Tuple[str, datetime.date, Optional[str]], List[Tuple[Transaction, Posting]]]
seen_trades = dict(
) # type: Dict[Tuple[str, datetime.date, Any], List[Tuple[Transaction, Posting]]]
seen_release_transfers = dict(
) # type: Dict[Tuple[datetime.date, str], List[Tuple[Transaction, Posting]]]
seen_trade_transfers = dict(
) # type: Dict[Tuple[datetime.date, str], List[Tuple[Transaction, Posting]]]
income_account_prefix = self.income_account + ':'
for entry in entries:
if not isinstance(entry, Transaction): continue
for posting in entry.postings:
if posting.account.startswith(income_account_prefix):
date = (posting.meta.get(POSTING_DATE_KEY)
if posting.meta is not None else None)
seen_releases.setdefault((posting.account, date),
[]).append((entry, posting))
elif posting.account in self.stock_accounts:
date = (posting.meta.get(POSTING_DATE_KEY)
if posting.meta is not None else None)
if posting.units.number > ZERO:
seen_release_stock_postings.setdefault(
(posting.account, date,
(posting.cost or posting.cost_spec).label),
[]).append((entry, posting))
else:
ref = posting.meta.get(TRADE_REFERENCE_NUMBER_KEY)
seen_trades.setdefault((posting.account, date, ref),
[]).append((entry, posting))
elif posting.account == self.asset_cash_account:
date = (posting.meta.get(POSTING_DATE_KEY)
if posting.meta is not None else None)
ref = (posting.meta.get(TRADE_REFERENCE_NUMBER_KEY)
if posting.meta is not None else None)
if ref is not None and ref.startswith('>'):
seen_trade_transfers.setdefault(
(date, ref[1:]), []).append((entry, posting))
award_id = posting.meta.get(AWARD_ID_KEY)
if award_id is not None and award_id.startswith('>'):
seen_release_transfers.setdefault(
(date, award_id[1:]), []).append((entry, posting))
return seen_releases, seen_release_stock_postings, seen_trades, seen_release_transfers, seen_trade_transfers
def _make_journal_entry(self, r: Release):
txn = Transaction(
meta=collections.OrderedDict(),
date=r.release_date,
flag='*',
payee=self.payee,
narration='Stock Vesting',
tags=EMPTY_SET,
links=EMPTY_SET,
postings=[])
txn.postings.append(
Posting(
account=self.get_income_account(r),
units=-r.amount_released,
cost=None,
meta={POSTING_DATE_KEY: r.release_date},
price=r.vest_price,
flag=None,
))
vest_cost_spec = CostSpec(
number_per=r.vest_price.number,
currency=r.vest_price.currency,
number_total=None,
date=r.vest_date,
label=r.award_id,
merge=False)
txn.postings.append(
Posting(
account=self.asset_account + ':Cash',
units=r.released_market_value_minus_taxes,
cost=None,
meta={
POSTING_DATE_KEY: r.release_date,
AWARD_NOTE_KEY:
'Market value of vested shares minus taxes.',
AWARD_ID_KEY: r.award_id,
},
price=None,
flag=None))
if r.net_release_shares is not None:
# Shares were retained
txn.postings.append(
Posting(
account=self.asset_account + ':' + r.symbol,
units=r.net_release_shares,
cost=vest_cost_spec,
meta={
POSTING_DATE_KEY: r.release_date,
AWARD_ID_KEY: r.award_id,
},
price=None,
flag=None))
txn.postings.append(
Posting(
account=self.asset_account + ':Cash',
units=-Amount(
number=round(
r.vest_price.number * r.net_release_shares.number,
2),
currency=r.vest_price.currency),
cost=None,
meta={
POSTING_DATE_KEY: r.release_date,
AWARD_NOTE_KEY: 'Cost of shares retained',
AWARD_ID_KEY: r.award_id,
},
price=None,
flag=None,
))
else:
# Shares were sold
# Add capital gains posting.
txn.postings.append(
Posting(
meta=None,
account=self.capital_gains_account + ':' + r.symbol,
units=-r.capital_gains,
cost=None,
price=None,
flag=None,
))
capital_gains_amount = r.capital_gains
if r.fee_amount is not None:
capital_gains_amount = amount_sub(capital_gains_amount,
r.fee_amount)
# Add cash posting for capital gains.
txn.postings.append(
Posting(
account=self.asset_account + ':Cash',
units=capital_gains_amount,
cost=None,
meta={
POSTING_DATE_KEY: r.release_date,
AWARD_NOTE_KEY: 'Capital gains less transaction fees',
AWARD_ID_KEY: r.award_id,
},
price=None,
flag=None,
))
if r.fee_amount is not None:
txn.postings.append(
Posting(
account=self.fees_account,
units=r.fee_amount,
cost=None,
meta={
POSTING_DATE_KEY: r.release_date,
AWARD_NOTE_KEY: 'Supplemental transaction fee',
AWARD_ID_KEY: r.award_id,
},
price=None,
flag=None,
))
if self.tax_accounts is None:
# Just use a single unknown account to catch all of the tax costs.
# This allows the resultant entry to match a payroll entry that includes the tax costs.
txn.postings.append(
Posting(
account=FIXME_ACCOUNT,
units=r.total_tax_amount,
cost=None,
meta=dict(),
price=None,
flag=None,
))
else:
for tax_key, tax_account_pattern in self.tax_accounts.items():
if tax_key not in r.fields:
continue
amount = parse_amount(r.fields[tax_key])
account = tax_account_pattern.format(year=r.release_date.year)
txn.postings.append(
Posting(
account=account,
units=amount,
cost=None,
meta={POSTING_DATE_KEY: r.release_date},
price=None,
flag=None,
))
return txn
def _make_transfer_journal_entry(self, r: Release):
date = r.settlement_date or r.release_date
return Transaction(
meta=collections.OrderedDict(),
date=date,
flag='*',
payee=self.payee,
narration='Stock Vesting - %s' % r.transfer_description,
tags=EMPTY_SET,
links=EMPTY_SET,
postings=[
Posting(
account=self.asset_cash_account,
units=-r.transfer_amount,
cost=None,
meta=collections.OrderedDict([
(POSTING_DATE_KEY, date),
(AWARD_ID_KEY, '>' + r.award_id),
(AWARD_NOTE_KEY, r.transfer_description),
]),
price=None,
flag=None,
),
Posting(
account=FIXME_ACCOUNT,
units=r.transfer_amount,
cost=None,
meta=None,
price=None,
flag=None,
),
])
def _make_transfer_trade_journal_entry(self, t: TradeConfirmation):
return Transaction(
meta=collections.OrderedDict(),
date=t.settlement_date,
flag='*',
payee=self.payee,
narration='Transfer due to stock sale',
tags=EMPTY_SET,
links=EMPTY_SET,
postings=[
Posting(
account=self.asset_cash_account,
units=-t.net_amount,
cost=None,
meta=collections.OrderedDict([
(POSTING_DATE_KEY, t.settlement_date),
(TRADE_REFERENCE_NUMBER_KEY, '>' + t.reference_number),
]),
price=None,
flag=None,
),
Posting(
account=FIXME_ACCOUNT,
units=t.net_amount,
cost=None,
meta=None,
price=None,
flag=None,
),
])
def _make_trade_journal_entry(self, t: TradeConfirmation):
txn = Transaction(
meta=collections.OrderedDict(),
date=t.settlement_date,
flag='*',
payee=self.payee,
narration='Sell',
tags=EMPTY_SET,
links=EMPTY_SET,
postings=[])
txn.postings.append(
Posting(
account=self.get_stock_account(t),
units=-t.quantity,
cost=CostSpec(
number_per=MISSING,
number_total=None,
currency=t.gross_amount.currency,
date=None,
label=None,
merge=False),
price=t.share_price,
meta={
POSTING_DATE_KEY: t.trade_date,
TRADE_REFERENCE_NUMBER_KEY: t.reference_number
},
flag=None,
))
txn.postings.append(
Posting(
account=self.capital_gains_account + ':' + t.symbol,
units=MISSING,
meta=None,
cost=None,
price=None,
flag=None,
))
txn.postings.append(
Posting(
account=self.fees_account,
units=t.fees,
cost=None,
meta={
POSTING_DATE_KEY: t.trade_date,
TRADE_REFERENCE_NUMBER_KEY: t.reference_number,
},
price=None,
flag=None,
))
txn.postings.append(
Posting(
account=self.asset_cash_account,
units=t.net_amount,
cost=None,
meta=None,
price=None,
flag=None,
))
return txn
def is_posting_cleared(self, posting: Posting):
if posting.meta is None:
return False
if posting.account.startswith('Income:'):
return True
return ((AWARD_ID_KEY in posting.meta or
TRADE_REFERENCE_NUMBER_KEY in posting.meta) and
POSTING_DATE_KEY in posting.meta)
def prepare(self, journal, results: SourceResults):
seen_releases, seen_release_stock_postings, seen_trades, seen_release_transfers, seen_trade_transfers = self._preprocess_entries(
journal.all_entries)
for seen_dict, valid_set in (
(seen_releases, self.release_dates),
(seen_release_stock_postings, self.release_stock_posting_keys),
(seen_trades, self.trade_keys),
(seen_release_transfers, self.expected_release_transfers),
(seen_trade_transfers, self.expected_trade_transfers),
):
for seen_key, pairs in seen_dict.items():
expected = 1 if seen_key in valid_set else 0
num_extra = len(pairs) - expected
if num_extra != 0:
results.add_invalid_reference(
InvalidSourceReference(num_extra, pairs))
for r in self.releases:
key = self.get_release_key(r)
if key not in seen_releases:
results.add_pending_entry(
self._make_import_result(self._make_journal_entry(r), r))
if (r.transfer_amount is not None and (
r.settlement_date or r.release_date,
r.award_id) not in seen_release_transfers):
results.add_pending_entry(
self._make_import_result(
self._make_transfer_journal_entry(r), r))
for r in self.trades:
key = self.get_trade_key(r)
if key not in seen_trades:
results.add_pending_entry(
self._make_import_result(
self._make_trade_journal_entry(r), r))
# FIXME: seems to be separate transactions now
# if (r.settlement_date,
# r.reference_number) not in seen_trade_transfers:
# results.add_pending_entry(
# self._make_import_result(
# self._make_transfer_trade_journal_entry(r), r))
results.add_accounts(self.managed_accounts)
def _make_import_result(self, txn: Transaction,
x: Union[Release, TradeConfirmation]):
return ImportResult(
date=txn.date,
entries=[txn],
info=dict(type='application/pdf', filename=os.path.abspath(x.path)))
@property
def name(self):
return 'stockplanconnect'
def get_associated_data(self,
entry: Directive) -> Optional[List[AssociatedData]]:
if not isinstance(entry, Transaction): return None
result = [] # type: List[AssociatedData]
already_seen = set() # type: Set[int]
for posting in entry.postings:
if posting.account in self.income_accounts and posting.meta is not None:
date = posting.meta.get(POSTING_DATE_KEY)
if date is not None:
release = self.release_dates.get((posting.account, date))
if release is not None and id(release) not in already_seen:
already_seen.add(id(release))
result.append(
AssociatedData(
meta=(POSTING_DATE_KEY, date),
posting=posting,
description='Release confirmation',
type='application/pdf',
path=os.path.realpath(release.path),
))
elif posting.account in self.stock_accounts and posting.meta is not None:
date = posting.meta.get(POSTING_DATE_KEY)
if posting.units.number > ZERO:
pass
else:
ref = posting.meta.get(TRADE_REFERENCE_NUMBER_KEY)
trade = self.trade_keys.get((posting.account, date, ref))
if trade is not None and id(trade) not in already_seen:
already_seen.add(id(trade))
result.append(
AssociatedData(
meta=(TRADE_REFERENCE_NUMBER_KEY, ref),
posting=posting,
description='Trade confirmation',
type='application/pdf',
path=os.path.realpath(trade.path),
))
elif posting.account == self.asset_cash_account:
date = posting.meta.get(POSTING_DATE_KEY)
ref = posting.meta.get(TRADE_REFERENCE_NUMBER_KEY)
if ref is not None and ref.startswith('>'):
trade = self.trade_keys.get((date, ref[1:]))
if trade is not None and id(trade) not in already_seen:
already_seen.add(id(trade))
result.append(
AssociatedData(
meta=(TRADE_REFERENCE_NUMBER_KEY, ref),
posting=posting,
description='Trade confirmation',
type='application/pdf',
path=os.path.realpath(trade.path),
))
award_id = posting.meta.get(AWARD_ID_KEY)
if award_id is not None and award_id.startswith('>'):
release = self.expected_release_transfers.get((date, award_id[1:]))
if release is not None and id(release) not in already_seen:
already_seen.add(id(release))
result.append(
AssociatedData(
meta=(AWARD_ID_KEY, award_id),
posting=posting,
description='Release confirmation',
type='application/pdf',
path=os.path.realpath(release.path),
))
return result
def load(spec, log_status):
return StockplanconnectSource(log_status=log_status, **spec)