-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathportfolio.py
More file actions
254 lines (206 loc) · 8.28 KB
/
portfolio.py
File metadata and controls
254 lines (206 loc) · 8.28 KB
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
import json
from enum import Enum
from typing import Callable, Dict, List, Optional, Self
import pandas as pd
from utils import percent
from yfcache import Quote
class TradeOp(Enum):
BUY = 1
SELL = 2
DEPOSIT = 3
WITHDRAW = 4
def __str__(self) -> str:
return self.name
class LogEvent:
op: TradeOp
timestamp: Optional[ pd.Timestamp ]
commission: float
memo: str
def __init__(self,
op: TradeOp,
timestamp: Optional[ pd.Timestamp ] = None,
commission : float = 0,
memo: Optional [ str ] = None):
self.op = op
self.timestamp = timestamp
self.commission = commission
self.memo = memo or ''
def display(self) -> str:
return f"{self.timestamp} {self.op}"
class BuyEvent(LogEvent):
symbol: str
quantity: int
price: float
def __init__(self, symbol: str, quantity: int, price: float,
timestamp: Optional[ pd.Timestamp ] = None,
commission : float = 0,
memo: Optional [ str ] = None):
super().__init__(TradeOp.BUY, timestamp, commission, memo)
self.symbol = symbol
self.quantity = quantity
self.price = price
def display(self) -> str:
return (
f"{super().display()} "
f"{self.symbol} {self.quantity} @ {self.price:,.2f} = "
f"${self.quantity * self.price:,.2f} ({self.memo})"
)
class SellEvent(LogEvent):
def __init__(self, symbol: str, quantity: int, price: float,
timestamp: Optional[ pd.Timestamp ] = None,
commission : float = 0,
memo: Optional [ str ] = None):
super().__init__(TradeOp.SELL, timestamp, commission, memo)
self.symbol = symbol
self.quantity = quantity
self.price = price
def display(self) -> str:
return (
f"{super().display()} "
f"{self.symbol} {self.quantity} @ {self.price:,.2f} = "
f"${self.quantity * self.price:,.2f} ({self.memo})"
)
class DepositEvent(LogEvent):
def __init__(self, amount: float,
timestamp: Optional[ pd.Timestamp ] = None,
commission : float = 0,
memo: Optional [ str ] = None):
super().__init__(TradeOp.DEPOSIT, timestamp, commission, memo)
self.amount = amount
def display(self) -> str:
return (
f"{super().display()} "
f"${self.amount:,.2f} ({self.memo})"
)
class WithdrawEvent(LogEvent):
def __init__(self, amount: float,
timestamp: Optional[ pd.Timestamp ] = None,
commission : float = 0,
memo: Optional [ str ] = None):
super().__init__(TradeOp.WITHDRAW, timestamp, commission, memo)
self.amount = amount
def display(self) -> str:
return (
f"{super().display()} "
"{self.amount:,.2f} ({self.memo})"
)
class Portfolio:
_name: str
_filename: Optional[ str ]
_positions: Dict[str, int]
_cash: float
initial_value: float = -1.0
quote: Quote
loggers: List[ Callable[['Portfolio', LogEvent], None]]
def __init__(self, cash: float = 100000.0, name: Optional[ str ] = None):
self._name = name or 'no name'
self._filename = None
self._cash = cash
self._positions = { }
self.quote = Quote.empty()
self._alloc = { }
self._cash_alloc = 1.0
self.loggers = []
def _log(self, evt: LogEvent):
for l in self.loggers:
l(self, evt)
def add_logger(self, logger: Callable[['Portfolio', LogEvent], None]):
self.loggers.append(logger)
def remove_logger(self, logger: Callable[['Portfolio', LogEvent], None]):
self.loggers.remove(logger)
def set_quote(self, quote: Quote) -> Self:
self.quote = quote
if self.initial_value < 0 and self.value() > 0:
self.initial_value = self.value()
return self
def price(self, symbol: str) -> float:
return self.quote.Close(symbol)
def buy(self, symbol: str, quantity: int, memo: Optional[ str ]=None) -> int:
self._positions[symbol] = self._positions.get(symbol, 0) + quantity
self._cash -= (quantity * self.price(symbol))
assert(self._cash >= 0.0)
self._log(BuyEvent(symbol, quantity, self.price(symbol), self.quote.timestamp, memo=memo))
return self._positions[symbol]
def sell(self, symbol: str, quantity: int, memo: Optional[ str ]=None) -> int:
assert 0 <= quantity <= self._positions.get(symbol, 0), f"Invalid sell quantity for {symbol} {quantity}"
self._positions[symbol] -= quantity
self._cash += (quantity * self.price(symbol))
self._log(SellEvent(symbol, quantity, self.price(symbol), self.quote.timestamp, memo=memo))
if self._positions[symbol] == 0:
del self._positions[symbol]
return 0
else:
return self._positions[symbol]
@property
def cash(self) -> float:
return self._cash
def deposit(self, amount: float, memo: Optional[ str ]=None) -> float:
assert(amount > 0)
self._cash += amount
self._log(DepositEvent(amount, self.quote.timestamp, memo=memo))
return self._cash
def withdraw(self, amount: float, memo: Optional[ str ]=None) -> float:
assert(amount > 0)
self._cash -= amount
self._log(WithdrawEvent(amount, self.quote.timestamp, memo=memo))
return self._cash
@property
def name(self) -> str:
return self._name
def set_position(self, symbol: str, quantity: int) -> Self:
self._positions[symbol] = quantity
return self
def set_positions(self, positions: Dict[str, int]) -> Self:
for k, v in positions.items():
self.set_position(k, v)
return self
def position(self, symbol: str) -> int:
return self._positions.get(symbol, 0)
def tickers(self) -> List[ str ]:
return list(self._positions.keys())
def value(self, quote: Optional[Quote] = None) -> float:
if quote is not None:
self.set_quote(quote)
def ticker_value(symbol: str) -> float:
return self.position(symbol) * self.price(symbol)
return self._cash + sum(ticker_value(symbol) for symbol in self._positions.keys())
def holding(self, symbol: str) -> float:
return self.price(symbol) * self.position(symbol)
def __str__(self) -> str:
value = self.value()
text = f"{self.name} ${value:,.2f}\n\tCash: ${self._cash:,.2f}/{percent(self.cash, value)}%"
for symbol, position in self._positions.items():
holding = self.holding(symbol)
text += f"\n\t{symbol}\t${holding:,.2f}/{position}/{percent(holding, value)}%"
return text
@staticmethod
def load(filename: str) -> "Portfolio":
"""Loads a portfolio from a json file.
This method can also be used to create special portfolios:
- *empty* will return an empty portfolio with no cash.
Args:
filename (str): Name of the file to load, or name of "special" portfolios.
Returns:
Portfolio: A fresh Portfolio instance.
"""
if filename == '*empty*':
p = Portfolio(0, name='Empty Portfolio')
else:
with open(filename, "r") as input:
obj = json.load(input)
p = Portfolio(obj.get('cash', 0))
p._filename = filename
p._name = obj.get('name', 'No Name')
p.set_positions(obj.get('positions', {}))
return p
def save(self, filename: Optional[ str ] = None):
if filename is None:
filename = self._filename
if filename is None:
raise ValueError("No fiename for this portfolio.")
with open(filename, "w+") as output:
json.dump({
"name": self._name,
"cash": self.cash,
"positions": self._positions
}, output, indent=2)