forked from gotasty/tastypl
-
Notifications
You must be signed in to change notification settings - Fork 1
/
tastypl.go
1958 lines (1865 loc) · 64.4 KB
/
tastypl.go
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
// Copyright (C) 2017 Go Tasty
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package main
import (
"encoding/csv"
"flag"
"fmt"
"os"
"sort"
"strconv"
"strings"
"time"
chart "github.com/Graeme22/go-chart"
"github.com/Graeme22/go-chart/util"
"github.com/golang/glog"
"github.com/shopspring/decimal"
)
type transaction struct {
// Initial group of fields straight from the CSV. Those should be
// considered immutable, don't change the values imported from the CSV.
date time.Time // [0]
txType string // [1]
action string // [2]
symbol string // [3] OCC symbol for options, or underlying name otherwise
instrument string // [4]
description string // [5]
value decimal.Decimal // [6]
quantity decimal.Decimal // [7]
avgPrice decimal.Decimal // [8]
commission decimal.Decimal // [9]
fees decimal.Decimal // [10]
multiplier uint16 // [11]
rootSymbol string // [12] Added Sep 2021
underlying string // [13] was [12]
expDate time.Time // [14] was [13]
strike decimal.Decimal // [15] was [14]
// [16] PUT or call
order string // [16] order # (unused)
// Various flags inferred from the transactions to help make things simpler.
option bool // or non-option (such as future/equity) if false
future bool // true if futures (or options on futures), else equity or index
small bool // true if small exchange future (future must be true as well)
crypto bool // true if cryptocurrency
mtm bool // mark-to-market daily settlement for futures
call bool // or put if false
long bool // or short if false
open bool // or closing transaction if false. Only used on options.
// Starts as quantity, decremented as we close the position.
// Only really meaningful for opening transactions.
qtyOpen decimal.Decimal
// If this is an opening options transaction and we detected that this was
// the result of a roll, this points to the closing transaction of the
// position we rolled from.
rolledFrom *transaction
// Realized P&L on this transaction.
// Only really meaningful for closing transactions.
rpl decimal.Decimal
// Opening transaction from which the realized P&L was made.
// Only really meaningful for closing transactions.
// Exception: for equity trades resulting from options assignment/exercise,
// this points to the trade of the option's assignment exercise.
openTx *transaction
}
var (
oneHundred = decimal.New(100, 0)
oneThousand = decimal.New(1000, 0)
// Cutoff point for YTD stuff.
ytdStart = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
indexSymbols = map[string]struct{}{
"SPX": struct{}{},
"RUT": struct{}{},
"DJX": struct{}{},
"OEX": struct{}{},
"VIX": struct{}{},
"NDX": struct{}{},
"MNX": struct{}{},
"RVX": struct{}{},
"XSP": struct{}{},
"XEO": struct{}{},
}
// How many dollars is one point worth.
// This is madness. Can't wait for the Small Exchange.
futuresPoints = map[string]decimal.Decimal{
// Equities
"/ES": decimal.RequireFromString("50"),
"/MES": decimal.RequireFromString("5"),
"/YM": decimal.RequireFromString("5"),
"/MYM": decimal.RequireFromString("0.5"),
"/NQ": decimal.RequireFromString("20"),
"/MNQ": decimal.RequireFromString("2"),
"/RTY": decimal.RequireFromString("50"),
"/M2K": decimal.RequireFromString("5"),
// Yield curve
"/GE": decimal.RequireFromString("2500"),
"/ZT": decimal.RequireFromString("2000"),
"/ZF": decimal.RequireFromString("1000"),
"/ZN": decimal.RequireFromString("1000"),
"/ZB": decimal.RequireFromString("1000"),
// Metals
"/GC": decimal.RequireFromString("100"),
"/MGC": decimal.RequireFromString("10"),
"/SI": decimal.RequireFromString("5000"),
"/SIL": decimal.RequireFromString("1000"),
"/HG": decimal.RequireFromString("25000"),
// Energy
"/CL": decimal.RequireFromString("1000"),
"/QM": decimal.RequireFromString("500"),
"/NG": decimal.RequireFromString("10000"),
"/QG": decimal.RequireFromString("2500"),
// Ags
"/ZC": decimal.RequireFromString("50"),
"/ZS": decimal.RequireFromString("50"),
"/ZW": decimal.RequireFromString("50"),
// FX
"/6A": decimal.RequireFromString("100000"),
"/M6A": decimal.RequireFromString("10000"),
"/6B": decimal.RequireFromString("62500"),
"/M6B": decimal.RequireFromString("6250"),
"/6C": decimal.RequireFromString("100000"),
"/MCD": decimal.RequireFromString("10000"),
"/6E": decimal.RequireFromString("125000"),
"/M6E": decimal.RequireFromString("12500"),
"/6J": decimal.RequireFromString("125000000"),
"/MJY": decimal.RequireFromString("12500000"),
"/6M": decimal.RequireFromString("500000"),
// Crypto
"/BTC": decimal.RequireFromString("5"),
// Small exchange (see also below for symbol parsing)
"/SPRE": decimal.RequireFromString("1"),
"/SM75": decimal.RequireFromString("1"),
"/SFX": decimal.RequireFromString("1"),
"/S10Y": decimal.RequireFromString("1"),
"/S2Y": decimal.RequireFromString("1"), // 2021.02.22
"/S30Y": decimal.RequireFromString("1"), // 2021.02.22
"/SMO": decimal.RequireFromString("1"), // 2021.05.17
"/STIX": decimal.RequireFromString("1"), // 2020.08.24
"/S420": decimal.RequireFromString("1"), // 2020.06.20
"/SCCX": decimal.RequireFromString("1"), // 2020.10.04
}
// Small exchange symbols. Required for parsing underlying symbol to determine if
// it is a regular future or small exchange (they have different formats)
smallFuturesSymbols = []string{
"/SPRE",
"/SM75",
"/SFX",
"/S10Y",
"/STIX",
"/S2Y",
"/S30Y",
"/SMO",
"/S420",
"/SCCX",
}
// Cryptocurrencies. Array not used at the moment.
cryptoSymbols = []string{
"BCH/USD",
"BTC/USD",
"ETH/USD",
"LTC/USD",
}
)
func (t *transaction) String() string {
return t.description
}
// NetCredit is the net credit after rolls on a per contract basis.
func (t *transaction) NetCredit() decimal.Decimal {
net := t.avgPrice
earlier := t.rolledFrom
for earlier != nil {
net = net.Add(earlier.rpl.Div(earlier.quantity))
earlier = earlier.openTx.rolledFrom
}
return net
}
// per contract fees, see:
// https://tastyworks.desk.com/customer/en/portal/articles/2696746-commissions-and-fees-breakdown
var (
clearingFee = decimal.New(10, -2) // -0.10
// Options Regulatory Fee (rounded to nearest cent)
orFee = decimal.New(415, -4) // -0.0415
// Trading Activity Fee (only for sales, rounded up)
finraTAF = decimal.New(2, -3) // -0.002
// SEC Regulatory Fee (on notional amount, only for sales, rounded up)
secFee = decimal.New(231, -7) // -0.0000231
)
func roundUp(d decimal.Decimal) decimal.Decimal {
return d.Mul(oneHundred).Ceil().Div(oneHundred)
}
// There is a rounding error in the fees reported by the desktop app and
// web-based account management interface. Here we recompute the correct
// amount and fix the transaction.
// TODO: This computes higher fees than it should for some reason.
func (t *transaction) fixFees() {
if t.txType != "Trade" {
return
}
fees := clearingFee.Mul(t.quantity)
fees = fees.Add(orFee.Mul(t.quantity).Round(2))
if !t.long {
fees = fees.Add(roundUp(finraTAF.Mul(t.quantity)))
fees = fees.Add(roundUp(secFee.Mul(t.value)))
}
fees = fees.Neg()
if !t.fees.Equal(fees) {
glog.V(5).Infof("fee %s doesn't matched computed fee %s in %s", t.fees, fees, t)
t.fees = fees
}
}
func (t *transaction) sanityCheck() {
if t.quantity.Sign() <= 0 {
glog.Fatalf("quantity is negative in %s", t)
}
if !t.option {
return // TODO: no other check yet for futures/equities
} else if t.mtm {
glog.Fatalf("options position can't be marked-to-market in %s", t)
} else if t.multiplier == 0 {
glog.Fatalf("options position must have a non-zero multiplier in %s", t)
} else if !t.quantity.Equal(t.quantity.Truncate(0)) {
glog.Fatalf("options quantity must be a whole number in %s", t)
}
if t.strike.LessThanOrEqual(decimal.Zero) {
glog.Fatalf("strike price can't be less than or equal to zero in %s", t)
}
if t.date.After(t.expDate) {
glog.Fatalf("transaction date %s happened after expiration %s in %s",
t.date, t.expDate, t)
}
if t.future {
return // TODO: symbology for options on futures
}
var cp byte
if t.call {
cp = 'C'
} else {
cp = 'P'
}
// Recompute OCC symbol and ensure what we have is the same
// See https://www.theocc.com/components/docs/initiatives/symbology/symbology_initiative_v1_8.pdf
strike := t.strike.Mul(oneThousand).IntPart()
expDate := t.expDate.Format("060102")
const symfmt = "%- 6s%s%c%08d"
symbol := fmt.Sprintf(symfmt, t.underlying, expDate, cp, strike)
if symbol != t.symbol {
if _, index := indexSymbols[t.underlying]; !index {
glog.Fatalf("expected symbol %q but found %q in %s", symbol, t.symbol, t)
}
// PM-settled index options have an additional "P" in the symbol.
// This is a hack to accept those.
pm := t.underlying + "P"
symbol = fmt.Sprintf(symfmt, pm, expDate, cp, strike)
if symbol != t.symbol {
// Weekly index options have an additional "W" in the symbol.
// This is another hack to accept those.
wk := t.underlying + "W"
symbol = fmt.Sprintf(symfmt, wk, expDate, cp, strike)
if symbol != t.symbol {
glog.Fatalf("expected symbol %q but found %q in %s", symbol, t.symbol, t)
}
}
}
}
func (t *transaction) parsePrice() decimal.Decimal {
// Parse the open price from the description :-/
at := strings.IndexByte(t.description, '@')
var adj decimal.Decimal
if at == -1 {
prefix := "Removal of " + t.underlying + " due to expiration, last mark:"
if !strings.HasPrefix(t.description, prefix) {
glog.Fatal("Can't infer transaction price from %s", t)
}
at = len(prefix) - 1
contract := t.underlying[:len(t.underlying)-2]
if t.small {
// Smalls have 2 digit year, regular have 1. Sigh.
contract = t.underlying[:len(t.underlying)-3]
}
pointValue, ok := futuresPoints[contract]
if !ok {
glog.Fatalf("Don't know how much a point of %s is worth in %s", contract, t)
}
adj = t.value.Div(pointValue)
}
p := t.description[at+2:]
price, err := decimal.NewFromString(p)
if err != nil {
glog.Fatalf("Can't parse opening price of futures transaction %s: %s", t, err)
}
return price.Add(adj)
}
// Helper function to work around the fact that some CSV records for options
// on futures are missing fields we need but that we can thankfully extract
// from the symbol.
func parseFuturesOptionSymbol(rec []string) {
// e.g.: Sold 1 /6EZ8 EUUV8 10/05/18 Put 1.15 @ 0.0027
// Symbol: "./6EZ8 EUUV8 181005P1.15" -- not sure why the leading dot there.
symbol := rec[3]
if symbol[0] != '/' {
glog.Fatalf("unexpected symbol for option on futures: %q", rec)
}
sym := strings.Split(symbol, " ")
// Synthesize missing fields from the CSV:
rec[11] = "1" // Multiplier
rec[13] = sym[0] // Underlying
last := sym[len(sym)-1] // <YYMMDD><P|C><strike>
rec[14] = last[2:4] + "/" + last[4:6] + "/" + last[0:2] // Expiration
rec[15] = last[7:] // Strike
switch last[6] {
case 'C':
rec[16] = "CALL"
case 'P':
rec[16] = "PUT"
default:
glog.Fatalf("couldn't find P or C in symbol: %q", rec)
}
}
func (t *transaction) ytd() bool {
return t.date.After(ytdStart)
}
func loadCSV(path string) [][]string {
f, err := os.Open(path)
if err != nil {
glog.Fatal(err)
}
defer f.Close()
reader := csv.NewReader(f)
records, err := reader.ReadAll()
if err != nil {
glog.Fatal(err)
}
return records
}
func parseDecimal(value string) decimal.Decimal {
if value == "" {
return decimal.Decimal{}
}
if value == "--" {
return decimal.Decimal{}
}
d, err := decimal.NewFromString(strings.Replace(value, ",", "", -1))
if err != nil {
glog.Fatal(err)
}
return d
}
// More ugliness. TW changed export formats in Apri 2021 (at least). Exporting timezone identifiers instead of numeric is problematic.
// What variant of CST is it? Central (Chicago)? China? Cuba? And The local system will decide, even worse.
// They also sometimes format the offset as 00:00 and other times as 0000. Transactions from their API use RFC3339, CSV exports use almost* variants
const RFC3339 = "2006-01-02T15:04:05-07:00"
const almostRFC3339 = "2006-01-02T15:04:05-0700"
const anotherAlmostRFC3339 = "2006-01-02T15:04:05.000CDT"
const andAnotherAlmostRFC3339 = "2006-01-02T15:04:05.000CST"
type position struct {
// Opening transaction(s) for this position
opens []*transaction
}
// We consider other transactions within this time window as candidates
// when trying to detect rolls.
const rollWindow = 30 * time.Second
// Used to track recent transactions to detect rolls (for options only).
type recentKey struct {
underlying string
call bool // or put if false
long bool // or short if false
open bool // or closing transaction if false.
}
type portfolio struct {
ytd bool // Only track YTD transactions
ignoreacat bool // Ignore ACAT transactions
// All transactions.
transactions []*transaction
// Recent transactions, used to detect rolls of options positions.
// Transactions older than rollWindow should get purged.
recentTx map[recentKey][]*transaction
// Map a futures contract name to the last mark to market settlement
// price seen for that contract.
lastMarkToMarket map[string]decimal.Decimal
moneyMov decimal.Decimal // sum of all ACH/wire movements
// Map of symbol to opening transaction(s)
positions map[string]*position
cash decimal.Decimal // Cash on hand
premium decimal.Decimal // Sum of premium for currently open positions.
rpl decimal.Decimal // Total realized P&L
comms decimal.Decimal
fees decimal.Decimal
intrs decimal.Decimal // interest
// Misc. cash changes
miscCash decimal.Decimal
// Cumulative tallies
optionsNotionalSold decimal.Decimal
optionsNotionalBought decimal.Decimal
putsTraded int64
callsTraded int64
equityNotionalSold decimal.Decimal
equityNotionalBought decimal.Decimal
futuresNotionalSold decimal.Decimal
futuresNotionalBought decimal.Decimal
cryptoNotionalSold decimal.Decimal
cryptoNotionalBought decimal.Decimal
// Summary of realized P&L per underlying
rplPerUnderlying map[string]decimal.Decimal
numTrades uint16 // Number of trades executed
}
func NewPortfolio(records [][]string, ytd, nofutures, ignoreacat bool) *portfolio {
p := &portfolio{
ytd: ytd,
ignoreacat: ignoreacat,
positions: make(map[string]*position),
recentTx: make(map[recentKey][]*transaction),
lastMarkToMarket: make(map[string]decimal.Decimal),
rplPerUnderlying: make(map[string]decimal.Decimal),
}
// The CSV is sorted from newest to oldest transaction, reverse it.
for i := len(records)/2 - 1; i >= 0; i-- {
opp := len(records) - 1 - i
records[i], records[opp] = records[opp], records[i]
}
p.parseTransactions(records, nofutures)
var prevTime time.Time
var prevRPL decimal.Decimal
logDailyRPL := func() {
if dpl := p.rpl.Sub(prevRPL); !dpl.Equal(decimal.Zero) {
glog.V(4).Infof("Day P/L realized for %s: %9s", prevTime.Format("01/02/06"), dpl.StringFixed(2))
prevRPL = p.rpl
}
}
for i, tx := range p.transactions {
if prevTime.After(tx.date) {
glog.Fatalf("transaction log out of order at time %s (tx=%s)", tx.date, tx)
} else if tx.date.Sub(prevTime) > rollWindow && len(p.recentTx) > 0 {
// More than rollWindow time has elapsed between two transactions,
// clear our map of recent transactions as we can't possibly find
// any rolls in it anymore.
p.recentTx = make(map[recentKey][]*transaction)
}
if prevTime.YearDay() != tx.date.YearDay() {
logDailyRPL()
}
prevTime = tx.date
// When we are handling an assignment or exercise, the transaction in the
// underlying can appear either before or after the transaction that retires the
// option position. This is problematic for us, because we need to adjut the
// cost basis or P&L by the amount of the premium, so we need to tie together
// the two transactions somehow. Work around this inconsistency in the CSV by
// detecting assignment/exercise transaction pairs and making the option
// transaction point to the equity transaction.
if tx.txType == "Receive Deliver" && i != len(p.transactions)-1 {
nextTx := p.transactions[i+1]
p.maybeLinkAssignmentExercises(tx, nextTx)
}
p.handleTransaction(tx)
}
logDailyRPL()
return p
}
func (p *portfolio) maybeLinkAssignmentExercises(tx, nextTx *transaction) {
if !(nextTx.txType == "Receive Deliver" && tx.date.Equal(nextTx.date)) {
return
}
var op *transaction
var buy bool
if tx.option {
op = tx
buy = nextTx.long
} else if nextTx.option {
op = nextTx
buy = tx.long
} else {
return
}
shares := op.quantity.Mul(decimal.New(int64(op.multiplier), 0))
price := op.strike.Mul(shares)
if buy {
price = price.Neg()
}
if tx.openTx == nil && tx.action == "" &&
nextTx.action != "" && tx.underlying == nextTx.symbol &&
nextTx.quantity.Equal(shares) && nextTx.value.Equal(price) {
// First case: option transaction appears before equity transaction.
tx.openTx = nextTx
} else if nextTx.openTx == nil && tx.action != "" &&
nextTx.action == "" && tx.symbol == nextTx.underlying &&
tx.quantity.Equal(shares) && tx.value.Equal(price) {
// Second case: equity transaction appears before option transaction.
nextTx.openTx = tx
}
}
func (p *portfolio) parseNonOptionTransaction(record []string) {
switch record[1] {
case "Money Movement":
amount := parseDecimal(record[6])
switch record[5] {
case "INTEREST ON CREDIT BALANCE":
p.intrs = p.intrs.Add(amount)
case "ACH DEPOSIT", "ACH DISBURSEMENT", "Wire Funds Received":
p.moneyMov = p.moneyMov.Add(amount)
case "Regulatory fee adjustment":
// TW incorrectly calculates some regulatory fees (!) so in order
// to fix the small discrepancies that build up over time, they
// reconcile the fees with what their clearing firm (Apex)
// actually charged by adding weekly transactions to adjust
// customer balances on their platforms. Can't believe they
// haven't fixed this by now, this has been going on for months...
p.fees = p.fees.Add(amount)
default:
if strings.HasPrefix(record[5], "FROM ") {
// Interest paid, e.g. "FROM 10/16 THRU 11/15 @ 8 %"
p.intrs = p.intrs.Add(amount)
return
} else if record[4] == "Equity" && record[3] != "" {
// Interest paid on short stock (borrow fees)
p.intrs = p.intrs.Add(amount)
return
}
glog.V(2).Infof("unhandled money movement: %#v", record)
p.miscCash = p.miscCash.Add(amount)
}
default:
glog.V(1).Infof("unhandled %#v", record)
}
}
// AddTransaction adds an individual transaction. Usually all the
// transactions are passed to the constructor and bulk-imported.
// Transactions must be added in chronological order.
func (p *portfolio) AddTransaction(record []string) {
tx := p.parseTransaction(len(p.transactions), record, &p.ytd)
if tx == nil {
return
}
p.transactions = append(p.transactions, tx)
defer func() {
if e := recover(); e != nil {
panic(fmt.Errorf("when handling %s: %v", record, e))
}
}()
prevTime := p.transactions[len(p.transactions)-1].date
if prevTime.After(tx.date) {
glog.Fatalf("adding a transaction out of order at time %s (last=%s tx=%s)",
prevTime, tx.date, tx)
} else if tx.date.Sub(prevTime) > rollWindow && len(p.recentTx) > 0 {
// More than rollWindow time has elapsed between two transactions,
// clear our map of recent transactions as we can't possibly find
// any rolls in it anymore.
p.recentTx = make(map[recentKey][]*transaction)
}
if tx.txType == "Receive Deliver" {
prevTx := p.transactions[len(p.transactions)-2]
p.maybeLinkAssignmentExercises(prevTx, tx)
}
p.handleTransaction(tx)
}
// parseTransactions parses raw transactions from the CSV and adds them to the
// transaction history.
func (p *portfolio) parseTransactions(records [][]string, nofutures bool) {
p.transactions = make([]*transaction, len(records))
var j int
ytd := p.ytd
for i, rec := range records {
if tx := p.parseTransaction(i, rec, &ytd); tx != nil {
if nofutures && tx.future {
continue
}
p.transactions[j] = tx
j++
}
}
if ignored := len(records) - j; ignored != 0 {
glog.V(3).Infof("Ignored %d non-option transactions", ignored)
}
p.transactions = p.transactions[:j]
}
func (p *portfolio) parseTransaction(i int, rec []string, ytd *bool) *transaction {
date, err := time.Parse(almostRFC3339, rec[0])
if err != nil {
date, err = time.Parse(RFC3339, rec[0])
}
if err != nil {
date, err = time.Parse(anotherAlmostRFC3339, rec[0])
}
if err != nil {
date, err = time.Parse(andAnotherAlmostRFC3339, rec[0])
}
if err != nil {
glog.Fatalf("record #%d, bad transaction date: %s", i, err)
}
if *ytd && date.After(ytdStart) {
// Reset running counts as we only want YTD numbers.
p.miscCash = decimal.Zero
p.intrs = decimal.Zero
p.moneyMov = decimal.Zero
// Note: we don't reset p.cash as the only way to have the correct
// amount of cash ultimately in the account is of course to take
// into account (bad pun, sorry) the entire account history.
*ytd = false // So we don't reset again.
}
value := parseDecimal(rec[6])
comm := parseDecimal(rec[9])
// When TW fixes up a transaction due to a bug/issue on their end, they
// rollback a previous one, which leads to positive commission/fee amounts.
adminTx := rec[1] == "Administrative Transfer"
if comm.GreaterThan(decimal.Zero) && !adminTx {
glog.Fatalf("record #%d, positive commission amount %s in %q", i, rec[9], rec)
}
fees := parseDecimal(rec[10])
if fees.GreaterThan(decimal.Zero) && !adminTx {
glog.Fatalf("record #%d, positive fees amount %s in %q", i, rec[10], rec)
}
p.cash = p.cash.Add(value).Add(comm).Add(fees)
txType := rec[1]
instrument := rec[4]
var call bool
var mtm bool
option := true
if instrument == "Future Option" && rec[3][0] == '.' {
rec[3] = rec[3][1:] // Not sure why there is a dot there but drop it
}
switch rec[16] {
case "PUT":
case "CALL":
call = true
case "":
// Handle non-trade transactions.
if txType != "Trade" && txType != "Receive Deliver" {
// Detect daily mark-to-market of futures held overnight
if txType == "Money Movement" && instrument == "Future" &&
(strings.HasSuffix(rec[5], "Final settlement price") ||
strings.HasSuffix(rec[5], "Preliminary settlement price")) {
mtm = true
} else {
p.parseNonOptionTransaction(rec)
return nil
}
}
if instrument == "Future Option" {
// As of version v0.31.5 TW's CSV export for options on futures is a bit buggy
// and various columns are not set, so we get here. Work around that for now
// by extracting the columns from the symbol.
parseFuturesOptionSymbol(rec)
call = rec[16] == "CALL"
} else if strings.HasSuffix(instrument, "Option") {
glog.Fatalf("WTF, record #%d should be a non-option transaction: %q", i, rec)
} else {
// fallthrough (this is a trade but a non-option transaction)
option = false
if txType == "Receive Deliver" && instrument == "Future" && strings.HasSuffix(rec[5], "due to expiration") {
lastMark, ok := p.lastMarkToMarket[rec[3]]
if !ok {
glog.Fatalf("Future expired without ever getting marked: %s", rec)
}
rec[5] += ", last mark: " + lastMark.String()
}
}
default:
glog.Fatalf("record #%d, bad put/call type: %q", i, rec[16])
}
mult, err := strconv.ParseUint(rec[11], 10, 16)
if option && err != nil {
glog.Fatalf("record #%d, bad multiplier: %s", i, err)
}
expDate, err := time.Parse("1/02/06", rec[14])
if option && err != nil {
glog.Fatalf("record #%d, bad transaction date: %s", i, err)
}
action := rec[2]
long := strings.HasPrefix(action, "BUY")
// Pretend expiration is at 23:00 on the day of expiration so that
// expDate > tx date for transactions on the day of expiration.
if option {
expDate = expDate.Add(23 * time.Hour)
}
qty := parseDecimal(rec[7])
tx := &transaction{
date: date,
txType: txType,
action: action,
symbol: rec[3],
instrument: instrument,
description: rec[5],
value: value,
quantity: qty,
avgPrice: parseDecimal(rec[8]),
commission: comm,
fees: fees,
multiplier: uint16(mult),
underlying: rec[13],
expDate: expDate,
strike: parseDecimal(rec[15]),
option: option,
future: strings.HasPrefix(instrument, "Future"),
small: strings.HasPrefix(instrument, "Future") && isSmallFuture(rec[3]),
crypto: strings.HasPrefix(instrument, "Cryptocurrency"),
mtm: mtm,
call: call,
long: long,
open: strings.HasSuffix(action, "_TO_OPEN"),
qtyOpen: qty,
}
if !option {
tx.underlying = tx.symbol
} else if !strings.HasPrefix(tx.symbol, tx.underlying) {
glog.Fatalf("invalid symbol %q for underlying %q in %s",
tx.symbol, tx.underlying, tx)
}
// Pending clarification from TW support.
//tx.fixFees()
tx.sanityCheck()
if tx.mtm {
p.updateSettlementPrice(tx)
}
return tx
}
func isSmallFuture(u string) bool {
for _, s := range smallFuturesSymbols {
if strings.HasPrefix(u, s) {
return true
}
}
return false
}
func (p *portfolio) updateSettlementPrice(tx *transaction) {
if !tx.mtm {
glog.Fatalf("must pass a futures mark-to-market transaction in argument, got %s", tx)
}
prefix := tx.underlying + " mark to market at "
if !strings.HasPrefix(tx.description, prefix) {
glog.Fatalf("Unexpected futures mark-to-market tx description %q", tx)
}
price := tx.description[len(prefix):]
space := strings.IndexByte(price, ' ')
if space <= 0 {
glog.Fatalf("Unexpected futures mark-to-market tx description %q", tx)
}
price = price[:space]
mark, err := decimal.NewFromString(price)
if err != nil {
glog.Fatalf("Can't parse futures mark-to-market settlement value %q from %q", price, tx)
}
p.lastMarkToMarket[tx.underlying] = mark
}
// For a transction on an outright futures, return the notional amount of the
// price at which the transaction was filled.
func futuresNotional(tx *transaction) decimal.Decimal {
var contract string
if !tx.future {
glog.Fatalf("expected a futures transaction but got %s", tx)
}
points := tx.parsePrice()
if tx.small {
// Smalls have 2 digit year, regular have 1
contract = tx.underlying[:len(tx.underlying)-3]
} else {
contract = tx.underlying[:len(tx.underlying)-2]
}
pointValue, ok := futuresPoints[contract]
if !ok {
glog.Fatalf("Don't know how much a point of %s is worth in %s", contract, tx)
}
notional := points.Mul(pointValue).Mul(tx.quantity)
if tx.long {
notional = notional.Neg()
}
return notional
}
func (p *portfolio) handleTrade(tx *transaction, count bool) {
// Update cumulative stats.
if count {
if tx.option {
if tx.open {
contracts := tx.quantity.IntPart()
if tx.call {
p.callsTraded += contracts
} else {
p.putsTraded += contracts
}
}
if tx.long {
p.optionsNotionalBought = p.optionsNotionalBought.Add(tx.value)
} else {
p.optionsNotionalSold = p.optionsNotionalSold.Add(tx.value)
}
} else if tx.future { // outright futures (futures options are handled in the case above)
notional := futuresNotional(tx)
if tx.long {
p.futuresNotionalBought = p.futuresNotionalBought.Add(notional)
} else {
p.futuresNotionalSold = p.futuresNotionalSold.Add(notional)
}
} else if tx.instrument == "Equity" {
if tx.long {
p.equityNotionalBought = p.equityNotionalBought.Add(tx.value)
} else {
p.equityNotionalSold = p.equityNotionalSold.Add(tx.value)
}
} else if tx.crypto {
if tx.long {
p.cryptoNotionalBought = p.cryptoNotionalBought.Add(tx.value)
} else {
p.cryptoNotionalSold = p.cryptoNotionalSold.Add(tx.value)
}
}
}
switch tx.action {
case "SELL_TO_OPEN", "BUY_TO_OPEN":
p.openPosition(tx)
p.detectRoll(tx)
case "SELL_TO_CLOSE", "BUY_TO_CLOSE":
p.closePosition(tx, count)
p.detectRoll(tx)
default:
if tx.future && !tx.option {
// TODO check what happens for equities
if tx.value.Equal(decimal.Zero) { // Open
p.openPosition(tx)
} else { // Settle
p.closePosition(tx, count)
}
} else {
glog.Fatalf("Unhandled action type %q in %s %#v", tx.action, tx, tx)
}
}
}
func (p *portfolio) handleAssignmentOrExercise(tx *transaction, count bool) {
expired := strings.HasSuffix(tx.description, "due to expiration.")
if !expired {
costBasisAdj := tx.description == "Reversal for cost basis adjustment"
if strings.HasSuffix(tx.description, "via ACAT") || costBasisAdj {
if strings.HasPrefix(tx.description, "Removed ") {
glog.V(4).Infof("ACAT transfer out: %s (following P&L ignored)", tx)
p.closePosition(tx, false)
return
} else if costBasisAdj && !tx.open {
glog.V(8).Infof("Ignored ACAT cost basis adjustment %s", tx)
return
} else if p.ignoreacat {
glog.V(7).Infof("Ignored ACAT %s", tx)
return
}
} else if strings.HasPrefix(tx.description, "Cash settlement of") { // e.g. for VIX options that expire ITM
glog.V(4).Infof("Recording P/L for %s of %s", tx, tx.value)
// Sucks that we have to record the P/L manually here. We can't
// just fall through to calling handleTrade() below because that
// will close the position. The settlement is actually two
// transactions: one for the cash settlement, one for the
// expiration. So here we handle the cash settlement manually,
// and the next transaction will actually expire (i.e. close) the
// opening transaction, without recording any P/L.
p.recordPL(tx, tx.value)
if !tx.option {
glog.Fatalf("not an options trade %s: %#v", tx, tx)
}
if tx.long {
p.optionsNotionalSold = p.optionsNotionalSold.Add(tx.value)
} else {
p.optionsNotionalBought = p.optionsNotionalBought.Add(tx.value)
}
return
}
if tx.open && !tx.future && tx.value.Equal(decimal.Zero) {
glog.Infof("Incoming ACAT without a cost basis in %s: %s on %s",
tx.underlying, tx, tx.date)
}
// Trade caused by an assignment or exercise.
// We get two entries per position: one to tell us the position
// expired and was assigned/exercised, and one with the transaction
// in the underlying equity.
if tx.action != "" {
p.handleTrade(tx, count)
return
}
}
// We can't use closePosition() here because we don't know whether
// we're closing a long or a short position. So the best we can
// do is just close all positions for this symbol. In theory, if
// we held both long and short positions for the same option, that
// would be problematic, in practice however I don't believe that's
// possible on TW.
pos, ok := p.positions[tx.symbol]
if !ok {
glog.Fatalf("Couldn't find an opening transaction for %s %#v", tx, tx)
}
remaining := tx.quantity.Abs() // clone
for _, open := range pos.opens {
closed := decimal.Min(remaining, open.qtyOpen)
premium := open.avgPrice.Mul(closed) // Amount of premium of assigned position
p.premium = p.premium.Sub(premium)
tx.rpl = premium
glog.V(3).Infof("position %s expired by %s ==> realized P&L = %s", open, tx, premium)
remaining = remaining.Sub(closed)
// Close off this opening transaction.
open.qtyOpen = open.qtyOpen.Sub(closed)
if expired {
if count {
p.recordPL(open, premium)
}
tx.openTx = open
} else if tx.openTx != nil {
// Adjust the cost basis of the underlying position by the amount of
// premium in the original option position.
if tx.openTx.open {
glog.V(3).Infof("Adjusting cost basis of %s by %s", tx.openTx, premium)
tx.openTx.rpl = premium
} else {
glog.V(3).Infof("Adjusting realized P&L of %s by %s", tx.openTx, premium)
if count {
p.recordPL(tx.openTx, premium)
}
}
} else {
// This is kind of a hack: if we couldn't link the two assignment/exercise
// transactions together, we fall back to recording the P&L of options
// separately here (rather than trying to adjust the cost basis / P&L in the
// underlying). We need this to properly compute P&L when adding transactions
// incrementally with AddTransaction().
p.recordPL(open, premium)
}
}
if !remaining.Equal(decimal.Zero) {
p.synthesizeOpeningTransaction(tx, remaining)
}
p.purgeClosed(tx, pos)
}
// Purge closed positions from our portfolio.
func (p *portfolio) purgeClosed(tx *transaction, pos *position) {
var stillOpen int
for _, open := range pos.opens {
if !open.qtyOpen.Equal(decimal.Zero) {
stillOpen++
}