feat: адаптивный движок (A1-A5) + UI улучшения (B3-B7)

Движок: adaptive corr threshold, regime adaptive K/stop, Kelly criterion,
correlation filter. UI: signal log, manual close, CSV export, dark/light
toggle, mobile responsive.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-08 23:22:59 +10:00
co-authored by Claude Opus 4.6
parent 69fcf1b8d0
commit 8800ffb604
8 changed files with 348 additions and 11 deletions
+81 -10
View File
@@ -5,10 +5,12 @@ from __future__ import annotations
import sqlite3
from datetime import date
import numpy as np
from ..config import Config, AssetConfig
from ..state import (
add_equity_snapshot, close_position, get_open_position, log_cb_event,
log_signal, open_position, update_asset, update_position,
add_equity_snapshot, close_position, get_open_position, get_trade_history,
log_cb_event, log_signal, open_position, update_asset, update_position,
)
from . import model as model_mod
from . import risk, signals
@@ -100,6 +102,39 @@ def _count_open_positions(conn: sqlite3.Connection) -> int:
return row["cnt"] if row else 0
# Correlated asset groups — don't take same direction in both
CORRELATED_GROUPS = [
{"BTC-USD", "ETH-USD"}, # major cryptos move together
]
def _check_correlation_conflict(conn: sqlite3.Connection, ticker: str,
direction: int) -> str | None:
"""Check if opening this position conflicts with a correlated open position.
Returns conflict message or None.
"""
# Find which group this ticker belongs to
group = None
for g in CORRELATED_GROUPS:
if ticker in g:
group = g
break
if group is None:
return None
# Check if any correlated asset has an open position in same direction
for other_ticker in group:
if other_ticker == ticker:
continue
pos = get_open_position(conn, other_ticker)
if pos and pos["direction"] == direction:
dir_str = "LONG" if direction == 1 else "SHORT"
return f"correlated with {other_ticker} {dir_str} — SKIP"
return None
def _check_position(conn, pos, prices, dates, asset, asset_cfg, cfg):
"""Check if open position should be closed. Returns log message or None."""
direction = pos["direction"]
@@ -166,8 +201,16 @@ def _check_position(conn, pos, prices, dates, asset, asset_cfg, cfg):
def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
"""Check for new trading signal. Returns log message or None."""
K = asset_cfg.K
corr_thresh = asset_cfg.corr_thresh
K_base = asset_cfg.K
corr_thresh_base = asset_cfg.corr_thresh
# Regime adaptive: adjust K and stop_mult based on volatility
K, stop_mult = risk.regime_adaptive_params(prices, len(prices) - 1, K_base)
# Adaptive corr threshold: adjust based on recent win rate
corr_thresh = risk.adaptive_corr_threshold(
corr_thresh_base, asset["wins"], asset["trades_count"],
)
# Load model
mdl = model_mod.load_model(ticker, cfg.model)
@@ -193,22 +236,50 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
if not confirmed:
log_signal(conn, ticker=ticker, date=str(dates[-1]),
correlation=corr, action="skip_corr")
return f"corr={corr:.3f} < {corr_thresh} — SKIP"
correlation=corr, action="skip_corr",
details=f"thresh={corr_thresh:.2f} K={K}")
return f"corr={corr:.3f} < {corr_thresh:.2f} (adaptive) K={K} — SKIP"
# Direction
direction = signals.get_direction(pred_new, K)
if direction is None:
return "indeterminate direction"
# Correlation filter
conflict = _check_correlation_conflict(conn, ticker, direction)
if conflict:
log_signal(conn, ticker=ticker, date=str(dates[-1]),
correlation=corr, direction=direction, action="skip_corr_filter",
details=conflict)
return conflict
entry_price = sw["last_price"]
# Stop
stop_dist, stop_price = risk.calculate_stop(prices, len(prices) - 1, entry_price, direction)
# Stop with regime-adaptive multiplier
atr = risk.compute_atr(prices, len(prices) - 1)
stop_dist = max(atr * stop_mult, entry_price * 0.005)
stop_price = entry_price - direction * stop_dist
# Kelly position sizing (uses historical WR and avg PnL)
trades = get_trade_history(conn, ticker=ticker, limit=50)
if len(trades) >= 10:
wins = [t for t in trades if (t["pnl_net"] or 0) > 0]
losses = [t for t in trades if (t["pnl_net"] or 0) <= 0]
wr = len(wins) / len(trades)
avg_win = np.mean([abs(t["pnl_pct"] or 0) for t in wins]) if wins else 1.0
avg_loss = np.mean([abs(t["pnl_pct"] or 0) for t in losses]) if losses else 1.0
kelly_f = risk.kelly_fraction(wr, avg_win, avg_loss)
# Use Kelly instead of fixed risk
risk_cfg_adjusted = type(cfg.risk)(
per_trade=kelly_f,
max_position_pct=cfg.risk.max_position_pct,
max_open_positions=cfg.risk.max_open_positions,
)
else:
risk_cfg_adjusted = cfg.risk
# Position sizing
pos_size, pos_value = risk.calculate_position(
asset["equity"], entry_price, stop_dist, cfg.risk,
asset["equity"], entry_price, stop_dist, risk_cfg_adjusted,
)
# Open position
+56
View File
@@ -102,6 +102,62 @@ def check_circuit_breaker(prices: np.ndarray, equity: float, peak_equity: float,
return False, None, {}
def adaptive_corr_threshold(base_thresh: float, recent_wins: int,
recent_total: int, window: int = 20) -> float:
"""Adjust correlation threshold based on rolling win rate.
If WR > 55% → lower threshold by 0.1 (take more trades)
If WR < 40% → raise threshold by 0.1 (be more selective)
"""
if recent_total < 5:
return base_thresh
wr = recent_wins / recent_total
if wr > 0.55:
return max(base_thresh - 0.1, 0.3)
if wr < 0.40:
return min(base_thresh + 0.1, 0.8)
return base_thresh
def regime_adaptive_params(prices: np.ndarray, idx: int, K_base: int,
stop_mult_base: float = 2.0) -> tuple[int, float]:
"""Adapt K and stop multiplier based on volatility regime.
ATR14/ATR50 ratio:
< 0.7 (low vol) → K-1, tighter stops (1.5x)
> 1.5 (high vol) → K+1, wider stops (2.5x)
else (normal) → no change
"""
atr14 = compute_atr(prices, idx, period=14)
atr50 = compute_atr(prices, idx, period=50)
ratio = atr14 / atr50 if atr50 > 0 else 1.0
if ratio < 0.7:
return max(K_base - 1, 2), 1.5
if ratio > 1.5:
return K_base + 1, 2.5
return K_base, stop_mult_base
def kelly_fraction(win_rate: float, avg_win: float, avg_loss: float,
max_fraction: float = 0.15) -> float:
"""Kelly criterion for optimal position sizing.
f* = (p * b - q) / b
where p=win_rate, q=1-p, b=avg_win/avg_loss
Capped at max_fraction to avoid over-betting.
"""
if avg_loss <= 0 or win_rate <= 0:
return 0.02 # fallback to 2%
b = avg_win / avg_loss
q = 1.0 - win_rate
kelly = (win_rate * b - q) / b
# Half-Kelly for safety
kelly = kelly * 0.5
return max(0.01, min(kelly, max_fraction))
def calculate_pnl(entry_price: float, exit_price: float, direction: int,
pos_size: float, pos_value: float,
commission: float = 0.001) -> tuple[float, float]:
+7
View File
@@ -186,6 +186,13 @@ def log_signal(conn: sqlite3.Connection, **kwargs) -> None:
conn.commit()
def get_signal_log(conn: sqlite3.Connection, limit: int = 100) -> list[dict]:
rows = conn.execute(
"SELECT * FROM signals ORDER BY id DESC LIMIT ?", (limit,),
).fetchall()
return [dict(r) for r in rows]
# -- Equity snapshots --
def add_equity_snapshot(conn: sqlite3.Connection, ticker: str, equity: float,
+103 -1
View File
@@ -10,9 +10,12 @@ from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from ..config import Config
from fastapi.responses import StreamingResponse
from ..state import (
get_db, init_db, get_all_assets, get_open_position,
get_trade_history, get_equity_history,
get_trade_history, get_equity_history, get_signal_log,
close_position, get_asset, update_asset,
)
TEMPLATES_DIR = Path(__file__).parent / "templates"
@@ -93,6 +96,19 @@ def create_app(cfg: Config) -> FastAPI:
"trades": trades,
})
@app.get("/signals", response_class=HTMLResponse)
async def signals_page(request: Request):
conn = get_db()
init_db(conn)
signals = get_signal_log(conn, limit=200)
conn.close()
return templates.TemplateResponse("signals.html", {
"request": request,
"cfg": cfg,
"signals": signals,
})
@app.get("/settings", response_class=HTMLResponse)
async def settings_page(request: Request):
return templates.TemplateResponse("settings.html", {
@@ -146,4 +162,90 @@ def create_app(cfg: Config) -> FastAPI:
"logs": logs,
})
@app.post("/api/close-position/{pos_id}", response_class=HTMLResponse)
async def close_position_api(pos_id: int, request: Request):
from ..core import risk
conn = get_db()
init_db(conn)
row = conn.execute(
"SELECT * FROM positions WHERE id=? AND status='open'", (pos_id,),
).fetchone()
if not row:
conn.close()
return HTMLResponse("<p>Position not found or already closed.</p>")
pos = dict(row)
from ..core.signals import fetch_prices
prices, dates = fetch_prices(pos["ticker"], cfg.timeframe,
"max" if cfg.timeframe == "1d" else "730d")
last_price = float(prices[-1]) if prices is not None else pos["entry_price"]
last_date = str(dates[-1]) if dates is not None else ""
pnl_net, pnl_pct = risk.calculate_pnl(
pos["entry_price"], last_price, pos["direction"],
pos["pos_size"], pos["pos_value"],
)
close_position(conn, pos_id,
exit_price=last_price, exit_date=last_date,
exit_reason="manual", pnl_net=pnl_net, pnl_pct=pnl_pct)
asset = get_asset(conn, pos["ticker"])
if asset:
new_equity = asset["equity"] + pnl_net
new_peak = max(asset["peak_equity"], new_equity)
win = pnl_net > 0
update_asset(conn, pos["ticker"],
equity=new_equity, peak_equity=new_peak,
trades_count=asset["trades_count"] + 1,
wins=asset["wins"] + (1 if win else 0),
losses=asset["losses"] + (0 if win else 1),
total_pnl=asset["total_pnl"] + pnl_net)
conn.close()
dir_str = "LONG" if pos["direction"] == 1 else "SHORT"
result = "WIN" if pnl_net > 0 else "LOSS"
return HTMLResponse(
f"<p>Closed {dir_str} {pos['ticker']} @ ${last_price:,.2f} "
f"PnL ${pnl_net:+,.2f} [{result}]</p>"
)
@app.get("/api/export-csv")
async def export_csv():
import csv
import io
conn = get_db()
init_db(conn)
trades = get_trade_history(conn, limit=10000)
conn.close()
output = io.StringIO()
writer = csv.writer(output)
writer.writerow([
"ticker", "direction", "entry_date", "entry_price",
"exit_date", "exit_price", "exit_reason",
"pnl_net", "pnl_pct", "pos_size", "pos_value",
"correlation", "k_used",
])
for t in trades:
writer.writerow([
t["ticker"],
"LONG" if t["direction"] == 1 else "SHORT",
t["entry_date"], t["entry_price"],
t.get("exit_date", ""), t.get("exit_price", ""),
t.get("exit_reason", ""),
t.get("pnl_net", ""), t.get("pnl_pct", ""),
t["pos_size"], t["pos_value"],
t.get("correlation", ""), t.get("k_used", ""),
])
output.seek(0)
return StreamingResponse(
iter([output.getvalue()]),
media_type="text/csv",
headers={"Content-Disposition": "attachment; filename=trades.csv"},
)
return app
@@ -51,6 +51,12 @@
table { font-size: 0.9em; }
.chart-container { position: relative; height: 300px; margin-bottom: 1.5rem; }
.actions { margin: 1rem 0; }
@media (max-width: 768px) {
.grid-stats { grid-template-columns: repeat(2, 1fr); }
table { font-size: 0.8em; }
.stat-value { font-size: 1.4em; }
nav ul { gap: 0.3rem; }
}
</style>
</head>
<body>
@@ -62,6 +68,7 @@
<li><a href="/">Dashboard</a></li>
<li><a href="/positions">Positions</a></li>
<li><a href="/history">History</a></li>
<li><a href="/signals">Signals</a></li>
<li><a href="/settings">Settings</a></li>
</ul>
<ul>
@@ -72,6 +79,11 @@
<span class="badge badge-live">LIVE</span>
{% endif %}
</li>
<li>
<a href="#" id="theme-toggle" title="Toggle theme" style="cursor:pointer;">
<span id="theme-icon">&#9790;</span>
</a>
</li>
</ul>
</nav>
@@ -83,6 +95,29 @@
<small>RemizovTrader v0.1.0 — PDE/SDE Neural ODE</small>
</footer>
<script>
(function() {
const html = document.documentElement;
const saved = localStorage.getItem('theme');
if (saved) html.setAttribute('data-theme', saved);
const toggle = document.getElementById('theme-toggle');
const icon = document.getElementById('theme-icon');
function updateIcon() {
icon.textContent = html.getAttribute('data-theme') === 'dark' ? '\u263E' : '\u2600';
}
updateIcon();
toggle.addEventListener('click', function(e) {
e.preventDefault();
const next = html.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
html.setAttribute('data-theme', next);
localStorage.setItem('theme', next);
updateIcon();
});
})();
</script>
{% block scripts %}{% endblock %}
</body>
</html>
@@ -5,6 +5,9 @@
<h2>Trade History</h2>
{% if trades %}
<div class="actions">
<a href="/api/export-csv" role="button" class="outline">Export CSV</a>
</div>
<table>
<thead>
<tr>
@@ -8,6 +8,7 @@
<th>Correlation</th>
<th>Day</th>
<th>Equity</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@@ -24,6 +25,15 @@
<td>{{ "%.3f"|format(p.correlation or 0) }}</td>
<td>{{ p.entry_date }}</td>
<td>${{ "%.2f"|format(p.equity) }}</td>
<td>
<button class="outline secondary"
hx-post="/api/close-position/{{ p.id }}"
hx-target="closest tr"
hx-swap="outerHTML"
hx-confirm="Close this position at market price?">
Close
</button>
</td>
</tr>
{% endfor %}
</tbody>
@@ -0,0 +1,53 @@
{% extends "base.html" %}
{% block title_suffix %} — Signals{% endblock %}
{% block content %}
<h2>Signal Log</h2>
{% if signals %}
<table>
<thead>
<tr>
<th>Date</th>
<th>Asset</th>
<th>Action</th>
<th>Direction</th>
<th>Correlation</th>
<th>Details</th>
</tr>
</thead>
<tbody>
{% for s in signals %}
<tr>
<td>{{ s.date }}</td>
<td>{{ s.ticker }}</td>
<td>
{% if s.action == 'open' %}
<span class="badge badge-long">OPEN</span>
{% elif 'skip' in s.action %}
<span class="badge badge-cb">SKIP</span>
{% else %}
{{ s.action }}
{% endif %}
</td>
<td>
{% if s.direction %}
<span class="badge {{ 'badge-long' if s.direction == 1 else 'badge-short' }}">
{{ 'L' if s.direction == 1 else 'S' }}
</span>
{% else %}
—
{% endif %}
</td>
<td>{{ "%.3f"|format(s.correlation) if s.correlation else '—' }}</td>
<td>{{ s.details or '' }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<article>
<p>No signals recorded yet.</p>
</article>
{% endif %}
{% endblock %}