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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
warnings.filterwarnings("ignore")
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import yfinance as yf
|
| 7 |
+
import gradio as gr
|
| 8 |
+
import plotly.graph_objects as go
|
| 9 |
+
|
| 10 |
+
from sklearn.impute import SimpleImputer
|
| 11 |
+
from sklearn.preprocessing import StandardScaler
|
| 12 |
+
from sklearn.pipeline import Pipeline
|
| 13 |
+
from sklearn.neighbors import KNeighborsClassifier
|
| 14 |
+
from sklearn.metrics import balanced_accuracy_score, accuracy_score
|
| 15 |
+
|
| 16 |
+
APP_TITLE = "Goshawk Adaptive BTCUSD Research Engine"
|
| 17 |
+
HORIZON = 5
|
| 18 |
+
K_CANDIDATES = [5, 7, 9, 11, 15, 21]
|
| 19 |
+
SL_GRID = [0.8, 1.0, 1.2, 1.5, 1.8, 2.0, 2.5, 3.0]
|
| 20 |
+
RR_GRID = [1.0, 1.25, 1.5, 2.0, 2.5, 3.0, 4.0]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def get_btc(period):
|
| 24 |
+
df = yf.download("BTC-USD", period=period, interval="1d",
|
| 25 |
+
auto_adjust=True, progress=False)
|
| 26 |
+
if df is None or df.empty:
|
| 27 |
+
raise ValueError("Yahoo Finance BTC verisi döndürmedi.")
|
| 28 |
+
if isinstance(df.columns, pd.MultiIndex):
|
| 29 |
+
df.columns = df.columns.get_level_values(0)
|
| 30 |
+
df = df[["Open", "High", "Low", "Close", "Volume"]].dropna().copy()
|
| 31 |
+
df.index = pd.to_datetime(df.index)
|
| 32 |
+
return df
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def calc_atr(df, n=14):
|
| 36 |
+
pc = df.Close.shift(1)
|
| 37 |
+
tr = pd.concat([(df.High-df.Low), (df.High-pc).abs(),
|
| 38 |
+
(df.Low-pc).abs()], axis=1).max(axis=1)
|
| 39 |
+
return tr.ewm(alpha=1/n, adjust=False).mean()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def calc_rsi(s, n=14):
|
| 43 |
+
d = s.diff()
|
| 44 |
+
up = d.clip(lower=0).ewm(alpha=1/n, adjust=False).mean()
|
| 45 |
+
dn = (-d.clip(upper=0)).ewm(alpha=1/n, adjust=False).mean()
|
| 46 |
+
rs = up / dn.replace(0, np.nan)
|
| 47 |
+
return 100 - 100/(1+rs)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def make_features(df):
|
| 51 |
+
c, v = df.Close, df.Volume
|
| 52 |
+
x = pd.DataFrame(index=df.index)
|
| 53 |
+
for n in [1, 2, 3, 5, 10, 20, 50]:
|
| 54 |
+
x[f"ret_{n}"] = c.pct_change(n)
|
| 55 |
+
for n in [5, 10, 20, 50]:
|
| 56 |
+
ema = c.ewm(span=n, adjust=False).mean()
|
| 57 |
+
x[f"ema_gap_{n}"] = c/ema - 1
|
| 58 |
+
x["rsi_14"] = calc_rsi(c)/100
|
| 59 |
+
x["atr_pct"] = calc_atr(df)/c
|
| 60 |
+
x["range_pct"] = (df.High-df.Low)/c
|
| 61 |
+
x["body_pct"] = (df.Close-df.Open)/df.Open
|
| 62 |
+
daily_ret = c.pct_change()
|
| 63 |
+
x["volatility_10"] = daily_ret.rolling(10).std()
|
| 64 |
+
x["volatility_20"] = daily_ret.rolling(20).std()
|
| 65 |
+
x["volume_z20"] = (v-v.rolling(20).mean())/v.rolling(20).std().replace(0, np.nan)
|
| 66 |
+
x["volume_change"] = v.pct_change()
|
| 67 |
+
macd = c.ewm(span=12, adjust=False).mean()-c.ewm(span=26, adjust=False).mean()
|
| 68 |
+
x["macd_pct"] = macd/c
|
| 69 |
+
return x.replace([np.inf, -np.inf], np.nan), calc_atr(df)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def make_target(df, atr, horizon=HORIZON, threshold=0.20):
|
| 73 |
+
future_ret = df.Close.shift(-horizon)/df.Close - 1
|
| 74 |
+
band = threshold*(atr/df.Close)*np.sqrt(horizon)
|
| 75 |
+
target = np.where(future_ret > band, 1,
|
| 76 |
+
np.where(future_ret < -band, -1, 0))
|
| 77 |
+
return pd.Series(target, index=df.index), future_ret
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def model_pipe(k):
|
| 81 |
+
return Pipeline([
|
| 82 |
+
("imputer", SimpleImputer(strategy="median")),
|
| 83 |
+
("scaler", StandardScaler()),
|
| 84 |
+
("knn", __import__("sklearn").neighbors.KNeighborsClassifier(
|
| 85 |
+
n_neighbors=int(k), weights="distance", metric="minkowski", p=2
|
| 86 |
+
))
|
| 87 |
+
])
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def tune_k(X, y, candidates=K_CANDIDATES):
|
| 91 |
+
# Chronological inner split; labels are already forward-looking, so purge horizon.
|
| 92 |
+
split = int(len(X)*0.80)
|
| 93 |
+
tr_end = max(50, split-HORIZON)
|
| 94 |
+
xtr, ytr = X.iloc[:tr_end], y.iloc[:tr_end]
|
| 95 |
+
xva, yva = X.iloc[split:], y.iloc[split:]
|
| 96 |
+
scores = []
|
| 97 |
+
for k in candidates:
|
| 98 |
+
if len(xtr) <= k or len(xva) < 20:
|
| 99 |
+
continue
|
| 100 |
+
m = model_pipe(k)
|
| 101 |
+
m.fit(xtr, ytr.astype(int))
|
| 102 |
+
pred = m.predict(xva)
|
| 103 |
+
scores.append((balanced_accuracy_score(yva.astype(int), pred), k))
|
| 104 |
+
if not scores:
|
| 105 |
+
return 9, []
|
| 106 |
+
scores.sort(reverse=True)
|
| 107 |
+
return int(scores[0][1]), scores
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def barrier_trade(df, i, side, sl_atr, rr, atr_values, horizon=HORIZON):
|
| 111 |
+
entry = float(df.Close.iloc[i])
|
| 112 |
+
av = float(atr_values.iloc[i])
|
| 113 |
+
if not np.isfinite(av) or av <= 0:
|
| 114 |
+
return None
|
| 115 |
+
stop_dist = sl_atr*av
|
| 116 |
+
target_dist = stop_dist*rr
|
| 117 |
+
end = min(i+horizon, len(df)-1)
|
| 118 |
+
for j in range(i+1, end+1):
|
| 119 |
+
hi, lo = float(df.High.iloc[j]), float(df.Low.iloc[j])
|
| 120 |
+
if side == 1:
|
| 121 |
+
sl_hit, tp_hit = lo <= entry-stop_dist, hi >= entry+target_dist
|
| 122 |
+
else:
|
| 123 |
+
sl_hit, tp_hit = hi >= entry+stop_dist, lo <= entry-target_dist
|
| 124 |
+
# Daily OHLC cannot reveal which barrier came first: assume the adverse one.
|
| 125 |
+
if sl_hit and tp_hit:
|
| 126 |
+
return -sl_atr*av/entry
|
| 127 |
+
if sl_hit:
|
| 128 |
+
return -sl_atr*av/entry
|
| 129 |
+
if tp_hit:
|
| 130 |
+
return target_dist/entry
|
| 131 |
+
exit_price = float(df.Close.iloc[end])
|
| 132 |
+
return side*(exit_price-entry)/entry
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def optimize_barriers(df, atr_values, end_index, side, fee_pct, slip_pct):
|
| 136 |
+
# Optimize only on the pre-validation segment; validation is kept separate.
|
| 137 |
+
start = max(70, end_index-600)
|
| 138 |
+
cost = 2*(fee_pct+slip_pct)/100
|
| 139 |
+
best, rows = None, []
|
| 140 |
+
for sl in SL_GRID:
|
| 141 |
+
for rr in RR_GRID:
|
| 142 |
+
results = []
|
| 143 |
+
for i in range(start, end_index-HORIZON):
|
| 144 |
+
r = barrier_trade(df, i, side, sl, rr, atr_values)
|
| 145 |
+
if r is not None:
|
| 146 |
+
results.append(r-cost)
|
| 147 |
+
if len(results) < 35:
|
| 148 |
+
continue
|
| 149 |
+
a = np.asarray(results)
|
| 150 |
+
# Conservative objective: mean return penalized by dispersion.
|
| 151 |
+
score = a.mean() - 0.25*a.std()
|
| 152 |
+
rows.append((score, sl, rr, len(a), a.mean(), (a > 0).mean()))
|
| 153 |
+
if not rows:
|
| 154 |
+
return 1.5, 2.0, None, []
|
| 155 |
+
rows.sort(reverse=True)
|
| 156 |
+
best = rows[0]
|
| 157 |
+
return float(best[1]), float(best[2]), best, rows[:10]
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def evaluate_oos(df, atr_values, X, y, train_end, sl, rr, fee_pct, slip_pct, k):
|
| 161 |
+
# Fit strictly before validation, then predict the later validation segment.
|
| 162 |
+
model = model_pipe(k)
|
| 163 |
+
model.fit(X.iloc[:train_end], y.iloc[:train_end].astype(int))
|
| 164 |
+
test_start = train_end + HORIZON
|
| 165 |
+
test_end = len(X)-HORIZON
|
| 166 |
+
if test_end <= test_start+10:
|
| 167 |
+
return [], None, None
|
| 168 |
+
preds = model.predict(X.iloc[test_start:test_end])
|
| 169 |
+
actual = y.iloc[test_start:test_end].astype(int).to_numpy()
|
| 170 |
+
bacc = balanced_accuracy_score(actual, preds)
|
| 171 |
+
trades = []
|
| 172 |
+
cost = 2*(fee_pct+slip_pct)/100
|
| 173 |
+
for offset, pred in enumerate(preds):
|
| 174 |
+
i = test_start+offset
|
| 175 |
+
if pred not in (-1, 1):
|
| 176 |
+
continue
|
| 177 |
+
result = barrier_trade(df, i, int(pred), sl, rr, atr_values)
|
| 178 |
+
if result is not None:
|
| 179 |
+
trades.append(result-cost)
|
| 180 |
+
return trades, bacc, accuracy_score(actual, preds)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def monte_carlo(trades, simulations=500, horizon=100):
|
| 184 |
+
if len(trades) < 10:
|
| 185 |
+
return None
|
| 186 |
+
rng = np.random.default_rng(42)
|
| 187 |
+
arr = np.asarray(trades, dtype=float)
|
| 188 |
+
finals, max_dds = [], []
|
| 189 |
+
for _ in range(simulations):
|
| 190 |
+
sample = rng.choice(arr, size=horizon, replace=True)
|
| 191 |
+
equity = np.cumprod(1+sample)
|
| 192 |
+
peak = np.maximum.accumulate(np.r_[1.0, equity])[1:]
|
| 193 |
+
dd = equity/peak-1
|
| 194 |
+
finals.append(equity[-1]-1)
|
| 195 |
+
max_dds.append(float(dd.min()))
|
| 196 |
+
return {
|
| 197 |
+
"median": float(np.median(finals)),
|
| 198 |
+
"p05": float(np.percentile(finals, 5)),
|
| 199 |
+
"p95": float(np.percentile(finals, 95)),
|
| 200 |
+
"dd95": float(np.percentile(max_dds, 5))
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def adaptive_risk(min_risk, max_risk, bacc, agreement, drawdown, expectancy, n_trades):
|
| 205 |
+
# Transparent conservative policy, not a trained RL agent.
|
| 206 |
+
quality = np.clip((bacc-0.33)/0.17, 0, 1)
|
| 207 |
+
neighbor = np.clip((agreement-0.33)/0.50, 0, 1)
|
| 208 |
+
edge = np.clip(expectancy/0.01, 0, 1) if np.isfinite(expectancy) else 0
|
| 209 |
+
sample = np.clip(n_trades/40, 0, 1)
|
| 210 |
+
score = 0.35*quality + 0.25*neighbor + 0.25*edge + 0.15*sample
|
| 211 |
+
risk = min_risk + (max_risk-min_risk)*score
|
| 212 |
+
if drawdown <= -0.15:
|
| 213 |
+
risk *= 0.25
|
| 214 |
+
elif drawdown <= -0.10:
|
| 215 |
+
risk *= 0.40
|
| 216 |
+
elif drawdown <= -0.06:
|
| 217 |
+
risk *= 0.65
|
| 218 |
+
return float(np.clip(risk, min_risk, max_risk)), float(score)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def run_engine(period, equity, min_risk, max_risk, max_leverage,
|
| 222 |
+
fee_pct, slip_pct, train_window):
|
| 223 |
+
try:
|
| 224 |
+
df = get_btc(period)
|
| 225 |
+
if len(df) < 400:
|
| 226 |
+
raise ValueError("En az 400 günlük mum gerekli.")
|
| 227 |
+
# Avoid using a possibly incomplete current daily candle.
|
| 228 |
+
df = df.iloc[:-1].copy()
|
| 229 |
+
X, atr_values = make_features(df)
|
| 230 |
+
y, forward_returns = make_target(df, atr_values)
|
| 231 |
+
data = X.copy()
|
| 232 |
+
data["target"] = y
|
| 233 |
+
valid_mask = data.notna().all(axis=1) & data.target.notna()
|
| 234 |
+
valid_idx = data.index[valid_mask]
|
| 235 |
+
Xv = X.loc[valid_idx].copy()
|
| 236 |
+
yv = y.loc[valid_idx].astype(int).copy()
|
| 237 |
+
# Last HORIZON rows are not eligible as labels for training.
|
| 238 |
+
Xv, yv = Xv.iloc[:-HORIZON], yv.iloc[:-HORIZON]
|
| 239 |
+
if len(Xv) < 250:
|
| 240 |
+
raise ValueError("Özelliklerden sonra yeterli eğitim örneği kalmadı.")
|
| 241 |
+
|
| 242 |
+
# Reserve a final chronological OOS block.
|
| 243 |
+
oos_n = min(150, max(60, int(len(Xv)*0.20)))
|
| 244 |
+
development_end = len(Xv)-oos_n-HORIZON
|
| 245 |
+
if development_end < 180:
|
| 246 |
+
raise ValueError("Walk-forward için veri yetersiz.")
|
| 247 |
+
dev_X, dev_y = Xv.iloc[:development_end], yv.iloc[:development_end]
|
| 248 |
+
if len(dev_X) > int(train_window):
|
| 249 |
+
dev_X, dev_y = dev_X.iloc[-int(train_window):], dev_y.iloc[-int(train_window):]
|
| 250 |
+
|
| 251 |
+
best_k, k_scores = tune_k(dev_X, dev_y)
|
| 252 |
+
# KNN's K is selected on an inner chronological validation split.
|
| 253 |
+
# Fit the final development model for the current signal.
|
| 254 |
+
current_x = X.iloc[[-1]]
|
| 255 |
+
current_model = model_pipe(best_k)
|
| 256 |
+
current_model.fit(dev_X, dev_y)
|
| 257 |
+
probs = current_model.predict_proba(current_x)
|
| 258 |
+
classes = current_model.named_steps["knn"].classes_
|
| 259 |
+
pmap = {int(c): float(p) for c, p in zip(classes, probs[0])}
|
| 260 |
+
p_up, p_flat, p_down = pmap.get(1, 0), pmap.get(0, 0), pmap.get(-1, 0)
|
| 261 |
+
side = 1 if p_up >= p_down else -1
|
| 262 |
+
|
| 263 |
+
# Neighbor agreement from the fitted KNN's own training set.
|
| 264 |
+
imp = current_model.named_steps["imputer"]
|
| 265 |
+
scaler = current_model.named_steps["scaler"]
|
| 266 |
+
ztr = scaler.transform(imp.transform(dev_X))
|
| 267 |
+
znow = scaler.transform(imp.transform(current_x))
|
| 268 |
+
from sklearn.neighbors import NearestNeighbors
|
| 269 |
+
nn = NearestNeighbors(n_neighbors=best_k).fit(ztr)
|
| 270 |
+
_, ix = nn.kneighbors(znow)
|
| 271 |
+
agreement = float((dev_y.iloc[ix[0]].to_numpy() == side).mean())
|
| 272 |
+
|
| 273 |
+
# Optimize TP/SL on development data only; final OOS is not used in selection.
|
| 274 |
+
dev_df_end = development_end
|
| 275 |
+
aligned_df = df.loc[Xv.index]
|
| 276 |
+
aligned_atr = atr_values.loc[Xv.index]
|
| 277 |
+
# Use the development block for barrier optimization.
|
| 278 |
+
sl, rr, opt, top_rows = optimize_barriers(
|
| 279 |
+
aligned_df.iloc[:dev_df_end], aligned_atr.iloc[:dev_df_end],
|
| 280 |
+
dev_df_end, side, float(fee_pct), float(slip_pct)
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
# Independent untouched OOS evaluation.
|
| 284 |
+
oos_df = aligned_df.iloc[:]
|
| 285 |
+
oos_atr = aligned_atr
|
| 286 |
+
oos_trades, oos_bacc, oos_acc = evaluate_oos(
|
| 287 |
+
oos_df, oos_atr, Xv, yv, development_end,
|
| 288 |
+
sl, rr, float(fee_pct), float(slip_pct), best_k
|
| 289 |
+
)
|
| 290 |
+
mc = monte_carlo(oos_trades)
|
| 291 |
+
expectancy = float(np.mean(oos_trades)) if oos_trades else 0.0
|
| 292 |
+
|
| 293 |
+
recent = df.Close.tail(30)
|
| 294 |
+
drawdown = float(recent.iloc[-1]/recent.cummax().iloc[-1]-1)
|
| 295 |
+
risk_pct, risk_score = adaptive_risk(
|
| 296 |
+
float(min_risk), float(max_risk),
|
| 297 |
+
float(oos_bacc if oos_bacc is not None else 0.33),
|
| 298 |
+
agreement, drawdown, expectancy, len(oos_trades)
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
entry = float(df.Close.iloc[-1])
|
| 302 |
+
current_atr = float(atr_values.iloc[-1])
|
| 303 |
+
stop_dist = sl*current_atr
|
| 304 |
+
target_dist = stop_dist*rr
|
| 305 |
+
stop = entry-stop_dist if side == 1 else entry+stop_dist
|
| 306 |
+
target = entry+target_dist if side == 1 else entry-target_dist
|
| 307 |
+
|
| 308 |
+
# Trade gate is deliberately conservative.
|
| 309 |
+
trade_ok = (
|
| 310 |
+
max(p_up, p_down) >= 0.43
|
| 311 |
+
and abs(p_up-p_down) >= 0.12
|
| 312 |
+
and agreement >= 0.55
|
| 313 |
+
and oos_bacc is not None and oos_bacc >= 0.36
|
| 314 |
+
and len(oos_trades) >= 15
|
| 315 |
+
and expectancy > 0
|
| 316 |
+
and p_flat < 0.60
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
risk_cash = float(equity)*risk_pct/100
|
| 320 |
+
cost_rate = 2*(float(fee_pct)+float(slip_pct))/100
|
| 321 |
+
per_btc_risk = stop_dist + entry*cost_rate
|
| 322 |
+
btc_qty = risk_cash/per_btc_risk if per_btc_risk > 0 else 0
|
| 323 |
+
max_notional = float(equity)*float(max_leverage)
|
| 324 |
+
notional = btc_qty*entry
|
| 325 |
+
capped = notional > max_notional
|
| 326 |
+
if capped:
|
| 327 |
+
btc_qty = max_notional/entry
|
| 328 |
+
notional = btc_qty*entry
|
| 329 |
+
actual_risk = btc_qty*per_btc_risk
|
| 330 |
+
margin = notional/max(float(max_leverage), 1)
|
| 331 |
+
if not trade_ok:
|
| 332 |
+
signal = "WAIT — OOS KANITI YETERSİZ"
|
| 333 |
+
btc_qty = notional = actual_risk = margin = 0.0
|
| 334 |
+
else:
|
| 335 |
+
signal = "LONG" if side == 1 else "SHORT"
|
| 336 |
+
|
| 337 |
+
k_text = " · ".join([f"K={kk}: {ss:.3f}" for ss, kk in sorted(k_scores, reverse=True)])
|
| 338 |
+
mc_text = (
|
| 339 |
+
f"100 işlem bootstrap medyan: {mc['median']:.1%} · "
|
| 340 |
+
f"%5 kötü senaryo: {mc['p05']:.1%} · "
|
| 341 |
+
f"%5 kuyruk max DD: {mc['dd95']:.1%}"
|
| 342 |
+
if mc else "Monte Carlo için en az 10 OOS işlem gerekli."
|
| 343 |
+
)
|
| 344 |
+
report = f"""
|
| 345 |
+
# {signal}
|
| 346 |
+
|
| 347 |
+
**Son kapanmış günlük mum:** {df.index[-1].date()} · **Referans fiyat:** ${entry:,.2f}
|
| 348 |
+
|
| 349 |
+
## Otomatik öğrenme
|
| 350 |
+
| Metrik | Sonuç |
|
| 351 |
+
|---|---:|
|
| 352 |
+
| P(LONG) | {p_up:.1%} |
|
| 353 |
+
| P(FLAT) | {p_flat:.1%} |
|
| 354 |
+
| P(SHORT) | {p_down:.1%} |
|
| 355 |
+
| Seçilen K | {best_k} |
|
| 356 |
+
| Komşu yön uyumu | {agreement:.1%} |
|
| 357 |
+
| OOS balanced accuracy | {oos_bacc if oos_bacc is not None else float('nan'):.3f} |
|
| 358 |
+
| OOS accuracy | {oos_acc if oos_acc is not None else float('nan'):.3f} |
|
| 359 |
+
| OOS işlem sayısı | {len(oos_trades)} |
|
| 360 |
+
| OOS expectancy / işlem | {expectancy:.3%} |
|
| 361 |
+
| Piyasa rejimi | {('Yüksek' if X.iloc[-1].volatility_20 > 0.045 else 'Düşük' if X.iloc[-1].volatility_20 < 0.018 else 'Orta')} volatilite |
|
| 362 |
+
|
| 363 |
+
**K optimizasyonu:** {k_text}
|
| 364 |
+
|
| 365 |
+
## Bağımsız TP / SL optimizasyonu
|
| 366 |
+
| Parametre | Değer |
|
| 367 |
+
|---|---:|
|
| 368 |
+
| SL mesafesi | {sl:.2f} ATR |
|
| 369 |
+
| TP mesafesi | {rr:.2f}R |
|
| 370 |
+
| Stop-loss | ${stop:,.2f} |
|
| 371 |
+
| Take-profit | ${target:,.2f} |
|
| 372 |
+
| ATR(14) | ${current_atr:,.2f} |
|
| 373 |
+
|
| 374 |
+
## Adaptif risk ve pozisyon
|
| 375 |
+
| Parametre | Değer |
|
| 376 |
+
|---|---:|
|
| 377 |
+
| Hesap büyüklüğü | ${equity:,.2f} |
|
| 378 |
+
| Model risk skoru | {risk_score:.2f} |
|
| 379 |
+
| Dinamik risk | {risk_pct:.2f}% |
|
| 380 |
+
| Risk bütçesi | ${risk_cash:,.2f} |
|
| 381 |
+
| BTC miktarı | {btc_qty:.6f} |
|
| 382 |
+
| Nominal pozisyon | ${notional:,.2f} |
|
| 383 |
+
| Tahmini teminat | ${margin:,.2f} |
|
| 384 |
+
| Tahmini stop kaybı + maliyet | ${actual_risk:,.2f} |
|
| 385 |
+
| Kaldıraç sınırı uygulandı | {"Evet" if capped else "Hayır"} |
|
| 386 |
+
| Son 30 günlük kapanış DD | {drawdown:.2%} |
|
| 387 |
+
|
| 388 |
+
## Monte Carlo — OOS işlem sonuçları
|
| 389 |
+
{mc_text}
|
| 390 |
+
"""
|
| 391 |
+
fig = go.Figure([go.Candlestick(
|
| 392 |
+
x=df.index[-150:], open=df.Open.tail(150), high=df.High.tail(150),
|
| 393 |
+
low=df.Low.tail(150), close=df.Close.tail(150), name="BTCUSD"
|
| 394 |
+
)])
|
| 395 |
+
if trade_ok:
|
| 396 |
+
fig.add_hline(y=stop, line_dash="dash", annotation_text="SL")
|
| 397 |
+
fig.add_hline(y=target, line_dash="dash", annotation_text="TP")
|
| 398 |
+
fig.update_layout(title="BTCUSD Daily — last 150 candles", height=520,
|
| 399 |
+
xaxis_rangeslider_visible=False)
|
| 400 |
+
|
| 401 |
+
top = pd.DataFrame(top_rows, columns=[
|
| 402 |
+
"score", "SL_ATR", "RR", "samples", "mean_net_return", "win_rate"
|
| 403 |
+
])
|
| 404 |
+
if not top.empty:
|
| 405 |
+
top["mean_net_return"] = top.mean_net_return.map(lambda v: f"{v:.3%}")
|
| 406 |
+
top["win_rate"] = top.win_rate.map(lambda v: f"{v:.1%}")
|
| 407 |
+
top["score"] = top.score.map(lambda v: f"{v:.5f}")
|
| 408 |
+
disclaimer = (
|
| 409 |
+
"**Önemli:** Araştırma prototipidir; otomatik emir göndermez ve kâr garantisi vermez. "
|
| 410 |
+
"K seçimi, TP/SL seçimi ve nihai OOS ayrımı kronolojik yapılır; yine de tekrar "
|
| 411 |
+
"denemeler ve veri sağlayıcı farkları overfitting yaratabilir. OOS sonuçları "
|
| 412 |
+
"tek başına canlı performans kanıtı değildir. Monte Carlo geçmiş OOS işlemlerini "
|
| 413 |
+
"bootstrap eder; rejim değişimini garantiyle modellemez. BTC-USD spot verisi "
|
| 414 |
+
"broker CFD fiyatı değildir. Spread, swap, funding, komisyon, lot sözleşmesi, "
|
| 415 |
+
"marjin ve minimum miktarı broker şartlarına göre ayrıca doğrulayın. Stop emirleri "
|
| 416 |
+
"gap/slippage nedeniyle hesaplanan riskten daha fazla kaybettirebilir. Bu sürüm "
|
| 417 |
+
"online learning veya gerçek RL ajanı değildir; her çalıştırmada yeniden eğitim "
|
| 418 |
+
"ve şeffaf adaptif risk kuralı kullanır."
|
| 419 |
+
)
|
| 420 |
+
return report, fig, top, disclaimer
|
| 421 |
+
|
| 422 |
+
except Exception as e:
|
| 423 |
+
return f"# Hata\n{type(e).__name__}: {e}", None, pd.DataFrame(), \
|
| 424 |
+
"Veri bağlantısını ve parametreleri kontrol edin."
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
with gr.Blocks(title=APP_TITLE, theme=gr.themes.Soft()) as demo:
|
| 428 |
+
gr.Markdown(
|
| 429 |
+
"# GOSHAWK — Adaptive KNN BTCUSD Research Engine\n"
|
| 430 |
+
"K otomatik seçimi · TP/SL optimizasyonu · ayrı kronolojik OOS test · "
|
| 431 |
+
"adaptif risk · Monte Carlo."
|
| 432 |
+
)
|
| 433 |
+
with gr.Row():
|
| 434 |
+
with gr.Column():
|
| 435 |
+
period = gr.Dropdown(["2y", "5y", "max"], value="5y", label="Veri geçmişi")
|
| 436 |
+
train_window = gr.Slider(300, 1500, value=900, step=50, label="Maksimum eğitim penceresi")
|
| 437 |
+
equity = gr.Number(value=10000, label="Hesap büyüklüğü (USD)")
|
| 438 |
+
max_leverage = gr.Slider(1, 10, value=3, step=1, label="Azami kaldıraç")
|
| 439 |
+
with gr.Column():
|
| 440 |
+
min_risk = gr.Slider(0.05, 0.5, value=0.10, step=0.05, label="Minimum risk (%)")
|
| 441 |
+
max_risk = gr.Slider(0.25, 1.5, value=0.75, step=0.05, label="Maksimum risk (%)")
|
| 442 |
+
fee_pct = gr.Number(value=0.05, label="Tek yön komisyon (%)")
|
| 443 |
+
slip_pct = gr.Number(value=0.03, label="Tek yön slippage (%)")
|
| 444 |
+
run = gr.Button("Öğren, optimize et ve test et", variant="primary")
|
| 445 |
+
output = gr.Markdown()
|
| 446 |
+
chart = gr.Plot()
|
| 447 |
+
optimization = gr.Dataframe(label="En iyi TP/SL kombinasyonları", interactive=False)
|
| 448 |
+
disclaimer = gr.Markdown()
|
| 449 |
+
run.click(
|
| 450 |
+
run_engine,
|
| 451 |
+
inputs=[period, equity, min_risk, max_risk, max_leverage,
|
| 452 |
+
fee_pct, slip_pct, train_window],
|
| 453 |
+
outputs=[output, chart, optimization, disclaimer]
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
if __name__ == "__main__":
|
| 457 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|