forked from jbms/beancount-import
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschwab_csv.py
1913 lines (1669 loc) · 64.7 KB
/
schwab_csv.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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Schwab.com brokerage transaction source.
Imports transactions from Schwab.com brokerage/banking history CSV files.
To use, first you have to download Schwab CSV data into a directory on your filesystem. If
you have a structure like this:
financial/
data/
schwab/
transactions/
positions/
And you download your transaction history CSV into `transactions/` and your positions
statement CSV into `positions/`, then you could specify your beancount-import source like
this:
dict(module="beancount_import.source.schwab_csv",
transaction_csv_filenames=glob.glob("data/schwab/transactions/*.csv"),
position_csv_filenames=glob.glob("data/schwab/positions/*.csv"),
)
The importer can also optionally make use of Schwab's lot details CSV downloads in order
to correctly fill in cost-basis on stock sales, even for sales of stock from multiple
lots. For this to work reliably, you should ensure that you download the lot details
regularly (ideally at least once between each transaction involving a given commodity).
Downloading lot details CSV by hand could be quite tedious; the
[finance-dl](https://github.com/jbms/finance-dl) package is recommended.
To use lot details, add a `lots_csv_filenames` key to your beancount-import source.
Finance-dl will place lot details under `positions/lots/` with one directory per date
downloaded and one file per commodity. So your source spec might look like this:
dict(module="beancount_import.source.schwab_csv",
transaction_csv_filenames=glob.glob("data/schwab/transactions/*.csv"),
position_csv_filenames=glob.glob("data/schwab/positions/*.csv"),
lots_csv_filenames=glob.glob("data/schwab/positions/lots/*/*.csv"),
)
This importer also makes use of certain metadata keys on your accounts. In order to label
a beancount account as a Schwab account whose authoritative transaction source is this
importer, specify the `schwab_account` metadata key as the account ID exactly as it
appears in your Schwab CSV downloads. For example:
2015-11-09 open Assets:Investments:Schwab:Brokerage-1234
schwab_account: "XXXX-1234"
You can also optionally specify accounts to be used for recording dividends, capital
gains, interest, fees, and taxes:
2015-11-09 open Assets:Investments:Schwab:Brokerage-1234
schwab_account: "XXXX-1234"
div_income_account: "Income:Dividend:Schwab"
interest_income_account: "Income:Interest:Schwab"
capital_gains_account: "Income:Capital-Gains:Schwab"
fees_account: "Expenses:Brokerage-Fees:Schwab"
taxes_account: "Expenses:Taxes"
These are all optional and will fall back to `Expenses:FIXME` if not specified.
This importer will add the metadata keys `date`, `source_desc`, and `schwab_action` to the
imported transactions; these (along with the account and transaction amount) are used to
match and reconcile/clear already-imported transactions with transactions found in the
CSV.
Sub-accounts of the asset, dividend, and capital gains accounts will be created per
security as needed; e.g. `Assets:Investments:Schwab:Brokerage-1234:XYZ` would be created
to track the balance of `XYZ` shares owned, and `Income:Dividend:Schwab:XYZ` for dividends
earned from `XYZ`, etc.
Caveats
=======
* Because Schwab CSV downloads do not provide any unique transaction identifier, and it is
possible for two identical rows to exist in the CSV and be actual separate but identical
transactions, no de-duplication is performed on incoming CSV rows. Thus, it's required to
download non-overlapping CSV statements.
* Not all Schwab "actions" (transaction types) are supported. There's no reference for all
the possible actions, and Schwab could add new ones any time. If your CSV includes an
unsupported action, you'll get a `ValueError: 'Foo' is not a valid BrokerageAction` or
`ValueError: 'Foo' is not a valid BankingEntryType` for banking files. Please
file an issue (and ideally a pull request!) to add support for that action.
* If you have multiple transactions involving a commodity between two downloads of lot
details (particularly two different sales), the importer may not be able to infer the lots
involved in each sale. In this case it will fall back to empty cost-basis on the sale and
you may have to fill it in manually in order to avoid ambiguity errors from beancount.
* The lot details logic assumes that if you have lot details for any commodity at a given
point in time, you have downloaded lot details for all commodities. If lot details are
missing for a commodity, it will assume that's because you no longer hold that commodity.
"""
from __future__ import annotations
import csv
import datetime
import enum
import os.path
import re
from collections import Counter, OrderedDict
from dataclasses import dataclass
from decimal import Decimal
from io import StringIO
from typing import (
AbstractSet,
Callable,
Dict,
Iterable,
Iterator,
List,
Mapping,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
)
from typing_extensions import TypedDict
from beancount.core.amount import Amount
from beancount.core.data import (
EMPTY_SET,
Balance,
Directive,
Meta,
Open,
Posting,
Price,
Transaction,
)
from beancount.core.flags import FLAG_OKAY
from beancount.core.number import MISSING, D
from beancount.core.position import CostSpec
from beancount_import.journal_editor import JournalEditor
from beancount_import.matching import FIXME_ACCOUNT
from beancount_import.posting_date import POSTING_DATE_KEY
from beancount_import.source import ImportResult, InvalidSourceReference, SourceResults
from beancount_import.source.description_based_source import (
SOURCE_DESC_KEYS,
DescriptionBasedSource,
get_account_mapping as orig_get_account_mapping,
)
from beancount_import.unbook import group_postings_by_meta, unbook_postings
CASH_CURRENCY="USD"
class BrokerageAction(enum.Enum):
# Please keep these alphabetized:
ADR_MGMT_FEE = "ADR Mgmt Fee"
BANK_INTEREST = "Bank Interest"
BOND_INTEREST = "Bond Interest"
BUY = "Buy"
BUY_TO_CLOSE = "Buy to Close"
BUY_TO_OPEN = "Buy to Open"
CASH_DIVIDEND = "Cash Dividend"
CASH_IN_LIEU = "Cash In Lieu"
EXPIRED = "Expired"
FOREIGN_TAX_PAID = "Foreign Tax Paid"
JOURNAL = "Journal"
JOURNALED_SHARES = "Journaled Shares"
LONG_TERM_CAP_GAIN = "Long Term Cap Gain"
LONG_TERM_CAP_GAIN_REINVEST = "Long Term Cap Gain Reinvest"
MARGIN_INTEREST = "Margin Interest"
CREDIT_INTEREST = "Credit Interest"
MISC_CASH_ENTRY = "Misc Cash Entry"
MONEYLINK_DEPOSIT = "MoneyLink Deposit"
MONEYLINK_TRANSFER = "MoneyLink Transfer"
PRIOR_YEAR_CASH_DIVIDEND = "Pr Yr Cash Div"
PRIOR_YEAR_DIV_REINVEST = "Pr Yr Div Reinvest"
PRIOR_YEAR_SPECIAL_DIVIDEND = "Pr Yr Special Div"
PROMOTIONAL_AWARD = "Promotional Award"
QUAL_DIV_REINVEST = "Qual Div Reinvest"
QUALIFIED_DIVIDEND = "Qualified Dividend"
NON_QUALIFIED_DIVIDEND = "Non-Qualified Div"
REINVEST_DIVIDEND = "Reinvest Dividend"
REINVEST_SHARES = "Reinvest Shares"
REVERSE_SPLIT = "Reverse Split"
SECURITY_TRANSFER = "Security Transfer"
SELL = "Sell"
SELL_TO_CLOSE = "Sell to Close"
SELL_TO_OPEN = "Sell to Open"
SERVICE_FEE = "Service Fee"
SHORT_TERM_CAP_GAIN = "Short Term Cap Gain"
SHORT_TERM_CAP_GAIN_REINVEST = "Short Term Cap Gain Reinvest"
SPECIAL_DIVIDEND = "Special Dividend"
STOCK_MERGER = "Stock Merger"
STOCK_PLAN_ACTIVITY = "Stock Plan Activity"
STOCK_SPLIT = "Stock Split"
WIRE_FUNDS = "Wire Funds"
WIRE_FUNDS_RECEIVED = "Wire Funds Received"
FUNDS_RECEIVED = "Funds Received"
class BankingEntryType(enum.Enum):
# Please keep these alphabetized:
ACH = "ACH"
ATM = "ATM"
ATMREBATE = "ATMREBATE"
CHECK = "CHECK"
DEPOSIT = "DEPOSIT"
INTADJUST = "INTADJUST"
TRANSFER = "TRANSFER"
VISA = "VISA"
WIRE = "WIRE"
@dataclass(frozen=True)
class MergerSpecification:
symbol: str
quantity: Optional[Decimal]
description: str
@dataclass(frozen=True)
class RawEntry:
account: str
date: datetime.date
description: str
amount: Optional[Amount]
filename: str
line: int
def get_meta_account(self, account_meta: Meta, key: str) -> str:
return cast(str, account_meta.get(key, FIXME_ACCOUNT))
def get_processed_entry(
self, account: str, account_meta: Meta, lots: LotsDB
) -> Optional[TransactionEntry]:
raise NotImplementedError("subclasses must implement get_processed_entry")
@dataclass(frozen=True)
class RawBankEntry(RawEntry):
entry_type: BankingEntryType
check_no: Optional[int]
running_balance: Amount
def get_processed_entry(
self, account: str, account_meta: Meta, lots: LotsDB
) -> Optional[TransactionEntry]:
interest_account = self.get_meta_account(account_meta,
INTEREST_INCOME_ACCOUNT_KEY)
fees_account = self.get_meta_account(account_meta, FEES_ACCOUNT_KEY)
shared_attrs: SharedAttrsDict = SharedAttrsDict(
account=account,
date=self.date,
action=self.entry_type,
description=self.description,
amount=self.amount,
filename=self.filename,
line=self.line,
)
if self.amount is None:
return None
if self.entry_type == BankingEntryType.INTADJUST:
return BankInterest(
interest_account=interest_account,
**shared_attrs,
)
elif self.entry_type == BankingEntryType.ATMREBATE:
return BankFee(fees_account=fees_account, **shared_attrs)
return TransactionEntry(**shared_attrs)
@dataclass(frozen=True)
class RawBrokerageEntry(RawEntry):
action: BrokerageAction
symbol: str
quantity: Optional[Decimal]
price: Optional[Decimal]
fees: Optional[Decimal]
merger_spec: Optional[MergerSpecification]
def get_processed_entry(
self, account: str, account_meta: Meta, lots: LotsDB
) -> Optional[TransactionEntry]:
capital_gains_account = self.get_meta_account(account_meta, CAPITAL_GAINS_ACCOUNT_KEY)
fees_account = self.get_meta_account(account_meta, FEES_ACCOUNT_KEY)
interest_account = self.get_meta_account(account_meta, INTEREST_INCOME_ACCOUNT_KEY)
dividend_account = self.get_meta_account(account_meta, DIV_INCOME_ACCOUNT_KEY)
taxes_account = self.get_meta_account(account_meta, TAXES_ACCOUNT_KEY)
schwab_account = get_schwab_account_from_meta(account_meta)
amount = self.amount
if self.action == BrokerageAction.STOCK_PLAN_ACTIVITY:
quantity = self.quantity
assert quantity is not None, quantity
symbol = self.symbol
assert symbol, symbol
amount = Amount(quantity, currency=symbol)
if self.action == BrokerageAction.EXPIRED:
# could expire/settle to non-zero value, otherwise turn the None to zero
amount = Amount(Decimal(0), currency=CASH_CURRENCY) if self.amount is None else self.amount
if amount is None and self.quantity is not None:
amount = Amount(self.quantity, self.symbol)
assert amount is not None, self
shared_attrs: SharedAttrsDict = dict(
account=account,
date=self.date,
action=self.action,
description=self.description,
amount=amount,
filename=self.filename,
line=self.line,
)
if self.action == BrokerageAction.STOCK_MERGER:
assert self.quantity is not None
assert self.merger_spec is not None
assert self.merger_spec.quantity is not None
return Merger(
fees_account=fees_account,
symbol=self.symbol,
quantity=self.quantity,
price=self.price,
fees=self.fees,
merger_spec=self.merger_spec,
**shared_attrs
)
if self.action == BrokerageAction.STOCK_PLAN_ACTIVITY:
cost = lots.get_cost(schwab_account, self.symbol, self.date)
return StockPlanActivity(symbol=self.symbol, cost=cost, **shared_attrs)
if self.action in (
BrokerageAction.CASH_DIVIDEND,
BrokerageAction.CASH_IN_LIEU,
BrokerageAction.PRIOR_YEAR_CASH_DIVIDEND,
BrokerageAction.PRIOR_YEAR_DIV_REINVEST,
BrokerageAction.PRIOR_YEAR_SPECIAL_DIVIDEND,
BrokerageAction.SPECIAL_DIVIDEND,
BrokerageAction.QUALIFIED_DIVIDEND,
BrokerageAction.NON_QUALIFIED_DIVIDEND,
BrokerageAction.QUAL_DIV_REINVEST,
BrokerageAction.REINVEST_DIVIDEND,
BrokerageAction.LONG_TERM_CAP_GAIN_REINVEST,
BrokerageAction.SHORT_TERM_CAP_GAIN_REINVEST,
):
return CashDividend(
symbol=self.symbol,
dividend_account=dividend_account,
**shared_attrs,
)
if self.action == BrokerageAction.BANK_INTEREST:
return BankInterest(
interest_account=interest_account,
**shared_attrs,
)
if self.action in (BrokerageAction.REVERSE_SPLIT, BrokerageAction.STOCK_SPLIT):
assert self.quantity is not None
lot_splits = lots.split(schwab_account, self.symbol, self.date, self.quantity)
return StockSplit(
lot_splits=lot_splits,
**shared_attrs,
)
if self.action == BrokerageAction.PROMOTIONAL_AWARD:
return PromotionalAward(
interest_account=interest_account,
**shared_attrs,
)
if self.action == BrokerageAction.BOND_INTEREST:
return BondInterest(
symbol=self.symbol,
interest_account=interest_account,
**shared_attrs,
)
if self.action in (BrokerageAction.MONEYLINK_TRANSFER,
BrokerageAction.MONEYLINK_DEPOSIT,
BrokerageAction.JOURNAL,
BrokerageAction.JOURNALED_SHARES,
BrokerageAction.SECURITY_TRANSFER,
BrokerageAction.WIRE_FUNDS,
BrokerageAction.WIRE_FUNDS_RECEIVED,
BrokerageAction.FUNDS_RECEIVED):
return Transfer(**shared_attrs)
if self.action in (BrokerageAction.SELL,
BrokerageAction.SELL_TO_OPEN,
BrokerageAction.SELL_TO_CLOSE
):
quantity = self.quantity
assert quantity is not None
price = self.price
assert price is not None
lot_info = lots.get_sale_lots(schwab_account, self.symbol, self.date, quantity)
return Sell(
capital_gains_account=capital_gains_account,
fees_account=fees_account,
symbol=self.symbol,
price=price,
quantity=quantity,
fees=self.fees,
lots=lot_info,
**shared_attrs,
)
if self.action in (BrokerageAction.BUY,
BrokerageAction.BUY_TO_OPEN,
BrokerageAction.BUY_TO_CLOSE,
BrokerageAction.REINVEST_SHARES
):
quantity = self.quantity
assert quantity is not None
price = self.price
assert price is not None
return Buy(
capital_gains_account=capital_gains_account,
fees_account=fees_account,
symbol=self.symbol,
price=price,
quantity=quantity,
fees=self.fees,
**shared_attrs,
)
if self.action in (BrokerageAction.SHORT_TERM_CAP_GAIN, BrokerageAction.LONG_TERM_CAP_GAIN):
return FundGainsDistribution(symbol=self.symbol, capital_gains_account=capital_gains_account, **shared_attrs)
if self.action in (BrokerageAction.ADR_MGMT_FEE,
BrokerageAction.SERVICE_FEE,
BrokerageAction.MISC_CASH_ENTRY):
# MISC_CASH_ENTRY appears to only be used to refund fees.
# If that changes, it will need to be re-categorized.
return Fee(fees_account=fees_account, **shared_attrs)
if self.action == BrokerageAction.FOREIGN_TAX_PAID:
return TaxPaid(taxes_account=taxes_account, **shared_attrs)
if self.action == BrokerageAction.MARGIN_INTEREST or self.action == BrokerageAction.CREDIT_INTEREST:
return Interest(interest_account=interest_account, **shared_attrs)
if self.action == BrokerageAction.EXPIRED:
assert self.quantity is not None
price = Decimal(0) if self.price is None else self.price
lot_info = lots.get_sale_lots(schwab_account, self.symbol, self.date, self.quantity)
if self.quantity > 0:
# an expiring long option means it is sold at the end => the posting has a negative 'quantity'
return Buy(
capital_gains_account=capital_gains_account,
fees_account=fees_account,
symbol=self.symbol,
quantity=self.quantity,
price=price,
fees=self.fees,
**shared_attrs
)
else:
return Sell(
capital_gains_account=capital_gains_account,
fees_account=fees_account,
symbol=self.symbol,
quantity=self.quantity,
price=price,
fees=self.fees,
lots=lot_info,
**shared_attrs
)
assert False, self.action
@dataclass(frozen=True)
class RawLot:
"""A single cost-basis lot of a single holding from Lot Details CSV."""
symbol: str
account: str
asof: datetime.date
opened: datetime.date
quantity: Decimal
price: Decimal
cost: Decimal
class SharedAttrsDict(TypedDict):
account: str
date: datetime.date
action: Union[BrokerageAction, BankingEntryType]
description: str
amount: Amount
filename: str
line: int
class InfoDict(TypedDict):
type: str
filename: str
line: int
@dataclass(frozen=True)
class DirectiveEntry:
date: datetime.date
filename: str
line: int
def get_directive(self) -> Directive:
raise NotImplementedError("subclasses must implement get_directive")
def get_import_result(self) -> ImportResult:
return ImportResult(
date=self.date, info=self.get_info(), entries=[self.get_directive()]
)
def get_info(self) -> InfoDict:
return dict(
type="text/csv",
filename=self.filename,
line=self.line,
)
def get_accounts(self) -> List[str]:
"""Get any accounts for which this importer is authoritative."""
return []
@dataclass(frozen=True)
class TransactionEntry(DirectiveEntry):
account: str
date: datetime.date
action: Union[BrokerageAction, BankingEntryType]
description: str
amount: Amount
filename: str
line: int
def get_action(self) -> str:
return self.action.value
def get_directive(self) -> Transaction:
return Transaction(
meta=None,
date=self.date,
flag=FLAG_OKAY,
payee=None,
narration=f"{self.get_narration_prefix()} - {self.description}",
tags=EMPTY_SET,
links=EMPTY_SET,
postings=self.get_postings(),
)
def get_postings(self) -> List[Posting]:
return [
Posting(
account=self.get_primary_account(),
units=self.amount,
cost=self.get_cost(),
price=None,
flag=None,
meta=self.get_meta(),
),
Posting(
account=self.get_other_account(),
units=self.get_other_units(),
cost=None,
price=None,
flag=None,
meta={},
),
]
def get_primary_account(self) -> str:
sub = self.get_sub_account()
return f"{self.account}:{sub}" if sub is not None else self.account
def get_accounts(self) -> List[str]:
return [self.get_primary_account()]
def get_cost(self) -> Optional[CostSpec]:
return None
def get_sub_account(self) -> Optional[str]:
return None
def get_other_account(self) -> str:
return FIXME_ACCOUNT
def get_other_units(self) -> Union[Amount, Type[MISSING]]:
return -self.amount
def get_meta(self) -> Meta:
return OrderedDict(
source_desc=self.description,
date=self.date,
**{POSTING_META_ACTION_KEY: self.get_action()},
)
def get_narration_prefix(self) -> str:
return self.action.value
@dataclass(frozen=True)
class BankFee(TransactionEntry):
fees_account: str
def get_other_account(self) -> str:
return self.fees_account
@dataclass(frozen=True)
class Fee(BankFee):
def get_sub_account(self) -> Optional[str]:
return "Cash"
@dataclass(frozen=True)
class TaxPaid(TransactionEntry):
taxes_account: str
def get_sub_account(self) -> Optional[str]:
return "Cash"
def get_other_account(self) -> str:
return self.taxes_account
def get_narration_prefix(self) -> str:
return "INVBANKTRAN"
@dataclass(frozen=True)
class Interest(TransactionEntry):
interest_account: str
def get_sub_account(self) -> Optional[str]:
return "Cash"
def get_other_account(self) -> str:
return self.interest_account
@dataclass(frozen=True)
class StockPlanActivity(TransactionEntry):
symbol: str
cost: Optional[Decimal]
def get_cost(self) -> Optional[CostSpec]:
cost = self.cost
if cost is None:
cost = Decimal("1")
currency = "FIXME"
else:
currency = CASH_CURRENCY
return CostSpec(
number_per=cost,
number_total=None,
currency=currency,
date=None,
label=None,
merge=None,
)
def get_sub_account(self) -> Optional[str]:
return self.symbol
def get_other_units(self) -> Union[Amount, Type[MISSING]]:
return MISSING
def get_narration_prefix(self) -> str:
return "TRANSFER"
@dataclass(frozen=True)
class CashDividend(TransactionEntry):
symbol: str
dividend_account: str
def get_sub_account(self) -> Optional[str]:
return "Cash"
def get_other_account(self) -> str:
return f"{self.dividend_account}:{self.symbol}"
def get_narration_prefix(self) -> str:
return "INCOME - DIV"
@dataclass(frozen=True)
class BondInterest(TransactionEntry):
symbol: str
interest_account: str
def get_sub_account(self) -> Optional[str]:
return "Cash"
def get_other_account(self) -> str:
return f"{self.interest_account}:{self.symbol}"
def get_narration_prefix(self) -> str:
return "BOND INTEREST"
@dataclass(frozen=True)
class BankInterest(TransactionEntry):
interest_account: str
def get_sub_account(self) -> Optional[str]:
if self.action == BankingEntryType.INTADJUST:
# Checking interest, cash is held in main account
return None
return "Cash"
def get_other_account(self) -> str:
return self.interest_account
def get_narration_prefix(self) -> str:
return "INTEREST"
@dataclass(frozen=True)
class PromotionalAward(TransactionEntry):
interest_account: str
def get_sub_account(self) -> Optional[str]:
if self.action == BankingEntryType.INTADJUST:
# Checking interest, cash is held in main account
return None
return "Cash"
def get_other_account(self) -> str:
return self.interest_account
def get_narration_prefix(self) -> str:
return "PROMOTIONAL AWARD"
@dataclass(frozen=True)
class FundGainsDistribution(TransactionEntry):
"""
ETFs and Mutual Funds can have distributions of capital gains
generated by internal activity.
"""
symbol: str
capital_gains_account: str
def get_sub_account(self) -> Optional[str]:
return "Cash"
def get_other_account(self) -> str:
return f"{self.capital_gains_account}:{self.symbol}"
def get_narration_prefix(self) -> str:
return "INCOME - CAP GAINS"
@dataclass(frozen=True)
class Transfer(TransactionEntry):
def get_sub_account(self) -> Optional[str]:
if self.amount.currency != CASH_CURRENCY:
return self.amount.currency
return "Cash"
def get_narration_prefix(self) -> str:
return "TRANSFER"
@dataclass(frozen=True)
class StockSplit(TransactionEntry):
lot_splits: List[LotSplit]
def get_sub_account(self) -> Optional[str]:
return self.amount.currency
def get_postings(self) -> List[Posting]:
postings = []
if not self.lot_splits:
return super().get_postings()
for split in self.lot_splits:
postings.append(
Posting(
account=self.get_primary_account(),
units=Amount(-split.prev_qty, self.amount.currency),
cost=CostSpec(
number_per=split.prev_cost,
number_total=None,
currency=CASH_CURRENCY,
date=split.date,
label=None,
merge=None,
),
price=None,
flag=None,
meta=self.get_meta(),
)
)
postings.append(
Posting(
account=self.get_primary_account(),
units=Amount(split.new_qty, self.amount.currency),
cost=CostSpec(
number_per=split.new_cost,
number_total=None,
currency=CASH_CURRENCY,
date=split.date,
label=None,
merge=None,
),
price=None,
flag=None,
meta=self.get_meta(),
)
)
return postings
def get_narration_prefix(self) -> str:
return "STOCKSPLIT"
@dataclass(frozen=True)
class Sell(TransactionEntry):
capital_gains_account: str
fees_account: str
symbol: str
quantity: Decimal
price: Decimal
fees: Optional[Decimal]
lots: Mapping[Decimal, Decimal]
def get_sub_account(self) -> Optional[str]:
return self.symbol
def get_other_account(self) -> str:
return f"{self.account}:Cash"
def get_postings(self) -> List[Posting]:
lots = list(self.lots.items())
cost_currency = CASH_CURRENCY
if not lots:
lots = [(MISSING, self.quantity)]
cost_currency = MISSING
postings = [
Posting(
account=self.get_primary_account(),
units=-Amount(lot_qty, currency=self.symbol),
cost=CostSpec(
number_per=lot_cost,
number_total=None,
currency=cost_currency,
date=None,
label=None,
merge=None,
),
price=Amount(self.price, currency=CASH_CURRENCY),
flag=None,
meta=self.get_meta(),
)
for lot_cost, lot_qty in lots
]
postings.append(
Posting(
account=self.get_other_account(),
units=self.amount,
cost=None,
price=None,
flag=None,
meta=self.get_meta(),
)
)
if self.action != BrokerageAction.SELL_TO_OPEN:
# too early to realize gains/losses when opening a short position
postings.append(
Posting(
account=self.get_cap_gains_account(),
units=MISSING,
cost=None,
price=None,
flag=None,
meta={},
)
)
fees = self.fees
if fees is not None:
postings.append(
Posting(
account=self.fees_account,
units=Amount(self.fees, currency=CASH_CURRENCY),
cost=None,
price=None,
flag=None,
meta={},
)
)
return postings
def get_narration_prefix(self) -> str:
if self.action in (BrokerageAction.SELL_TO_OPEN, BrokerageAction.SELL_TO_CLOSE):
return "SELLOPT"
elif self.action == BrokerageAction.EXPIRED:
return "SELLOPT - EXPIRED"
else:
return "SELLSTOCK"
def get_cap_gains_account(self) -> str:
return f"{self.capital_gains_account}:{self.symbol}"
def get_accounts(self) -> List[str]:
return [self.get_primary_account(), self.get_other_account()]
@dataclass(frozen=True)
class Buy(TransactionEntry):
capital_gains_account: str
fees_account: str
symbol: str
quantity: Decimal
price: Decimal
fees: Optional[Decimal]
def get_sub_account(self) -> Optional[str]:
return self.symbol
def get_other_account(self) -> str:
return f"{self.account}:Cash"
def get_postings(self) -> List[Posting]:
postings = [
Posting(
account=self.get_primary_account(),
units=Amount(self.quantity, currency=self.symbol),
cost=CostSpec(
number_per=self.price,
number_total=None,
currency=CASH_CURRENCY,
date=None,
label=None,
merge=None,
),
price=None,
flag=None,
meta=self.get_meta(),
),
Posting(
account=self.get_other_account(),
units=self.amount,
cost=None,
price=None,
flag=None,
meta=self.get_meta(),
),
]
if self.action in (BrokerageAction.BUY_TO_CLOSE, BrokerageAction.EXPIRED):
# need to record gains when closing a short position
postings.append(
Posting(
account=self.get_cap_gains_account(),
units=MISSING,
cost=None,
price=None,
flag=None,
meta={},
)
)
fees = self.fees
if fees is not None:
postings.append(
Posting(
account=self.fees_account,
units=Amount(self.fees, currency=CASH_CURRENCY),
cost=None,
price=None,
flag=None,
meta={},
)
)
return postings
def get_narration_prefix(self) -> str:
if self.action in (BrokerageAction.BUY_TO_OPEN, BrokerageAction.BUY_TO_CLOSE):
return "BUYOPT"
elif self.action == BrokerageAction.EXPIRED:
return "BUYOPT - EXPIRED"
else:
return "BUYSTOCK"
def get_cap_gains_account(self) -> str:
return f"{self.capital_gains_account}:{self.symbol}"
def get_accounts(self) -> List[str]:
return [self.get_primary_account(), self.get_other_account()]
@dataclass(frozen=True)
class Merger(TransactionEntry):
fees_account: str
symbol: str
quantity: Decimal
price: Optional[Decimal]
merger_spec: MergerSpecification
fees: Optional[Decimal]
def get_sub_account(self) -> Optional[str]:
return self.symbol
def get_other_account(self) -> str:
return f"{self.account}:{self.merger_spec.symbol}"
def get_postings(self) -> List[Posting]:
postings = [
Posting(
account=self.get_primary_account(),
units=Amount(self.quantity, currency=self.symbol),
cost=CostSpec(
number_per=self.price,
number_total=None,
currency=CASH_CURRENCY,
date=None,
# at the moment requires manually choosing the lot
label=None,
merge=None,
),
price=None,
flag=None,
meta=self.get_meta(),