-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperformance.py
More file actions
48 lines (36 loc) · 1.62 KB
/
performance.py
File metadata and controls
48 lines (36 loc) · 1.62 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
import matplotlib.pyplot as plt
from invest import Transaction
from strategies import DcaStrategy
def analyse_performance(strategy: DcaStrategy, transactions: list[Transaction]):
quantities_purchased = [t.quantity for t in transactions]
total_fees = len(transactions) * strategy.transaction_fees
total_amount_invested = (
sum([t.quantity * t.closing_price for t in transactions]) + total_fees
)
end_pru = total_amount_invested / sum(quantities_purchased)
last_price = transactions[-1].closing_price
diff = last_price - end_pru # < 0 = losses, > 0 = gains
dividends = sum([t.dividend for t in transactions])
pnl = diff * sum(quantities_purchased) + dividends
print("==== PNL")
print("- total_amount_invested: ", total_amount_invested)
print("- pnl: ", pnl)
print("==== renta")
print(" %: ", (pnl / total_amount_invested) * 100)
running_qte = 0.0
running_invested = 0.0
running_pru = []
for t in transactions:
running_qte += t.quantity
running_invested += (t.quantity * t.closing_price) + strategy.transaction_fees
running_pru.append(running_invested / running_qte)
plot(end_pru, transactions, running_pru)
def plot(pru: float, transactions: list[Transaction], running_pru: list[float]):
fig, ax = plt.subplots()
dates = [t.date for t in transactions]
closing_prices = [t.closing_price for t in transactions]
# Running PRU vs closing_prices = is my position line green/red in my portfolio
ax.plot(dates, closing_prices, color="b")
ax.plot(dates, running_pru, color="g")
# ax.axhline(y=pru, color="r")
plt.show()