-
Notifications
You must be signed in to change notification settings - Fork 1
/
portfolio.go
1477 lines (1284 loc) · 42 KB
/
portfolio.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 2021-2023
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package portfolio
import (
"context"
"encoding/hex"
"errors"
"fmt"
"math"
"sort"
"strings"
"time"
"github.com/goccy/go-json"
"github.com/google/uuid"
"github.com/jackc/pgtype"
"github.com/jackc/pgx/v4"
"github.com/olekukonko/tablewriter"
"github.com/penny-vault/pv-api/common"
"github.com/penny-vault/pv-api/data"
"github.com/penny-vault/pv-api/data/database"
"github.com/penny-vault/pv-api/dataframe"
"github.com/penny-vault/pv-api/observability/opentelemetry"
"github.com/penny-vault/pv-api/strategies"
"github.com/rs/zerolog/log"
"github.com/zeebo/blake3"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
)
var (
ErrEmptyUserID = errors.New("user id empty")
ErrStrategyNotFound = errors.New("strategy not found")
ErrHoldings = errors.New("holdings are out of sync, cannot rebalance portfolio")
ErrInvalidSell = errors.New("refusing to sell 0 shares - cannot rebalance portfolio; target allocation broken")
ErrTimeInverted = errors.New("start date occurs after through date")
ErrPortfolioNotFound = errors.New("could not find portfolio ID in database")
ErrGenerateHash = errors.New("could not create a new hash")
ErrTransactionsOutOfOrder = errors.New("transactions would be out-of-order if executed")
ErrRebalancePercentWrong = errors.New("rebalance total must equal 1.0")
ErrSecurityPriceNotAvailable = errors.New("security price not available for date")
ErrNoTickerColumn = errors.New("no ticker column present")
ErrInvalidDateRange = errors.New("invalid date range")
)
const (
SourceName = "PV"
)
const (
SellTransaction = "SELL"
BuyTransaction = "BUY"
InterestTransaction = "INTEREST"
DividendTransaction = "DIVIDEND"
SplitTransaction = "SPLIT"
DepositTransaction = "DEPOSIT"
WithdrawTransaction = "WITHDRAW"
)
const (
SplitFactor = "SplitFactor"
)
type Activity struct {
Date time.Time
Msg string
Tags []string
}
// Model stores a portfolio and associated price data that is used for computation
type Model struct {
Portfolio *Portfolio
// private
value float64
holdings map[data.Security]float64
activities []*Activity
justifications map[string][]*Justification
}
type Period struct {
Begin time.Time
End time.Time
}
// NewPortfolio create a portfolio
func NewPortfolio(name string, startDate time.Time, initial float64) *Model {
id, _ := uuid.New().MarshalBinary()
p := Portfolio{
ID: id,
Name: name,
AccountType: Taxable,
Benchmark: "BBG000BHTMY2",
Transactions: []*Transaction{},
TaxLots: &TaxLotInfo{
AsOf: time.Time{},
Method: TaxLotFIFOMethod,
Items: make([]*TaxLot, 0, 5),
},
StartDate: startDate,
}
model := Model{
Portfolio: &p,
justifications: make(map[string][]*Justification),
}
// Create initial deposit
trxID, _ := uuid.New().MarshalBinary()
t := Transaction{
ID: trxID,
Date: startDate,
Ticker: data.CashSecurity.Ticker,
CompositeFIGI: data.CashSecurity.CompositeFigi,
Kind: DepositTransaction,
PricePerShare: 1.0,
Shares: initial,
TotalValue: initial,
Justification: nil,
}
err := computeTransactionSourceID(&t)
if err != nil {
log.Warn().Stack().Err(err).Time("TransactionDate", startDate).Str("TransactionTicker", data.CashAsset).Str("TransactionType", DepositTransaction).Msg("couldn't compute SourceID for initial deposit")
}
p.Transactions = append(p.Transactions, &t)
model.holdings = map[data.Security]float64{
data.CashSecurity: initial,
}
return &model
}
func (pm *Model) processDividends(dividends dataframe.Map) []*Transaction {
addTransactions := make([]*Transaction, 0, len(dividends))
// for each holding check if there are splits
for k, v := range dividends {
securityMetric := data.NewSecurityMetricFromString(k)
if securityMetric.SecurityObject.Ticker == data.CashAsset {
continue
}
for idx, date := range v.Dates {
// it's in range
dividend := v.Vals[0][idx]
nShares := pm.holdings[securityMetric.SecurityObject]
totalValue := nShares * dividend
// there is a dividend, record it
pm.AddActivity(date, fmt.Sprintf("%s paid a $%.2f/share dividend", k, dividend), []string{"dividend"})
justification := []*Justification{{Key: "Dividend", Value: dividend}}
trx, err := createTransaction(date, &securityMetric.SecurityObject, DividendTransaction, 1.0,
totalValue, pm.Portfolio.AccountType, justification)
if err != nil {
log.Error().Stack().Err(err).Msg("failed to create transaction")
}
trx.Memo = fmt.Sprintf("$%.2f/share dividend", dividend)
// update cash position in holdings
pm.holdings[data.CashSecurity] += totalValue
if pm.Portfolio.TaxLots.CheckIfDividendIsQualified(trx) {
trx.TaxDisposition = QualifiedDividend
} else {
trx.TaxDisposition = NonQualifiedDividend
}
addTransactions = append(addTransactions, trx)
}
}
return addTransactions
}
func (pm *Model) processSplits(splits dataframe.Map) []*Transaction {
addTransactions := make([]*Transaction, 0, len(splits))
// for each holding check if there are splits
for k, v := range splits {
securityMetric := data.NewSecurityMetricFromString(k)
if securityMetric.SecurityObject.Ticker == data.CashAsset {
continue
}
for idx, date := range v.Dates {
// it's in range
splitFactor := v.Vals[0][idx]
nShares := pm.holdings[securityMetric.SecurityObject]
shares := splitFactor * nShares
// there is a split, record it
pm.AddActivity(date, fmt.Sprintf("shares of %s split by a factor of %.2f", k, splitFactor), []string{"split"})
justification := []*Justification{{Key: SplitFactor, Value: splitFactor}}
trx, err := createTransaction(date, &securityMetric.SecurityObject, SplitTransaction, 0.0, shares,
pm.Portfolio.AccountType, justification)
trx.Memo = fmt.Sprintf("split by a factor of %.2f", splitFactor)
pm.Portfolio.TaxLots.AdjustForSplit(&securityMetric.SecurityObject, splitFactor)
if err != nil {
log.Error().Stack().Err(err).Msg("failed to create transaction")
}
addTransactions = append(addTransactions, trx)
// update holdings
pm.holdings[securityMetric.SecurityObject] = shares
}
}
return addTransactions
}
// FillCorporateActions finds any corporate actions and creates transactions for them. The
// search occurs from the date of the last transaction to `through`
func (pm *Model) FillCorporateActions(ctx context.Context, through time.Time) error {
_, span := otel.Tracer(opentelemetry.Name).Start(ctx, "FillCorporateActions")
defer span.End()
p := pm.Portfolio
// nothing to do if there are no transactions
n := len(p.Transactions)
if n == 0 {
return nil
}
subLog := log.With().Str("PortfolioID", hex.EncodeToString(p.ID)).Str("Strategy", p.StrategyShortcode).Logger()
// check what date range to consider
lastTrxDate := p.Transactions[n-1].Date
from := time.Date(lastTrxDate.Year(), lastTrxDate.Month(), lastTrxDate.Day()+1, 0, 0, 0, 0, common.GetTimezone())
if from.After(through) {
// nothing to do
return nil
}
subLog.Debug().Time("From", from).Time("Through", through).Msg("evaluating corporate actions")
// Load split & dividend history
cnt := 0
for k := range pm.holdings {
if k.Ticker != data.CashAsset {
cnt++
}
}
if cnt == 0 {
return nil // nothing to do
}
holdings := make([]*data.Security, 0, len(pm.holdings))
for holding := range pm.holdings {
holdings = append(holdings, &data.Security{
Ticker: holding.Ticker,
CompositeFigi: holding.CompositeFigi,
})
}
dividends, err := data.NewDataRequest(holdings...).Metrics(data.MetricDividendCash).Between(from, through)
if err != nil {
log.Error().Err(err).Msg("could not load dividends")
return err
}
splits, err := data.NewDataRequest(holdings...).Metrics(data.MetricSplitFactor).Between(from, through)
if err != nil {
log.Error().Err(err).Msg("could not load splits")
return err
}
divTrx := pm.processDividends(dividends)
splitTrx := pm.processSplits(splits)
addTransactions := make([]*Transaction, 0, len(divTrx)+len(splitTrx))
addTransactions = append(addTransactions, divTrx...)
addTransactions = append(addTransactions, splitTrx...)
sort.SliceStable(addTransactions, func(i, j int) bool {
a := addTransactions[i]
b := addTransactions[j]
if a.Date.Equal(b.Date) {
if a.Kind == b.Kind {
// same type sort by ID
return hex.EncodeToString(a.ID) < hex.EncodeToString(b.ID)
}
// different types dividend first then splits
return a.Kind == DividendTransaction
}
return a.Date.Before(b.Date)
})
p.Transactions = append(p.Transactions, addTransactions...)
return nil
}
// RebalanceTo rebalance the portfolio to the target percentages
// Assumptions: can only rebalance current holdings
func (pm *Model) RebalanceTo(ctx context.Context, allocation *data.SecurityAllocation, justifications []*Justification) error {
ctx, span := otel.Tracer(opentelemetry.Name).Start(ctx, "RebalanceTo")
defer span.End()
span.SetAttributes(
attribute.KeyValue{
Key: "date",
Value: attribute.StringValue(allocation.Date.Format("2006-01-02")),
},
)
p := pm.Portfolio
err := pm.FillCorporateActions(ctx, allocation.Date)
if err != nil {
return err
}
nTrx := len(p.Transactions)
if nTrx > 0 {
lastDate := p.Transactions[nTrx-1].Date
if lastDate.After(allocation.Date) {
log.Error().Stack().Time("Date", allocation.Date).Time("LastTransactionDate", lastDate).
Msg("cannot rebalance portfolio when date is before last transaction date")
return ErrTransactionsOutOfOrder
}
}
// check that target sums to 1.0
var total float64
for _, v := range allocation.Members {
total += v
}
// Allow for floating point error
diff := math.Abs(1.0 - total)
if diff > 1.0e-11 {
log.Error().Stack().Float64("TotalPercentAllocated", total).Time("Date", allocation.Date).
Msg("TotalPercentAllocated must equal 1.0")
return ErrRebalancePercentWrong
}
// cash position of the portfolio
var cash float64
if currCash, ok := pm.holdings[data.CashSecurity]; ok {
cash += currCash
}
// get the current value of non-cash holdings
securityValue, err := pm.getPortfolioSecuritiesValue(allocation.Date)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, "security price data not available")
return err
}
// compute the investable value in the portfolio
investable := cash + securityValue
pm.value = investable
// process all targets
sells := make([]*Transaction, 0, 10)
buys := make([]*Transaction, 0, 10)
// sell any holdings that we no longer want
for security, shares := range pm.holdings {
if security.Ticker == data.CashAsset {
continue
}
if shares <= 1.0e-5 {
log.Warn().Stack().Str("Ticker", security.Ticker).Float64("Shares", shares).Msg("holdings are out of sync")
return ErrHoldings
}
if _, ok := allocation.Members[security]; !ok {
price := pm.getPriceSafe(allocation.Date, &security)
t, err := createTransaction(allocation.Date, &security, SellTransaction, price, shares, pm.Portfolio.AccountType, justifications)
if err != nil {
return err
}
cash += t.TotalValue
sells = append(sells, t)
}
}
// purchase holdings based on target
newHoldings := make(map[data.Security]float64)
for security, targetPercent := range allocation.Members {
targetDollars := investable * targetPercent
t, numShares, err := pm.modifyPosition(allocation.Date, &security, targetDollars, justifications)
if err != nil {
// don't fail if position could not be modified, just continue -- writing off asset as $0
log.Warn().Err(err).Time("Date", allocation.Date).Str("Ticker", security.Ticker).Msg("writing off asset")
continue
}
if t != nil {
switch t.Kind {
case SellTransaction:
sells = append(sells, t)
cash += t.TotalValue
case BuyTransaction:
buys = append(buys, t)
cash -= t.TotalValue
}
}
newHoldings[security] = numShares
}
sells = pm.Portfolio.TaxLots.Update(allocation.Date, buys, sells)
p.Transactions = append(p.Transactions, sells...)
p.Transactions = append(p.Transactions, buys...)
if cash > 1.0e-05 {
newHoldings[data.CashSecurity] = cash
}
pm.holdings = newHoldings
p.CurrentHoldings = buildHoldingsArray(allocation.Date, newHoldings)
return nil
}
// Table formats the portfolio into a human-readable string representation
func (pm *Model) Table() string {
s := &strings.Builder{}
s.WriteString(
fmt.Sprintf("Name: %s (%s)\n",
pm.Portfolio.Name,
hex.EncodeToString(pm.Portfolio.ID),
),
)
years := int(pm.Portfolio.EndDate.Sub(pm.Portfolio.StartDate)/(time.Hour*24)) / 365
s.WriteString(
fmt.Sprintf("Time Period: %s to %s (%dy)\n\n",
pm.Portfolio.StartDate.Format("2006-01-02"),
pm.Portfolio.EndDate.Format("2006-01-02"),
years,
),
)
if len(pm.Portfolio.Transactions) == 0 {
return "<NO DATA>" // nothing to do as there is no data available in the dataframe
}
// construct table header
tableCols := append([]string{"Date"}, "Action", "Security", "Shares", "Price per Share", "Total")
// initialize table
table := tablewriter.NewWriter(s)
table.SetHeader(tableCols)
footer := make([]string, len(tableCols))
footer[0] = "Num Rows"
footer[1] = fmt.Sprintf("%d", len(pm.Portfolio.Transactions))
table.SetFooter(footer)
table.SetBorder(false) // Set Border to false
for _, trx := range pm.Portfolio.Transactions {
row := []string{
trx.Date.Format("2006-01-02"),
trx.Kind,
trx.Ticker,
fmt.Sprintf("%.2f", trx.Shares),
fmt.Sprintf("$%.2f", trx.PricePerShare),
fmt.Sprintf("$%.2f", trx.TotalValue),
}
table.Append(row)
}
table.Render()
return s.String()
}
// TargetPortfolio invests the portfolio in the ratios specified by the PieHistory `target`.
func (pm *Model) TargetPortfolio(ctx context.Context, target data.PortfolioPlan) error {
ctx, span := otel.Tracer(opentelemetry.Name).Start(ctx, "TargetPortfolio")
defer span.End()
p := pm.Portfolio
log.Info().Msg("building target portfolio")
if len(target) == 0 {
log.Debug().Stack().Msg("target rows = 0; nothing to do!")
return nil
}
// Set time range of portfolio
p.EndDate = target.EndDate()
now := time.Now()
if now.Before(p.EndDate) {
p.EndDate = now
}
span.SetAttributes(
attribute.KeyValue{
Key: "StartDate",
Value: attribute.StringValue(p.StartDate.Format("2006-01-02")),
},
attribute.KeyValue{
Key: "EndDate",
Value: attribute.StringValue(p.EndDate.Format("2006-01-02")),
},
)
// Adjust first transaction to the target portfolio's first date if
// there are no other transactions in the portfolio
if len(p.Transactions) == 1 {
p.StartDate = target.StartDate()
p.Transactions[0].Date = p.StartDate
}
// Create transactions
for _, allocation := range target {
// HACK - if the date is Midnight adjust to market close (i.e. 4pm EST)
// This should really be set correctly for the day. The problem is if the
// transaction is on a day where the market closes early (either because of
// a holiday or because a "circuit-breaker" threshold was reached) we do
// not have a reliable datasource that tells us the time the market closed.
//
// Generally speaking getting the time slightly off here is immaterial so this
// is an OK hack
if allocation.Date.Hour() == 0 && allocation.Date.Minute() == 0 && allocation.Date.Second() == 0 {
allocation.Date = allocation.Date.Add(time.Hour * 16)
}
justifications := make([]*Justification, 0, len(allocation.Justifications))
for k, v := range allocation.Justifications {
j := &Justification{
Key: k,
Value: v,
}
justifications = append(justifications, j)
}
pm.justifications[allocation.Date.String()] = justifications
err := pm.RebalanceTo(ctx, allocation, justifications)
if err != nil {
return err
}
}
return nil
}
// BuildPredictedHoldings creates a PortfolioHoldingItem from a date, target map, and justification map
func BuildPredictedHoldings(tradeDate time.Time, target map[data.Security]float64, justificationMap map[string]float64) *PortfolioHoldingItem {
holdings := make([]*ReportableHolding, 0, len(target))
for k, v := range target {
h := ReportableHolding{
Ticker: k.Ticker,
CompositeFIGI: k.CompositeFigi,
Shares: v * 100.0,
PercentPortfolio: float32(v),
}
holdings = append(holdings, &h)
}
justification := make([]*Justification, 0, len(justificationMap))
for k, v := range justificationMap {
j := Justification{
Key: k,
Value: v,
}
justification = append(justification, &j)
}
return &PortfolioHoldingItem{
Time: tradeDate,
Holdings: holdings,
Justification: justification,
Predicted: true,
}
}
// UpdateTransactions calculates new transactions based on the portfolio strategy
// from the portfolio end date to `through`
func (pm *Model) UpdateTransactions(ctx context.Context, through time.Time) error {
ctx, span := otel.Tracer(opentelemetry.Name).Start(ctx, "portfolio.UpdateTransactions")
defer span.End()
p := pm.Portfolio
trxCalcStartDate := p.EndDate.AddDate(0, -6, 1)
addTrxOnDate := p.EndDate.AddDate(0, 0, 1)
subLog := log.With().Str("PortfolioID", hex.EncodeToString(p.ID)).Str("Strategy", p.StrategyShortcode).Logger()
if through.Before(trxCalcStartDate) {
span.SetStatus(codes.Error, "cannot update portfolio due to dates being out of order")
subLog.Error().Stack().
Time("Begin", trxCalcStartDate).
Time("End", through).
Msg("cannot update portfolio dates are out of order")
return ErrInvalidDateRange
}
arguments := make(map[string]json.RawMessage)
if err := json.Unmarshal([]byte(p.StrategyArguments), &arguments); err != nil {
subLog.Error().Stack().Err(err).Msg("could not unmarshal strategy arguments")
return err
}
strategy, ok := strategies.StrategyMap[p.StrategyShortcode]
if !ok {
span.SetStatus(codes.Error, "strategy not found")
subLog.Error().Stack().Msg("portfolio strategy not found")
return ErrStrategyNotFound
}
stratObject, err := strategy.Factory(arguments)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, "failed to initialize portfolio strategy")
subLog.Error().Err(err).Stack().Msg("failed to initialize portfolio strategy")
return err
}
subLog.Info().Time("TrxCalcStartDate", trxCalcStartDate).Time("AddTrxOnDate", addTrxOnDate).Msg("computing portfolio strategy over date period")
targetPortfolio, predictedAssets, err := stratObject.Compute(ctx, trxCalcStartDate, through)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, "failed to execute portfolio strategy")
subLog.Error().Err(err).Stack().Msg("failed to execute portfolio strategy")
return err
}
// thin the targetPortfolio to only include info on or after the startDate
targetPortfolio = targetPortfolio.Trim(addTrxOnDate, through)
err = pm.TargetPortfolio(ctx, targetPortfolio)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, "failed to apply target porfolio")
subLog.Error().Err(err).Msg("failed to apply target portfolio")
return err
}
// make sure any corporate actions are applied
if err := pm.FillCorporateActions(ctx, through); err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, "could not update corporate actions")
subLog.Error().Err(err).Msg("could not update corporate actions")
return err
}
pm.Portfolio.PredictedAssets = BuildPredictedHoldings(predictedAssets.Date, predictedAssets.Members, predictedAssets.Justifications)
p.EndDate = through
return nil
}
// DATABASE FUNCTIONS
// LOAD
func (pm *Model) LoadTransactionsFromDB(ctx context.Context) error {
p := pm.Portfolio
trx, err := database.TrxForUser(ctx, p.UserID)
if err != nil {
log.Error().Stack().Err(err).
Str("PortfolioID", hex.EncodeToString(p.ID)).
Str("UserID", p.UserID).
Msg("unable to get database transaction object")
return nil
}
// Get portfolio transactions
transactionSQL := `SELECT
id,
event_date,
cleared,
commission,
composite_figi,
justification,
transaction_type,
memo,
price_per_share::double precision,
num_shares::double precision,
gain_loss::double precision,
source,
encode(source_id, 'hex'),
tags,
tax_type,
ticker,
total_value
FROM portfolio_transactions
WHERE portfolio_id=$1 AND user_id=$2
ORDER BY sequence_num`
rows, err := trx.Query(ctx, transactionSQL, p.ID, p.UserID)
if err != nil {
log.Error().Stack().Err(err).
Str("PortfolioID", hex.EncodeToString(p.ID)).
Str("UserID", p.UserID).
Str("Query", transactionSQL).
Msg("could not load portfolio transactions from database")
if err := trx.Rollback(ctx); err != nil {
log.Error().Stack().Err(err).Msg("could not rollback transaction")
}
return err
}
transactions := make([]*Transaction, 0, 1000)
for rows.Next() {
t := Transaction{}
var compositeFIGI pgtype.Text
var memo pgtype.Text
var taxDisposition pgtype.Text
var pricePerShare pgtype.Float8
var shares pgtype.Float8
var gainLoss pgtype.Float8
var sourceID pgtype.Text
err := rows.Scan(&t.ID, &t.Date, &t.Cleared, &t.Commission, &compositeFIGI,
&t.Justification, &t.Kind, &memo, &pricePerShare, &shares, &gainLoss, &t.Source,
&sourceID, &t.Tags, &taxDisposition, &t.Ticker, &t.TotalValue)
if err != nil {
log.Warn().Stack().Err(err).
Str("PortfolioID", hex.EncodeToString(p.ID)).
Str("UserID", p.UserID).
Str("Query", transactionSQL).
Msg("failed scanning row into transaction fields")
if err := trx.Rollback(ctx); err != nil {
log.Error().Stack().Err(err).Msg("could not rollback transaction")
}
return err
}
if compositeFIGI.Status == pgtype.Present {
t.CompositeFIGI = compositeFIGI.String
}
if memo.Status == pgtype.Present {
t.Memo = memo.String
}
if taxDisposition.Status == pgtype.Present {
t.TaxDisposition = taxDisposition.String
}
if pricePerShare.Status == pgtype.Present {
t.PricePerShare = pricePerShare.Float
}
if shares.Status == pgtype.Present {
t.Shares = shares.Float
}
if gainLoss.Status == pgtype.Present {
t.GainLoss = gainLoss.Float
}
if sourceID.Status == pgtype.Present {
t.SourceID = sourceID.String
}
// put event date in the correct time zone
t.Date = time.Date(t.Date.Year(), t.Date.Month(), t.Date.Day(), 16, 0, 0, 0, common.GetTimezone())
transactions = append(transactions, &t)
}
p.Transactions = transactions
if err := trx.Commit(ctx); err != nil {
log.Error().Stack().Err(err).Msg("could not commit transaction to database")
}
return nil
}
func LoadFromDB(ctx context.Context, portfolioIDs []string, userID string) ([]*Model, error) {
subLog := log.With().Str("UserID", userID).Strs("PortfolioIDs", portfolioIDs).Logger()
if userID == "" {
subLog.Error().Stack().Msg("userID cannot be an empty string")
return nil, ErrEmptyUserID
}
trx, err := database.TrxForUser(ctx, userID)
if err != nil {
subLog.Error().Stack().Msg("failed to create database transaction for user")
return nil, err
}
var rows pgx.Rows
if len(portfolioIDs) > 0 {
portfolioSQL := `
SELECT
id,
name,
strategy_shortcode,
arguments,
start_date,
CASE WHEN end_date IS NULL THEN start_date
ELSE end_DATE
END AS end_date,
holdings,
notifications,
benchmark
FROM
portfolios
WHERE
id = ANY ($1) AND user_id=$2`
rows, err = trx.Query(ctx, portfolioSQL, portfolioIDs, userID)
} else {
portfolioSQL := `
SELECT
id,
name,
strategy_shortcode,
arguments,
start_date,
CASE WHEN end_date IS NULL THEN start_date
ELSE end_DATE
END AS end_date,
holdings,
notifications,
benchmark
FROM
portfolios
WHERE
user_id=$1`
rows, err = trx.Query(ctx, portfolioSQL, userID)
}
if err != nil {
subLog.Warn().Stack().Err(err).Msg("could not load portfolio from database")
if err := trx.Rollback(ctx); err != nil {
log.Error().Stack().Err(err).Msg("could not rollback transaction")
}
return nil, err
}
sz := len(portfolioIDs)
if sz == 0 {
sz = 10
}
resultSet := make([]*Model, 0, sz)
for rows.Next() {
p := &Portfolio{
UserID: userID,
Transactions: []*Transaction{},
}
pm := &Model{
Portfolio: p,
justifications: make(map[string][]*Justification),
}
tz := common.GetTimezone()
tmpHoldings := make(map[string]float64)
err = rows.Scan(&p.ID, &p.Name, &p.StrategyShortcode, &p.StrategyArguments, &p.StartDate, &p.EndDate, &tmpHoldings, &p.Notifications, &p.Benchmark)
pm.holdings = make(map[data.Security]float64, len(tmpHoldings))
for k, v := range tmpHoldings {
if k == data.CashAsset {
pm.holdings[data.CashSecurity] = v
} else {
security, err := data.SecurityFromFigi(k)
if err != nil {
subLog.Warn().Str("CompositeFigi", k).Msg("portfolio holds inactive security")
continue
}
pm.holdings[*security] = v
}
}
p.StartDate = p.StartDate.In(tz)
p.EndDate = p.EndDate.In(tz)
if err != nil {
subLog.Warn().Stack().Err(err).Msg("could not load portfolio from database")
if err := trx.Rollback(ctx); err != nil {
log.Error().Stack().Err(err).Msg("could not rollback transaction")
}
return nil, err
}
p.CurrentHoldings = buildHoldingsArray(time.Now(), pm.holdings)
resultSet = append(resultSet, pm)
}
if len(resultSet) == 0 && len(portfolioIDs) != 0 {
return nil, ErrPortfolioNotFound
}
if err := trx.Commit(ctx); err != nil {
log.Error().Stack().Err(err).Msg("could not commit transaction to database")
}
return resultSet, nil
}
func (pm *Model) AddActivity(date time.Time, msg string, tags []string) {
if pm.activities == nil {
pm.activities = make([]*Activity, 0, 5)
}
pm.activities = append(pm.activities, &Activity{
Date: date,
Msg: msg,
Tags: tags,
})
}
func (pm *Model) SaveActivities(ctx context.Context) error {
p := pm.Portfolio
userID := p.UserID
subLog := log.With().Str("PortfolioID", hex.EncodeToString(p.ID)).Str("Strategy", p.StrategyShortcode).Str("UserID", userID).Logger()
if pm.activities == nil {
pm.activities = make([]*Activity, 0, 5)
}
// Save to database
trx, err := database.TrxForUser(ctx, userID)
if err != nil {
subLog.Error().Stack().Err(err).Msg("unable to get database transaction for user")
return err
}
for _, activity := range pm.activities {
sql := `INSERT INTO activity ("user_id", "portfolio_id", "event_date", "activity", "tags") VALUES ($1, $2, $3, $4, $5)`
if _, err := trx.Exec(ctx, sql, userID, p.ID, activity.Date, activity.Msg, activity.Tags); err != nil {
subLog.Error().Err(err).Msg("could not create activity")
if err := trx.Rollback(ctx); err != nil {
log.Error().Stack().Err(err).Msg("could not rollback transaction")
}
return err
}
}
err = trx.Commit(ctx)
if err != nil {
subLog.Error().Stack().Err(err).Msg("failed to commit portfolio transaction")
if err := trx.Rollback(ctx); err != nil {
log.Error().Stack().Err(err).Msg("could not rollback transaction")
}
return err
}
return nil
}
func (pm *Model) SetStatus(ctx context.Context, msg string) error {
p := pm.Portfolio
userID := p.UserID
subLog := log.With().Str("PortfolioID", hex.EncodeToString(p.ID)).Str("Strategy", p.StrategyShortcode).Str("UserID", userID).Str("Status", msg).Logger()
// Save to database
trx, err := database.TrxForUser(ctx, userID)
if err != nil {
subLog.Error().Stack().Err(err).Msg("unable to get database transaction for user")
return err
}
sql := `UPDATE portfolios SET status=$1 WHERE id=$2`
if _, err := trx.Exec(ctx, sql, msg, p.ID); err != nil {
subLog.Error().Err(err).Msg("could not update portfolio status")
}
err = trx.Commit(ctx)
if err != nil {
subLog.Error().Stack().Err(err).Msg("failed to commit portfolio transaction")
if err := trx.Rollback(ctx); err != nil {
log.Error().Stack().Err(err).Msg("could not rollback transaction")
}
return err
}
return nil
}
// Save portfolio to database along with all transaction data
func (pm *Model) Save(ctx context.Context, userID string) error {
p := pm.Portfolio
p.UserID = userID
subLog := log.With().Str("PortfolioID", hex.EncodeToString(p.ID)).Str("Strategy", p.StrategyShortcode).Str("UserID", userID).Logger()
if err := pm.SaveActivities(ctx); err != nil {
subLog.Error().Err(err).Msg("could not save activities")
}
// Save to database
trx, err := database.TrxForUser(ctx, userID)
if err != nil {
subLog.Error().Stack().Err(err).Msg("unable to get database transaction for user")
return err
}
err = pm.SaveWithTransaction(ctx, trx, userID, false)
if err != nil {
subLog.Error().Stack().Err(err).Msg("failed to create portfolio transactions")
if err := trx.Rollback(ctx); err != nil {
log.Error().Stack().Err(err).Msg("could not rollback transaction")
}