-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathverify_signals_performance.py
More file actions
396 lines (333 loc) Β· 15.7 KB
/
Copy pathverify_signals_performance.py
File metadata and controls
396 lines (333 loc) Β· 15.7 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
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
#!/usr/bin/env python3
"""
Verify Signals Performance - Run after 1 month to analyze signal accuracy
This script analyzes all signals and positions to:
1. Check if entry prices matched live prices at signal time
2. Verify if stop loss/target were hit correctly
3. Calculate actual P&L vs expected
4. Generate performance report
5. Identify any issues with stale data or incorrect prices
"""
import pandas as pd
import sys
import os
from datetime import datetime, timedelta
import json
if hasattr(sys.stdout, 'reconfigure'):
sys.stdout.reconfigure(encoding='utf-8')
def safe_float(v, default=0.0):
import math
if v is None or pd.isna(v) or (isinstance(v, float) and math.isnan(v)):
return default
return float(v)
def safe_int(v, default=0):
import math
if v is None or pd.isna(v) or (isinstance(v, float) and math.isnan(v)):
return default
return int(v)
def safe_str(v, default=""):
if v is None or pd.isna(v):
return default
return str(v)
# Import from main scanner
import importlib.util
spec = importlib.util.spec_from_file_location("scanner", "streamlined_ipo_scanner.py")
scanner_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(scanner_module)
get_live_price = scanner_module.get_live_price
logger = scanner_module.logger
# Metadata & State (Legacy CSVs removed, using MongoDB)
from db import get_all_signals_df, get_all_positions_df
REPORT_FILE = "signals_performance_report.json"
def analyze_signals(version=None):
"""Analyze all signals for performance"""
print("π Analyzing Signals Performance...")
print("=" * 80)
# Load signals from MongoDB
signals_df = get_all_signals_df()
if signals_df.empty:
print("β No signals found!")
return None
if version:
if 'strategy_version' in signals_df.columns:
# Handle float/string comparison safely
signals_df = signals_df[signals_df['strategy_version'].astype(str) == str(version)]
elif 'version' in signals_df.columns:
signals_df = signals_df[signals_df['version'].astype(str) == str(version)]
print(f"\nπ Found {len(signals_df)} signals to analyze\n")
results = {
'total_signals': len(signals_df),
'active_signals': 0,
'closed_signals': 0,
'signals_analysis': [],
'summary': {
'total_pnl': 0,
'winning_signals': 0,
'losing_signals': 0,
'avg_pnl': 0,
'max_profit': 0,
'max_loss': 0
}
}
for idx, signal in signals_df.iterrows():
symbol = signal['symbol']
entry_price = signal['entry_price']
stop_loss = signal['stop_loss']
target_price = signal['target_price']
signal_date = pd.to_datetime(signal['signal_date']).date()
status = signal.get('status', 'ACTIVE')
exit_price = signal.get('exit_price', 0)
exit_date = signal.get('exit_date', '')
pnl_pct = signal.get('pnl_pct', 0)
days_held = signal.get('days_held', 0)
grade = signal.get('grade', 'N/A')
signal_type = signal.get('signal_type', 'UNKNOWN')
today = datetime.today().date()
days_since_signal = (today - signal_date).days
print(f"\n{'='*80}")
print(f"π Signal: {symbol} ({signal_type})")
print(f" Grade: {grade} | Status: {status}")
print(f" Signal Date: {signal_date} ({days_since_signal} days ago)")
print(f" Entry: βΉ{entry_price:.2f} | Stop: βΉ{stop_loss:.2f} | Target: βΉ{target_price:.2f}")
# Get current live price
current_price = None
price_source = "Unknown"
try:
current_price, price_source, _, _vol = get_live_price(symbol)
if current_price:
print(f" Current Price: βΉ{current_price:.2f} ({price_source})")
except Exception as e:
print(f" β οΈ Could not fetch current price: {e}")
signal_analysis = {
'symbol': symbol,
'signal_date': safe_str(signal_date),
'signal_type': safe_str(signal_type),
'grade': safe_str(grade),
'status': safe_str(status),
'entry_price': safe_float(entry_price),
'stop_loss': safe_float(stop_loss),
'target_price': safe_float(target_price),
'days_since_signal': days_since_signal,
'current_price': safe_float(current_price) if current_price else None,
'price_source': safe_str(price_source),
'exit_price': safe_float(exit_price),
'exit_date': safe_str(exit_date),
'pnl_pct': safe_float(pnl_pct),
'days_held': safe_int(days_held),
'issues': []
}
# Analyze performance
if status == 'CLOSED' and exit_price > 0:
results['closed_signals'] += 1
actual_pnl = ((exit_price - entry_price) / entry_price) * 100
signal_analysis['actual_pnl'] = actual_pnl
signal_analysis['expected_pnl'] = float(pnl_pct)
# Check if stop loss or target was hit
if exit_price <= stop_loss * 1.01: # Allow 1% tolerance
signal_analysis['exit_reason'] = 'Stop Loss Hit'
print(f" π Exit: Stop Loss Hit at βΉ{exit_price:.2f}")
elif exit_price >= target_price * 0.99: # Allow 1% tolerance
signal_analysis['exit_reason'] = 'Target Hit'
print(f" π― Exit: Target Hit at βΉ{exit_price:.2f}")
else:
signal_analysis['exit_reason'] = 'Manual/Other'
print(f" π Exit: βΉ{exit_price:.2f} (Manual/Other)")
print(f" P&L: {actual_pnl:.2f}% (Expected: {pnl_pct:.2f}%)")
if actual_pnl > 0:
results['summary']['winning_signals'] += 1
else:
results['summary']['losing_signals'] += 1
results['summary']['total_pnl'] += actual_pnl
results['summary']['max_profit'] = max(results['summary']['max_profit'], actual_pnl)
results['summary']['max_loss'] = min(results['summary']['max_loss'], actual_pnl)
else:
results['active_signals'] += 1
if current_price:
current_pnl = ((current_price - entry_price) / entry_price) * 100
signal_analysis['current_pnl'] = current_pnl
print(f" π Current P&L: {current_pnl:.2f}%")
# Check if stop loss or target would be hit
if current_price <= stop_loss * 1.01:
signal_analysis['status_check'] = 'Near Stop Loss'
print(f" β οΈ Near Stop Loss!")
elif current_price >= target_price * 0.99:
signal_analysis['status_check'] = 'Near Target'
print(f" π― Near Target!")
else:
signal_analysis['status_check'] = 'In Range'
# Check for issues
if current_price:
price_diff = abs(current_price - entry_price)
price_diff_pct = (price_diff / entry_price * 100) if entry_price > 0 else 0
# If signal is old and price difference is significant, flag it
if days_since_signal > 7 and price_diff_pct > 10:
signal_analysis['issues'].append(f'Large price difference ({price_diff_pct:.1f}%) after {days_since_signal} days')
print(f" β οΈ ISSUE: Large price difference: {price_diff_pct:.1f}%")
results['signals_analysis'].append(signal_analysis)
# Calculate averages
if results['closed_signals'] > 0:
results['summary']['avg_pnl'] = results['summary']['total_pnl'] / results['closed_signals']
return results
def analyze_positions(version=None):
"""Analyze all positions for performance"""
print("\n\n" + "=" * 80)
print("π Analyzing Positions Performance...")
print("=" * 80)
# Load positions from MongoDB
positions_df = get_all_positions_df()
if positions_df.empty:
print("β No positions found!")
return None
if version:
if 'strategy_version' in positions_df.columns:
# Handle float/string comparison safely
positions_df = positions_df[positions_df['strategy_version'].astype(str) == str(version)]
elif 'version' in positions_df.columns:
positions_df = positions_df[positions_df['version'].astype(str) == str(version)]
print(f"\nπ° Found {len(positions_df)} positions to analyze\n")
results = {
'total_positions': len(positions_df),
'active_positions': 0,
'closed_positions': 0,
'positions_analysis': [],
'summary': {
'total_pnl': 0,
'winning_positions': 0,
'losing_positions': 0,
'avg_pnl': 0
}
}
for idx, pos in positions_df.iterrows():
symbol = pos['symbol']
entry_price = pos['entry_price']
entry_date = pd.to_datetime(pos['entry_date']).date()
status = pos.get('status', 'ACTIVE')
current_price = pos.get('current_price', entry_price)
stop_loss = pos.get('stop_loss', 0)
trailing_stop = pos.get('trailing_stop', 0)
pnl_pct = pos.get('pnl_pct', 0)
days_held = pos.get('days_held', 0)
exit_price = pos.get('exit_price', 0)
exit_date = pos.get('exit_date', '')
grade = pos.get('grade', 'N/A')
today = datetime.today().date()
days_since_entry = (today - entry_date).days
print(f"\n{'='*80}")
print(f"π° Position: {symbol} ({status})")
print(f" Grade: {grade}")
print(f" Entry Date: {entry_date} ({days_since_entry} days ago)")
print(f" Entry: βΉ{entry_price:.2f} | Stop: βΉ{stop_loss:.2f} | Trailing: βΉ{trailing_stop:.2f}")
# Get current live price
live_price = None
price_source = "Unknown"
try:
live_price, price_source, _, _vol = get_live_price(symbol)
if live_price:
print(f" Current Live Price: βΉ{live_price:.2f} ({price_source})")
print(f" Stored Price: βΉ{current_price:.2f}")
except Exception as e:
print(f" β οΈ Could not fetch live price: {e}")
position_analysis = {
'symbol': symbol,
'entry_date': safe_str(entry_date),
'grade': safe_str(grade),
'status': safe_str(status),
'entry_price': safe_float(entry_price),
'stop_loss': safe_float(stop_loss),
'trailing_stop': safe_float(trailing_stop),
'days_since_entry': days_since_entry,
'stored_current_price': safe_float(current_price),
'live_price': safe_float(live_price) if live_price else None,
'price_source': safe_str(price_source),
'exit_price': safe_float(exit_price),
'exit_date': safe_str(exit_date),
'pnl_pct': safe_float(pnl_pct),
'days_held': safe_int(days_held),
'issues': []
}
if status == 'CLOSED':
results['closed_positions'] += 1
if exit_price > 0:
actual_pnl = ((exit_price - entry_price) / entry_price) * 100
position_analysis['actual_pnl'] = actual_pnl
print(f" π Exit: βΉ{exit_price:.2f} | P&L: {actual_pnl:.2f}%")
if actual_pnl > 0:
results['summary']['winning_positions'] += 1
else:
results['summary']['losing_positions'] += 1
results['summary']['total_pnl'] += actual_pnl
else:
results['active_positions'] += 1
if live_price:
current_pnl = ((live_price - entry_price) / entry_price) * 100
position_analysis['current_pnl'] = current_pnl
print(f" π Current P&L: {current_pnl:.2f}%")
# Check price accuracy
stored_diff = abs(live_price - current_price)
stored_diff_pct = (stored_diff / current_price * 100) if current_price > 0 else 0
if stored_diff_pct > 3:
position_analysis['issues'].append(f'Stored price differs by {stored_diff_pct:.1f}% from live')
print(f" β οΈ ISSUE: Stored price differs by {stored_diff_pct:.1f}%")
results['positions_analysis'].append(position_analysis)
# Calculate averages
if results['closed_positions'] > 0:
results['summary']['avg_pnl'] = results['summary']['total_pnl'] / results['closed_positions']
return results
def generate_report(signals_results, positions_results):
"""Generate comprehensive performance report"""
print("\n\n" + "=" * 80)
print("π GENERATING PERFORMANCE REPORT")
print("=" * 80)
report = {
'report_date': str(datetime.today().date()),
'signals': signals_results,
'positions': positions_results
}
# Save to JSON
with open(REPORT_FILE, 'w', encoding='utf-8') as f:
json.dump(report, f, indent=2, ensure_ascii=False)
print(f"\nβ
Report saved to: {REPORT_FILE}")
# Print summary
print("\n" + "=" * 80)
print("π SUMMARY")
print("=" * 80)
if signals_results:
print(f"\nπ SIGNALS:")
print(f" Total Signals: {signals_results['total_signals']}")
print(f" Active: {signals_results['active_signals']}")
print(f" Closed: {signals_results['closed_signals']}")
if signals_results['closed_signals'] > 0:
print(f" Winning: {signals_results['summary']['winning_signals']}")
print(f" Losing: {signals_results['summary']['losing_signals']}")
print(f" Average P&L: {signals_results['summary']['avg_pnl']:.2f}%")
print(f" Max Profit: {signals_results['summary']['max_profit']:.2f}%")
print(f" Max Loss: {signals_results['summary']['max_loss']:.2f}%")
if positions_results:
print(f"\nπ° POSITIONS:")
print(f" Total Positions: {positions_results['total_positions']}")
print(f" Active: {positions_results['active_positions']}")
print(f" Closed: {positions_results['closed_positions']}")
if positions_results['closed_positions'] > 0:
print(f" Winning: {positions_results['summary']['winning_positions']}")
print(f" Losing: {positions_results['summary']['losing_positions']}")
print(f" Average P&L: {positions_results['summary']['avg_pnl']:.2f}%")
print("\n" + "=" * 80)
print("β
Analysis complete! Check the JSON report for detailed information.")
print("=" * 80)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Verify signals and positions performance")
parser.add_argument("--version", "-v", type=str, help="Filter strategy version (e.g. 3.3.0)")
args = parser.parse_args()
print("π SIGNALS PERFORMANCE VERIFICATION")
print("=" * 80)
print("This script analyzes all signals and positions to verify performance.")
print("Run this after 1 month to check signal accuracy and identify issues.\n")
if args.version:
print(f"Filtering by strategy version: {args.version}")
signals_results = analyze_signals(version=args.version)
positions_results = analyze_positions(version=args.version)
if signals_results or positions_results:
generate_report(signals_results, positions_results)
else:
print("\nβ No data to analyze!")