-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathportfolio_tracker.py
More file actions
320 lines (257 loc) · 11.1 KB
/
portfolio_tracker.py
File metadata and controls
320 lines (257 loc) · 11.1 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
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
"""
SpineRip Portfolio Tracker
Real-time portfolio tracking, P&L calculation, performance metrics
"""
import os
import json
from datetime import datetime, timedelta
from trading_ai import SpineRipAI
try:
from alpaca.trading.client import TradingClient
except ImportError:
print("Installing alpaca-py...")
os.system("pip install alpaca-py")
from alpaca.trading.client import TradingClient
class PortfolioTracker:
"""Track portfolio performance and metrics"""
def __init__(self, api_key=None, api_secret=None, paper=True):
"""Initialize tracker"""
self.api_key = api_key or os.getenv("ALPACA_API_KEY")
self.api_secret = api_secret or os.getenv("ALPACA_API_SECRET")
self.paper = paper
if not self.api_key or not self.api_secret:
self.demo_mode = True
print("⚠️ Demo mode - using simulated data")
else:
self.trading_client = TradingClient(self.api_key, self.api_secret, paper=paper)
self.demo_mode = False
def get_account_summary(self):
"""Get account balance and equity"""
if self.demo_mode:
return {
'cash': 10000.00,
'portfolio_value': 12500.00,
'buying_power': 40000.00,
'equity': 12500.00,
'last_equity': 10000.00
}
account = self.trading_client.get_account()
return {
'cash': float(account.cash),
'portfolio_value': float(account.portfolio_value),
'buying_power': float(account.buying_power),
'equity': float(account.equity),
'last_equity': float(account.last_equity)
}
def get_positions(self):
"""Get all open positions"""
if self.demo_mode:
return [
{
'symbol': 'AAPL',
'qty': 10,
'avg_entry_price': 150.00,
'current_price': 165.00,
'market_value': 1650.00,
'cost_basis': 1500.00,
'unrealized_pl': 150.00,
'unrealized_plpc': 10.0,
'side': 'long'
},
{
'symbol': 'TSLA',
'qty': 5,
'avg_entry_price': 200.00,
'current_price': 210.00,
'market_value': 1050.00,
'cost_basis': 1000.00,
'unrealized_pl': 50.00,
'unrealized_plpc': 5.0,
'side': 'long'
}
]
positions = self.trading_client.get_all_positions()
position_list = []
for pos in positions:
position_list.append({
'symbol': pos.symbol,
'qty': int(pos.qty),
'avg_entry_price': float(pos.avg_entry_price),
'current_price': float(pos.current_price),
'market_value': float(pos.market_value),
'cost_basis': float(pos.cost_basis),
'unrealized_pl': float(pos.unrealized_pl),
'unrealized_plpc': float(pos.unrealized_plpc) * 100,
'side': pos.side
})
return position_list
def get_portfolio_history(self, days=30):
"""Get portfolio performance history"""
if self.demo_mode:
# Generate demo history
import pandas as pd
dates = pd.date_range(end=datetime.now(), periods=days, freq='1D')
values = [10000 + (i * 50) + ((i % 5) * 100 - 250) for i in range(days)]
return {
'dates': [d.strftime('%Y-%m-%d') for d in dates],
'equity': values,
'profit_loss': [v - 10000 for v in values],
'profit_loss_pct': [((v - 10000) / 10000) * 100 for v in values]
}
# Get from Alpaca
history = self.trading_client.get_portfolio_history(
period=f"{days}D",
timeframe="1D"
)
dates = [datetime.fromtimestamp(ts).strftime('%Y-%m-%d') for ts in history.timestamp]
return {
'dates': dates,
'equity': history.equity,
'profit_loss': history.profit_loss,
'profit_loss_pct': history.profit_loss_pct
}
def calculate_metrics(self):
"""Calculate performance metrics"""
account = self.get_account_summary()
positions = self.get_positions()
# Total P&L
total_pl = account['equity'] - account['last_equity']
total_pl_pct = (total_pl / account['last_equity']) * 100 if account['last_equity'] > 0 else 0
# Position stats
total_positions = len(positions)
winning_positions = sum(1 for p in positions if p['unrealized_pl'] > 0)
losing_positions = sum(1 for p in positions if p['unrealized_pl'] < 0)
win_rate = (winning_positions / total_positions * 100) if total_positions > 0 else 0
# Largest winner/loser
if positions:
largest_winner = max(positions, key=lambda x: x['unrealized_plpc'])
largest_loser = min(positions, key=lambda x: x['unrealized_plpc'])
else:
largest_winner = None
largest_loser = None
return {
'total_pl': total_pl,
'total_pl_pct': total_pl_pct,
'total_positions': total_positions,
'winning_positions': winning_positions,
'losing_positions': losing_positions,
'win_rate': win_rate,
'largest_winner': largest_winner,
'largest_loser': largest_loser
}
def display_dashboard(self):
"""Display portfolio dashboard"""
print("\n" + "="*70)
print("📊 SPINERIP PORTFOLIO DASHBOARD")
print("="*70 + "\n")
# Account summary
account = self.get_account_summary()
print("💰 ACCOUNT SUMMARY")
print("-" * 70)
print(f"Portfolio Value: ${account['portfolio_value']:,.2f}")
print(f"Cash Available: ${account['cash']:,.2f}")
print(f"Buying Power: ${account['buying_power']:,.2f}")
# Calculate day change
day_pl = account['equity'] - account['last_equity']
day_pl_pct = (day_pl / account['last_equity']) * 100 if account['last_equity'] > 0 else 0
pl_emoji = "📈" if day_pl >= 0 else "📉"
print(f"\nToday's Change: {pl_emoji} ${day_pl:+,.2f} ({day_pl_pct:+.2f}%)")
# Performance metrics
print("\n📊 PERFORMANCE METRICS")
print("-" * 70)
metrics = self.calculate_metrics()
print(f"Total Positions: {metrics['total_positions']}")
print(f"Winning: {metrics['winning_positions']} 🟢")
print(f"Losing: {metrics['losing_positions']} 🔴")
print(f"Win Rate: {metrics['win_rate']:.1f}%")
# Positions
print("\n📋 OPEN POSITIONS")
print("-" * 70)
positions = self.get_positions()
if not positions:
print("No open positions")
else:
for pos in positions:
pl_emoji = "🟢" if pos['unrealized_pl'] >= 0 else "🔴"
print(f"\n{pl_emoji} {pos['symbol']}")
print(f" Shares: {pos['qty']}")
print(f" Entry: ${pos['avg_entry_price']:.2f}")
print(f" Current: ${pos['current_price']:.2f}")
print(f" Value: ${pos['market_value']:,.2f}")
print(f" P&L: ${pos['unrealized_pl']:+,.2f} ({pos['unrealized_plpc']:+.2f}%)")
# Best/Worst performers
if metrics['largest_winner'] and metrics['largest_loser']:
print("\n⭐ TOP PERFORMERS")
print("-" * 70)
winner = metrics['largest_winner']
loser = metrics['largest_loser']
print(f"\n🏆 Best: {winner['symbol']} (+{winner['unrealized_plpc']:.2f}%)")
print(f" ${winner['unrealized_pl']:+,.2f}")
print(f"\n💔 Worst: {loser['symbol']} ({loser['unrealized_plpc']:.2f}%)")
print(f" ${loser['unrealized_pl']:+,.2f}")
# Portfolio allocation
print("\n📊 PORTFOLIO ALLOCATION")
print("-" * 70)
if positions:
total_invested = sum(p['market_value'] for p in positions)
for pos in sorted(positions, key=lambda x: x['market_value'], reverse=True):
allocation = (pos['market_value'] / account['portfolio_value']) * 100
bar_length = int(allocation / 2)
bar = "█" * bar_length
print(f"{pos['symbol']:6} {bar:20} {allocation:5.1f}% ${pos['market_value']:>10,.2f}")
print("\n" + "="*70 + "\n")
def export_report(self, filename="portfolio_report.json"):
"""Export portfolio report to JSON"""
report = {
'timestamp': datetime.now().isoformat(),
'account': self.get_account_summary(),
'positions': self.get_positions(),
'metrics': self.calculate_metrics(),
'history': self.get_portfolio_history(30)
}
filepath = os.path.join(os.path.dirname(__file__), filename)
with open(filepath, 'w') as f:
json.dump(report, f, indent=2)
print(f"✅ Report exported to: {filepath}")
return filepath
def demo():
"""Demo portfolio tracker"""
print("\n" + "="*70)
print("📊 SPINERIP PORTFOLIO TRACKER")
print("="*70 + "\n")
tracker = PortfolioTracker()
# Display dashboard
tracker.display_dashboard()
# Performance history
print("📈 PERFORMANCE HISTORY (30 DAYS)")
print("-" * 70 + "\n")
history = tracker.get_portfolio_history(30)
# Show last 7 days
print("Last 7 Days:")
for i in range(-7, 0):
date = history['dates'][i]
equity = history['equity'][i]
pl = history['profit_loss'][i]
pl_pct = history['profit_loss_pct'][i]
emoji = "📈" if pl >= 0 else "📉"
print(f"{emoji} {date}: ${equity:>10,.2f} ({pl:+8,.2f} | {pl_pct:+6.2f}%)")
print("\n" + "="*70)
print("💰 SPINERIP PRO FEATURES")
print("="*70 + "\n")
print("✓ Real-time portfolio tracking")
print("✓ Detailed P&L analytics")
print("✓ Win rate calculations")
print("✓ Performance charts")
print("✓ Position alerts")
print("✓ Export reports (CSV/JSON)")
print("✓ Tax reporting")
print("✓ Historical backtesting")
print("\n💳 Upgrade to PRO:")
print(" Monthly: $19/month")
print(" Lifetime: $99 one-time")
print("\n💸 Cash App: $JustinHawpetoss7")
print("\n" + "="*70 + "\n")
# Export report
tracker.export_report()
if __name__ == "__main__":
demo()