-
Notifications
You must be signed in to change notification settings - Fork 1
/
portfolio.dart
211 lines (173 loc) · 6.52 KB
/
portfolio.dart
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
import 'package:async_redux/async_redux.dart';
import 'package:collection/collection.dart';
import 'package:fast_immutable_collections/fast_immutable_collections.dart';
import 'package:flutter/material.dart';
import 'package:mobile_app_flutter_redux/models/utils/map_deserialization_extension.dart';
import 'available_stock.dart';
import 'buy_or_sell.dart';
import 'cash_balance.dart';
import 'stock.dart';
import 'utils/utils.dart';
@immutable
class Portfolio {
static const Portfolio EMPTY = Portfolio._();
final IList<Stock> stocks;
final CashBalance cashBalance;
Portfolio({
Iterable<Stock>? stocks,
this.cashBalance = CashBalance.ZERO,
}) : stocks = IList.orNull(stocks) ?? const IListConst([]);
const Portfolio._()
: stocks = const IListConst([]),
cashBalance = CashBalance.ZERO;
Portfolio copyWith({
Iterable<Stock>? stocks,
CashBalance? cashBalance,
}) {
return Portfolio(
stocks: (stocks != null) ? stocks.toIList() : this.stocks,
cashBalance: cashBalance ?? this.cashBalance,
);
}
bool get isEmpty => stocks.isEmpty;
Portfolio addCashBalance(double howMuch) {
final newCashBalance = cashBalance.add(howMuch);
return copyWith(cashBalance: newCashBalance);
}
Portfolio removeCashBalance(double howMuch) {
final newCashBalance = cashBalance.remove(howMuch);
return copyWith(cashBalance: newCashBalance);
}
Portfolio withoutStock(String ticker) {
return withStock(ticker, 0, 0.0);
}
Portfolio withAddedStock(AvailableStock availableStock, int howMany) {
final pos = _getStockPositionInList(availableStock);
List<Stock> newStocks;
if (pos == -1) {
newStocks = [...stocks, availableStock.toStock(shares: howMany)];
} else {
final stock = stocks[pos];
final newShares = stock.howManyShares + howMany;
final newAveragePrice = round(
((stock.howManyShares * stock.averagePrice) + (howMany * availableStock.currentPrice)) /
newShares);
newStocks = [...stocks];
newStocks[pos] = Stock(
stock.ticker,
howManyShares: newShares,
averagePrice: newAveragePrice,
);
}
return copyWith(stocks: newStocks);
}
Portfolio withoutStocks() {
return copyWith(stocks: []);
}
Portfolio withStock(String ticker, int quantity, double averagePrice) {
final newStocks = stocks.where((stock) => stock.ticker != ticker).toList();
if (quantity > 0) {
final newStock = Stock(ticker, howManyShares: quantity, averagePrice: averagePrice);
newStocks.add(newStock);
}
return copyWith(stocks: newStocks);
}
int howManyStocks(String ticker) {
final stock = getStockOrNull(ticker);
return stock?.howManyShares ?? 0;
}
Stock getStock(String ticker) {
final stock = getStockOrNull(ticker);
if (stock == null) {
throw Exception('Stock $ticker not found.');
}
return stock;
}
Stock? getStockOrNull(String ticker) {
return stocks.firstWhereOrNull((stock) => stock.ticker == ticker);
}
bool hasStock(AvailableStock availableStock) {
return _getStockPositionInList(availableStock) != -1;
}
bool hasMoneyToBuyStock(AvailableStock availableStock) {
return cashBalance.amount >= availableStock.currentPrice;
}
Portfolio buyOrSell(BuyOrSell buyOrSell, AvailableStock availableStock, int howMany) {
return (buyOrSell == BuyOrSell.buy)
? buy(availableStock, howMany: howMany)
: sell(availableStock, howMany: howMany);
}
/// Buys [howMany] shares of [availableStock].
/// If the user does not have enough money, throws a [UserException].
Portfolio buy(AvailableStock availableStock, {required int howMany}) {
if (cashBalance.amount < availableStock.currentPrice * howMany) {
throw const UserException('Not enough money to buy stock');
} else {
final newCashBalance =
CashBalance(cashBalance.amount - availableStock.currentPrice * howMany);
final newPortfolio = withAddedStock(availableStock, howMany);
return newPortfolio.copyWith(cashBalance: newCashBalance);
}
}
/// Sells [howMany] shares of [availableStock].
/// If the user does not own the stock, or does not own enough shares, throws a [UserException].
/// This exception will be shown to the user in a dialog.
Portfolio sell(AvailableStock availableStock, {required int howMany}) {
final pos = _getStockPositionInList(availableStock);
if (pos == -1) {
throw const UserException('Cannot sell stock you do not own');
} else {
final stock = stocks[pos];
if (stock.howManyShares < howMany) {
throw UserException('Cannot sell $howMany shares of stock you do not own');
} else {
final newShares = stock.howManyShares - howMany;
final newAveragePrice = round(
((stock.howManyShares * stock.averagePrice) - (howMany * availableStock.currentPrice)) /
newShares);
var newStocks = [...stocks];
newStocks[pos] = Stock(
stock.ticker,
howManyShares: newShares,
averagePrice: newAveragePrice,
);
if (newShares == 0) {
newStocks = newStocks.where((stock) => stock.ticker != availableStock.ticker).toList();
}
final newCashBalance =
CashBalance(cashBalance.amount + availableStock.currentPrice * howMany);
return copyWith(stocks: newStocks, cashBalance: newCashBalance);
}
}
}
int _getStockPositionInList(AvailableStock availableStock) {
return stocks.indexWhere((stock) => stock.ticker == availableStock.ticker);
}
double get totalCostBasis {
return stocks.fold(0.0, (sum, stock) => sum + stock.costBasis) + cashBalance.amount;
}
@override
String toString() => 'Portfolio{stocks: $stocks, cashBalance: $cashBalance}';
Json toJson() => {
'stocks': stocks.map((stock) => stock.toJson()).toList(),
'cashBalance': cashBalance.toJson(),
};
factory Portfolio.fromJson(Json? json) {
if (json == null)
return Portfolio.EMPTY;
else {
IList<Stock> stocks = json.asIListOf('stocks', Stock.fromJson);
CashBalance cashBalance = json.asCashBalance('cashBalance') ?? CashBalance.ZERO;
return Portfolio(stocks: stocks, cashBalance: cashBalance);
}
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Portfolio &&
runtimeType == other.runtimeType &&
stocks == other.stocks &&
cashBalance == other.cashBalance;
@override
int get hashCode => stocks.hashCode ^ cashBalance.hashCode;
}