fix: resolve 8 critical issues from code review

C1: Fix BacktestDataLoader constructor args (was passing wrong kwargs)
C2: Fix BacktestResult attribute names (max_drawdown_pct, avg_hold_duration)
C3: Remove insecure JWT secret default (now required via env var)
C4: Fix .env.example to use TRADING_ prefix for all config vars
C5: Add missing fields to portfolio endpoint (daily_pnl_pct, total_pnl, trading_active)
C6: Add missing /portfolio/metrics endpoint
C7: Add 'value' field to equity curve response for frontend compatibility
C8: Add 6M/ALL periods and case-insensitive period enum parsing
Also: make app creation lazy to avoid config validation at import time
This commit is contained in:
Viktor Barzin 2026-02-22 17:48:40 +00:00
parent 870961f3e9
commit 2a56727267
No known key found for this signature in database
GPG key ID: 0EB088298288D958
5 changed files with 103 additions and 27 deletions

View file

@ -18,7 +18,19 @@ class HistoryPeriod(str, Enum):
ONE_WEEK = "1w"
ONE_MONTH = "1m"
THREE_MONTHS = "3m"
SIX_MONTHS = "6m"
ONE_YEAR = "1y"
ALL = "all"
@classmethod
def _missing_(cls, value: object) -> HistoryPeriod | None:
"""Accept uppercase variants like '1D', '1M', 'ALL'."""
if isinstance(value, str):
lower = value.lower()
for member in cls:
if member.value == lower:
return member
return None
def _period_to_timedelta(period: HistoryPeriod) -> timedelta:
@ -28,7 +40,9 @@ def _period_to_timedelta(period: HistoryPeriod) -> timedelta:
HistoryPeriod.ONE_WEEK: timedelta(weeks=1),
HistoryPeriod.ONE_MONTH: timedelta(days=30),
HistoryPeriod.THREE_MONTHS: timedelta(days=90),
HistoryPeriod.SIX_MONTHS: timedelta(days=180),
HistoryPeriod.ONE_YEAR: timedelta(days=365),
HistoryPeriod.ALL: timedelta(days=365 * 10), # effectively "all time"
}
return mapping[period]
@ -57,13 +71,25 @@ async def get_portfolio(
"cash": 0.0,
"buying_power": 0.0,
"daily_pnl": 0.0,
"daily_pnl_pct": 0.0,
"total_pnl": 0.0,
"total_pnl_pct": 0.0,
"trading_active": True,
}
# Compute percentage fields from snapshot data
daily_pnl_pct = (latest.daily_pnl / (latest.total_value - latest.daily_pnl) * 100.0
if latest.total_value != latest.daily_pnl else 0.0)
return {
"total_value": latest.total_value,
"cash": latest.cash,
"buying_power": latest.cash,
"daily_pnl": latest.daily_pnl,
"daily_pnl_pct": round(daily_pnl_pct, 2),
"total_pnl": latest.daily_pnl, # TODO: compute cumulative P&L from first snapshot
"total_pnl_pct": round(daily_pnl_pct, 2),
"trading_active": True, # TODO: read from Redis trading pause flag
}
@ -94,6 +120,53 @@ async def get_positions(
]
@router.get("/metrics")
async def get_portfolio_metrics(
request: Request,
_user: dict = Depends(get_current_user),
) -> dict:
"""Aggregate portfolio performance metrics — ROI, Sharpe, win rate, drawdown."""
from shared.models.trading import Trade, TradeStatus
from shared.models.timeseries import StrategyMetric
db = request.app.state.db_session_factory
async with db() as session:
# Total trades and win rate from trades table
trades_result = await session.execute(
select(Trade).where(Trade.status == TradeStatus.FILLED)
)
trades = trades_result.scalars().all()
# Latest strategy metrics for Sharpe
metrics_result = await session.execute(
select(StrategyMetric)
.order_by(desc(StrategyMetric.timestamp))
.limit(10)
)
strategy_metrics = metrics_result.scalars().all()
total_trades = len(trades)
winning = sum(1 for t in trades if t.pnl is not None and t.pnl > 0)
win_rate = winning / total_trades if total_trades > 0 else 0.0
total_pnl = sum(t.pnl for t in trades if t.pnl is not None)
# Approximate ROI from P&L (rough — proper calculation needs initial capital)
roi = total_pnl / 100_000.0 * 100.0 # assumes 100k starting capital
# Average Sharpe from strategy metrics
sharpe_values = [m.sharpe_ratio for m in strategy_metrics if m.sharpe_ratio is not None]
avg_sharpe = sum(sharpe_values) / len(sharpe_values) if sharpe_values else 0.0
return {
"roi": round(roi, 4),
"sharpe": round(avg_sharpe, 2),
"win_rate": round(win_rate, 4),
"max_drawdown": 0.0, # TODO: compute from portfolio snapshots
"total_trades": total_trades,
"avg_hold_duration": "0h", # TODO: compute from trade outcomes
}
@router.get("/history")
async def get_portfolio_history(
request: Request,
@ -116,6 +189,7 @@ async def get_portfolio_history(
return [
{
"timestamp": s.timestamp.isoformat(),
"value": s.total_value,
"total_value": s.total_value,
"cash": s.cash,
"positions_value": s.positions_value,