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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
use crate::asset::SubAllocations;
use anyhow::{anyhow, Context, Result};
use chrono::{NaiveDate, Duration};
use std::{
collections::HashMap,
fmt,
fs::File,
io::{BufRead, BufReader},
ops::{Add, Div, Mul, Sub},
vec::Vec,
};
use time::{macros::format_description, OffsetDateTime};
use yahoo_finance_api as yahoo;
// STOCK_DESCRIPTION holds the descriptions for the stock symbols which is used to print and
// display
lazy_static! {
static ref STOCK_DESCRIPTION: HashMap<StockSymbol, &'static str> = {
let mut m = HashMap::new();
m.insert(StockSymbol::VV, "US large cap");
m.insert(StockSymbol::VO, "US mid cap");
m.insert(StockSymbol::VB, "US small cap");
m.insert(StockSymbol::VTC, "US total corporate bond");
m.insert(StockSymbol::BND, "US total bond");
m.insert(StockSymbol::VXUS, "Total international stock");
m.insert(StockSymbol::VWO, "Emerging markets stock");
m.insert(StockSymbol::BNDX, "Total international bond");
m.insert(StockSymbol::VTIP, "Inflation protected securities");
m.insert(StockSymbol::VTI, "Total domestic stock");
m.insert(StockSymbol::VTIVX, "2045 Retirement fund");
m
};
}
/// StockSymbol is an enum which holds all stock symbols which are supported. Empty is used to
/// initiated structs which use this enum. Other<String> is a holder of any stock that is not
/// supported, where the String is the stock symbol.
#[derive(Clone, Eq, Hash, PartialEq, Debug)]
pub enum StockSymbol {
VXUS,
BNDX,
VTIP,
BND,
VWO,
VO,
VB,
VTC,
VV,
VMFXX,
VTI,
VTIVX,
Empty,
Other(String),
}
impl StockSymbol {
/// new creates a new StockSymbol enum based on the string value.
///
/// # Example
///
/// ```
/// use vapore::holdings::StockSymbol;
///
/// let bnd = StockSymbol::new("BND");
/// assert_eq!(bnd, StockSymbol::BND);
/// ```
pub fn new(symbol: &str) -> Self {
match symbol {
"VXUS" => StockSymbol::VXUS,
"BNDX" => StockSymbol::BNDX,
"VTIP" => StockSymbol::VTIP,
"BND" => StockSymbol::BND,
"VWO" => StockSymbol::VWO,
"VO" => StockSymbol::VO,
"VB" => StockSymbol::VB,
"VTC" => StockSymbol::VTC,
"VV" => StockSymbol::VV,
"VMFXX" => StockSymbol::VMFXX,
"VTI" => StockSymbol::VTI,
"VTIVX" => StockSymbol::VTIVX,
"" => StockSymbol::Empty,
_ => {
eprintln!("{} is not supported within this algorithm\n", symbol);
StockSymbol::Other(symbol.to_string())
}
}
}
/// description returns a string of the StockSymbol description. If the stock is not
/// supported, a "No description" String is returned.
///
/// # Example
///
/// ```
/// use vapore::holdings::StockSymbol;
///
/// let bnd = StockSymbol::new("BND");
/// let bnd_description = bnd.description();
/// assert_eq!(bnd_description, "BND: US total bond");
///
/// ```
pub fn description(&self) -> String {
let description_option = STOCK_DESCRIPTION.get(self);
if let Some(description) = description_option {
format!("{:?}: {}", self, description)
} else {
format!("No description for {:?}", self)
}
}
}
/// all_stock_descriptions returns a String containing the description of all stocks which are
/// supported with each separated by a new line. This is used to display on screen or write to
/// file all of the descriptions.
///
/// # Example
///
/// ```
/// use vapore::holdings;
///
/// let descriptions = holdings::all_stock_descriptions();
/// println!("{}", descriptions);
///
/// ```
pub fn all_stock_descriptions() -> String {
let mut descriptions = String::new();
for symbol in [
StockSymbol::VV,
StockSymbol::VO,
StockSymbol::VB,
StockSymbol::VTC,
StockSymbol::BND,
StockSymbol::VXUS,
StockSymbol::VWO,
StockSymbol::BNDX,
StockSymbol::VTIP,
StockSymbol::VTI,
StockSymbol::VTIVX,
] {
descriptions.push_str(&symbol.description());
descriptions.push('\n')
}
descriptions.pop();
descriptions
}
#[derive(Clone)]
pub struct StockInfo {
pub account_number: u32,
pub symbol: StockSymbol,
pub share_price: f32,
pub shares: f32,
pub total_value: f32,
account_added: bool,
symbol_added: bool,
share_price_added: bool,
shares_added: bool,
total_value_added: bool,
}
impl StockInfo {
/// new initializes a new StockInfo struct. Account number, symbol, share price etc. can then
/// be added with the other methods.
///
/// # Example
///
/// ```
/// use vapore::holdings;
///
/// let mut new_stock = holdings::StockInfo::new();
/// ```
pub fn new() -> Self {
StockInfo {
account_number: 0,
symbol: StockSymbol::Empty,
share_price: 0.0,
shares: 0.0,
total_value: 0.0,
account_added: false,
symbol_added: false,
share_price_added: false,
shares_added: false,
total_value_added: false,
}
}
/// add_account adds the vanguard account number to the StockInfo struct
///
/// # Example
///
/// ```
/// use vapore::holdings;
///
/// let mut new_stock = holdings::StockInfo::new();
/// new_stock.add_account(123456789);
///
/// assert_eq!(new_stock.account_number, 123456789);
/// ```
pub fn add_account(&mut self, account_number: u32) {
self.account_number = account_number;
self.account_added = true;
}
/// add_symbol adds the stock symbol to the StockInfo struct
///
/// # Example
///
/// ```
/// use vapore::holdings;
///
/// let mut new_stock = holdings::StockInfo::new();
/// new_stock.add_account(123456789);
/// new_stock.add_symbol(holdings::StockSymbol::BND);
///
/// assert_eq!(new_stock.symbol, holdings::StockSymbol::BND);
/// ```
pub fn add_symbol(&mut self, symbol: StockSymbol) {
self.symbol = symbol;
self.symbol_added = true;
}
/// add_share_price adds the stock quote price to the StockInfo struct
///
/// # Example
///
/// ```
/// use vapore::holdings;
///
/// let mut new_stock = holdings::StockInfo::new();
/// new_stock.add_account(123456789);
/// new_stock.add_symbol(holdings::StockSymbol::BND);
/// new_stock.add_share_price(234.50);
///
/// assert_eq!(new_stock.share_price, 234.50);
/// ```
pub fn add_share_price(&mut self, share_price: f32) {
self.share_price = share_price;
self.share_price_added = true;
}
/// add_share adds the stock total shares to the StockInfo struct
///
/// # Example
///
/// ```
/// use vapore::holdings;
///
/// let mut new_stock = holdings::StockInfo::new();
/// new_stock.add_account(123456789);
/// new_stock.add_symbol(holdings::StockSymbol::BND);
/// new_stock.add_share_price(234.50);
/// new_stock.add_shares(10.0)
///
/// assert_eq!(new_stock.shares, 10.0);
/// ```
pub fn add_shares(&mut self, share_num: f32) {
self.shares = share_num;
self.shares_added = true;
}
/// add_total_value adds the account total value of the stock to the StockInfo struct
///
/// # Example
///
/// ```
/// use vapore::holdings;
///
/// let mut new_stock = holdings::StockInfo::new();
/// new_stock.add_account(123456789);
/// new_stock.add_symbol(holdings::StockSymbol::BND);
/// new_stock.add_share_price(234.50);
/// new_stock.add_total_value(5000.00);
///
/// assert_eq!(new_stock.total_value, 5000.00);
/// ```
pub fn add_total_value(&mut self, total_value: f32) {
self.total_value = total_value;
self.total_value_added = true;
}
/// finished returns a bool of whether or not all struct values have been added.
///
/// # Example
///
/// ```
/// use vapore::holdings;
///
/// let mut new_stock = holdings::StockInfo::new();
/// new_stock.add_account(123456789);
/// new_stock.add_symbol(holdings::StockSymbol::BND);
/// new_stock.add_share_price(234.50);
/// new_stock.add_total_value(5000.00);
/// new_stock.add_shares(10.0);
///
/// assert!(new_stock.finished());
///
/// let empty_stock = holdings::StockInfo::new();
/// assert!(!empty_stock.finished())
/// ```
pub fn finished(&self) -> bool {
[
self.account_added,
self.symbol_added,
self.share_price_added,
self.shares_added,
self.total_value_added,
]
.iter()
.all(|value| *value)
}
}
impl Default for StockInfo {
fn default() -> Self {
Self::new()
}
}
pub async fn get_yahoo_quote(stock_symbol: StockSymbol) -> Result<f32> {
let stock_str = match stock_symbol {
StockSymbol::VO => "VO",
StockSymbol::VB => "VB",
StockSymbol::VV => "VV",
StockSymbol::BND => "BND",
StockSymbol::VWO => "VWO",
StockSymbol::VTC => "VTC",
StockSymbol::VXUS => "VXUS",
StockSymbol::BNDX => "BNDX",
StockSymbol::VTIP => "VTIP",
StockSymbol::VTI => "VTI",
StockSymbol::VTIVX => "VTIVX",
_ => "none",
};
if stock_str == "none" {
eprintln!("Stock symbol not supported for yahoo retrieval");
Ok(0.0)
} else {
let provider = yahoo::YahooConnector::new()?;
let response_err = provider
.get_latest_quotes(stock_str, "1m")
.await
.with_context(|| format!("Latest quote error for: {}", stock_str));
// If the market is closed, an error occurs. If so, get quote history then the last quote
if let Ok(response) = response_err {
Ok(response.last_quote()?.close as f32)
} else {
let today = OffsetDateTime::now_utc();
let week_ago = today - time::Duration::days(7);
let response = provider
.get_quote_history(stock_str, week_ago, today)
.await
.with_context(|| {
format!("Both attempts at quote retrieval failed for: {}", stock_str)
})?;
Ok(response.last_quote()?.close as f32)
}
}
}
pub async fn get_yahoo_eoy_quote(stock_symbol: StockSymbol, year: u32) -> Result<f32> {
let stock_str = match stock_symbol {
StockSymbol::VO => "VO",
StockSymbol::VB => "VB",
StockSymbol::VV => "VV",
StockSymbol::BND => "BND",
StockSymbol::VWO => "VWO",
StockSymbol::VTC => "VTC",
StockSymbol::VXUS => "VXUS",
StockSymbol::BNDX => "BNDX",
StockSymbol::VTIP => "VTIP",
StockSymbol::VTI => "VTI",
StockSymbol::VTIVX => "VTIVX",
_ => "none",
};
if stock_str == "none" {
eprintln!("Stock symbol not supported for yahoo retrieval");
Ok(0.0)
} else {
let provider = yahoo::YahooConnector::new()?;
let format = format_description!(
"[year]-[month]-[day] [hour]:[minute]:[second] [offset_hour sign:mandatory]"
);
let start =
OffsetDateTime::parse(&format!("{}-12-25 00:00:01 -05", year), format)?;
let stop =
OffsetDateTime::parse(&format!("{}-12-31 23:59:59 -05", year), format)?;
let response = provider
.get_quote_history(stock_str, start, stop)
.await
.with_context(|| format!("Quote history error for: {}", stock_str))?;
Ok(response.quotes()?.last().unwrap().close as f32)
}
}
/// AddType is an enum used to distinguish between when a stock quote or an account holdings is
/// wanted for input into a ShareValues struct.
pub enum AddType {
StockPrice,
HoldingValue,
}
/// ShareValues holds the values for the supported ETF stocks. The value can represent price,
/// holding value, stock quantity etc.
#[derive(Clone, PartialEq, Debug, Copy)]
pub struct ShareValues {
vxus: f32,
bndx: f32,
bnd: f32,
vwo: f32,
vo: f32,
vb: f32,
vtc: f32,
vv: f32,
vtip: f32,
vti: f32,
vtivx: f32,
vmfxx: f32,
outside_bond: f32,
outside_stock: f32,
}
impl ShareValues {
/// new creates a new ShareValues struct where all values are set to 0. This is used within
/// vapore to create a new struct for account holdings, etc.
///
/// # Example
/// ```
/// use vapore::holdings;
///
/// let new_values = holdings::ShareValues::new();
/// ```
pub fn new() -> Self {
ShareValues {
vxus: 0.0,
bndx: 0.0,
vtip: 0.0,
vti: 0.0,
vtivx: 0.0,
bnd: 0.0,
vwo: 0.0,
vo: 0.0,
vb: 0.0,
vtc: 0.0,
vv: 0.0,
vmfxx: 0.0,
outside_bond: 0.0,
outside_stock: 0.0,
}
}
pub fn value_added(&self, default_value: f32) -> bool {
[
self.vxus,
self.bndx,
self.vtip,
self.vti,
self.vtivx,
self.bnd,
self.vwo,
self.vo,
self.vb,
self.vtc,
self.vv,
self.vmfxx,
self.outside_bond,
self.outside_stock,
]
.iter()
.any(|val| val != &default_value)
}
/// new_quote creates a new ShareValues struct where all values are set to 1. This is used for
/// creating a new struct for stock quotes. This way if any quotes are missing, they are
/// automatically set to 1 to prevent any 0 division errors. This also has the effect of
/// outputting the dollar amount when target value is divided by quote price. This division
/// occurs to determine number of stocks to purchase/sell.
///
/// # Example
/// ```
/// use vapore::holdings;
///
/// let new_quotes = holdings::ShareValues::new_quote();
/// ```
pub fn new_quote() -> Self {
ShareValues {
vxus: 1.0,
bndx: 1.0,
vtip: 1.0,
vti: 1.0,
vtivx: 1.0,
bnd: 1.0,
vwo: 1.0,
vo: 1.0,
vb: 1.0,
vtc: 1.0,
vv: 1.0,
vmfxx: 1.0,
outside_bond: 1.0,
outside_stock: 1.0,
}
}
pub async fn add_missing_quotes(&mut self) -> Result<()> {
for stock_symbol in [
StockSymbol::VV,
StockSymbol::VO,
StockSymbol::VB,
StockSymbol::VTC,
StockSymbol::BND,
StockSymbol::VXUS,
StockSymbol::VWO,
StockSymbol::BNDX,
StockSymbol::VTIP,
StockSymbol::VTI,
StockSymbol::VTIVX,
] {
if self.stock_value(stock_symbol.clone()) == 1.0 {
let new_quote = get_yahoo_quote(stock_symbol.clone()).await?;
self.add_stock_value(stock_symbol, new_quote);
}
}
Ok(())
}
pub async fn add_missing_eoy_quotes(&mut self, year: u32) -> Result<()> {
for stock_symbol in [
StockSymbol::VV,
StockSymbol::VO,
StockSymbol::VB,
StockSymbol::VTC,
StockSymbol::BND,
StockSymbol::VXUS,
StockSymbol::VWO,
StockSymbol::BNDX,
StockSymbol::VTIP,
StockSymbol::VTI,
StockSymbol::VTIVX,
] {
if self.stock_value(stock_symbol.clone()) == 1.0 {
let new_quote = get_yahoo_eoy_quote(stock_symbol.clone(), year).await?;
self.add_stock_value(stock_symbol, new_quote);
}
}
Ok(())
}
/// new_target creates a new target ShareValues struct which determines what to what values to
/// rebalance to vanguard portfolio.
///
/// # Panic
///
/// Panics when the percentages and fractions do not add up to 1 when they are added together.
/// This is necessary to make sure everything adds up to 100% of the total portfolio. Adding
/// up to less or more than 100% can happen when the const values determining balance distribution
/// are changed without changing other values to make sure everything adds up.
///
/// # Example
///
/// ```
/// use vapore::{asset, holdings};
///
/// let sub_allocations = asset::SubAllocations::new().unwrap();
///
/// let brokerage_target = holdings::ShareValues::new_target(sub_allocations, 10000.0, 0.0, 0.0, 0.0, 0.0);
/// ```
pub fn new_target(
sub_allocations: SubAllocations,
total_vanguard_value: f32,
other_us_stock_value: f32,
other_us_bond_value: f32,
other_int_stock_value: f32,
other_int_bond_value: f32,
) -> Self {
// get total value
let total_value = total_vanguard_value
+ other_us_stock_value
+ other_us_bond_value
+ other_int_bond_value
+ other_int_stock_value;
// Calculate values for each stock
let vxus_value = (total_value * sub_allocations.int_tot_stock / 100.0)
- (other_int_stock_value * 2.0 / 3.0);
let bndx_value = (total_value * sub_allocations.int_bond / 100.0) - other_int_bond_value;
let bnd_value =
(total_value * sub_allocations.us_tot_bond / 100.0) - (other_us_bond_value / 2.0);
let vwo_value = (total_value * sub_allocations.int_emerging_stock / 100.0)
- (other_int_stock_value / 3.0);
let vo_value =
(total_value * sub_allocations.us_stock_mid / 100.0) - (other_us_stock_value / 3.0);
let vb_value =
(total_value * sub_allocations.us_stock_small / 100.0) - (other_us_stock_value / 3.0);
let vtc_value =
(total_value * sub_allocations.us_corp_bond / 100.0) - (other_us_bond_value / 2.0);
let vv_value =
(total_value * sub_allocations.us_stock_large / 100.0) - (other_us_stock_value / 3.0);
let vtip_value = total_value * sub_allocations.inflation_protected / 100.0;
// set vmfxx, ie cash, target value to 0 and return ShareValues
ShareValues {
vxus: vxus_value,
bndx: bndx_value,
bnd: bnd_value,
vwo: vwo_value,
vo: vo_value,
vb: vb_value,
vtc: vtc_value,
vv: vv_value,
vtip: vtip_value,
vti: 0.0,
vtivx: 0.0,
vmfxx: 0.0,
outside_bond: other_int_bond_value + other_us_bond_value,
outside_stock: other_us_stock_value + other_int_stock_value,
}
}
/// add_stockinfo_value adds stock value to the ShareValues struct with a StockInfo input. StockInfo
/// structs are constructed when parsing the CSV file downloaded from vangaurd. This is used
/// for both creating the stock quotes ShareValues struct and holding values ShareValuues
/// struc. The add_type is used to distinguish between these two groups to know where from
/// within the StockInfo struct to pull the dollar amount from.
///
/// # Panic
///
/// Panics when an empty stock symbol is passed. This will happen if the StockInfo struct is
/// initialized without any content added.
///
/// # Example
///
/// ```
/// use vapore::holdings;
///
/// let mut new_stock = holdings::StockInfo::new();
/// new_stock.add_account(123456789);
/// new_stock.add_symbol(holdings::StockSymbol::BND);
/// new_stock.add_share_price(234.50);
/// new_stock.add_total_value(5000.00);
///
/// let mut new_quotes = holdings::ShareValues::new_quote();
/// new_quotes.add_stockinfo_value(new_stock, holdings::AddType::StockPrice);
///
/// assert_eq!(new_quotes.stock_value(holdings::StockSymbol::BND), 234.50);
///
/// ```
pub fn add_stockinfo_value(&mut self, stock_info: StockInfo, add_type: AddType) {
let value = match add_type {
AddType::StockPrice => stock_info.share_price,
AddType::HoldingValue => stock_info.total_value,
};
match stock_info.symbol {
StockSymbol::VXUS => self.vxus = value,
StockSymbol::BNDX => self.bndx = value,
StockSymbol::VTIP => self.vtip = value,
StockSymbol::VTI => self.vti = value,
StockSymbol::VTIVX => self.vtivx = value,
StockSymbol::BND => self.bnd = value,
StockSymbol::VWO => self.vwo = value,
StockSymbol::VO => self.vo = value,
StockSymbol::VB => self.vb = value,
StockSymbol::VTC => self.vtc = value,
StockSymbol::VV => self.vv = value,
StockSymbol::VMFXX => self.vmfxx = value,
StockSymbol::Empty => panic!("Stock symbol not set before adding value"),
StockSymbol::Other(_) => (),
}
}
/// add_stock_value adds stock value to the ShareValues struct with a float.
///
/// # Panic
///
/// Panics when an empty stock symbol is passed. This will happen if the StockInfo struct is
/// initialized without any content added.
///
/// # Example
///
/// ```
/// use vapore::holdings;
///
/// let mut new_values = holdings::ShareValues::new();
/// new_values.add_stock_value(holdings::StockSymbol::BND, 5000.0);
///
/// assert_eq!(new_values.stock_value(holdings::StockSymbol::BND), 5000.0);
///
/// ```
pub fn add_stock_value(&mut self, stock_symbol: StockSymbol, value: f32) {
match stock_symbol {
StockSymbol::VXUS => self.vxus = value,
StockSymbol::BNDX => self.bndx = value,
StockSymbol::VTIP => self.vtip = value,
StockSymbol::VTI => self.vti = value,
StockSymbol::VTIVX => self.vtivx = value,
StockSymbol::BND => self.bnd = value,
StockSymbol::VWO => self.vwo = value,
StockSymbol::VO => self.vo = value,
StockSymbol::VB => self.vb = value,
StockSymbol::VTC => self.vtc = value,
StockSymbol::VV => self.vv = value,
StockSymbol::VMFXX => self.vmfxx = value,
StockSymbol::Empty => panic!("Stock symbol not set before adding value"),
StockSymbol::Other(_) => (),
}
}
/// Adds other stock value that is not included within the vanguard account. This is used for
/// calculating current stock/bond ratios
pub fn add_outside_stock_value(&mut self, stock_value: f32) {
self.outside_stock = stock_value
}
pub fn outside_stock_value(&self) -> f32 {
self.outside_stock
}
/// Adds other bond value that is not included within the vanguard account. This is used for
/// calculating current stock/bond ratios
pub fn add_outside_bond_value(&mut self, bond_value: f32) {
self.outside_bond = bond_value
}
pub fn outside_bond_value(&self) -> f32 {
self.outside_bond
}
pub fn subtract_stock_value(&mut self, stock_symbol: StockSymbol, value: f32) {
match stock_symbol {
StockSymbol::VXUS => self.vxus -= value,
StockSymbol::BNDX => self.bndx -= value,
StockSymbol::VTIP => self.vtip -= value,
StockSymbol::VTI => self.vti -= value,
StockSymbol::VTIVX => self.vtivx -= value,
StockSymbol::BND => self.bnd -= value,
StockSymbol::VWO => self.vwo -= value,
StockSymbol::VO => self.vo -= value,
StockSymbol::VB => self.vb -= value,
StockSymbol::VTC => self.vtc -= value,
StockSymbol::VV => self.vv -= value,
StockSymbol::VMFXX => self.vmfxx -= value,
StockSymbol::Empty => panic!("Stock symbol not set before adding value"),
StockSymbol::Other(_) => (),
}
}
/// stock_value retrieves the stored stock value within the ShareValues struct
///
/// # Panic
///
/// Panics when an empty stock symbol is passed. This will happen if the StockInfo struct is
/// initialized without any content added.
///
/// # Example
///
/// ```
/// use vapore::holdings;
///
/// let mut new_values = holdings::ShareValues::new();
/// new_values.add_stock_value(holdings::StockSymbol::BND, 5000.0);
///
/// assert_eq!(new_values.stock_value(holdings::StockSymbol::BND), 5000.0);
///
/// ```
pub fn stock_value(&self, stock_symbol: StockSymbol) -> f32 {
match stock_symbol {
StockSymbol::VXUS => self.vxus,
StockSymbol::BNDX => self.bndx,
StockSymbol::VTIP => self.vtip,
StockSymbol::VTI => self.vti,
StockSymbol::VTIVX => self.vtivx,
StockSymbol::BND => self.bnd,
StockSymbol::VWO => self.vwo,
StockSymbol::VO => self.vo,
StockSymbol::VB => self.vb,
StockSymbol::VTC => self.vtc,
StockSymbol::VV => self.vv,
StockSymbol::VMFXX => self.vmfxx,
StockSymbol::Empty => panic!("Value retrieval not supported for empty stock symbol"),
StockSymbol::Other(symbol) => panic!("Value retrieval not supported for {}", symbol),
}
}
/// total_value returns the sum of all of the values within the StockValue struct
///
/// # Example
///
/// ```
/// use vapore::holdings;
///
/// let mut new_values = holdings::ShareValues::new();
/// new_values.add_stock_value(holdings::StockSymbol::BND, 5000.0);
/// new_values.add_stock_value(holdings::StockSymbol::BNDX, 2000.0);
/// new_values.add_stock_value(holdings::StockSymbol::VB, 4000.0);
///
/// assert_eq!(new_values.total_value(), 11000.0);
///
/// ```
pub fn total_value(&self) -> f32 {
self.vxus
+ self.bndx
+ self.bnd
+ self.vwo
+ self.vo
+ self.vb
+ self.vtc
+ self.vv
+ self.vmfxx
+ self.vtip
+ self.vti
+ self.vtivx
}
/// percent_stock_bond_infl calculates the percent of stock, bond, and inflation protected
/// assets within the ShareValues. This should only be used when the struct contains dollar
/// value amounts for the stock values.
pub fn percent_stock_bond_infl(&self) -> (f32, f32, f32) {
let total_bond = self.bndx + self.bnd + self.vtc + self.outside_bond;
let total_stock = self.vwo + self.vo + self.vb + self.vv + self.vxus + self.outside_stock;
let total = self.total_value() - self.vmfxx + self.outside_bond + self.outside_stock;
(
total_stock / total * 100.0,
total_bond / total * 100.0,
self.vtip / total * 100.0,
)
}
}
impl Default for ShareValues {
fn default() -> Self {
Self::new()
}
}
impl Add for ShareValues {
type Output = ShareValues;
fn add(self, other: ShareValues) -> ShareValues {
ShareValues {
vxus: self.vxus + other.vxus,
bndx: self.bndx + other.bndx,
vtip: self.vtip + other.vtip,
vti: self.vti + other.vti,
vtivx: self.vtivx + other.vtivx,
bnd: self.bnd + other.bnd,
vwo: self.vwo + other.vwo,
vo: self.vo + other.vo,
vb: self.vb + other.vb,
vtc: self.vtc + other.vtc,
vv: self.vv + other.vv,
vmfxx: self.vmfxx + other.vmfxx,
outside_bond: self.outside_bond + other.outside_bond,
outside_stock: self.outside_stock + other.outside_stock,
}
}
}
impl Sub for ShareValues {
type Output = ShareValues;
fn sub(self, other: ShareValues) -> ShareValues {
ShareValues {
vxus: self.vxus - other.vxus,
bndx: self.bndx - other.bndx,
vtip: self.vtip - other.vtip,
vti: self.vti - other.vti,
vtivx: self.vtivx - other.vtivx,
bnd: self.bnd - other.bnd,
vwo: self.vwo - other.vwo,
vo: self.vo - other.vo,
vb: self.vb - other.vb,
vtc: self.vtc - other.vtc,
vv: self.vv - other.vv,
vmfxx: self.vmfxx - other.vmfxx,
outside_bond: self.outside_bond - other.outside_bond,
outside_stock: self.outside_stock - other.outside_stock,
}
}
}
impl Div for ShareValues {
type Output = ShareValues;
fn div(self, other: ShareValues) -> ShareValues {
ShareValues {
vxus: self.vxus / other.vxus,
bndx: self.bndx / other.bndx,
vtip: self.vtip / other.vtip,
vti: self.vti / other.vti,
vtivx: self.vtivx / other.vtivx,
bnd: self.bnd / other.bnd,
vwo: self.vwo / other.vwo,
vo: self.vo / other.vo,
vb: self.vb / other.vb,
vtc: self.vtc / other.vtc,
vv: self.vv / other.vv,
vmfxx: self.vmfxx / other.vmfxx,
outside_bond: self.outside_bond / other.outside_bond,
outside_stock: self.outside_stock / other.outside_stock,
}
}
}
impl Mul for ShareValues {
type Output = ShareValues;
fn mul(self, other: ShareValues) -> ShareValues {
ShareValues {
vxus: self.vxus * other.vxus,
bndx: self.bndx * other.bndx,
vtip: self.vtip * other.vtip,
vti: self.vti * other.vti,
vtivx: self.vtivx * other.vtivx,
bnd: self.bnd * other.bnd,
vwo: self.vwo * other.vwo,
vo: self.vo * other.vo,
vb: self.vb * other.vb,
vtc: self.vtc * other.vtc,
vv: self.vv * other.vv,
vmfxx: self.vmfxx * other.vmfxx,
outside_bond: self.outside_bond * other.outside_bond,
outside_stock: self.outside_stock * other.outside_stock,
}
}
}
impl fmt::Display for ShareValues {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (stock, bond, inflation) = self.percent_stock_bond_infl();
write!(
f,
"\
Symbol Value\n\
-------------------------------\n\
VV {:.2}\n\
VO {:.2}\n\
VB {:.2}\n\
VTC {:.2}\n\
BND {:.2}\n\
VXUS {:.2}\n\
VWO {:.2}\n\
BNDX {:.2}\n\
VTIP {:.2}\n\
VTI {:.2}\n\
VTIVX {:.2}\n\
-------------------------------\n\
Cash {:.2}\n\
Total {:.2}\n\
Outside stock {:.2}\n\
Outside bond {:.2}\n\
Stock:Bond:Infl {:.1}:{:.1}:{:.1}\n\
===============================
",
self.vv,
self.vo,
self.vb,
self.vtc,
self.bnd,
self.vxus,
self.vwo,
self.bndx,
self.vtip,
self.vti,
self.vtivx,
self.vmfxx,
self.total_value(),
self.outside_stock,
self.outside_bond,
stock,
bond,
inflation
)
}
}
pub enum HoldingType {
Brokerage,
TraditionalIra,
RothIra,
}
/// VanguardHoldings contains ShareValues structs for all accounts along with for the quotes. This
/// struct is creating during the parsing of the downloaded Vanguard file
#[derive(Clone, Debug)]
pub struct VanguardHoldings {
brokerage: Option<ShareValues>,
traditional_ira: Option<ShareValues>,
roth_ira: Option<ShareValues>,
quotes: ShareValues,
transactions: Vec<Transaction>,
traditional_shares_option: Option<ShareValues>,
distributions: f32,
}
impl VanguardHoldings {
/// new creates a new VanguardHoldings struct with the quotes added. The rest of the accounts
/// needs to be added later
///
/// # Example
///
/// ```
/// use vapore::holdings;
///
/// let new_quotes = holdings::ShareValues::new_quote();
///
/// let mut new_vanguard = holdings::VanguardHoldings::new(new_quotes);
/// ```
pub fn new(quotes: ShareValues) -> Self {
VanguardHoldings {
brokerage: None,
traditional_ira: None,
roth_ira: None,
quotes,
transactions: Vec::new(),
traditional_shares_option: None,
distributions: 0.0,
}
}
/// add_holding adds a new account to the VanguardHoldings struct
///
///
/// # Example
///
/// ```
/// use vapore::holdings;
///
/// let new_quotes = holdings::ShareValues::new_quote();
///
/// let new_values = holdings::ShareValues::new();
///
/// let mut new_vanguard = holdings::VanguardHoldings::new(new_quotes);
/// new_vanguard.add_holding(new_values, holdings::HoldingType::RothIra);
/// ```
pub fn add_holding(&mut self, holding: ShareValues, holding_type: HoldingType) {
match holding_type {
HoldingType::RothIra => self.roth_ira = Some(holding),
HoldingType::Brokerage => self.brokerage = Some(holding),
HoldingType::TraditionalIra => self.traditional_ira = Some(holding),
}
}
pub fn brokerage_holdings(&self) -> Option<ShareValues> {
self.brokerage
}
pub fn traditional_ira_holdings(&self) -> Option<ShareValues> {
self.traditional_ira
}
pub fn roth_ira_holdings(&self) -> Option<ShareValues> {
self.roth_ira
}
pub fn stock_quotes(&self) -> ShareValues {
self.quotes
}
pub fn transactions(&self) -> Vec<Transaction> {
self.transactions.clone()
}
pub fn distributions(&self) -> f32 {
self.distributions
}
// Calculated the previous end of year holdings value based on the holdings times the quotes
// from December 31st of the previous year.
pub async fn eoy_value(&mut self, year: u32) -> Result<Option<f32>> {
if let Some(holdings) = self.eoy_traditional_holdings(year) {
let mut quotes = ShareValues::new_quote();
quotes.add_missing_eoy_quotes(year - 1).await?;
let eoy_value = (holdings * quotes).total_value();
Ok(Some(eoy_value))
} else {
Ok(None)
}
}
// Takes the current holdings and subtracts all transaction since December 31st to come to the
// holdings at that date.
fn eoy_traditional_holdings(&mut self, year: u32) -> Option<ShareValues> {
let mut enough_transaction = false;
if let Some(trad_holdings) = self.traditional_shares_option {
if self.transactions.is_empty() {
eprintln!(
"No transactions found to calculate EOY holdings for minimum distribution"
);
None
} else {
let mut eoy_holdings = trad_holdings;
let previous_year = NaiveDate::from_ymd_opt(year as i32 - 1, 12, 31)?;
let following_year = previous_year + Duration::days(365);
for transaction in &self.transactions {
// If the transaction is newer thand December 31st of the previous year,
// subtract from the current holdings. Also stores a true value if anything is
// older to keep track whether or not enough transactions were pulled from
// Vanguard to get to December 31st.
if transaction.trade_date > previous_year {
// Cash is allocated in VMFXX. These are not shares in the transaction, so
// net amount needs to be subtracted
if transaction.symbol == StockSymbol::VMFXX {
eoy_holdings.subtract_stock_value(
transaction.symbol.clone(),
transaction.net_amount,
);
} else if transaction.symbol != StockSymbol::Empty {
eoy_holdings.subtract_stock_value(
transaction.symbol.clone(),
transaction.shares,
);
} else if transaction.transaction_type == TransactionType::DISTRIBUTION {
if transaction.trade_date < following_year {
self.distributions -= transaction.net_amount
}
}
} else {
enough_transaction = true;
}
}
if !enough_transaction {
eprintln!("Possibly not enough history in the downloaded Vanguard CSV to accurately calculate end of year holdings")
}
Some(eoy_holdings)
}
} else {
None
}
}
}
/// AccountHoldings is a holder of current, target, and purchase/sales information for an account.
/// It also creates a Display for this information.
pub struct AccountHoldings {
current: ShareValues,
target: ShareValues,
sale_purchases_needed: ShareValues,
}
impl AccountHoldings {
/// new creates a new AccountHoldings struct from current, target, and sales/purchases
/// Sharevalues structs.
///
/// # Example
///
/// ```
/// use vapore::{asset, holdings};
///
/// let sub_allocations = asset::SubAllocations::new().unwrap();
///
/// let quotes = holdings::ShareValues::new_quote();
///
/// let brokerage_current = holdings::ShareValues::new();
/// let brokerage_target = holdings::ShareValues::new_target(sub_allocations, 10000.0, 0.0, 0.0, 0.0, 0.0);
/// let purchase_sales = brokerage_current / quotes;
///
/// let brokerage_account = holdings::AccountHoldings::new(brokerage_current, brokerage_target, purchase_sales);
/// ```
pub fn new(
current: ShareValues,
target: ShareValues,
sale_purchases_needed: ShareValues,
) -> Self {
AccountHoldings {
current,
target,
sale_purchases_needed,
}
}
}
impl fmt::Display for AccountHoldings {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (current_stock, current_bond, current_inflation) =
self.current.percent_stock_bond_infl();
let current_stock_bond = format!(
"{:.1}:{:.1}:{:.1}",
current_stock, current_bond, current_inflation
);
let (target_stock, target_bond, target_inflation) = self.target.percent_stock_bond_infl();
let target_stock_bond = format!(
"{:.1}:{:.1}:{:.1}",
target_stock, target_bond, target_inflation
);
write!(
f,
"Symbol Purchase/Sell Current Target\n\
------------------------------------------------------\n\
VV {:<15.2}${:<15.2}${:<15.2}\n\
VO {:<15.2}${:<15.2}${:<15.2}\n\
VB {:<15.2}${:<15.2}${:<15.2}\n\
VTC {:<15.2}${:<15.2}${:<15.2}\n\
BND {:<15.2}${:<15.2}${:<15.2}\n\
VXUS {:<15.2}${:<15.2}${:<15.2}\n\
VWO {:<15.2}${:<15.2}${:<15.2}\n\
BNDX {:<15.2}${:<15.2}${:<15.2}\n\
VTIP {:<15.2}${:<15.2}${:<15.2}\n\
VTI {:<15.2}${:<15.2}${:<15.2}\n\
VTIVX {:<15.2}${:<15.2}${:<15.2}\n\
------------------------------------------------------\n\
Cash ${:<15.2}${:<15.2}\n\
Total ${:<15.2}\n\
Outside stock ${:<15.2}${:<15.2}\n\
Outside bond ${:<15.2}${:<15.2}\n\
Stock:Bond:Inflation {:<16}{:<15}\n\
======================================================",
self.sale_purchases_needed.vv,
self.current.vv,
self.target.vv,
self.sale_purchases_needed.vo,
self.current.vo,
self.target.vo,
self.sale_purchases_needed.vb,
self.current.vb,
self.target.vb,
self.sale_purchases_needed.vtc,
self.current.vtc,
self.target.vtc,
self.sale_purchases_needed.bnd,
self.current.bnd,
self.target.bnd,
self.sale_purchases_needed.vxus,
self.current.vxus,
self.target.vxus,
self.sale_purchases_needed.vwo,
self.current.vwo,
self.target.vwo,
self.sale_purchases_needed.bndx,
self.current.bndx,
self.target.bndx,
self.sale_purchases_needed.vtip,
self.current.vtip,
self.target.vtip,
self.sale_purchases_needed.vti,
self.current.vti,
self.target.vti,
self.sale_purchases_needed.vtivx,
self.current.vtivx,
self.target.vtivx,
self.current.vmfxx,
self.target.vmfxx,
self.current.total_value(),
self.current.outside_stock,
self.target.outside_stock,
self.current.outside_bond,
self.target.outside_bond,
current_stock_bond,
target_stock_bond,
)
}
}
/// VanguardRebalance holds AccountHoldings structs for each account; brokerage, traditional IRA,
/// and roth IRA. Each AccountHoldings struct holds the information of current holdings, target
/// holdings, and the amount of stocks needed to purchase/sell in order to rebalance
pub struct VanguardRebalance {
brokerage: Option<AccountHoldings>,
traditional_ira: Option<AccountHoldings>,
roth_ira: Option<AccountHoldings>,
retirement_target: Option<ShareValues>,
}
impl VanguardRebalance {
/// new creates a new empty VanguardRebalance struct
///
/// # Example
///
/// ```
/// use vapore::holdings;
///
/// let vanguard_rebalance = holdings::VanguardRebalance::new();
/// ```
pub fn new() -> Self {
VanguardRebalance {
brokerage: None,
traditional_ira: None,
roth_ira: None,
retirement_target: None,
}
}
/// add_account_holdings adds either roth IRA, traditional IRA, or brokerage AccountHoldings
/// struct to the current VanguardRebalance struct.
///
/// # Example
///
/// ```
/// use vapore::{asset, holdings};
///
/// let quotes = holdings::ShareValues::new_quote();
///
/// let sub_allocations = asset::SubAllocations::new().unwrap();
///
/// let brokerage_current = holdings::ShareValues::new();
/// let brokerage_target = holdings::ShareValues::new_target(sub_allocations, 10000.0, 0.0, 0.0, 0.0, 0.0);
/// let purchase_sales = brokerage_current / quotes;
///
/// let brokerage_account = holdings::AccountHoldings::new(brokerage_current, brokerage_target, purchase_sales);
///
/// let mut vanguard_rebalance = holdings::VanguardRebalance::new();
/// vanguard_rebalance.add_account_holdings(brokerage_account, holdings::HoldingType::Brokerage);
/// ```
pub fn add_account_holdings(&mut self, acct_holding: AccountHoldings, acct_type: HoldingType) {
match acct_type {
HoldingType::Brokerage => self.brokerage = Some(acct_holding),
HoldingType::TraditionalIra => self.traditional_ira = Some(acct_holding),
HoldingType::RothIra => self.roth_ira = Some(acct_holding),
}
}
pub fn add_retirement_target(&mut self, retirement_target: ShareValues) {
self.retirement_target = Some(retirement_target);
}
}
impl Default for VanguardRebalance {
fn default() -> Self {
Self::new()
}
}
impl fmt::Display for VanguardRebalance {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut out_string = String::new();
if let Some(retirement_target_values) = &self.retirement_target {
out_string.push_str(&format!(
"Retirement target:\n{}\n\n",
retirement_target_values
))
}
if let Some(traditional_ira_account) = &self.traditional_ira {
out_string.push_str(&format!(
"Traditional IRA:\n{}\n\n",
traditional_ira_account
))
}
if let Some(roth_ira_account) = &self.roth_ira {
out_string.push_str(&format!("Roth IRA:\n{}\n\n", roth_ira_account))
}
if let Some(brokerage_account) = &self.brokerage {
out_string.push_str(&format!("Brokerage:\n{}\n\n", brokerage_account))
}
write!(f, "{}", out_string.trim_end_matches('\n'))
}
}
#[derive(Clone, Debug)]
pub struct Transaction {
_account_number: u32,
trade_date: NaiveDate,
symbol: StockSymbol,
shares: f32,
net_amount: f32,
transaction_type: TransactionType,
}
#[derive(Clone, Eq, Hash, PartialEq, Debug)]
enum TransactionType {
CONVERSIONOUT,
DIVIDEND,
REINVESTMENT,
ADVISORFEE,
BUY,
CONVERSIONIN,
SELL,
FUNDSRECEIVED,
SWEEPOUT,
SWEEPIN,
DISTRIBUTION,
Other(String),
}
impl TransactionType {
/// new creates a new StockSymbol enum based on the string value.
///
/// # Example
///
/// ```
/// use vapore::holdings::TransactionType;
///
/// let div = TransactionType::new("Dividend");
/// assert_eq!(div, TransactionType::DIVIDEND);
/// ```
pub fn new(transaction_type: &str) -> Self {
match transaction_type {
"Conversion (outgoing)" => TransactionType::CONVERSIONOUT,
"Dividend" => TransactionType::DIVIDEND,
"Reinvestment" => TransactionType::REINVESTMENT,
"Advisor fee" => TransactionType::ADVISORFEE,
"Buy" => TransactionType::BUY,
"Conversion (incoming)" => TransactionType::CONVERSIONIN,
"Sell" => TransactionType::SELL,
"Funds Received" => TransactionType::FUNDSRECEIVED,
"Sweep out" => TransactionType::SWEEPOUT,
"Sweep in" => TransactionType::SWEEPIN,
"Distribution" => TransactionType::DISTRIBUTION,
_ => {
eprintln!(
"{} is not supported within this algorithm\n",
transaction_type
);
TransactionType::Other(transaction_type.to_string())
}
}
}
}
/// parse_csv_download takes in the file path of the downloaded file from Vanguard and parses it
/// into VanguardHoldings. The VanguardHoldings is a struct which holds the values of what is
/// contained within the vangaurd account along with quotes for each of the ETFs
pub async fn parse_csv_download(
csv_path: &str,
args: crate::arguments::Args,
) -> Result<VanguardHoldings> {
let mut header = Vec::new();
let mut transaction_header = Vec::new();
let csv_file = File::open(csv_path)?;
let mut accounts: HashMap<u32, ShareValues> = HashMap::new();
let mut quotes = ShareValues::new_quote();
let mut traditional_shares = ShareValues::new();
let mut holdings_row = true;
let mut transactions = Vec::new();
// iterate through all of the rows of the vanguard downlaoaded file and add the information to
// StockInfo structs, which then are aggregated into the accounts hashmap where the account
// number is the key
for row_result in BufReader::new(csv_file).lines() {
let row = row_result?;
if row.contains(',') {
if row.contains("Trade Date") {
holdings_row = false;
}
let row_split = row
.split(',')
.map(|value| value.to_string())
.collect::<Vec<String>>();
if row_split.len() > 4 {
if holdings_row {
let mut stock_info = StockInfo::new();
if header.is_empty() {
header = row_split
} else {
for (value, head) in row_split.iter().zip(&header) {
match head.as_str() {
"Account Number" => stock_info.add_account(value.parse::<u32>()?),
"Symbol" => {
if value.chars().count() > 1 {
stock_info.add_symbol(StockSymbol::new(value))
} else {
break;
}
}
"Shares" => stock_info.add_shares(value.parse::<f32>()?),
"Share Price" => stock_info.add_share_price(value.parse::<f32>()?),
"Total Value" => stock_info.add_total_value(value.parse::<f32>()?),
_ => continue,
}
}
if stock_info.finished() {
let account_value = accounts
.entry(stock_info.account_number)
.or_insert_with(ShareValues::new);
account_value
.add_stockinfo_value(stock_info.clone(), AddType::HoldingValue);
quotes.add_stockinfo_value(stock_info.clone(), AddType::StockPrice);
if let Some(traditional_acct_num) = args.trad_acct_option {
if stock_info.account_number == traditional_acct_num {
traditional_shares
.add_stock_value(stock_info.symbol, stock_info.shares);
}
}
}
}
} else if transaction_header.is_empty() {
transaction_header = row_split
} else {
let mut account_num_option = None;
let mut trade_date_option = None;
let mut symbol_option = None;
let mut shares_option = None;
let mut net_amount_option = None;
let mut transaction_type_option = None;
for (value, head) in row_split.iter().zip(&transaction_header) {
match head.as_str() {
"Account Number" => account_num_option = Some(value.parse::<u32>()?),
"Symbol" => symbol_option = Some(StockSymbol::new(value)),
"Shares" => shares_option = Some(value.parse::<f32>()?),
"Trade Date" => {
trade_date_option =
Some(NaiveDate::parse_from_str(value, "%Y-%m-%d")?)
}
"Net Amount" => net_amount_option = Some(value.parse::<f32>()?),
"Transaction Type" => {
transaction_type_option = Some(TransactionType::new(value))
}
_ => continue,
}
}
if let Some(account_number) = account_num_option {
if let Some(trad_account_num) = args.trad_acct_option {
if trad_account_num == account_number {
if let Some(symbol) = symbol_option {
if let Some(shares) = shares_option {
if let Some(trade_date) = trade_date_option {
if let Some(net_amount) = net_amount_option {
if let Some(transaction_type) =
transaction_type_option
{
transactions.push(Transaction {
_account_number: account_number,
symbol,
shares,
trade_date,
net_amount,
transaction_type,
})
}
}
}
}
}
}
}
}
}
}
}
}
quotes.add_missing_quotes().await?;
let account_numbers = accounts.keys().cloned().collect::<Vec<u32>>();
// if the brokerage account is input through CLI arguments, pull the data from the accounts
// hashmap and place the information into a variable which will be input into the
// VanguardHoldings struct
let mut brokerage = None;
if let Some(brokerage_acct) = args.brok_acct_option {
if let Some(brokerage_holdings) = accounts.get(&brokerage_acct) {
brokerage = Some(*brokerage_holdings)
} else {
return Err(anyhow!("{account_type} account number not found within vanguard download file\nInput account: {input:?}\nPossible accounts: {all_accounts:?}\n",
account_type= "Brokerage",
input=brokerage_acct,
all_accounts=account_numbers));
}
}
// if the traditional IRA account is input through CLI arguments, pull the data from the accounts
// hashmap and place the information into a variable which will be input into the
// VanguardHoldings struct
let mut traditional_ira = None;
if let Some(traditional_acct) = args.trad_acct_option {
if let Some(traditional_holdings) = accounts.get(&traditional_acct) {
traditional_ira = Some(*traditional_holdings)
} else {
return Err(anyhow!("{account_type} account number not found within vanguard download file\nInput account: {input:?}\nPossible accounts: {all_accounts:?}\n",
account_type= "Traditional IRA",
input= traditional_acct,
all_accounts= account_numbers)
);
}
}
// if the roth IRA account is input through CLI arguments, pull the data from the accounts
// hashmap and place the information into a variable which will be input into the
// VanguardHoldings struct
let mut roth_ira = None;
if let Some(roth_acct) = args.roth_acct_option {
if let Some(roth_holdings) = accounts.get(&roth_acct) {
roth_ira = Some(*roth_holdings)
} else {
return Err(anyhow!("{account_type:?} account number not found within vanguard download file\nInput account: {input:?}\nPossible accounts: {all_accounts:?}\n",
account_type= "Roth IRA",
input= roth_acct,
all_accounts= account_numbers)
);
}
}
let traditional_shares_option = if traditional_shares.value_added(0.0) {
Some(traditional_shares)
} else {
None
};
Ok(VanguardHoldings {
brokerage,
traditional_ira,
roth_ira,
quotes,
transactions,
traditional_shares_option,
distributions: 0.0,
})
}