forked from Y-Research-SBU/QuantAgent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_interface.py
More file actions
896 lines (745 loc) · 33.8 KB
/
web_interface.py
File metadata and controls
896 lines (745 loc) · 33.8 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
import json
import os
import re
import urllib.parse
from datetime import datetime
from pathlib import Path
from typing import Any, Dict
import pandas as pd
import yfinance as yf
from flask import Flask, jsonify, render_template, request, send_file
from openai import OpenAI
import static_util
from trading_graph import TradingGraph
app = Flask(__name__)
class WebTradingAnalyzer:
def __init__(self):
"""Initialize the web trading analyzer."""
self.trading_graph = TradingGraph()
self.data_dir = Path("data")
# Ensure data dir exists
self.data_dir.mkdir(parents=True, exist_ok=True)
# Available assets and their display names
self.asset_mapping = {
"SPX": "S&P 500",
"BTC": "Bitcoin",
"GC": "Gold Futures",
"NQ": "Nasdaq Futures",
"CL": "Crude Oil",
"ES": "E-mini S&P 500",
"DJI": "Dow Jones",
"QQQ": "Invesco QQQ Trust",
"VIX": "Volatility Index",
"DXY": "US Dollar Index",
"AAPL": "Apple Inc.", # New asset
"TSLA": "Tesla Inc.", # New asset
}
# Yahoo Finance symbol mapping
self.yfinance_symbols = {
"SPX": "^GSPC", # S&P 500
"BTC": "BTC-USD", # Bitcoin
"GC": "GC=F", # Gold Futures
"NQ": "NQ=F", # Nasdaq Futures
"CL": "CL=F", # Crude Oil
"ES": "ES=F", # E-mini S&P 500
"DJI": "^DJI", # Dow Jones
"QQQ": "QQQ", # Invesco QQQ Trust
"VIX": "^VIX", # Volatility Index
"DXY": "DX-Y.NYB", # US Dollar Index
}
# Yahoo Finance interval mapping
self.yfinance_intervals = {
"1m": "1m",
"5m": "5m",
"15m": "15m",
"30m": "30m",
"1h": "1h",
"4h": "4h", # yfinance supports 4h natively!
"1d": "1d",
"1w": "1wk",
"1mo": "1mo",
}
# Load persisted custom assets
self.custom_assets_file = self.data_dir / "custom_assets.json"
self.custom_assets = self.load_custom_assets()
def fetch_yfinance_data(
self, symbol: str, interval: str, start_date: str, end_date: str
) -> pd.DataFrame:
"""Fetch OHLCV data from Yahoo Finance."""
try:
yf_symbol = self.yfinance_symbols.get(symbol, symbol)
yf_interval = self.yfinance_intervals.get(interval, interval)
df = yf.download(
tickers=yf_symbol, start=start_date, end=end_date, interval=yf_interval
)
if df is None or df.empty:
return pd.DataFrame()
# Ensure df is a DataFrame, not a Series
if isinstance(df, pd.Series):
df = df.to_frame()
# Reset index to ensure we have a clean DataFrame
df = df.reset_index()
# Ensure we have a DataFrame
if not isinstance(df, pd.DataFrame):
return pd.DataFrame()
# Handle potential MultiIndex columns
if isinstance(df.columns, pd.MultiIndex):
df.columns = df.columns.get_level_values(0)
# Rename columns if needed
column_mapping = {
"Date": "Datetime",
"Open": "Open",
"High": "High",
"Low": "Low",
"Close": "Close",
"Volume": "Volume",
}
# Only rename columns that exist
existing_columns = {
old: new for old, new in column_mapping.items() if old in df.columns
}
df = df.rename(columns=existing_columns)
# Ensure we have the required columns
required_columns = ["Datetime", "Open", "High", "Low", "Close"]
if not all(col in df.columns for col in required_columns):
print(f"Warning: Missing columns. Available: {list(df.columns)}")
return pd.DataFrame()
# Select only the required columns
df = df[required_columns]
df["Datetime"] = pd.to_datetime(df["Datetime"])
return df
except Exception as e:
print(f"Error fetching data for {symbol}: {e}")
return pd.DataFrame()
def fetch_yfinance_data_with_datetime(
self,
symbol: str,
interval: str,
start_datetime: datetime,
end_datetime: datetime,
) -> pd.DataFrame:
"""Fetch OHLCV data from Yahoo Finance using datetime objects for exact time precision."""
try:
yf_symbol = self.yfinance_symbols.get(symbol, symbol)
yf_interval = self.yfinance_intervals.get(interval, interval)
print(
f"Fetching {yf_symbol} from {start_datetime} to {end_datetime} with interval {yf_interval}"
)
# Use datetime objects directly for yfinance
df = yf.download(
tickers=yf_symbol,
start=start_datetime,
end=end_datetime,
interval=yf_interval,
auto_adjust=True,
prepost=False,
)
if df is None or df.empty:
print(f"No data returned for {symbol}")
return pd.DataFrame()
# Ensure df is a DataFrame, not a Series
if isinstance(df, pd.Series):
df = df.to_frame()
# Reset index to ensure we have a clean DataFrame
df = df.reset_index()
# Ensure we have a DataFrame
if not isinstance(df, pd.DataFrame):
return pd.DataFrame()
# Handle potential MultiIndex columns
if isinstance(df.columns, pd.MultiIndex):
df.columns = df.columns.get_level_values(0)
# Rename columns if needed
column_mapping = {
"Date": "Datetime",
"Open": "Open",
"High": "High",
"Low": "Low",
"Close": "Close",
"Volume": "Volume",
}
# Only rename columns that exist
existing_columns = {
old: new for old, new in column_mapping.items() if old in df.columns
}
df = df.rename(columns=existing_columns)
# Ensure we have the required columns
required_columns = ["Datetime", "Open", "High", "Low", "Close"]
if not all(col in df.columns for col in required_columns):
print(f"Warning: Missing columns. Available: {list(df.columns)}")
return pd.DataFrame()
# Select only the required columns
df = df[required_columns]
df["Datetime"] = pd.to_datetime(df["Datetime"])
print(f"Successfully fetched {len(df)} data points for {symbol}")
print(f"Date range: {df['Datetime'].min()} to {df['Datetime'].max()}")
return df
except Exception as e:
print(f"Error fetching data for {symbol}: {e}")
return pd.DataFrame()
def get_available_assets(self) -> list:
"""Get list of available assets from the asset mapping dictionary."""
return sorted(list(self.asset_mapping.keys()))
def get_available_files(self, asset: str, timeframe: str) -> list:
"""Get available data files for a specific asset and timeframe."""
asset_dir = self.data_dir / asset.lower()
if not asset_dir.exists():
return []
pattern = f"{asset}_{timeframe}_*.csv"
files = list(asset_dir.glob(pattern))
return sorted(files)
def run_analysis(
self, df: pd.DataFrame, asset_name: str, timeframe: str
) -> Dict[str, Any]:
"""Run the trading analysis on the provided DataFrame."""
try:
# Debug: Check DataFrame structure
print(f"DataFrame columns: {df.columns}")
print(f"DataFrame index: {type(df.index)}")
print(f"DataFrame shape: {df.shape}")
# Prepare data for analysis
if len(df) > 49:
df_slice = df.tail(49).iloc[:-3]
else:
df_slice = df.tail(45)
# Ensure DataFrame has the expected structure
required_columns = ["Datetime", "Open", "High", "Low", "Close"]
if not all(col in df_slice.columns for col in required_columns):
return {
"success": False,
"error": f"Missing required columns. Available: {list(df_slice.columns)}",
}
# Reset index to avoid any MultiIndex issues
df_slice = df_slice.reset_index(drop=True)
# Debug: Check the slice before conversion
print(f"Slice columns: {df_slice.columns}")
print(f"Slice index: {type(df_slice.index)}")
# Convert to dict for tool input - use explicit conversion to avoid tuple keys
df_slice_dict = {}
for col in required_columns:
if col == "Datetime":
# Convert datetime objects to strings for JSON serialization
df_slice_dict[col] = (
df_slice[col].dt.strftime("%Y-%m-%d %H:%M:%S").tolist()
)
else:
df_slice_dict[col] = df_slice[col].tolist()
# Debug: Check the resulting dictionary
print(f"Dictionary keys: {list(df_slice_dict.keys())}")
print(f"Dictionary key types: {[type(k) for k in df_slice_dict.keys()]}")
# Format timeframe for display
display_timeframe = timeframe
if timeframe.endswith("h"):
display_timeframe += "our"
elif timeframe.endswith("m"):
display_timeframe += "in"
elif timeframe.endswith("d"):
display_timeframe += "ay"
elif timeframe == "1w":
display_timeframe = "1 week"
elif timeframe == "1mo":
display_timeframe = "1 month"
p_image = static_util.generate_kline_image(df_slice_dict)
t_image = static_util.generate_trend_image(df_slice_dict)
# Create initial state
initial_state = {
"kline_data": df_slice_dict,
"analysis_results": None,
"messages": [],
"time_frame": display_timeframe,
"stock_name": asset_name,
"pattern_image": p_image["pattern_image"],
"trend_image": t_image["trend_image"],
}
# Run the trading graph
final_state = self.trading_graph.graph.invoke(initial_state)
return {
"success": True,
"final_state": final_state,
"asset_name": asset_name,
"timeframe": display_timeframe,
"data_length": len(df_slice),
}
except Exception as e:
error_msg = str(e)
# Check for specific API key authentication errors
if (
"authentication" in error_msg.lower()
or "invalid api key" in error_msg.lower()
or "401" in error_msg
):
return {
"success": False,
"error": "❌ Invalid API Key: The OpenAI API key you provided is invalid or has expired. Please check your API key in the Settings section and try again.",
}
elif "rate limit" in error_msg.lower() or "429" in error_msg:
return {
"success": False,
"error": "⚠️ Rate Limit Exceeded: You've hit the OpenAI API rate limit. Please wait a moment and try again.",
}
elif "quota" in error_msg.lower() or "billing" in error_msg.lower():
return {
"success": False,
"error": "💳 Billing Issue: Your OpenAI account has insufficient credits or billing issues. Please check your OpenAI account.",
}
elif "network" in error_msg.lower() or "connection" in error_msg.lower():
return {
"success": False,
"error": "🌐 Network Error: Unable to connect to OpenAI servers. Please check your internet connection and try again.",
}
else:
return {"success": False, "error": f"❌ Analysis Error: {error_msg}"}
def extract_analysis_results(self, results: Dict[str, Any]) -> Dict[str, Any]:
"""Extract and format analysis results for web display."""
if not results["success"]:
return {"error": results["error"]}
final_state = results["final_state"]
# Extract analysis results from state fields
technical_indicators = final_state.get("indicator_report", "")
pattern_analysis = final_state.get("pattern_report", "")
trend_analysis = final_state.get("trend_report", "")
final_decision_raw = final_state.get("final_trade_decision", "")
# Extract chart data if available
pattern_chart = final_state.get("pattern_image", "")
trend_chart = final_state.get("trend_image", "")
pattern_image_filename = final_state.get("pattern_image_filename", "")
trend_image_filename = final_state.get("trend_image_filename", "")
# Parse final decision
final_decision = ""
if final_decision_raw:
try:
# Try to extract JSON from the decision
start = final_decision_raw.find("{")
end = final_decision_raw.rfind("}") + 1
if start != -1 and end != 0:
json_str = final_decision_raw[start:end]
decision_data = json.loads(json_str)
final_decision = {
"decision": decision_data.get("decision", "N/A"),
"risk_reward_ratio": decision_data.get(
"risk_reward_ratio", "N/A"
),
"forecast_horizon": decision_data.get(
"forecast_horizon", "N/A"
),
"justification": decision_data.get("justification", "N/A"),
}
else:
# If no JSON found, return the raw text
final_decision = {"raw": final_decision_raw}
except json.JSONDecodeError:
# If JSON parsing fails, return the raw text
final_decision = {"raw": final_decision_raw}
return {
"success": True,
"asset_name": results["asset_name"],
"timeframe": results["timeframe"],
"data_length": results["data_length"],
"technical_indicators": technical_indicators,
"pattern_analysis": pattern_analysis,
"trend_analysis": trend_analysis,
"pattern_chart": pattern_chart,
"trend_chart": trend_chart,
"pattern_image_filename": pattern_image_filename,
"trend_image_filename": trend_image_filename,
"final_decision": final_decision,
}
def get_timeframe_date_limits(self, timeframe: str) -> Dict[str, Any]:
"""Get valid date range limits for a given timeframe."""
limits = {
"1m": {"max_days": 7, "description": "1 minute data: max 7 days"},
"2m": {"max_days": 60, "description": "2 minute data: max 60 days"},
"5m": {"max_days": 60, "description": "5 minute data: max 60 days"},
"15m": {"max_days": 60, "description": "15 minute data: max 60 days"},
"30m": {"max_days": 60, "description": "30 minute data: max 60 days"},
"60m": {"max_days": 730, "description": "1 hour data: max 730 days"},
"90m": {"max_days": 60, "description": "90 minute data: max 60 days"},
"1h": {"max_days": 730, "description": "1 hour data: max 730 days"},
"4h": {"max_days": 730, "description": "4 hour data: max 730 days"},
"1d": {"max_days": 730, "description": "1 day data: max 730 days"},
"5d": {"max_days": 60, "description": "5 day data: max 60 days"},
"1w": {"max_days": 730, "description": "1 week data: max 730 days"},
"1wk": {"max_days": 730, "description": "1 week data: max 730 days"},
"1mo": {"max_days": 730, "description": "1 month data: max 730 days"},
"3mo": {"max_days": 730, "description": "3 month data: max 730 days"},
}
return limits.get(
timeframe, {"max_days": 730, "description": "Default: max 730 days"}
)
def validate_date_range(
self,
start_date: str,
end_date: str,
timeframe: str,
start_time: str = "00:00",
end_time: str = "23:59",
) -> Dict[str, Any]:
"""Validate date and time range for the given timeframe."""
try:
# Create datetime objects with time
start_datetime_str = f"{start_date} {start_time}"
end_datetime_str = f"{end_date} {end_time}"
start = datetime.strptime(start_datetime_str, "%Y-%m-%d %H:%M")
end = datetime.strptime(end_datetime_str, "%Y-%m-%d %H:%M")
if start >= end:
return {
"valid": False,
"error": "Start date/time must be before end date/time",
}
# Get timeframe limits
limits = self.get_timeframe_date_limits(timeframe)
max_days = limits["max_days"]
# Calculate time difference in days (including fractional days)
time_diff = end - start
days_diff = time_diff.total_seconds() / (24 * 3600) # Convert to days
if days_diff > max_days:
return {
"valid": False,
"error": f"Time range too large. {limits['description']}. Please select a smaller range.",
"max_days": max_days,
"current_days": round(days_diff, 2),
}
return {"valid": True, "days": round(days_diff, 2)}
except ValueError as e:
return {"valid": False, "error": f"Invalid date/time format: {str(e)}"}
def validate_api_key(self) -> Dict[str, Any]:
"""Validate the current API key by making a simple test call."""
try:
client = OpenAI()
# Make a simple test call
_ = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Hello"}],
max_tokens=5,
)
return {"valid": True, "message": "API key is valid"}
except Exception as e:
error_msg = str(e)
if (
"authentication" in error_msg.lower()
or "invalid api key" in error_msg.lower()
or "401" in error_msg
):
return {
"valid": False,
"error": "❌ Invalid API Key: The OpenAI API key is invalid or has expired. Please update it in the Settings section.",
}
elif "rate limit" in error_msg.lower() or "429" in error_msg:
return {
"valid": False,
"error": "⚠️ Rate Limit Exceeded: You've hit the OpenAI API rate limit. Please wait a moment and try again.",
}
elif "quota" in error_msg.lower() or "billing" in error_msg.lower():
return {
"valid": False,
"error": "💳 Billing Issue: Your OpenAI account has insufficient credits or billing issues. Please check your OpenAI account.",
}
elif "network" in error_msg.lower() or "connection" in error_msg.lower():
return {
"valid": False,
"error": "🌐 Network Error: Unable to connect to OpenAI servers. Please check your internet connection.",
}
else:
return {"valid": False, "error": f"❌ API Key Error: {error_msg}"}
def load_custom_assets(self) -> list:
"""Load custom assets from persistent JSON file."""
try:
if self.custom_assets_file.exists():
with open(self.custom_assets_file, "r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, list):
return data
return []
except Exception as e:
print(f"Error loading custom assets: {e}")
return []
def save_custom_asset(self, symbol: str) -> bool:
"""Save a custom asset symbol persistently (avoid duplicates)."""
try:
symbol = symbol.strip()
if not symbol:
return False
if symbol in self.custom_assets:
return True # already present
self.custom_assets.append(symbol)
# write to file
with open(self.custom_assets_file, "w", encoding="utf-8") as f:
json.dump(self.custom_assets, f, indent=2)
return True
except Exception as e:
print(f"Error saving custom asset '{symbol}': {e}")
return False
# Initialize the analyzer
analyzer = WebTradingAnalyzer()
@app.route("/")
def index():
"""Main landing page - redirect to demo."""
return render_template("demo_new.html")
@app.route("/demo")
def demo():
"""Demo page with new interface."""
return render_template("demo_new.html")
@app.route("/output")
def output():
"""Output page with analysis results."""
# Get results from session or query parameters
results = request.args.get("results")
if results:
try:
# Handle URL-encoded results
results = urllib.parse.unquote(results)
results_data = json.loads(results)
return render_template("output.html", results=results_data)
except (json.JSONDecodeError, Exception) as e:
print(f"Error parsing results: {e}")
# Fall back to default results
# Default results if none provided
default_results = {
"asset_name": "BTC",
"timeframe": "1h",
"data_length": 1247,
"technical_indicators": "RSI (14): 65.4 - Neutral to bullish momentum\nMACD: Bullish crossover with increasing histogram\nMoving Averages: Price above 50-day and 200-day MA\nBollinger Bands: Price in upper band, showing strength\nVolume: Above average volume supporting price action",
"pattern_analysis": "Bull Flag Pattern: Consolidation after strong upward move\nGolden Cross: 50-day MA crossing above 200-day MA\nHigher Highs & Higher Lows: Uptrend confirmation\nVolume Pattern: Increasing volume on price advances",
"trend_analysis": "Primary Trend: Bullish (Long-term)\nSecondary Trend: Bullish (Medium-term)\nShort-term Trend: Consolidating with bullish bias\nADX: 28.5 - Moderate trend strength\nPrice Action: Higher highs and higher lows maintained\nMomentum: Positive divergence on RSI",
"pattern_chart": "",
"trend_chart": "",
"pattern_image_filename": "",
"trend_image_filename": "",
"final_decision": {
"decision": "LONG",
"risk_reward_ratio": "1:2.5",
"forecast_horizon": "24-48 hours",
"justification": "Based on comprehensive analysis of technical indicators, pattern recognition, and trend analysis, the system recommends a LONG position on BTC. The analysis shows strong bullish momentum with key support levels holding, and multiple technical indicators confirming upward movement.",
},
}
return render_template("output.html", results=default_results)
@app.route("/api/analyze", methods=["POST"])
def analyze():
try:
data = request.get_json()
data_source = data.get("data_source")
asset = data.get("asset")
timeframe = data.get("timeframe")
redirect_to_output = data.get("redirect_to_output", False)
if data_source != "live":
return jsonify({"error": "Only live Yahoo Finance data is supported."})
# Live Yahoo Finance data only
start_date = data.get("start_date")
start_time = data.get("start_time", "00:00")
end_date = data.get("end_date")
end_time = data.get("end_time", "23:59")
use_current_time = data.get("use_current_time", False)
# Create datetime objects for validation
if start_date:
start_datetime_str = f"{start_date} {start_time}"
try:
start_dt = datetime.strptime(start_datetime_str, "%Y-%m-%d %H:%M")
except ValueError:
return jsonify({"error": "Invalid start date/time format."})
if start_dt > datetime.now():
return jsonify({"error": "Start date/time cannot be in the future."})
if end_date:
if use_current_time:
end_dt = datetime.now()
else:
end_datetime_str = f"{end_date} {end_time}"
try:
end_dt = datetime.strptime(end_datetime_str, "%Y-%m-%d %H:%M")
except ValueError:
return jsonify({"error": "Invalid end date/time format."})
if end_dt > datetime.now():
return jsonify({"error": "End date/time cannot be in the future."})
if start_date and start_dt and end_dt and end_dt < start_dt:
return jsonify(
{"error": "End date/time cannot be earlier than start date/time."}
)
# Fetch data with datetime objects
df = analyzer.fetch_yfinance_data_with_datetime(
asset, timeframe, start_dt, end_dt
)
if df.empty:
return jsonify({"error": "No data available for the specified parameters"})
display_name = analyzer.asset_mapping.get(asset, asset)
if display_name is None:
display_name = asset
results = analyzer.run_analysis(df, display_name, timeframe)
formatted_results = analyzer.extract_analysis_results(results)
# If redirect is requested, return redirect URL with results
if redirect_to_output:
if formatted_results.get("success", False):
# Create a version without base64 images for URL encoding
# Base64 images are too large for URL parameters
url_safe_results = formatted_results.copy()
url_safe_results["pattern_chart"] = "" # Remove base64 data
url_safe_results["trend_chart"] = "" # Remove base64 data
# Encode results for URL
results_json = json.dumps(url_safe_results)
encoded_results = urllib.parse.quote(results_json)
redirect_url = f"/output?results={encoded_results}"
# Store full results (with images) in session or temporary storage
# For now, we'll pass them back in the response for the frontend to handle
return jsonify(
{
"redirect": redirect_url,
"full_results": formatted_results, # Include images in response body
}
)
else:
return jsonify(
{"error": formatted_results.get("error", "Analysis failed")}
)
return jsonify(formatted_results)
except Exception as e:
return jsonify({"error": str(e)})
@app.route("/api/files/<asset>/<timeframe>")
def get_files(asset, timeframe):
"""API endpoint to get available files for an asset/timeframe."""
try:
files = analyzer.get_available_files(asset, timeframe)
file_list = []
for i, file_path in enumerate(files):
match = re.search(r"_(\d+)\.csv$", file_path.name)
file_number = match.group(1) if match else "N/A"
file_list.append(
{"index": i, "number": file_number, "name": file_path.name}
)
return jsonify({"files": file_list})
except Exception as e:
return jsonify({"error": str(e)})
@app.route("/api/save-custom-asset", methods=["POST"])
def save_custom_asset():
"""Save a custom asset symbol server-side for persistence."""
try:
data = request.get_json()
symbol = (data.get("symbol") or "").strip()
if not symbol:
return jsonify({"success": False, "error": "Symbol required"}), 400
ok = analyzer.save_custom_asset(symbol)
if not ok:
return jsonify({"success": False, "error": "Failed to save symbol"}), 500
return jsonify({"success": True, "symbol": symbol})
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
@app.route("/api/custom-assets", methods=["GET"])
def custom_assets():
"""Return server-persisted custom assets."""
try:
return jsonify({"custom_assets": analyzer.custom_assets or []})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/assets")
def get_assets():
"""API endpoint to get available assets."""
try:
assets = analyzer.get_available_assets()
asset_list = []
for asset in assets:
asset_list.append(
{"code": asset, "name": analyzer.asset_mapping.get(asset, asset)}
)
# Include server-persisted custom assets at the end
for custom in analyzer.custom_assets:
asset_list.append({"code": custom, "name": custom})
return jsonify({"assets": asset_list})
except Exception as e:
return jsonify({"error": str(e)})
@app.route("/api/timeframe-limits/<timeframe>")
def get_timeframe_limits(timeframe):
"""API endpoint to get date range limits for a timeframe."""
try:
limits = analyzer.get_timeframe_date_limits(timeframe)
return jsonify(limits)
except Exception as e:
return jsonify({"error": str(e)})
@app.route("/api/validate-date-range", methods=["POST"])
def validate_date_range():
"""API endpoint to validate date and time range for a timeframe."""
try:
data = request.get_json()
start_date = data.get("start_date")
end_date = data.get("end_date")
timeframe = data.get("timeframe")
start_time = data.get("start_time", "00:00")
end_time = data.get("end_time", "23:59")
if not all([start_date, end_date, timeframe]):
return jsonify({"error": "Missing required parameters"})
validation = analyzer.validate_date_range(
start_date, end_date, timeframe, start_time, end_time
)
return jsonify(validation)
except Exception as e:
return jsonify({"error": str(e)})
@app.route("/api/update-api-key", methods=["POST"])
def update_api_key():
"""API endpoint to update OpenAI API key."""
try:
data = request.get_json()
new_api_key = data.get("api_key")
if not new_api_key:
return jsonify({"error": "API key is required"})
print(f"Updating API key to: {new_api_key[:8]}...{new_api_key[-4:]}")
# Update the environment variable
os.environ["OPENAI_API_KEY"] = new_api_key
# Refresh the trading graph LLMs with the new API key
analyzer.trading_graph.refresh_llms()
print("API key updated successfully")
return jsonify({"success": True, "message": "API key updated successfully"})
except Exception as e:
print(f"Error in update_api_key: {str(e)}")
return jsonify({"error": str(e)})
@app.route("/api/get-api-key-status")
def get_api_key_status():
"""API endpoint to check if API key is set."""
try:
api_key = os.environ.get("OPENAI_API_KEY")
if api_key and api_key != "your-openai-api-key-here":
# Return masked version for security
masked_key = (
api_key[:3] + "..." + api_key[-3:] if len(api_key) > 12 else "***"
)
return jsonify({"has_key": True, "masked_key": masked_key})
else:
return jsonify({"has_key": False})
except Exception as e:
return jsonify({"error": str(e)})
@app.route("/api/images/<image_type>")
def get_image(image_type):
"""API endpoint to serve generated images."""
try:
if image_type == "pattern":
image_path = "kline_chart.png"
elif image_type == "trend":
image_path = "trend_graph.png"
elif image_type == "pattern_chart":
image_path = "pattern_chart.png"
elif image_type == "trend_chart":
image_path = "trend_chart.png"
else:
return jsonify({"error": "Invalid image type"})
if not os.path.exists(image_path):
return jsonify({"error": "Image not found"})
return send_file(image_path, mimetype="image/png")
except Exception as e:
return jsonify({"error": str(e)})
@app.route("/api/validate-api-key", methods=["POST"])
def validate_api_key():
"""API endpoint to validate the current API key."""
try:
validation = analyzer.validate_api_key()
return jsonify(validation)
except Exception as e:
return jsonify({"valid": False, "error": str(e)})
@app.route("/assets/<path:filename>")
def serve_assets(filename):
"""Serve static assets from the assets folder."""
try:
return send_file(f"assets/{filename}")
except FileNotFoundError:
return jsonify({"error": "Asset not found"}), 404
if __name__ == "__main__":
# Create templates directory if it doesn't exist
templates_dir = Path("templates")
templates_dir.mkdir(exist_ok=True)
# Create static directory if it doesn't exist
static_dir = Path("static")
static_dir.mkdir(exist_ok=True)
app.run(debug=True, host="127.0.0.1", port=5000)