Spaces:
Running
Running
Calculation Speed Improvement
Browse files- backend/app/main.py +123 -59
- frontend/src/App.tsx +31 -29
backend/app/main.py
CHANGED
|
@@ -5,7 +5,7 @@ from fastapi import FastAPI, HTTPException, Response
|
|
| 5 |
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
from fastapi.responses import FileResponse
|
| 7 |
import mimetypes
|
| 8 |
-
from pydantic import BaseModel, Field
|
| 9 |
import numpy as np
|
| 10 |
import pandas as pd
|
| 11 |
import yfinance as yf
|
|
@@ -16,7 +16,7 @@ from sklearn.ensemble import RandomForestClassifier
|
|
| 16 |
from sklearn.svm import SVC
|
| 17 |
from sklearn.preprocessing import StandardScaler
|
| 18 |
from sklearn.metrics import accuracy_score
|
| 19 |
-
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
|
| 20 |
from sklearn.pipeline import Pipeline
|
| 21 |
import tensorflow as tf
|
| 22 |
from tensorflow.keras import Sequential
|
|
@@ -50,7 +50,7 @@ DEFAULT_RF_PARAMS = {'max_depth': 10, 'min_samples_split': 50, 'n_estimators': 2
|
|
| 50 |
DEFAULT_SVM_PARAMS = {'C': 50, 'kernel': 'rbf', 'probability': True, 'random_state': 42}
|
| 51 |
THRESHOLD_RF = 0.6
|
| 52 |
|
| 53 |
-
# ===
|
| 54 |
class RFParams(BaseModel):
|
| 55 |
n_estimators: Optional[int] = None
|
| 56 |
max_depth: Optional[int] = None
|
|
@@ -63,12 +63,10 @@ class SVMParams(BaseModel):
|
|
| 63 |
class PredictAllRequest(BaseModel):
|
| 64 |
symbol: str
|
| 65 |
horizon_days: int = Field(..., ge=1, le=60)
|
| 66 |
-
# Frontend'den gelen yeni ayarlar
|
| 67 |
use_grid_search: bool = Field(False, description="True ise, en iyi parametreleri bulmak için GridSearchCV çalıştır (YAVAŞ)")
|
| 68 |
rf_params: Optional[RFParams] = None
|
| 69 |
svm_params: Optional[SVMParams] = None
|
| 70 |
|
| 71 |
-
# (Diğer Pydantic modelleri aynı kalıyor)
|
| 72 |
class ModelResult(BaseModel):
|
| 73 |
model: str; accuracy: float; trend: Literal["Up", "Down", "Neutral"]; predicted_close: float
|
| 74 |
class ChartDataPoint(BaseModel):
|
|
@@ -78,10 +76,10 @@ class PredictAllResponse(BaseModel):
|
|
| 78 |
symbol: str; results: List[ModelResult]; chart_data: List[ChartDataPoint]; messages: List[str]
|
| 79 |
|
| 80 |
# === FastAPI config ===
|
| 81 |
-
app = FastAPI(title="SmartStock API", version="FINAL-HYBRID-CONFIGURABLE")
|
| 82 |
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])
|
| 83 |
|
| 84 |
-
# === Veri İndirme ve İşleme Fonksiyonları (
|
| 85 |
def _download_data(symbol: str) -> pd.DataFrame:
|
| 86 |
end_date, start_date = datetime.now(), datetime.now() - timedelta(days=365*5)
|
| 87 |
try:
|
|
@@ -130,19 +128,15 @@ def _label_trend(df: pd.DataFrame, horizon: int) -> pd.Series:
|
|
| 130 |
else: labels.append(0)
|
| 131 |
return pd.Series(labels,index=df.index[:len(labels)],name="label")
|
| 132 |
|
| 133 |
-
# ===
|
| 134 |
def _get_model_paths(symbol: str, horizon: int, model_name: str, num_classes: int, use_grid_search: bool, manual_params: bool):
|
| 135 |
safe_symbol=symbol.replace('.IS','_IS')
|
| 136 |
-
# GridSearch veya Manuel ayar ise dosya adı farklı olur
|
| 137 |
mode = "gridsearch" if use_grid_search and not manual_params else ("manual" if manual_params else "fast")
|
| 138 |
-
|
| 139 |
base_path=os.path.join(MODEL_DIR,f"{safe_symbol}_{horizon}d_{model_name}_{num_classes}class_{mode}")
|
| 140 |
return base_path+".pkl",base_path+".keras"
|
| 141 |
|
| 142 |
def _is_model_fresh(data_path: str, max_age_hours: int = 24):
|
| 143 |
if not os.path.exists(data_path): return False
|
| 144 |
-
# Render'ın geçici diski için "tazelik" (freshness) her zaman False döner,
|
| 145 |
-
# ama yerel test (ngrok) için bu mantık çalışır.
|
| 146 |
model_time=datetime.fromtimestamp(os.path.getmtime(data_path)); return datetime.now()-model_time<timedelta(hours=max_age_hours)
|
| 147 |
|
| 148 |
def _save_model(model, scaler, symbol: str, horizon: int, model_name: str, num_classes: int, use_grid_search: bool, manual_params: bool, lookback: Optional[int] = None, accuracy: Optional[float] = 0.0):
|
|
@@ -164,7 +158,7 @@ def _load_model(symbol: str, horizon: int, model_name: str, num_classes: int, us
|
|
| 164 |
except Exception as e: print(f"❌ LSTM model yüklenemedi: {e}"); return None,None,None,0.0
|
| 165 |
return model,scaler,lookback,accuracy
|
| 166 |
|
| 167 |
-
# ===
|
| 168 |
def _get_or_train_model(
|
| 169 |
symbol: str,
|
| 170 |
horizon: int,
|
|
@@ -179,10 +173,7 @@ def _get_or_train_model(
|
|
| 179 |
manual_params: Optional[dict] = None
|
| 180 |
):
|
| 181 |
|
| 182 |
-
# Manuel parametre modu
|
| 183 |
has_manual_params = bool(manual_params and any(v is not None for v in manual_params.values()))
|
| 184 |
-
|
| 185 |
-
# 1. DOSYA YOLUNU KONTROL ET
|
| 186 |
data_path,_ = _get_model_paths(symbol, horizon, model_name, num_classes, use_grid_search, has_manual_params)
|
| 187 |
|
| 188 |
if _is_model_fresh(data_path):
|
|
@@ -193,12 +184,10 @@ def _get_or_train_model(
|
|
| 193 |
messages.append(f"⏳ '{model_name}' ({num_classes}-sınıf) modeli eğitiliyor...");
|
| 194 |
print(f"🔥 '{model_name}' ({num_classes}-sınıf) {symbol} için eğitilecek...")
|
| 195 |
model,scaler,lookback,acc=None,None,None,0.0
|
| 196 |
-
|
| 197 |
class_weight = 'balanced' if num_classes == 3 else None
|
| 198 |
-
|
| 199 |
y_train_mapped = y_train.copy()
|
| 200 |
y_test_mapped = y_test.copy()
|
| 201 |
-
if num_classes == 3:
|
| 202 |
y_train_mapped = y_train + 1
|
| 203 |
y_test_mapped = y_test + 1
|
| 204 |
|
|
@@ -213,7 +202,8 @@ def _get_or_train_model(
|
|
| 213 |
|
| 214 |
if use_grid_search and not has_manual_params:
|
| 215 |
print(f"🔥 RF: GridSearchCV ile optimize ediliyor (YAVAŞ)...")
|
| 216 |
-
|
|
|
|
| 217 |
grid=GridSearchCV(RandomForestClassifier(random_state=42, class_weight=class_weight), param_grid, cv=tscv, n_jobs=1)
|
| 218 |
grid.fit(X_train, y_train)
|
| 219 |
print(f"✅ RF için en iyi parametreler: {grid.best_params_}");
|
|
@@ -238,7 +228,8 @@ def _get_or_train_model(
|
|
| 238 |
if use_grid_search and not has_manual_params:
|
| 239 |
print(f"🔥 SVM: GridSearchCV ile optimize ediliyor (YAVAŞ)...")
|
| 240 |
pipeline=Pipeline([('scaler',StandardScaler()),('svm',SVC(probability=True,random_state=42,class_weight=class_weight))])
|
| 241 |
-
|
|
|
|
| 242 |
grid=GridSearchCV(pipeline, param_grid, cv=TimeSeriesSplit(n_splits=3), n_jobs=1);
|
| 243 |
grid.fit(X_train, y_train)
|
| 244 |
print(f"✅ SVM için en iyi parametreler: {grid.best_params_}");
|
|
@@ -256,7 +247,6 @@ def _get_or_train_model(
|
|
| 256 |
acc=float(accuracy_score(y_test, model.predict(X_test)))
|
| 257 |
|
| 258 |
elif model_name=="LSTM":
|
| 259 |
-
# LSTM için manuel parametre veya GridSearch eklemedik (zaten yavaş)
|
| 260 |
lookback=30; scaler=StandardScaler();
|
| 261 |
X_train_s=scaler.fit_transform(X_train);
|
| 262 |
y_cat=to_categorical(y_train_mapped, num_classes=num_classes)
|
|
@@ -269,7 +259,15 @@ def _get_or_train_model(
|
|
| 269 |
LSTM(50),Dropout(0.2),Dense(25,activation="relu"),Dense(num_classes, activation="softmax")
|
| 270 |
]);
|
| 271 |
model.compile(optimizer="adam",loss="categorical_crossentropy",metrics=["accuracy"])
|
| 272 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
|
| 274 |
X_test_s=scaler.transform(X_test)
|
| 275 |
X_test_seq=[X_test_s[i-lookback:i] for i in range(lookback,len(X_test_s))]
|
|
@@ -289,7 +287,7 @@ def _get_or_train_model(
|
|
| 289 |
return None, None, None, 0.0
|
| 290 |
|
| 291 |
|
| 292 |
-
# === Tahmin Fonksiyonu (
|
| 293 |
def _get_prediction(model, scaler, lookback, model_name, X_full, df_with_features, num_classes: int):
|
| 294 |
trend = "Neutral"
|
| 295 |
if model_name=="LSTM":
|
|
@@ -316,7 +314,6 @@ def _get_prediction(model, scaler, lookback, model_name, X_full, df_with_feature
|
|
| 316 |
trend_map = {-1: "Down", 1: "Up"}
|
| 317 |
trend = trend_map.get(int(pred_idx), "Neutral")
|
| 318 |
|
| 319 |
-
# <<< ÖNCEKİ 'NameError' HATASI BURADA DÜZELTİLDİ >>>
|
| 320 |
last_close=df_with_features["close"].iloc[-1].item()
|
| 321 |
|
| 322 |
if trend=="Up": next_close=last_close*1.01
|
|
@@ -325,10 +322,10 @@ def _get_prediction(model, scaler, lookback, model_name, X_full, df_with_feature
|
|
| 325 |
return trend,float(np.round(next_close,2))
|
| 326 |
|
| 327 |
|
| 328 |
-
# ===
|
| 329 |
@app.post("/predict_all", response_model=PredictAllResponse)
|
| 330 |
async def predict_all(req: PredictAllRequest):
|
| 331 |
-
messages=["🚀 Hibrit analiz (
|
| 332 |
try:
|
| 333 |
df_raw=_download_data(req.symbol);
|
| 334 |
messages.append("✅ Veri başarıyla indirildi.")
|
|
@@ -347,7 +344,7 @@ async def predict_all(req: PredictAllRequest):
|
|
| 347 |
|
| 348 |
split_idx_3class = int(len(y_3class) * 0.8)
|
| 349 |
if split_idx_3class < 50 or (len(y_3class) - split_idx_3class) < 50:
|
| 350 |
-
|
| 351 |
|
| 352 |
non_neutral_mask = (y_3class != 0)
|
| 353 |
y_2class = y_3class[non_neutral_mask]
|
|
@@ -358,23 +355,27 @@ async def predict_all(req: PredictAllRequest):
|
|
| 358 |
run_2class_models = split_idx_2class >= 50 and (len(y_2class) - split_idx_2class) >= 50
|
| 359 |
|
| 360 |
if not run_2class_models:
|
| 361 |
-
|
| 362 |
|
| 363 |
results=[]; trained_models={}
|
| 364 |
|
| 365 |
-
#
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
# LSTM
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
|
| 379 |
if run_2class_models:
|
| 380 |
# --- RF (2-Sınıf, Sinyal Verisi) ---
|
|
@@ -406,9 +407,8 @@ async def predict_all(req: PredictAllRequest):
|
|
| 406 |
trained_models["SVM"]={'model':model,'scaler':scaler,'lookback':lookback, 'acc': acc, 'num_classes': 2, 'X_cols': ALL_FEATURES_RAW_AND_SIGNAL}
|
| 407 |
except Exception as e: print(f"❌ 'SVM' için hata: {e}"); messages.append(f"❌ 'SVM' işlenirken hata oluştu: {str(e)}")
|
| 408 |
|
| 409 |
-
# --- 5. Tahminleri
|
| 410 |
chart_data=[]
|
| 411 |
-
chart_df_features = df_features_full.tail(90)
|
| 412 |
|
| 413 |
X_predict_full = df_features_full[ALL_FEATURES_RAW_AND_SIGNAL].values.astype(np.float32)
|
| 414 |
X_predict_signal = df_features_full[FEATURES_SIGNAL_ONLY].values.astype(np.float32)
|
|
@@ -423,24 +423,88 @@ async def predict_all(req: PredictAllRequest):
|
|
| 423 |
)
|
| 424 |
results.append(ModelResult(model=model_name, accuracy=m_data['acc'], trend=trend, predicted_close=predicted_close))
|
| 425 |
|
| 426 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 427 |
for i in range(len(chart_df_features)):
|
| 428 |
current_date_index = chart_df_features.index[i]
|
| 429 |
-
|
| 430 |
-
chart_point={"date":current_date_index.strftime('%Y-%m-%d'),"real":chart_df_features['close'].iloc[i].item()}
|
| 431 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 432 |
for model_name in ["RandomForest", "SVM", "LSTM"]:
|
| 433 |
-
if model_name in
|
| 434 |
-
|
| 435 |
-
#
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
|
|
|
| 444 |
|
| 445 |
chart_data.append(ChartDataPoint(**chart_point))
|
| 446 |
|
|
@@ -457,7 +521,7 @@ async def predict_all(req: PredictAllRequest):
|
|
| 457 |
raise HTTPException(500,detail=f"Bir sunucu hatası oluştu: {str(e)}")
|
| 458 |
|
| 459 |
|
| 460 |
-
# === Frontend Sunma Kodu (
|
| 461 |
BASE_DIR = Path(__file__).resolve().parent
|
| 462 |
PROJECT_ROOT = BASE_DIR.parent.parent
|
| 463 |
FRONTEND_DIST = PROJECT_ROOT / "frontend" / "dist"
|
|
|
|
| 5 |
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
from fastapi.responses import FileResponse
|
| 7 |
import mimetypes
|
| 8 |
+
from pydantic import BaseModel, Field
|
| 9 |
import numpy as np
|
| 10 |
import pandas as pd
|
| 11 |
import yfinance as yf
|
|
|
|
| 16 |
from sklearn.svm import SVC
|
| 17 |
from sklearn.preprocessing import StandardScaler
|
| 18 |
from sklearn.metrics import accuracy_score
|
| 19 |
+
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
|
| 20 |
from sklearn.pipeline import Pipeline
|
| 21 |
import tensorflow as tf
|
| 22 |
from tensorflow.keras import Sequential
|
|
|
|
| 50 |
DEFAULT_SVM_PARAMS = {'C': 50, 'kernel': 'rbf', 'probability': True, 'random_state': 42}
|
| 51 |
THRESHOLD_RF = 0.6
|
| 52 |
|
| 53 |
+
# === API Modelleri ===
|
| 54 |
class RFParams(BaseModel):
|
| 55 |
n_estimators: Optional[int] = None
|
| 56 |
max_depth: Optional[int] = None
|
|
|
|
| 63 |
class PredictAllRequest(BaseModel):
|
| 64 |
symbol: str
|
| 65 |
horizon_days: int = Field(..., ge=1, le=60)
|
|
|
|
| 66 |
use_grid_search: bool = Field(False, description="True ise, en iyi parametreleri bulmak için GridSearchCV çalıştır (YAVAŞ)")
|
| 67 |
rf_params: Optional[RFParams] = None
|
| 68 |
svm_params: Optional[SVMParams] = None
|
| 69 |
|
|
|
|
| 70 |
class ModelResult(BaseModel):
|
| 71 |
model: str; accuracy: float; trend: Literal["Up", "Down", "Neutral"]; predicted_close: float
|
| 72 |
class ChartDataPoint(BaseModel):
|
|
|
|
| 76 |
symbol: str; results: List[ModelResult]; chart_data: List[ChartDataPoint]; messages: List[str]
|
| 77 |
|
| 78 |
# === FastAPI config ===
|
| 79 |
+
app = FastAPI(title="SmartStock API", version="FINAL-HYBRID-CONFIGURABLE-V2-Optimized")
|
| 80 |
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])
|
| 81 |
|
| 82 |
+
# === Veri İndirme ve İşleme Fonksiyonları (Değişiklik Yok) ===
|
| 83 |
def _download_data(symbol: str) -> pd.DataFrame:
|
| 84 |
end_date, start_date = datetime.now(), datetime.now() - timedelta(days=365*5)
|
| 85 |
try:
|
|
|
|
| 128 |
else: labels.append(0)
|
| 129 |
return pd.Series(labels,index=df.index[:len(labels)],name="label")
|
| 130 |
|
| 131 |
+
# === Model Kayıt/Yükleme Fonksiyonları (Değişiklik Yok) ===
|
| 132 |
def _get_model_paths(symbol: str, horizon: int, model_name: str, num_classes: int, use_grid_search: bool, manual_params: bool):
|
| 133 |
safe_symbol=symbol.replace('.IS','_IS')
|
|
|
|
| 134 |
mode = "gridsearch" if use_grid_search and not manual_params else ("manual" if manual_params else "fast")
|
|
|
|
| 135 |
base_path=os.path.join(MODEL_DIR,f"{safe_symbol}_{horizon}d_{model_name}_{num_classes}class_{mode}")
|
| 136 |
return base_path+".pkl",base_path+".keras"
|
| 137 |
|
| 138 |
def _is_model_fresh(data_path: str, max_age_hours: int = 24):
|
| 139 |
if not os.path.exists(data_path): return False
|
|
|
|
|
|
|
| 140 |
model_time=datetime.fromtimestamp(os.path.getmtime(data_path)); return datetime.now()-model_time<timedelta(hours=max_age_hours)
|
| 141 |
|
| 142 |
def _save_model(model, scaler, symbol: str, horizon: int, model_name: str, num_classes: int, use_grid_search: bool, manual_params: bool, lookback: Optional[int] = None, accuracy: Optional[float] = 0.0):
|
|
|
|
| 158 |
except Exception as e: print(f"❌ LSTM model yüklenemedi: {e}"); return None,None,None,0.0
|
| 159 |
return model,scaler,lookback,accuracy
|
| 160 |
|
| 161 |
+
# === OPTİMİZASYON 1: _get_or_train_model (LSTM Epoch Düşürme) ===
|
| 162 |
def _get_or_train_model(
|
| 163 |
symbol: str,
|
| 164 |
horizon: int,
|
|
|
|
| 173 |
manual_params: Optional[dict] = None
|
| 174 |
):
|
| 175 |
|
|
|
|
| 176 |
has_manual_params = bool(manual_params and any(v is not None for v in manual_params.values()))
|
|
|
|
|
|
|
| 177 |
data_path,_ = _get_model_paths(symbol, horizon, model_name, num_classes, use_grid_search, has_manual_params)
|
| 178 |
|
| 179 |
if _is_model_fresh(data_path):
|
|
|
|
| 184 |
messages.append(f"⏳ '{model_name}' ({num_classes}-sınıf) modeli eğitiliyor...");
|
| 185 |
print(f"🔥 '{model_name}' ({num_classes}-sınıf) {symbol} için eğitilecek...")
|
| 186 |
model,scaler,lookback,acc=None,None,None,0.0
|
|
|
|
| 187 |
class_weight = 'balanced' if num_classes == 3 else None
|
|
|
|
| 188 |
y_train_mapped = y_train.copy()
|
| 189 |
y_test_mapped = y_test.copy()
|
| 190 |
+
if num_classes == 3:
|
| 191 |
y_train_mapped = y_train + 1
|
| 192 |
y_test_mapped = y_test + 1
|
| 193 |
|
|
|
|
| 202 |
|
| 203 |
if use_grid_search and not has_manual_params:
|
| 204 |
print(f"🔥 RF: GridSearchCV ile optimize ediliyor (YAVAŞ)...")
|
| 205 |
+
# GridSearch için parametre grid'ini RAM'e göre küçültün (Render Free tier için)
|
| 206 |
+
param_grid={'n_estimators':[100, 200], 'max_depth':[10], 'min_samples_split':[50, 100]}
|
| 207 |
grid=GridSearchCV(RandomForestClassifier(random_state=42, class_weight=class_weight), param_grid, cv=tscv, n_jobs=1)
|
| 208 |
grid.fit(X_train, y_train)
|
| 209 |
print(f"✅ RF için en iyi parametreler: {grid.best_params_}");
|
|
|
|
| 228 |
if use_grid_search and not has_manual_params:
|
| 229 |
print(f"🔥 SVM: GridSearchCV ile optimize ediliyor (YAVAŞ)...")
|
| 230 |
pipeline=Pipeline([('scaler',StandardScaler()),('svm',SVC(probability=True,random_state=42,class_weight=class_weight))])
|
| 231 |
+
# GridSearch için parametre grid'ini RAM'e göre küçültün
|
| 232 |
+
param_grid={'svm__C':[1, 50], 'svm__kernel':['rbf']} # 'poly' yavaştır ve çok RAM yer
|
| 233 |
grid=GridSearchCV(pipeline, param_grid, cv=TimeSeriesSplit(n_splits=3), n_jobs=1);
|
| 234 |
grid.fit(X_train, y_train)
|
| 235 |
print(f"✅ SVM için en iyi parametreler: {grid.best_params_}");
|
|
|
|
| 247 |
acc=float(accuracy_score(y_test, model.predict(X_test)))
|
| 248 |
|
| 249 |
elif model_name=="LSTM":
|
|
|
|
| 250 |
lookback=30; scaler=StandardScaler();
|
| 251 |
X_train_s=scaler.fit_transform(X_train);
|
| 252 |
y_cat=to_categorical(y_train_mapped, num_classes=num_classes)
|
|
|
|
| 259 |
LSTM(50),Dropout(0.2),Dense(25,activation="relu"),Dense(num_classes, activation="softmax")
|
| 260 |
]);
|
| 261 |
model.compile(optimizer="adam",loss="categorical_crossentropy",metrics=["accuracy"])
|
| 262 |
+
|
| 263 |
+
# === HIZ OPTİMİZASYONU: Epoch ve Patience düşürüldü ===
|
| 264 |
+
model.fit(np.array(X_seq),np.array(y_seq),
|
| 265 |
+
epochs=15, # 50'den 15'e düşürüldü
|
| 266 |
+
batch_size=32,
|
| 267 |
+
validation_split=0.1,
|
| 268 |
+
callbacks=[EarlyStopping(monitor='val_loss', patience=3)], # 5'ten 3'e düşürüldü
|
| 269 |
+
verbose=0)
|
| 270 |
+
# === === ===
|
| 271 |
|
| 272 |
X_test_s=scaler.transform(X_test)
|
| 273 |
X_test_seq=[X_test_s[i-lookback:i] for i in range(lookback,len(X_test_s))]
|
|
|
|
| 287 |
return None, None, None, 0.0
|
| 288 |
|
| 289 |
|
| 290 |
+
# === Tahmin Fonksiyonu (Değişiklik Yok) ===
|
| 291 |
def _get_prediction(model, scaler, lookback, model_name, X_full, df_with_features, num_classes: int):
|
| 292 |
trend = "Neutral"
|
| 293 |
if model_name=="LSTM":
|
|
|
|
| 314 |
trend_map = {-1: "Down", 1: "Up"}
|
| 315 |
trend = trend_map.get(int(pred_idx), "Neutral")
|
| 316 |
|
|
|
|
| 317 |
last_close=df_with_features["close"].iloc[-1].item()
|
| 318 |
|
| 319 |
if trend=="Up": next_close=last_close*1.01
|
|
|
|
| 322 |
return trend,float(np.round(next_close,2))
|
| 323 |
|
| 324 |
|
| 325 |
+
# === Ana API Endpoint'i (Optimizasyonlar 2 ve 3) ===
|
| 326 |
@app.post("/predict_all", response_model=PredictAllResponse)
|
| 327 |
async def predict_all(req: PredictAllRequest):
|
| 328 |
+
messages=["🚀 Hibrit analiz (Optimize V2) başlatıldı..."]
|
| 329 |
try:
|
| 330 |
df_raw=_download_data(req.symbol);
|
| 331 |
messages.append("✅ Veri başarıyla indirildi.")
|
|
|
|
| 344 |
|
| 345 |
split_idx_3class = int(len(y_3class) * 0.8)
|
| 346 |
if split_idx_3class < 50 or (len(y_3class) - split_idx_3class) < 50:
|
| 347 |
+
raise HTTPException(400, f"Modeli eğitmek/test etmek için yeterli 3-sınıflı veri yok.")
|
| 348 |
|
| 349 |
non_neutral_mask = (y_3class != 0)
|
| 350 |
y_2class = y_3class[non_neutral_mask]
|
|
|
|
| 355 |
run_2class_models = split_idx_2class >= 50 and (len(y_2class) - split_idx_2class) >= 50
|
| 356 |
|
| 357 |
if not run_2class_models:
|
| 358 |
+
messages.append(f"⚠️ RF/SVM için 2-sınıflı veri yetersiz, bu modeller atlanıyor.")
|
| 359 |
|
| 360 |
results=[]; trained_models={}
|
| 361 |
|
| 362 |
+
# === OPTİMİZASYON 2: GridSearch sırasında LSTM'i atla (RAM Tasarrufu) ===
|
| 363 |
+
if req.use_grid_search:
|
| 364 |
+
messages.append("⚠️ GridSearch aktif, RAM tasarrufu için LSTM atlanıyor.")
|
| 365 |
+
print("ℹ️ GridSearch aktif, LSTM atlanıyor.")
|
| 366 |
+
else:
|
| 367 |
+
# --- LSTM (3-Sınıf, Ham+Sinyal Verisi) ---
|
| 368 |
+
try:
|
| 369 |
+
X_train_full, X_test_full = X_full_df.values[:split_idx_3class], X_full_df.values[split_idx_3class:]
|
| 370 |
+
y_train_3class, y_test_3class = y_3class[:split_idx_3class], y_3class[split_idx_3class:]
|
| 371 |
+
|
| 372 |
+
model,scaler,lookback,acc = _get_or_train_model(
|
| 373 |
+
req.symbol, req.horizon_days, "LSTM",
|
| 374 |
+
X_train_full, y_train_3class, X_test_full, y_test_3class,
|
| 375 |
+
messages, num_classes=3, use_grid_search=False, manual_params=None
|
| 376 |
+
)
|
| 377 |
+
trained_models["LSTM"]={'model':model,'scaler':scaler,'lookback':lookback, 'acc': acc, 'num_classes': 3, 'X_cols': ALL_FEATURES_RAW_AND_SIGNAL}
|
| 378 |
+
except Exception as e: print(f"❌ 'LSTM' için hata: {e}"); messages.append(f"❌ 'LSTM' işlenirken hata oluştu: {str(e)}")
|
| 379 |
|
| 380 |
if run_2class_models:
|
| 381 |
# --- RF (2-Sınıf, Sinyal Verisi) ---
|
|
|
|
| 407 |
trained_models["SVM"]={'model':model,'scaler':scaler,'lookback':lookback, 'acc': acc, 'num_classes': 2, 'X_cols': ALL_FEATURES_RAW_AND_SIGNAL}
|
| 408 |
except Exception as e: print(f"❌ 'SVM' için hata: {e}"); messages.append(f"❌ 'SVM' işlenirken hata oluştu: {str(e)}")
|
| 409 |
|
| 410 |
+
# --- 5. Tahminleri (Ana Tahmin) Oluştur ---
|
| 411 |
chart_data=[]
|
|
|
|
| 412 |
|
| 413 |
X_predict_full = df_features_full[ALL_FEATURES_RAW_AND_SIGNAL].values.astype(np.float32)
|
| 414 |
X_predict_signal = df_features_full[FEATURES_SIGNAL_ONLY].values.astype(np.float32)
|
|
|
|
| 423 |
)
|
| 424 |
results.append(ModelResult(model=model_name, accuracy=m_data['acc'], trend=trend, predicted_close=predicted_close))
|
| 425 |
|
| 426 |
+
# === OPTİMİZASYON 3: Geriye dönük grafik testi (Toplu Tahmin) ===
|
| 427 |
+
|
| 428 |
+
# 1. Son 90 günün verisini al
|
| 429 |
+
chart_df_features = df_features_full.tail(90)
|
| 430 |
+
|
| 431 |
+
# 2. Gerekli tüm özellikleri tek seferde al (Sinyal+Full)
|
| 432 |
+
# Tahmin edilecek son 90 günü ve LSTM'in lookback'i için gereken geçmişi al
|
| 433 |
+
lookback_buffer = 30 # LSTM'in maksimum lookback'i
|
| 434 |
+
chart_start_index = max(0, len(df_features_full) - 90 - lookback_buffer)
|
| 435 |
+
|
| 436 |
+
X_chart_full = df_features_full[ALL_FEATURES_RAW_AND_SIGNAL].iloc[chart_start_index:].values.astype(np.float32)
|
| 437 |
+
X_chart_signal = df_features_full[FEATURES_SIGNAL_ONLY].iloc[chart_start_index:].values.astype(np.float32)
|
| 438 |
+
|
| 439 |
+
predictions_map = {} # Tahminleri burada sakla
|
| 440 |
+
|
| 441 |
+
try:
|
| 442 |
+
if "RandomForest" in trained_models and trained_models["RandomForest"].get('model'):
|
| 443 |
+
m_data_rf = trained_models["RandomForest"]
|
| 444 |
+
X_to_predict_rf = X_chart_signal[-90:] # Sadece son 90 gün sinyali
|
| 445 |
+
|
| 446 |
+
up_class_index = np.where(m_data_rf['model'].classes_ == 1)[0][0]
|
| 447 |
+
probas = m_data_rf['model'].predict_proba(X_to_predict_rf)[:, up_class_index]
|
| 448 |
+
trends = np.where(probas >= THRESHOLD_RF, "Up", "Down")
|
| 449 |
+
predictions_map["RandomForest"] = trends
|
| 450 |
+
|
| 451 |
+
if "SVM" in trained_models and trained_models["SVM"].get('model'):
|
| 452 |
+
m_data_svm = trained_models["SVM"]
|
| 453 |
+
X_to_predict_svm = X_chart_full[-90:] # Sadece son 90 gün full veri
|
| 454 |
+
|
| 455 |
+
preds_idx = m_data_svm['model'].predict(X_to_predict_svm)
|
| 456 |
+
trend_map_svm = {-1: "Down", 1: "Up"}
|
| 457 |
+
trends = [trend_map_svm.get(int(p), "Neutral") for p in preds_idx]
|
| 458 |
+
predictions_map["SVM"] = trends
|
| 459 |
+
|
| 460 |
+
if "LSTM" in trained_models and trained_models["LSTM"].get('model'):
|
| 461 |
+
m_data_lstm = trained_models["LSTM"]
|
| 462 |
+
lookback = m_data_lstm['lookback']
|
| 463 |
+
num_classes = m_data_lstm['num_classes']
|
| 464 |
+
|
| 465 |
+
# Veriyi SADECE BİR KEZ scale et (buffer ile birlikte)
|
| 466 |
+
X_scaled_full_chart = m_data_lstm['scaler'].transform(X_chart_full)
|
| 467 |
+
|
| 468 |
+
X_seq_list = []
|
| 469 |
+
# Son 90 gün için dizileri oluştur
|
| 470 |
+
# X_scaled_full_chart'ın son 90 elemanı üzerinden döner
|
| 471 |
+
for i in range(len(X_scaled_full_chart) - 90, len(X_scaled_full_chart)):
|
| 472 |
+
X_seq_list.append(X_scaled_full_chart[i-lookback:i])
|
| 473 |
+
|
| 474 |
+
if X_seq_list:
|
| 475 |
+
preds_mapped = np.argmax(m_data_lstm['model'].predict(np.array(X_seq_list), verbose=0), axis=1)
|
| 476 |
+
if num_classes == 3: trend_map_lstm = {0: "Down", 1: "Neutral", 2: "Up"}
|
| 477 |
+
else: trend_map_lstm = {0: "Down", 1: "Up"}
|
| 478 |
+
trends = [trend_map_lstm.get(int(p), "Neutral") for p in preds_mapped]
|
| 479 |
+
predictions_map["LSTM"] = trends
|
| 480 |
+
|
| 481 |
+
except Exception as e:
|
| 482 |
+
print(f"❌ Grafik geri-test hatası: {e}")
|
| 483 |
+
messages.append(f"⚠️ Grafik verisi oluşturulamadı: {e}")
|
| 484 |
+
|
| 485 |
+
# 4. Sonuçları birleştir (Bu döngü artık ÇOK HIZLI)
|
| 486 |
for i in range(len(chart_df_features)):
|
| 487 |
current_date_index = chart_df_features.index[i]
|
| 488 |
+
last_close = chart_df_features['close'].iloc[i].item()
|
|
|
|
| 489 |
|
| 490 |
+
chart_point = {
|
| 491 |
+
"date": current_date_index.strftime('%Y-%m-%d'),
|
| 492 |
+
"real": last_close
|
| 493 |
+
}
|
| 494 |
+
|
| 495 |
for model_name in ["RandomForest", "SVM", "LSTM"]:
|
| 496 |
+
if model_name in predictions_map and i < len(predictions_map[model_name]):
|
| 497 |
+
trend = predictions_map[model_name][i]
|
| 498 |
+
# Not: Grafik için _get_prediction'daki fiyatı değil,
|
| 499 |
+
# o günün 'real' fiyatına göre trendi yansıtıyoruz.
|
| 500 |
+
# Eğer trend 'Up' ise, bir sonraki günün fiyatını tahmin etmek yerine,
|
| 501 |
+
# o günün fiyatını 'tahmin' olarak gösteriyoruz (veya _get_prediction'daki mantığı kullanabiliriz).
|
| 502 |
+
# Frontend'deki mantık _get_prediction'a dayalıysa:
|
| 503 |
+
if trend == "Up": chart_point[model_name] = last_close * 1.01
|
| 504 |
+
elif trend == "Down": chart_point[model_name] = last_close * 0.99
|
| 505 |
+
else: chart_point[model_name] = last_close
|
| 506 |
+
else:
|
| 507 |
+
chart_point[model_name] = None # Tahmin yok
|
| 508 |
|
| 509 |
chart_data.append(ChartDataPoint(**chart_point))
|
| 510 |
|
|
|
|
| 521 |
raise HTTPException(500,detail=f"Bir sunucu hatası oluştu: {str(e)}")
|
| 522 |
|
| 523 |
|
| 524 |
+
# === Frontend Sunma Kodu (Değişiklik Yok) ===
|
| 525 |
BASE_DIR = Path(__file__).resolve().parent
|
| 526 |
PROJECT_ROOT = BASE_DIR.parent.parent
|
| 527 |
FRONTEND_DIST = PROJECT_ROOT / "frontend" / "dist"
|
frontend/src/App.tsx
CHANGED
|
@@ -3,10 +3,10 @@ import {
|
|
| 3 |
LineChart, Line, XAxis, YAxis, Tooltip, Legend, ResponsiveContainer, CartesianGrid
|
| 4 |
} from 'recharts';
|
| 5 |
|
| 6 |
-
// --- (İkonlar için SVG Kodları) ---
|
| 7 |
const SettingsIcon = () => (
|
| 8 |
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
| 9 |
-
<path d="M19.14,12.94c0.04-0.3,0.06-0.61,0.06-0.94c0-0.32-0.02-0.64-0.07-0.94l2.03-1.58c0.18-0.14,0.23-0.41,0.12-0.61 l-1.92-3.32c-0.12-0.2-0.37-0.28-0.59-0.22l-2.39,0.96c-0.5-0.38-1.03-0.7-1.62-0.94L14.4,2.81c-0.04-0.24-0.24-0.41-0.48-0.41 h-3.84c-0.24,0-0.43,0.17-0.48,0.41L9.2,4.81C8.61,5.05,8.08,5.36,7.59,5.74L5.2,4.78C4.98,4.7,4.73,4.78,4.61,4.98L2.69,8.3 c-0.11,0.2-0.06,0.47,0.12,0.61l2.03,1.58C4.78,10.76,4.76,11.06,4.76,11.36c0,0.32,0.02,0.64,0.07,0.94l-2.03,1.58 c-0.18,0.14-0.23,0.41-0.12,0.61l1.92,3.32c0.12,0.2,0.37,0.28,0.59,0.22l2.39-0.96c0.5,0.38,1.03,0.7,1.62,0.94l0.39,2.01 c0.04,0.24,0.24,0.41,0.48,0.41h3.84c0.24,0,0.43
|
| 10 |
</svg>
|
| 11 |
);
|
| 12 |
const CloseIcon = () => (
|
|
@@ -15,7 +15,7 @@ const CloseIcon = () => (
|
|
| 15 |
</svg>
|
| 16 |
);
|
| 17 |
|
| 18 |
-
// --- Tipler (
|
| 19 |
type Trend = 'Up' | 'Down' | 'Neutral';
|
| 20 |
type ModelResult = { model: string; accuracy: number; trend: Trend; predicted_close: number; };
|
| 21 |
type ChartProps = { data: Array<Record<string, any>> };
|
|
@@ -26,7 +26,7 @@ type PredictAllResponse = {
|
|
| 26 |
messages: string[];
|
| 27 |
};
|
| 28 |
|
| 29 |
-
// ---
|
| 30 |
type RFParams = {
|
| 31 |
n_estimators: number | null;
|
| 32 |
max_depth: number | null;
|
|
@@ -76,8 +76,7 @@ const PredictionChart: React.FC<ChartProps> = ({ data }) => {
|
|
| 76 |
);
|
| 77 |
};
|
| 78 |
|
| 79 |
-
// ---
|
| 80 |
-
// Bu bileşen, main.py dosyasındaki DEFAULT_RF_PARAMS ve DEFAULT_SVM_PARAMS'ı bilmeli
|
| 81 |
const DEFAULT_RF = { n_estimators: 200, max_depth: 10, min_samples_split: 50 };
|
| 82 |
const DEFAULT_SVM = { C: 50, kernel: 'rbf' };
|
| 83 |
|
|
@@ -98,7 +97,6 @@ const SettingsModal: React.FC<SettingsModalProps> = ({
|
|
| 98 |
}) => {
|
| 99 |
if (!isOpen) return null;
|
| 100 |
|
| 101 |
-
// Manuel girişi sayıya veya null'a çevirir
|
| 102 |
const handleNumChange = (val: string): number | null => {
|
| 103 |
const num = parseInt(val, 10);
|
| 104 |
return Number.isNaN(num) ? null : num;
|
|
@@ -115,12 +113,14 @@ const SettingsModal: React.FC<SettingsModalProps> = ({
|
|
| 115 |
<div className="modal-body">
|
| 116 |
{/* --- GridSearch Checkbox --- */}
|
| 117 |
<div className="field" style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
|
|
|
|
| 118 |
<label htmlFor="gridsearch" style={{ color: 'var(--text)', fontWeight: 600 }}>
|
| 119 |
-
|
| 120 |
<span style={{ color: '#64748b', fontWeight: 400, fontSize: 12, display: 'block' }}>
|
| 121 |
-
|
| 122 |
</span>
|
| 123 |
</label>
|
|
|
|
| 124 |
<input
|
| 125 |
type="checkbox"
|
| 126 |
id="gridsearch"
|
|
@@ -134,10 +134,10 @@ const SettingsModal: React.FC<SettingsModalProps> = ({
|
|
| 134 |
|
| 135 |
<h3 className="sub-title">Manuel Parametreler</h3>
|
| 136 |
<p className="sub-title-desc">
|
| 137 |
-
(Bu alanları doldurmak,
|
| 138 |
</p>
|
| 139 |
|
| 140 |
-
{/* --- RandomForest Ayarları --- */}
|
| 141 |
<h4 className="model-title">RandomForest</h4>
|
| 142 |
<div className="field-grid">
|
| 143 |
<div className="field">
|
|
@@ -169,7 +169,7 @@ const SettingsModal: React.FC<SettingsModalProps> = ({
|
|
| 169 |
</div>
|
| 170 |
</div>
|
| 171 |
|
| 172 |
-
{/* --- SVM Ayarları --- */}
|
| 173 |
<h4 className="model-title">SVM</h4>
|
| 174 |
<div className="field-grid">
|
| 175 |
<div className="field">
|
|
@@ -193,7 +193,7 @@ const SettingsModal: React.FC<SettingsModalProps> = ({
|
|
| 193 |
</div>
|
| 194 |
</div>
|
| 195 |
|
| 196 |
-
{/* --- LSTM Ayarları (
|
| 197 |
<h4 className="model-title">LSTM</h4>
|
| 198 |
<p className="sub-title-desc" style={{ marginTop: 0 }}>LSTM manuel ayarları şu anda desteklenmemektedir.</p>
|
| 199 |
|
|
@@ -209,17 +209,16 @@ const SettingsModal: React.FC<SettingsModalProps> = ({
|
|
| 209 |
|
| 210 |
|
| 211 |
export const App: React.FC = () => {
|
| 212 |
-
const [symbol, setSymbol] = useState('GARAN.IS');
|
| 213 |
const [horizon, setHorizon] = useState(5);
|
| 214 |
const [loading, setLoading] = useState(false);
|
| 215 |
const [messages, setMessages] = useState<string[]>([]);
|
| 216 |
const [error, setError] = useState<string | null>(null);
|
| 217 |
const [response, setResponse] = useState<PredictAllResponse | null>(null);
|
| 218 |
|
| 219 |
-
// ---
|
| 220 |
const [showSettings, setShowSettings] = useState(false);
|
| 221 |
const [useGridSearch, setUseGridSearch] = useState(false);
|
| 222 |
-
// Varsayılanlar null, böylece backend DEFAULT_PARAMS'ı kullanır
|
| 223 |
const [rfParams, setRfParams] = useState<RFParams>({ n_estimators: null, max_depth: null, min_samples_split: null });
|
| 224 |
const [svmParams, setSvmParams] = useState<SVMParams>({ C: null, kernel: 'rbf' });
|
| 225 |
// --- ---
|
|
@@ -231,8 +230,7 @@ export const App: React.FC = () => {
|
|
| 231 |
setError(null);
|
| 232 |
setResponse(null);
|
| 233 |
|
| 234 |
-
// ---
|
| 235 |
-
// Sadece değeri olan (null olmayan) parametreleri göndeririz
|
| 236 |
const cleanRfParams = {
|
| 237 |
n_estimators: rfParams.n_estimators || undefined,
|
| 238 |
max_depth: rfParams.max_depth || undefined,
|
|
@@ -240,8 +238,8 @@ export const App: React.FC = () => {
|
|
| 240 |
};
|
| 241 |
|
| 242 |
const cleanSvmParams = {
|
| 243 |
-
|
| 244 |
-
|
| 245 |
};
|
| 246 |
|
| 247 |
const requestBody = {
|
|
@@ -257,7 +255,7 @@ export const App: React.FC = () => {
|
|
| 257 |
const res = await fetch(`${BACKEND_URL}/predict_all`, {
|
| 258 |
method: 'POST',
|
| 259 |
headers: { 'Content-Type': 'application/json' },
|
| 260 |
-
body: JSON.stringify(requestBody)
|
| 261 |
});
|
| 262 |
if (!res.ok) {
|
| 263 |
const err = await res.json().catch(() => ({ detail: 'Sunucu hatası' }));
|
|
@@ -273,6 +271,7 @@ export const App: React.FC = () => {
|
|
| 273 |
}
|
| 274 |
};
|
| 275 |
|
|
|
|
| 276 |
const chartData = useMemo(() => {
|
| 277 |
if (!response) return [];
|
| 278 |
return response.chart_data.map((r) => ({
|
|
@@ -291,14 +290,12 @@ export const App: React.FC = () => {
|
|
| 291 |
<img src="/icon-512.png" alt="SmartStock Logo" />
|
| 292 |
</div>
|
| 293 |
<div className="title">SmartStock</div>
|
| 294 |
-
{/* --- DEĞİŞİKLİK: Ayarlar Butonu --- */}
|
| 295 |
<button className="icon-button settings-button" onClick={() => setShowSettings(true)}>
|
| 296 |
<SettingsIcon />
|
| 297 |
</button>
|
| 298 |
-
{/* --- --- */}
|
| 299 |
</header>
|
| 300 |
|
| 301 |
-
{/* ---
|
| 302 |
<SettingsModal
|
| 303 |
isOpen={showSettings}
|
| 304 |
onClose={() => setShowSettings(false)}
|
|
@@ -309,10 +306,10 @@ export const App: React.FC = () => {
|
|
| 309 |
svmParams={svmParams}
|
| 310 |
setSvmParams={setSvmParams}
|
| 311 |
/>
|
| 312 |
-
{/* --- --- */}
|
| 313 |
|
| 314 |
<div className="card">
|
| 315 |
<form onSubmit={handleSubmit}>
|
|
|
|
| 316 |
<div className="field">
|
| 317 |
<label>Hisse Kodu</label>
|
| 318 |
<input
|
|
@@ -323,7 +320,6 @@ export const App: React.FC = () => {
|
|
| 323 |
required
|
| 324 |
/>
|
| 325 |
</div>
|
| 326 |
-
|
| 327 |
<div className="field">
|
| 328 |
<label>Tahmin Süresi (gün)</label>
|
| 329 |
<input
|
|
@@ -338,11 +334,14 @@ export const App: React.FC = () => {
|
|
| 338 |
required
|
| 339 |
/>
|
| 340 |
</div>
|
|
|
|
| 341 |
|
| 342 |
<div className="actions">
|
|
|
|
| 343 |
<button type="submit" disabled={loading}>
|
| 344 |
-
{loading ? (useGridSearch ? 'Optimize Ediliyor
|
| 345 |
</button>
|
|
|
|
| 346 |
</div>
|
| 347 |
</form>
|
| 348 |
|
|
@@ -354,9 +353,11 @@ export const App: React.FC = () => {
|
|
| 354 |
</div>
|
| 355 |
)}
|
| 356 |
{loading && (
|
|
|
|
| 357 |
<div style={{ padding: 8, color: '#94a3b8', textAlign: 'center' }}>
|
| 358 |
-
Modeller eğitiliyor... {useGridSearch ? '(
|
| 359 |
</div>
|
|
|
|
| 360 |
)}
|
| 361 |
|
| 362 |
{!loading && messages.length > 0 && (
|
|
@@ -368,6 +369,7 @@ export const App: React.FC = () => {
|
|
| 368 |
|
| 369 |
{error && <div className="result error-box" style={{ marginTop: 12 }}>{error}</div>}
|
| 370 |
|
|
|
|
| 371 |
{response && (
|
| 372 |
<>
|
| 373 |
<div className="result" style={{ marginTop: 12 }}>
|
|
@@ -386,7 +388,7 @@ export const App: React.FC = () => {
|
|
| 386 |
|
| 387 |
<div className="footer">PWA • React + FastAPI • Demo amaçlıdır</div>
|
| 388 |
|
| 389 |
-
{/* ---
|
| 390 |
<style>{`
|
| 391 |
.result { font-family: inherit; }
|
| 392 |
.error-box {
|
|
|
|
| 3 |
LineChart, Line, XAxis, YAxis, Tooltip, Legend, ResponsiveContainer, CartesianGrid
|
| 4 |
} from 'recharts';
|
| 5 |
|
| 6 |
+
// --- (İkonlar için SVG Kodları - Değişiklik Yok) ---
|
| 7 |
const SettingsIcon = () => (
|
| 8 |
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
| 9 |
+
<path d="M19.14,12.94c0.04-0.3,0.06-0.61,0.06-0.94c0-0.32-0.02-0.64-0.07-0.94l2.03-1.58c0.18-0.14,0.23-0.41,0.12-0.61 l-1.92-3.32c-0.12-0.2-0.37-0.28-0.59-0.22l-2.39,0.96c-0.5-0.38-1.03-0.7-1.62-0.94L14.4,2.81c-0.04-0.24-0.24-0.41-0.48-0.41 h-3.84c-0.24,0-0.43,0.17-0.48,0.41L9.2,4.81C8.61,5.05,8.08,5.36,7.59,5.74L5.2,4.78C4.98,4.7,4.73,4.78,4.61,4.98L2.69,8.3 c-0.11,0.2-0.06,0.47,0.12,0.61l2.03,1.58C4.78,10.76,4.76,11.06,4.76,11.36c0,0.32,0.02,0.64,0.07,0.94l-2.03,1.58 c-0.18,0.14-0.23,0.41-0.12,0.61l1.92,3.32c0.12,0.2,0.37,0.28,0.59,0.22l2.39-0.96c0.5,0.38,1.03,0.7,1.62,0.94l0.39,2.01 c0.04,0.24,0.24,0.41,0.48,0.41h3.84c0.24,0,0.43,0.17,0.48,0.41l0.39-2.01c0.59-0.24,1.12-0.56,1.62-0.94l2.39,0.96 c0.22,0.08,0.47,0,0.59-0.22l1.92-3.32C21.4,14.93,21.35,14.66,21.17,14.52l-2.03-1.58z M12,15.5c-1.93,0-3.5-1.57-3.5-3.5 s1.57-3.5,3.5-3.5s3.5,1.57,3.5,3.5S13.93,15.5,12,15.5z" />
|
| 10 |
</svg>
|
| 11 |
);
|
| 12 |
const CloseIcon = () => (
|
|
|
|
| 15 |
</svg>
|
| 16 |
);
|
| 17 |
|
| 18 |
+
// --- Tipler (Değişiklik Yok) ---
|
| 19 |
type Trend = 'Up' | 'Down' | 'Neutral';
|
| 20 |
type ModelResult = { model: string; accuracy: number; trend: Trend; predicted_close: number; };
|
| 21 |
type ChartProps = { data: Array<Record<string, any>> };
|
|
|
|
| 26 |
messages: string[];
|
| 27 |
};
|
| 28 |
|
| 29 |
+
// --- Ayar Tipleri (Değişiklik Yok) ---
|
| 30 |
type RFParams = {
|
| 31 |
n_estimators: number | null;
|
| 32 |
max_depth: number | null;
|
|
|
|
| 76 |
);
|
| 77 |
};
|
| 78 |
|
| 79 |
+
// --- Ayarlar Modalı Bileşeni (Değişiklik Yok) ---
|
|
|
|
| 80 |
const DEFAULT_RF = { n_estimators: 200, max_depth: 10, min_samples_split: 50 };
|
| 81 |
const DEFAULT_SVM = { C: 50, kernel: 'rbf' };
|
| 82 |
|
|
|
|
| 97 |
}) => {
|
| 98 |
if (!isOpen) return null;
|
| 99 |
|
|
|
|
| 100 |
const handleNumChange = (val: string): number | null => {
|
| 101 |
const num = parseInt(val, 10);
|
| 102 |
return Number.isNaN(num) ? null : num;
|
|
|
|
| 113 |
<div className="modal-body">
|
| 114 |
{/* --- GridSearch Checkbox --- */}
|
| 115 |
<div className="field" style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
|
| 116 |
+
{/* --- DEĞİŞİKLİK: Metin güncellendi --- */}
|
| 117 |
<label htmlFor="gridsearch" style={{ color: 'var(--text)', fontWeight: 600 }}>
|
| 118 |
+
Optimizasyon Kullan (GridSearch)
|
| 119 |
<span style={{ color: '#64748b', fontWeight: 400, fontSize: 12, display: 'block' }}>
|
| 120 |
+
En iyi RF/SVM parametrelerini bulur. (LSTM atlanır, ~1-2 dk sürebilir)
|
| 121 |
</span>
|
| 122 |
</label>
|
| 123 |
+
{/* --- --- --- */}
|
| 124 |
<input
|
| 125 |
type="checkbox"
|
| 126 |
id="gridsearch"
|
|
|
|
| 134 |
|
| 135 |
<h3 className="sub-title">Manuel Parametreler</h3>
|
| 136 |
<p className="sub-title-desc">
|
| 137 |
+
(Bu alanları doldurmak, Optimizasyonu devre dışı bırakır ve Hızlı Eğitimi bu ayarlarla yapar)
|
| 138 |
</p>
|
| 139 |
|
| 140 |
+
{/* --- RandomForest Ayarları (Değişiklik Yok) --- */}
|
| 141 |
<h4 className="model-title">RandomForest</h4>
|
| 142 |
<div className="field-grid">
|
| 143 |
<div className="field">
|
|
|
|
| 169 |
</div>
|
| 170 |
</div>
|
| 171 |
|
| 172 |
+
{/* --- SVM Ayarları (Değişiklik Yok) --- */}
|
| 173 |
<h4 className="model-title">SVM</h4>
|
| 174 |
<div className="field-grid">
|
| 175 |
<div className="field">
|
|
|
|
| 193 |
</div>
|
| 194 |
</div>
|
| 195 |
|
| 196 |
+
{/* --- LSTM Ayarları (Değişiklik Yok) --- */}
|
| 197 |
<h4 className="model-title">LSTM</h4>
|
| 198 |
<p className="sub-title-desc" style={{ marginTop: 0 }}>LSTM manuel ayarları şu anda desteklenmemektedir.</p>
|
| 199 |
|
|
|
|
| 209 |
|
| 210 |
|
| 211 |
export const App: React.FC = () => {
|
| 212 |
+
const [symbol, setSymbol] = useState('GARAN.IS');
|
| 213 |
const [horizon, setHorizon] = useState(5);
|
| 214 |
const [loading, setLoading] = useState(false);
|
| 215 |
const [messages, setMessages] = useState<string[]>([]);
|
| 216 |
const [error, setError] = useState<string | null>(null);
|
| 217 |
const [response, setResponse] = useState<PredictAllResponse | null>(null);
|
| 218 |
|
| 219 |
+
// --- Ayarlar state'leri (Değişiklik Yok) ---
|
| 220 |
const [showSettings, setShowSettings] = useState(false);
|
| 221 |
const [useGridSearch, setUseGridSearch] = useState(false);
|
|
|
|
| 222 |
const [rfParams, setRfParams] = useState<RFParams>({ n_estimators: null, max_depth: null, min_samples_split: null });
|
| 223 |
const [svmParams, setSvmParams] = useState<SVMParams>({ C: null, kernel: 'rbf' });
|
| 224 |
// --- ---
|
|
|
|
| 230 |
setError(null);
|
| 231 |
setResponse(null);
|
| 232 |
|
| 233 |
+
// --- Ayarları backend'e gönderme (Değişiklik Yok) ---
|
|
|
|
| 234 |
const cleanRfParams = {
|
| 235 |
n_estimators: rfParams.n_estimators || undefined,
|
| 236 |
max_depth: rfParams.max_depth || undefined,
|
|
|
|
| 238 |
};
|
| 239 |
|
| 240 |
const cleanSvmParams = {
|
| 241 |
+
C: svmParams.C || undefined,
|
| 242 |
+
kernel: svmParams.kernel || undefined,
|
| 243 |
};
|
| 244 |
|
| 245 |
const requestBody = {
|
|
|
|
| 255 |
const res = await fetch(`${BACKEND_URL}/predict_all`, {
|
| 256 |
method: 'POST',
|
| 257 |
headers: { 'Content-Type': 'application/json' },
|
| 258 |
+
body: JSON.stringify(requestBody)
|
| 259 |
});
|
| 260 |
if (!res.ok) {
|
| 261 |
const err = await res.json().catch(() => ({ detail: 'Sunucu hatası' }));
|
|
|
|
| 271 |
}
|
| 272 |
};
|
| 273 |
|
| 274 |
+
// --- chartData (Değişiklik Yok) ---
|
| 275 |
const chartData = useMemo(() => {
|
| 276 |
if (!response) return [];
|
| 277 |
return response.chart_data.map((r) => ({
|
|
|
|
| 290 |
<img src="/icon-512.png" alt="SmartStock Logo" />
|
| 291 |
</div>
|
| 292 |
<div className="title">SmartStock</div>
|
|
|
|
| 293 |
<button className="icon-button settings-button" onClick={() => setShowSettings(true)}>
|
| 294 |
<SettingsIcon />
|
| 295 |
</button>
|
|
|
|
| 296 |
</header>
|
| 297 |
|
| 298 |
+
{/* --- Ayarlar Modalı (Değişiklik Yok) --- */}
|
| 299 |
<SettingsModal
|
| 300 |
isOpen={showSettings}
|
| 301 |
onClose={() => setShowSettings(false)}
|
|
|
|
| 306 |
svmParams={svmParams}
|
| 307 |
setSvmParams={setSvmParams}
|
| 308 |
/>
|
|
|
|
| 309 |
|
| 310 |
<div className="card">
|
| 311 |
<form onSubmit={handleSubmit}>
|
| 312 |
+
{/* --- Form Alanları (Değişiklik Yok) --- */}
|
| 313 |
<div className="field">
|
| 314 |
<label>Hisse Kodu</label>
|
| 315 |
<input
|
|
|
|
| 320 |
required
|
| 321 |
/>
|
| 322 |
</div>
|
|
|
|
| 323 |
<div className="field">
|
| 324 |
<label>Tahmin Süresi (gün)</label>
|
| 325 |
<input
|
|
|
|
| 334 |
required
|
| 335 |
/>
|
| 336 |
</div>
|
| 337 |
+
{/* --- --- --- */}
|
| 338 |
|
| 339 |
<div className="actions">
|
| 340 |
+
{/* --- DEĞİŞİKLİK: Buton metni güncellendi --- */}
|
| 341 |
<button type="submit" disabled={loading}>
|
| 342 |
+
{loading ? (useGridSearch ? 'Optimize Ediliyor...' : 'Eğitiliyor (Hızlı)...') : 'Tahmin Et'}
|
| 343 |
</button>
|
| 344 |
+
{/* --- --- --- */}
|
| 345 |
</div>
|
| 346 |
</form>
|
| 347 |
|
|
|
|
| 353 |
</div>
|
| 354 |
)}
|
| 355 |
{loading && (
|
| 356 |
+
// --- DEĞİŞİKLİK: Yüklenme metni güncellendi ---
|
| 357 |
<div style={{ padding: 8, color: '#94a3b8', textAlign: 'center' }}>
|
| 358 |
+
Modeller eğitiliyor... {useGridSearch ? '(Optimizasyon modu, LSTM atlanıyor, ~1-2 dk)' : '(Hızlı mod, ~30-60sn)'}
|
| 359 |
</div>
|
| 360 |
+
// --- --- ---
|
| 361 |
)}
|
| 362 |
|
| 363 |
{!loading && messages.length > 0 && (
|
|
|
|
| 369 |
|
| 370 |
{error && <div className="result error-box" style={{ marginTop: 12 }}>{error}</div>}
|
| 371 |
|
| 372 |
+
{/* --- Sonuç Alanı (Değişiklik Yok) --- */}
|
| 373 |
{response && (
|
| 374 |
<>
|
| 375 |
<div className="result" style={{ marginTop: 12 }}>
|
|
|
|
| 388 |
|
| 389 |
<div className="footer">PWA • React + FastAPI • Demo amaçlıdır</div>
|
| 390 |
|
| 391 |
+
{/* --- CSS (Değişiklik Yok) --- */}
|
| 392 |
<style>{`
|
| 393 |
.result { font-family: inherit; }
|
| 394 |
.error-box {
|