-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
3751 lines (3072 loc) · 141 KB
/
app.py
File metadata and controls
3751 lines (3072 loc) · 141 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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Flask web application for financial chart analysis with local LLM."""
# Fix UTF-8 encoding for Windows PowerShell
import sys
import io
if sys.stdout.encoding != 'utf-8':
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
if sys.stderr.encoding != 'utf-8':
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
from flask import Flask, render_template, request, jsonify, redirect, url_for, session
from flask_login import login_required, current_user
from data_fetcher import FinancialDataFetcher, normalize_crypto_symbol
from chart_generator import ChartGenerator
from pattern_recognizer import PatternRecognizer
from llm_analyzer import LLMAnalyzer
from config import Config
from datetime import datetime, timedelta
import json
import traceback
import pandas as pd
import os
# Phase 2: Database and Authentication
try:
from models import db, User, Watchlist, Alert, Portfolio, Transaction, OptionsPosition, AnalysisHistory, MLPattern, MLPrediction, PortfolioSnapshot, PortfolioAccount, Dividend, DiscussionThread, ThreadReply, ThreadVote, CopyTradingFollow
from db_config import init_database
from auth import init_auth, get_auth_routes, require_api_auth
from monitoring_service import init_monitoring_service, get_monitoring_service
from ml_pattern_detector import MLPatternDetector
PHASE2_ENABLED = True
except ImportError as e:
print(f"⚠ Phase 2 features not available: {e}")
print("ℹ Run 'install_phase2.bat' to enable database and authentication")
PHASE2_ENABLED = False
# Define dummy decorator for when auth is not available
def require_api_auth(f):
"""Dummy auth decorator when Phase 2 is disabled"""
return f
# Phase 3: Advanced Trading Intelligence
try:
from options_analyzer import OptionsAnalyzer
from trading_time_analyzer import TradingTimeAnalyzer
from sentiment_analyzer import SentimentAnalyzer
from risk_analyzer import RiskAnalyzer
PHASE3_ENABLED = True
except ImportError as e:
print(f"⚠ Phase 3 features not available: {e}")
print("ℹ Run 'install_phase3.bat' to enable advanced analysis")
PHASE3_ENABLED = False
# Phase 4: Portfolio Management & Real-Time Intelligence
try:
from volatility_monitor import VolatilityMonitor
from portfolio_analyzer import PortfolioAnalyzer
from smart_alerts import SmartAlertsEngine
from alert_suggestions import AlertSuggestionEngine
from news_fetcher import NewsFetcher
from correlation_analyzer import CorrelationAnalyzer
from trade_journal import TradeJournal
from politician_trades import PoliticianTradeTracker
PHASE4_ENABLED = True
except ImportError as e:
print(f"⚠ Phase 4 features not available: {e}")
print("ℹ Phase 4 requires Phase 2 database and Phase 3 analyzers")
PHASE4_ENABLED = False
from werkzeug.middleware.proxy_fix import ProxyFix
def _get_current_user_id():
"""Safely get current user ID without requiring login_manager"""
uid = session.get('user_id')
if uid:
return uid
try:
if hasattr(app, 'login_manager') and current_user.is_authenticated:
return current_user.id
except Exception:
pass
return None
app = Flask(__name__)
app.config.from_object(Config)
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1)
# Add logging for debugging
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# Phase 2: Initialize database and authentication
if PHASE2_ENABLED:
try:
# Initialize database
database = init_database(app)
logger.info("✓ Database initialized")
# Initialize authentication
login_manager, google_oauth = init_auth(app)
logger.info("✓ Authentication system initialized")
# Initialize ML pattern detector
ml_detector = MLPatternDetector()
logger.info("✓ ML Pattern Detector initialized")
# Initialize monitoring service with longer interval to reduce API load
monitoring_svc = init_monitoring_service(app, check_interval=900) # 15 minutes
logger.info("✓ Real-time Monitoring Service initialized (15min interval)")
# Register authentication routes
auth_routes = get_auth_routes(google_oauth)
@app.route('/login')
def login():
return auth_routes['login']()
@app.route('/authorize')
def authorize():
return auth_routes['authorize']()
@app.route('/logout')
def logout():
return auth_routes['logout']()
logger.info("✓ Authentication routes registered")
except Exception as e:
logger.error(f"✗ Failed to initialize Phase 2 features: {e}")
PHASE2_ENABLED = False
else:
logger.info("ℹ Running in Phase 1 mode (no authentication)")
# Phase 3: Initialize advanced analyzers
if PHASE3_ENABLED:
try:
options_analyzer = OptionsAnalyzer()
logger.info("✓ Options Analyzer initialized")
trading_time_analyzer = TradingTimeAnalyzer()
logger.info("✓ Trading Time Analyzer initialized")
sentiment_analyzer = SentimentAnalyzer()
logger.info("✓ Sentiment Analyzer initialized")
risk_analyzer = RiskAnalyzer()
logger.info("✓ Risk Analyzer initialized")
except Exception as e:
logger.error(f"✗ Failed to initialize Phase 3 features: {e}")
PHASE3_ENABLED = False
else:
logger.info("ℹ Phase 3 features not available")
# Phase 4: Initialize portfolio management & volatility monitoring
if PHASE4_ENABLED and PHASE2_ENABLED:
try:
volatility_monitor = VolatilityMonitor()
logger.info("✓ Volatility Monitor initialized")
portfolio_analyzer = PortfolioAnalyzer()
logger.info("✓ Portfolio Analyzer initialized")
smart_alerts = SmartAlertsEngine()
logger.info("✓ Smart Alerts Engine initialized")
# Initialize alert suggestions engine with other analyzers
pattern_rec = PatternRecognizer() if 'PatternRecognizer' in dir() else None
sentiment_an = sentiment_analyzer if PHASE3_ENABLED else None
alert_suggestions = AlertSuggestionEngine(
pattern_recognizer=pattern_rec,
sentiment_analyzer=sentiment_an,
volatility_monitor=volatility_monitor,
portfolio_analyzer=portfolio_analyzer
)
logger.info("✓ AI Alert Suggestion Engine initialized")
# Initialize news fetcher
news_fetcher = NewsFetcher()
logger.info("✓ News Fetcher initialized")
# Initialize correlation analyzer
correlation_analyzer = CorrelationAnalyzer()
logger.info("✓ Correlation Analyzer initialized")
except Exception as e:
logger.error(f"✗ Failed to initialize Phase 4 features: {e}")
PHASE4_ENABLED = False
else:
if not PHASE2_ENABLED:
logger.info("ℹ Phase 4 requires Phase 2 (database)")
else:
logger.info("ℹ Phase 4 features not available")
# Initialize components
try:
data_fetcher = FinancialDataFetcher()
logger.info("✓ FinancialDataFetcher initialized")
except Exception as e:
logger.error(f"✗ Failed to initialize FinancialDataFetcher: {e}")
raise
try:
chart_generator = ChartGenerator()
logger.info("✓ ChartGenerator initialized")
except Exception as e:
logger.error(f"✗ Failed to initialize ChartGenerator: {e}")
raise
try:
pattern_recognizer = PatternRecognizer()
logger.info("✓ PatternRecognizer initialized")
except Exception as e:
logger.error(f"✗ Failed to initialize PatternRecognizer: {e}")
raise
try:
llm_analyzer = LLMAnalyzer()
logger.info("✓ LLMAnalyzer initialized")
except Exception as e:
logger.error(f"✗ Failed to initialize LLMAnalyzer: {e}")
raise
# Initialize Trade Journal after LLM Analyzer (Feature #5)
if PHASE4_ENABLED and PHASE2_ENABLED:
try:
trade_journal = TradeJournal(llm_analyzer)
logger.info("✓ Trade Journal initialized")
except Exception as e:
logger.error(f"✗ Failed to initialize Trade Journal: {e}")
@app.before_request
def log_request():
"""Log all incoming requests."""
logger.info(f"→ {request.method} {request.path}")
@app.after_request
def log_response(response):
"""Log all responses."""
logger.info(f"← {request.method} {request.path} → {response.status_code}")
return response
@app.route('/')
def index():
"""Render the main dashboard."""
logger.debug("Rendering dashboard.html as main page")
if PHASE2_ENABLED:
# Require login for Phase 2
if not current_user.is_authenticated:
return redirect(url_for('login'))
return render_template('dashboard.html')
@app.route('/api/test/yfinance', methods=['GET'])
def test_yfinance():
"""Test endpoint to verify Yahoo Finance connectivity."""
try:
symbol = request.args.get('symbol', 'AAPL')
logger.info(f"Testing Yahoo Finance with symbol: {symbol}")
# Try to fetch minimal data
stock_data = data_fetcher.fetch_stock_data(symbol, period='5d', interval='1d')
if stock_data is None:
return jsonify({
'status': 'failed',
'error': 'No data returned from Yahoo Finance',
'symbol': symbol,
'message': 'Yahoo Finance API may be down or rate limiting'
}), 503
if stock_data.empty:
return jsonify({
'status': 'failed',
'error': 'Empty data returned',
'symbol': symbol,
'message': 'Symbol may be invalid or data not available'
}), 404
return jsonify({
'status': 'success',
'symbol': symbol,
'rows': len(stock_data),
'columns': list(stock_data.columns),
'latest_price': float(stock_data['Close'].iloc[-1]) if 'Close' in stock_data.columns else None,
'message': 'Yahoo Finance connection working'
}), 200
except Exception as e:
logger.error(f"Error testing Yahoo Finance: {e}", exc_info=True)
return jsonify({
'status': 'error',
'error': str(e),
'message': 'Exception during Yahoo Finance test'
}), 500
@app.route('/dashboard')
def dashboard():
"""Render the enhanced dashboard with watchlist, alerts, and comparison features."""
logger.debug("Rendering dashboard.html")
if PHASE2_ENABLED:
# Require login for Phase 2
if not current_user.is_authenticated:
return redirect(url_for('login'))
return render_template('dashboard.html')
@app.route('/simple')
def simple():
"""Render the simple/classic interface."""
logger.debug("Rendering index.html (simple interface)")
return render_template('index.html')
@app.route('/portfolio')
@login_required
def portfolio():
"""Render the portfolio analytics dashboard (Phase 4)."""
logger.debug("Rendering portfolio.html")
if not PHASE4_ENABLED:
return "Portfolio features are not enabled", 503
return render_template('portfolio.html')
@app.route('/copytrading')
@login_required
def copytrading():
"""Render the copy trading research page."""
logger.debug("Rendering copytrading.html")
return render_template('copytrading.html')
@app.route('/admin')
@login_required
def admin_page():
"""Render the admin dashboard (admin only)."""
if not current_user.is_admin():
return redirect(url_for('portfolio'))
return render_template('admin.html')
@app.route('/community')
@login_required
def community_page():
"""Render the community discussion page."""
return render_template('community.html')
# ===================== ADMIN API =====================
@app.route('/api/admin/users', methods=['GET'])
@require_api_auth
def admin_list_users():
"""List all users (admin only)."""
if not current_user.is_admin():
return jsonify({'error': 'Unauthorized'}), 403
users = User.query.order_by(User.created_at.desc()).all()
return jsonify({'users': [u.to_dict() for u in users]})
@app.route('/api/admin/users/<int:user_id>/role', methods=['PUT'])
@require_api_auth
def admin_change_role(user_id):
"""Change a user's role (admin only)."""
if not current_user.is_admin():
return jsonify({'error': 'Unauthorized'}), 403
data = request.get_json()
role = data.get('role')
if role not in ('user', 'moderator', 'admin'):
return jsonify({'error': 'Invalid role'}), 400
user = User.query.get_or_404(user_id)
if user.id == current_user.id:
return jsonify({'error': 'Cannot change your own role'}), 400
user.role = role
db.session.commit()
return jsonify({'success': True, 'user': user.to_dict()})
@app.route('/api/admin/users/<int:user_id>/active', methods=['PUT'])
@require_api_auth
def admin_toggle_active(user_id):
"""Enable/disable a user account (admin only)."""
if not current_user.is_admin():
return jsonify({'error': 'Unauthorized'}), 403
user = User.query.get_or_404(user_id)
if user.id == current_user.id:
return jsonify({'error': 'Cannot disable your own account'}), 400
data = request.get_json()
user.is_active = data.get('is_active', True)
db.session.commit()
return jsonify({'success': True, 'user': user.to_dict()})
@app.route('/api/admin/stats', methods=['GET'])
@require_api_auth
def admin_stats():
"""Get admin dashboard stats."""
if not current_user.is_admin():
return jsonify({'error': 'Unauthorized'}), 403
total_users = User.query.count()
active_users = User.query.filter_by(is_active=True).count()
total_threads = DiscussionThread.query.count()
total_holdings = Portfolio.query.count()
return jsonify({
'total_users': total_users,
'active_users': active_users,
'total_threads': total_threads,
'total_holdings': total_holdings,
})
# ===================== COMMUNITY API =====================
@app.route('/api/community/threads', methods=['GET'])
@require_api_auth
def list_threads():
"""List discussion threads with optional category filter."""
category = request.args.get('category', 'all')
page = int(request.args.get('page', 1))
per_page = int(request.args.get('per_page', 20))
query = DiscussionThread.query
if category != 'all':
query = query.filter_by(category=category)
query = query.order_by(DiscussionThread.pinned.desc(), DiscussionThread.created_at.desc())
pagination = query.paginate(page=page, per_page=per_page, error_out=False)
threads = []
for t in pagination.items:
td = t.to_dict()
td['reply_count'] = ThreadReply.query.filter_by(thread_id=t.id).count()
threads.append(td)
return jsonify({
'threads': threads,
'total': pagination.total,
'pages': pagination.pages,
'current_page': page,
})
@app.route('/api/community/threads', methods=['POST'])
@require_api_auth
def create_thread():
"""Create a new discussion thread."""
data = request.get_json()
title = (data.get('title') or '').strip()
body = (data.get('body') or '').strip()
if not title or not body:
return jsonify({'error': 'Title and body are required'}), 400
thread = DiscussionThread(
user_id=current_user.id,
title=title[:200],
body=body[:10000],
symbol=(data.get('symbol') or '').upper()[:10] or None,
category=data.get('category', 'general'),
)
db.session.add(thread)
db.session.commit()
return jsonify({'success': True, 'thread': thread.to_dict()}), 201
@app.route('/api/community/threads/<int:thread_id>', methods=['GET'])
@require_api_auth
def get_thread(thread_id):
"""Get a single thread with its replies."""
thread = DiscussionThread.query.get_or_404(thread_id)
thread.views = (thread.views or 0) + 1
db.session.commit()
td = thread.to_dict()
replies = ThreadReply.query.filter_by(thread_id=thread_id)\
.order_by(ThreadReply.created_at.asc()).all()
td['replies'] = [r.to_dict() for r in replies]
# Include current user's votes
votes = ThreadVote.query.filter_by(user_id=current_user.id, thread_id=thread_id).all()
user_votes = {}
for v in votes:
key = f'reply_{v.reply_id}' if v.reply_id else 'thread'
user_votes[key] = v.vote
td['user_votes'] = user_votes
return jsonify(td)
@app.route('/api/community/threads/<int:thread_id>/replies', methods=['POST'])
@require_api_auth
def add_reply(thread_id):
"""Add a reply to a thread."""
thread = DiscussionThread.query.get_or_404(thread_id)
if thread.locked:
return jsonify({'error': 'Thread is locked'}), 403
data = request.get_json()
body = (data.get('body') or '').strip()
if not body:
return jsonify({'error': 'Reply body is required'}), 400
reply = ThreadReply(
thread_id=thread_id,
user_id=current_user.id,
body=body[:10000],
)
db.session.add(reply)
thread.updated_at = datetime.utcnow()
db.session.commit()
return jsonify({'success': True, 'reply': reply.to_dict()}), 201
@app.route('/api/community/threads/<int:thread_id>/vote', methods=['POST'])
@require_api_auth
def vote_thread(thread_id):
"""Upvote/downvote a thread."""
thread = DiscussionThread.query.get_or_404(thread_id)
data = request.get_json()
vote_val = data.get('vote', 1)
if vote_val not in (1, -1):
return jsonify({'error': 'Vote must be 1 or -1'}), 400
existing = ThreadVote.query.filter_by(
user_id=current_user.id, thread_id=thread_id, reply_id=None
).first()
if existing:
if existing.vote == vote_val:
# Remove vote
thread.upvotes = (thread.upvotes or 0) - vote_val
db.session.delete(existing)
else:
# Change vote
thread.upvotes = (thread.upvotes or 0) + (vote_val - existing.vote)
existing.vote = vote_val
else:
thread.upvotes = (thread.upvotes or 0) + vote_val
db.session.add(ThreadVote(
user_id=current_user.id, thread_id=thread_id, reply_id=None, vote=vote_val
))
db.session.commit()
return jsonify({'success': True, 'upvotes': thread.upvotes})
@app.route('/api/community/replies/<int:reply_id>/vote', methods=['POST'])
@require_api_auth
def vote_reply(reply_id):
"""Upvote/downvote a reply."""
reply = ThreadReply.query.get_or_404(reply_id)
data = request.get_json()
vote_val = data.get('vote', 1)
if vote_val not in (1, -1):
return jsonify({'error': 'Vote must be 1 or -1'}), 400
existing = ThreadVote.query.filter_by(
user_id=current_user.id, thread_id=reply.thread_id, reply_id=reply_id
).first()
if existing:
if existing.vote == vote_val:
reply.upvotes = (reply.upvotes or 0) - vote_val
db.session.delete(existing)
else:
reply.upvotes = (reply.upvotes or 0) + (vote_val - existing.vote)
existing.vote = vote_val
else:
reply.upvotes = (reply.upvotes or 0) + vote_val
db.session.add(ThreadVote(
user_id=current_user.id, thread_id=reply.thread_id, reply_id=reply_id, vote=vote_val
))
db.session.commit()
return jsonify({'success': True, 'upvotes': reply.upvotes})
@app.route('/api/community/threads/<int:thread_id>', methods=['DELETE'])
@require_api_auth
def delete_thread(thread_id):
"""Delete a thread (author or moderator)."""
thread = DiscussionThread.query.get_or_404(thread_id)
if thread.user_id != current_user.id and not current_user.is_moderator():
return jsonify({'error': 'Unauthorized'}), 403
db.session.delete(thread)
db.session.commit()
return jsonify({'success': True})
@app.route('/api/community/threads/<int:thread_id>/lock', methods=['PUT'])
@require_api_auth
def lock_thread(thread_id):
"""Lock/unlock a thread (moderator only)."""
if not current_user.is_moderator():
return jsonify({'error': 'Unauthorized'}), 403
thread = DiscussionThread.query.get_or_404(thread_id)
data = request.get_json()
thread.locked = data.get('locked', True)
db.session.commit()
return jsonify({'success': True, 'locked': thread.locked})
@app.route('/api/community/threads/<int:thread_id>/pin', methods=['PUT'])
@require_api_auth
def pin_thread(thread_id):
"""Pin/unpin a thread (moderator only)."""
if not current_user.is_moderator():
return jsonify({'error': 'Unauthorized'}), 403
thread = DiscussionThread.query.get_or_404(thread_id)
data = request.get_json()
thread.pinned = data.get('pinned', True)
db.session.commit()
return jsonify({'success': True, 'pinned': thread.pinned})
@app.route('/api/community/online', methods=['GET'])
@require_api_auth
def online_users():
"""List recently active users (active in last 5 minutes)."""
cutoff = datetime.utcnow() - timedelta(minutes=5)
users = User.query.filter(User.last_active >= cutoff).all()
return jsonify({'online': [{'id': u.id, 'name': u.name, 'picture_url': u.picture_url} for u in users]})
# ===================== COPY TRADING MEMBER API =====================
@app.route('/api/copytrading/members', methods=['GET'])
@require_api_auth
def list_copy_trading_members():
"""List users who have opted in to member copy trading."""
members = User.query.filter_by(copy_trading_enabled=True, is_active=True).all()
result = []
for m in members:
holdings_count = Portfolio.query.filter_by(user_id=m.id).count()
follower_count = CopyTradingFollow.query.filter_by(leader_id=m.id).count()
is_following = CopyTradingFollow.query.filter_by(
follower_id=current_user.id, leader_id=m.id
).first() is not None
result.append({
'id': m.id,
'name': m.name,
'picture_url': m.picture_url,
'bio': m.bio,
'holdings_count': holdings_count,
'follower_count': follower_count,
'is_following': is_following,
'member_since': m.created_at.isoformat() if m.created_at else None,
})
return jsonify({'members': result})
@app.route('/api/copytrading/opt-in', methods=['POST'])
@require_api_auth
def toggle_copy_trading():
"""Toggle copy trading opt-in for current user."""
data = request.get_json()
current_user.copy_trading_enabled = data.get('enabled', False)
if data.get('bio') is not None:
current_user.bio = (data['bio'] or '')[:500]
db.session.commit()
return jsonify({'success': True, 'enabled': current_user.copy_trading_enabled})
@app.route('/api/copytrading/follow/<int:leader_id>', methods=['POST'])
@require_api_auth
def follow_member(leader_id):
"""Follow a member for copy trading."""
if leader_id == current_user.id:
return jsonify({'error': 'Cannot follow yourself'}), 400
leader = User.query.get_or_404(leader_id)
if not leader.copy_trading_enabled:
return jsonify({'error': 'This user has not enabled copy trading'}), 400
existing = CopyTradingFollow.query.filter_by(
follower_id=current_user.id, leader_id=leader_id
).first()
if existing:
return jsonify({'error': 'Already following'}), 400
db.session.add(CopyTradingFollow(follower_id=current_user.id, leader_id=leader_id))
db.session.commit()
return jsonify({'success': True})
@app.route('/api/copytrading/unfollow/<int:leader_id>', methods=['POST'])
@require_api_auth
def unfollow_member(leader_id):
"""Unfollow a copy trading member."""
follow = CopyTradingFollow.query.filter_by(
follower_id=current_user.id, leader_id=leader_id
).first()
if follow:
db.session.delete(follow)
db.session.commit()
return jsonify({'success': True})
@app.route('/api/copytrading/status', methods=['GET'])
@require_api_auth
def copy_trading_status():
"""Get current user's copy trading status."""
return jsonify({
'enabled': current_user.copy_trading_enabled or False,
'bio': current_user.bio or '',
'follower_count': CopyTradingFollow.query.filter_by(leader_id=current_user.id).count(),
'following_count': CopyTradingFollow.query.filter_by(follower_id=current_user.id).count(),
})
@app.route('/api/user/heartbeat', methods=['POST'])
@require_api_auth
def user_heartbeat():
"""Update user's last active timestamp."""
current_user.last_active = datetime.utcnow()
db.session.commit()
return jsonify({'success': True})
@app.route('/api/user/preferences', methods=['GET'])
@require_api_auth
def get_preferences():
"""Get current user's preferences."""
prefs = current_user.preferences or {}
return jsonify({'preferences': prefs})
@app.route('/api/user/preferences', methods=['PUT'])
@require_api_auth
def save_preferences():
"""Save current user's preferences."""
data = request.get_json()
if not isinstance(data, dict):
return jsonify({'error': 'Invalid data'}), 400
# Only allow known safe keys
allowed = {'darkMode', 'autoRefreshWatchlist', 'notificationsEnabled',
'defaultPeriod', 'defaultChartType'}
prefs = {k: v for k, v in data.items() if k in allowed}
current_user.preferences = {**(current_user.preferences or {}), **prefs}
db.session.commit()
return jsonify({'success': True, 'preferences': current_user.preferences})
@app.route('/api/analyze', methods=['POST'])
def analyze_stock():
"""Analyze a stock symbol and return comprehensive results."""
logger.info("Starting stock analysis...")
try:
data = request.get_json()
if data is None:
logger.error("No JSON data in request")
return jsonify({'error': 'No JSON data provided'}), 400
symbol = data.get('symbol', 'AAPL').upper()
logger.info(f"Analyzing symbol: {symbol}")
period = data.get('period', '6mo')
interval = data.get('interval', '1d')
chart_type = data.get('chart_type', 'candlestick')
# Fetch stock data
logger.info(f"Fetching data for {symbol} (period={period}, interval={interval})")
stock_data = data_fetcher.fetch_stock_data(symbol, period, interval)
if stock_data is None:
logger.error(f"No data returned for {symbol} - check Yahoo Finance API status")
return jsonify({
'error': f'Unable to fetch data for {symbol}. Yahoo Finance may be rate limiting or the symbol may be invalid.',
'symbol': symbol,
'suggestion': 'Try again in a few moments or verify the symbol is correct.'
}), 503
if stock_data.empty:
logger.error(f"Empty dataframe for {symbol}")
return jsonify({
'error': f'No data available for {symbol}',
'symbol': symbol,
'suggestion': 'Please verify the symbol is correct.'
}), 404
logger.info(f"Data fetched: {len(stock_data)} rows")
# Calculate indicators
logger.debug("Calculating technical indicators...")
try:
stock_data = pattern_recognizer.calculate_indicators(stock_data)
except Exception as e:
logger.error(f"Error calculating indicators: {e}")
return jsonify({'error': f'Error calculating indicators: {str(e)}'}), 500
# Generate chart
logger.debug(f"Generating {chart_type} chart...")
try:
if chart_type == 'line':
chart_base64 = chart_generator.generate_line_chart(
stock_data, symbol
)
elif chart_type == 'volume':
chart_base64 = chart_generator.generate_volume_chart(
stock_data, symbol
)
else: # Default to candlestick
chart_base64 = chart_generator.generate_candlestick_chart(
stock_data, symbol
)
except Exception as e:
logger.error(f"Error generating chart: {e}")
# Continue without chart
chart_base64 = ""
# Detect patterns
logger.debug("Detecting patterns...")
try:
candlestick_patterns = pattern_recognizer.detect_candlestick_patterns(stock_data)
support_resistance = pattern_recognizer.detect_support_resistance(stock_data)
trend = pattern_recognizer.detect_trend(stock_data)
signals = pattern_recognizer.generate_signals(stock_data)
except Exception as e:
logger.error(f"Error detecting patterns: {e}")
candlestick_patterns = []
support_resistance = {'support': [], 'resistance': []}
trend = 'unknown'
signals = {}
# Get latest values
try:
latest = stock_data.iloc[-1]
prev = stock_data.iloc[-2] if len(stock_data) > 1 else latest
except Exception as e:
logger.error(f"Error accessing stock data: {e}")
return jsonify({'error': f'Error processing stock data: {str(e)}'}), 500
# Prepare indicators summary
try:
indicators = {
'RSI': round(float(latest.get('RSI', 0)), 2) if pd.notna(latest.get('RSI')) else 0,
'MACD': round(float(latest.get('MACD', 0)), 4) if pd.notna(latest.get('MACD')) else 0,
'MACD_Signal': round(float(latest.get('MACD_Signal', 0)), 4) if pd.notna(latest.get('MACD_Signal')) else 0,
'SMA_20': round(float(latest.get('SMA_20', 0)), 2) if pd.notna(latest.get('SMA_20')) else 0,
'SMA_50': round(float(latest.get('SMA_50', 0)), 2) if pd.notna(latest.get('SMA_50')) else 0,
'BB_High': round(float(latest.get('BB_High', 0)), 2) if pd.notna(latest.get('BB_High')) else 0,
'BB_Low': round(float(latest.get('BB_Low', 0)), 2) if pd.notna(latest.get('BB_Low')) else 0,
}
except Exception as e:
logger.error(f"Error preparing indicators: {e}")
indicators = {'RSI': 0, 'MACD': 0, 'MACD_Signal': 0, 'SMA_20': 0, 'SMA_50': 0, 'BB_High': 0, 'BB_Low': 0}
# LLM analysis
logger.debug("Running LLM analysis...")
try:
llm_analysis = llm_analyzer.analyze_chart(
chart_base64,
symbol,
indicators,
candlestick_patterns,
context=f"Current trend: {trend}"
)
except Exception as e:
logger.error(f"Error in LLM analysis: {e}")
llm_analysis = f"Error performing AI analysis: {str(e)}"
# ML Pattern Detection (Phase 2)
ml_patterns = []
ml_prediction = None
if PHASE2_ENABLED and ml_detector:
logger.debug("Detecting ML patterns...")
try:
ml_patterns = ml_detector.detect_patterns(stock_data, symbol)
logger.info(f"Detected {len(ml_patterns)} ML patterns")
except Exception as e:
logger.error(f"Error detecting ML patterns: {e}")
logger.debug("Generating ML prediction...")
try:
ml_prediction = ml_detector.make_prediction(stock_data, symbol)
if ml_prediction:
logger.info(f"ML Prediction: {ml_prediction['predicted_direction']} ({ml_prediction['confidence']*100:.1f}% confidence)")
except Exception as e:
logger.error(f"Error making ML prediction: {e}")
# Phase 3: Advanced Analysis
sentiment_analysis = None
risk_analysis = None
timing_analysis = None
if PHASE3_ENABLED:
logger.debug("Running Phase 3 analysis...")
try:
sentiment_analysis = sentiment_analyzer.analyze_sentiment(stock_data, symbol)
logger.info(f"Sentiment: {sentiment_analysis.get('sentiment_label', 'N/A')}")
except Exception as e:
logger.error(f"Error in sentiment analysis: {e}")
try:
risk_analysis = risk_analyzer.comprehensive_risk_analysis(stock_data, symbol)
logger.info(f"Risk Score: {risk_analysis.get('overall_risk_score', 'N/A')}")
except Exception as e:
logger.error(f"Error in risk analysis: {e}")
try:
timing_analysis = {
'entry': trading_time_analyzer.analyze_entry_points(stock_data, symbol),
'exit': trading_time_analyzer.analyze_exit_points(stock_data, symbol),
'volume': trading_time_analyzer.analyze_volume_profile(stock_data, symbol)
}
logger.info(f"Entry Score: {timing_analysis['entry'].get('entry_score', 'N/A')}")
except Exception as e:
logger.error(f"Error in timing analysis: {e}")
# Company info
logger.debug("Fetching company info...")
try:
company_info = data_fetcher.get_company_info(symbol)
except Exception as e:
logger.error(f"Error fetching company info: {e}")
company_info = {'name': symbol, 'sector': 'N/A', 'industry': 'N/A', 'market_cap': 'N/A', 'description': 'N/A'}
# Prepare response
try:
response = {
'symbol': symbol,
'company_info': company_info,
'current_price': round(float(latest['Close']), 2),
'price_change': round(float(latest['Close'] - prev['Close']), 2),
'price_change_pct': round(float((latest['Close'] - prev['Close']) / prev['Close'] * 100), 2) if float(prev['Close']) != 0 else 0,
'volume': int(latest['Volume']) if not pd.isna(latest['Volume']) else 0,
'trend': trend,
'chart': f'data:image/png;base64,{chart_base64}' if chart_base64 else '',
'indicators': indicators,
'signals': signals,
'support_resistance': {
'support': [round(float(x), 2) for x in support_resistance['support'][-3:]] if support_resistance['support'] else [],
'resistance': [round(float(x), 2) for x in support_resistance['resistance'][-3:]] if support_resistance['resistance'] else []
},
'patterns': candlestick_patterns,
'ml_patterns': ml_patterns,
'ml_prediction': ml_prediction,
'sentiment': sentiment_analysis,
'risk': risk_analysis,
'timing': timing_analysis,
'llm_analysis': llm_analysis
}
except Exception as e:
logger.error(f"Error preparing response: {e}")
logger.error(traceback.format_exc())
return jsonify({'error': f'Error preparing response: {str(e)}'}), 500
logger.info(f"✓ Analysis complete for {symbol}")
return jsonify(response)
except Exception as e:
logger.error(f"Error analyzing stock: {e}")
logger.error(traceback.format_exc())
return jsonify({'error': str(e), 'traceback': traceback.format_exc()}), 500
@app.route('/api/technical-chart', methods=['POST'])
def generate_technical_chart():
"""Generate technical chart with customizable indicators."""
try:
data = request.get_json()
if data is None:
return jsonify({'error': 'No JSON data provided'}), 400
symbol = data.get('symbol', 'AAPL').upper()
period = data.get('period', '6mo')
interval = data.get('interval', '1d')
indicators = data.get('indicators', []) # ['rsi', 'macd', 'bb', 'ma']
logger.info(f"Generating technical chart for {symbol} with indicators: {indicators}")
# Fetch stock data
stock_data = data_fetcher.fetch_stock_data(symbol, period, interval)
if stock_data is None or stock_data.empty:
return jsonify({'error': f'No data found for {symbol}'}), 404
# Generate technical chart
chart_base64 = chart_generator.generate_technical_chart(
stock_data, symbol, indicators
)
# Get current stats
latest = stock_data.iloc[-1]
current_price = float(latest['Close'])
prev_close = float(stock_data.iloc[-2]['Close']) if len(stock_data) > 1 else current_price
price_change = current_price - prev_close
price_change_pct = (price_change / prev_close * 100) if prev_close != 0 else 0
return jsonify({
'symbol': symbol,
'chart': f'data:image/png;base64,{chart_base64}',
'current_price': round(current_price, 2),
'price_change': round(price_change, 2),
'price_change_pct': round(price_change_pct, 2),
'indicators': indicators
})
except Exception as e:
logger.error(f"Error generating technical chart: {e}")
logger.error(traceback.format_exc())
return jsonify({'error': str(e)}), 500