Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -3,28 +3,23 @@ from fastapi.middleware.cors import CORSMiddleware
|
|
| 3 |
from pydantic import BaseModel
|
| 4 |
from typing import Dict, Any, List, Optional
|
| 5 |
|
| 6 |
-
# Import core logic modules
|
| 7 |
from data_processor import DataProcessor
|
| 8 |
from sentiment_analyzer import SentimentAnalyzer
|
| 9 |
from model_handler import ModelHandler
|
| 10 |
from trading_logic import TradingLogic
|
| 11 |
from plotter import create_mplfinance_chart
|
| 12 |
|
| 13 |
-
# Initialize core components
|
| 14 |
data_processor = DataProcessor()
|
| 15 |
sentiment_analyzer = SentimentAnalyzer()
|
| 16 |
model_handler = ModelHandler()
|
| 17 |
trading_logic = TradingLogic()
|
| 18 |
|
| 19 |
-
# FastAPI app setup
|
| 20 |
app = FastAPI(
|
| 21 |
title="Ultimate Market Analysis & Prediction API",
|
| 22 |
version="1.0.0",
|
| 23 |
description="API for fetching market data, technical indicators, Chronos-2 predictions, and simulated analysis for GC=F and BTC-USD."
|
| 24 |
)
|
| 25 |
|
| 26 |
-
# Add CORS middleware for frontend access
|
| 27 |
-
# HATI-HATI: Ganti "*" dengan domain frontend React Anda saat deployment produksi
|
| 28 |
app.add_middleware(
|
| 29 |
CORSMiddleware,
|
| 30 |
allow_origins=["*"],
|
|
@@ -33,8 +28,6 @@ app.add_middleware(
|
|
| 33 |
allow_headers=["*"],
|
| 34 |
)
|
| 35 |
|
| 36 |
-
# --- Skema Respon Pydantic ---
|
| 37 |
-
|
| 38 |
class TradingMetrics(BaseModel):
|
| 39 |
Ticker: str
|
| 40 |
Current_Price: str
|
|
@@ -47,7 +40,7 @@ class TradingMetrics(BaseModel):
|
|
| 47 |
Volume: str
|
| 48 |
|
| 49 |
class ChartAnalysisResponse(BaseModel):
|
| 50 |
-
chart_html_base64: Optional[str] = None
|
| 51 |
metrics: Optional[TradingMetrics] = None
|
| 52 |
raw_predictions: Optional[List[float]] = None
|
| 53 |
error: Optional[str] = None
|
|
@@ -59,8 +52,6 @@ class SentimentAnalysisResponse(BaseModel):
|
|
| 59 |
class FundamentalsResponse(BaseModel):
|
| 60 |
fundamentals_data: Dict[str, Any]
|
| 61 |
|
| 62 |
-
# --- Endpoint API ---
|
| 63 |
-
|
| 64 |
@app.get("/")
|
| 65 |
def read_root():
|
| 66 |
return {"message": "Welcome to the Ultimate Market Analysis API. Use /docs for API documentation."}
|
|
@@ -70,42 +61,34 @@ def get_chart_analysis(
|
|
| 70 |
ticker: str = Query(..., description="Market Ticker (e.g., GC=F, BTC-USD)"),
|
| 71 |
interval: str = Query(..., description="Time Interval (e.g., 1d, 1h, 5m)")
|
| 72 |
):
|
| 73 |
-
"""
|
| 74 |
-
Mengambil data pasar, menghitung indikator, menghasilkan prediksi,
|
| 75 |
-
dan mengembalikan gambar chart (Base64) serta metrik trading.
|
| 76 |
-
"""
|
| 77 |
try:
|
| 78 |
-
# 1. Fetch data
|
| 79 |
df = data_processor.get_market_data(ticker, interval)
|
| 80 |
if df.empty:
|
| 81 |
return ChartAnalysisResponse(error=f"No data available for {ticker} at {interval}")
|
| 82 |
|
| 83 |
-
# 2. Calculate Indicators
|
| 84 |
df = data_processor.calculate_indicators(df)
|
| 85 |
-
|
| 86 |
-
# 3. Prepare and Predict
|
| 87 |
prepared_data = data_processor.prepare_for_chronos(df)
|
| 88 |
predictions = model_handler.predict(prepared_data, horizon=10)
|
| 89 |
-
|
| 90 |
current_price = df['Close'].iloc[-1]
|
| 91 |
|
| 92 |
-
# 4. Generate Chart (returns Base64 HTML string)
|
| 93 |
chart_html = create_mplfinance_chart(
|
| 94 |
df,
|
| 95 |
ticker=f'{ticker} ({interval})',
|
| 96 |
predictions=predictions
|
| 97 |
)
|
| 98 |
|
| 99 |
-
# 5. Generate Signal and Metrics
|
| 100 |
signal, confidence = trading_logic.generate_signal(
|
| 101 |
predictions, current_price, df
|
| 102 |
)
|
| 103 |
|
|
|
|
|
|
|
|
|
|
| 104 |
tp, sl = trading_logic.calculate_tp_sl(
|
| 105 |
-
current_price,
|
| 106 |
)
|
| 107 |
|
| 108 |
-
# 6. Format Metrics
|
| 109 |
metrics = TradingMetrics(
|
| 110 |
Ticker=ticker,
|
| 111 |
Current_Price=f"${current_price:.2f}",
|
|
@@ -125,14 +108,11 @@ def get_chart_analysis(
|
|
| 125 |
)
|
| 126 |
|
| 127 |
except Exception as e:
|
| 128 |
-
#
|
| 129 |
raise HTTPException(status_code=500, detail=f"Error in chart analysis: {str(e)}")
|
| 130 |
|
| 131 |
@app.get("/analysis/sentiment", response_model=SentimentAnalysisResponse)
|
| 132 |
def get_sentiment_analysis(ticker: str = Query(..., description="Market Ticker (e.g., GC=F, BTC-USD)")):
|
| 133 |
-
"""
|
| 134 |
-
Menganalisis dan mengembalikan skor sentimen pasar dan ringkasan berita (Simulasi).
|
| 135 |
-
"""
|
| 136 |
try:
|
| 137 |
sentiment_score, news_summary_html = sentiment_analyzer.analyze_market_sentiment(ticker)
|
| 138 |
|
|
@@ -146,9 +126,6 @@ def get_sentiment_analysis(ticker: str = Query(..., description="Market Ticker (
|
|
| 146 |
|
| 147 |
@app.get("/analysis/fundamentals", response_model=FundamentalsResponse)
|
| 148 |
def get_fundamentals_analysis(ticker: str = Query(..., description="Market Ticker (e.g., GC=F, BTC-USD)")):
|
| 149 |
-
"""
|
| 150 |
-
Mengambil data fundamental pasar utama (Simulasi).
|
| 151 |
-
"""
|
| 152 |
try:
|
| 153 |
fundamentals = data_processor.get_fundamental_data(ticker)
|
| 154 |
|
|
|
|
| 3 |
from pydantic import BaseModel
|
| 4 |
from typing import Dict, Any, List, Optional
|
| 5 |
|
|
|
|
| 6 |
from data_processor import DataProcessor
|
| 7 |
from sentiment_analyzer import SentimentAnalyzer
|
| 8 |
from model_handler import ModelHandler
|
| 9 |
from trading_logic import TradingLogic
|
| 10 |
from plotter import create_mplfinance_chart
|
| 11 |
|
|
|
|
| 12 |
data_processor = DataProcessor()
|
| 13 |
sentiment_analyzer = SentimentAnalyzer()
|
| 14 |
model_handler = ModelHandler()
|
| 15 |
trading_logic = TradingLogic()
|
| 16 |
|
|
|
|
| 17 |
app = FastAPI(
|
| 18 |
title="Ultimate Market Analysis & Prediction API",
|
| 19 |
version="1.0.0",
|
| 20 |
description="API for fetching market data, technical indicators, Chronos-2 predictions, and simulated analysis for GC=F and BTC-USD."
|
| 21 |
)
|
| 22 |
|
|
|
|
|
|
|
| 23 |
app.add_middleware(
|
| 24 |
CORSMiddleware,
|
| 25 |
allow_origins=["*"],
|
|
|
|
| 28 |
allow_headers=["*"],
|
| 29 |
)
|
| 30 |
|
|
|
|
|
|
|
| 31 |
class TradingMetrics(BaseModel):
|
| 32 |
Ticker: str
|
| 33 |
Current_Price: str
|
|
|
|
| 40 |
Volume: str
|
| 41 |
|
| 42 |
class ChartAnalysisResponse(BaseModel):
|
| 43 |
+
chart_html_base64: Optional[str] = None
|
| 44 |
metrics: Optional[TradingMetrics] = None
|
| 45 |
raw_predictions: Optional[List[float]] = None
|
| 46 |
error: Optional[str] = None
|
|
|
|
| 52 |
class FundamentalsResponse(BaseModel):
|
| 53 |
fundamentals_data: Dict[str, Any]
|
| 54 |
|
|
|
|
|
|
|
| 55 |
@app.get("/")
|
| 56 |
def read_root():
|
| 57 |
return {"message": "Welcome to the Ultimate Market Analysis API. Use /docs for API documentation."}
|
|
|
|
| 61 |
ticker: str = Query(..., description="Market Ticker (e.g., GC=F, BTC-USD)"),
|
| 62 |
interval: str = Query(..., description="Time Interval (e.g., 1d, 1h, 5m)")
|
| 63 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
try:
|
|
|
|
| 65 |
df = data_processor.get_market_data(ticker, interval)
|
| 66 |
if df.empty:
|
| 67 |
return ChartAnalysisResponse(error=f"No data available for {ticker} at {interval}")
|
| 68 |
|
|
|
|
| 69 |
df = data_processor.calculate_indicators(df)
|
|
|
|
|
|
|
| 70 |
prepared_data = data_processor.prepare_for_chronos(df)
|
| 71 |
predictions = model_handler.predict(prepared_data, horizon=10)
|
| 72 |
+
|
| 73 |
current_price = df['Close'].iloc[-1]
|
| 74 |
|
|
|
|
| 75 |
chart_html = create_mplfinance_chart(
|
| 76 |
df,
|
| 77 |
ticker=f'{ticker} ({interval})',
|
| 78 |
predictions=predictions
|
| 79 |
)
|
| 80 |
|
|
|
|
| 81 |
signal, confidence = trading_logic.generate_signal(
|
| 82 |
predictions, current_price, df
|
| 83 |
)
|
| 84 |
|
| 85 |
+
# Pastikan ATR tersedia sebelum menghitung TP/SL
|
| 86 |
+
atr_value = df['ATR'].iloc[-1] if 'ATR' in df.columns and not df['ATR'].empty else 0
|
| 87 |
+
|
| 88 |
tp, sl = trading_logic.calculate_tp_sl(
|
| 89 |
+
current_price, atr_value, signal
|
| 90 |
)
|
| 91 |
|
|
|
|
| 92 |
metrics = TradingMetrics(
|
| 93 |
Ticker=ticker,
|
| 94 |
Current_Price=f"${current_price:.2f}",
|
|
|
|
| 108 |
)
|
| 109 |
|
| 110 |
except Exception as e:
|
| 111 |
+
# PENTING: Menggunakan HTTPException 500 dengan detail spesifik
|
| 112 |
raise HTTPException(status_code=500, detail=f"Error in chart analysis: {str(e)}")
|
| 113 |
|
| 114 |
@app.get("/analysis/sentiment", response_model=SentimentAnalysisResponse)
|
| 115 |
def get_sentiment_analysis(ticker: str = Query(..., description="Market Ticker (e.g., GC=F, BTC-USD)")):
|
|
|
|
|
|
|
|
|
|
| 116 |
try:
|
| 117 |
sentiment_score, news_summary_html = sentiment_analyzer.analyze_market_sentiment(ticker)
|
| 118 |
|
|
|
|
| 126 |
|
| 127 |
@app.get("/analysis/fundamentals", response_model=FundamentalsResponse)
|
| 128 |
def get_fundamentals_analysis(ticker: str = Query(..., description="Market Ticker (e.g., GC=F, BTC-USD)")):
|
|
|
|
|
|
|
|
|
|
| 129 |
try:
|
| 130 |
fundamentals = data_processor.get_fundamental_data(ticker)
|
| 131 |
|