392 lines
19 KiB
Python
392 lines
19 KiB
Python
"""Plain EMA crossover portfolio backtest using next-open execution."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
import math
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
|
|
from .backtest import BacktestResult, _cost, _fill_price
|
|
from .config import StrategyConfig, ThaiMarketRules, TradingCosts
|
|
from .portfolio import round_quantity
|
|
|
|
|
|
@dataclass
|
|
class _Position:
|
|
symbol: str
|
|
entry_date: pd.Timestamp
|
|
entry_price: float
|
|
quantity: int
|
|
entry_cost: float
|
|
min_low: float
|
|
max_high: float
|
|
dividend_cash: float = 0.0
|
|
holding_sessions: int = 0
|
|
|
|
|
|
def _number(value: object, default: float = 0.0) -> float:
|
|
if value is None or pd.isna(value):
|
|
return default
|
|
return float(value)
|
|
|
|
|
|
def _metrics(curve: pd.DataFrame, trades: pd.DataFrame) -> dict[str, float]:
|
|
if curve.empty:
|
|
return {key: 0.0 for key in (
|
|
"total_return", "cagr", "max_drawdown", "win_rate", "average_win",
|
|
"average_loss", "expectancy_per_trade", "profit_factor",
|
|
"average_trade_return", "average_holding_period", "exposure_pct",
|
|
"trades_per_month", "gross_dividend_cash",
|
|
)}
|
|
equity = curve["equity"].astype(float)
|
|
start_equity = float(equity.iloc[0])
|
|
total_return = float(equity.iloc[-1] / start_equity - 1) if start_equity else 0.0
|
|
years = max((equity.index[-1] - equity.index[0]).days / 365.25, 1 / 252)
|
|
drawdown = equity / equity.cummax() - 1
|
|
pnl = trades["total_pnl"].astype(float) if not trades.empty else pd.Series(dtype=float)
|
|
winners, losers = pnl[pnl > 0], pnl[pnl < 0]
|
|
gross_loss = float(abs(losers.sum()))
|
|
return {
|
|
"total_return": total_return,
|
|
"cagr": float((max(float(equity.iloc[-1]), 1.0) / max(start_equity, 1.0)) ** (1 / years) - 1),
|
|
"max_drawdown": float(drawdown.min()),
|
|
"win_rate": float((pnl > 0).mean()) if len(pnl) else 0.0,
|
|
"average_win": float(winners.mean()) if len(winners) else 0.0,
|
|
"average_loss": float(losers.mean()) if len(losers) else 0.0,
|
|
"expectancy_per_trade": float(pnl.mean()) if len(pnl) else 0.0,
|
|
"profit_factor": float(winners.sum() / gross_loss) if gross_loss else (math.inf if len(winners) else 0.0),
|
|
"average_trade_return": float(trades["return_pct"].mean()) if not trades.empty else 0.0,
|
|
"average_holding_period": float(trades["holding_sessions"].mean()) if not trades.empty else 0.0,
|
|
"exposure_pct": float(curve["exposure"].mean()) if "exposure" in curve else 0.0,
|
|
"trades_per_month": float(len(trades) / max(years * 12, 1 / 12)),
|
|
"gross_dividend_cash": float(trades["dividend_cash"].sum()) if not trades.empty else 0.0,
|
|
}
|
|
|
|
|
|
def run_ema_crossover_backtest(
|
|
features_by_symbol: dict[str, pd.DataFrame],
|
|
market: pd.DataFrame,
|
|
*,
|
|
fast: int = 20,
|
|
slow: int = 50,
|
|
strategy: StrategyConfig | None = None,
|
|
rules: ThaiMarketRules | None = None,
|
|
costs: TradingCosts | None = None,
|
|
start: str | None = None,
|
|
end: str | None = None,
|
|
lot_sizes: dict[str, int] | None = None,
|
|
max_position_pct: float = 0.20,
|
|
min_price: float = 2.0,
|
|
min_value_turnover_thb: float = 20_000_000.0,
|
|
market_filter: str = "none",
|
|
exit_mode: str = "cross_under",
|
|
max_loss_pct: float | None = None,
|
|
yahoo_split_adjusted: bool = True,
|
|
) -> BacktestResult:
|
|
"""Buy a fast-over-slow EMA cross and exit on the reverse cross.
|
|
|
|
Signals are computed from closing prices and filled at the next available open.
|
|
Optional market filters, EMA21-low exits and hard loss stops can be used for
|
|
controlled overlay comparisons.
|
|
The portfolio caps each name at a fixed fraction of equity, spreads available
|
|
cash equally across simultaneous entry signals, and uses cash-only fills.
|
|
"""
|
|
if fast < 1 or slow < 2 or fast >= slow:
|
|
raise ValueError("EMA spans must be positive integers with fast < slow")
|
|
if not 0 < max_position_pct <= 1:
|
|
raise ValueError("max_position_pct must be greater than 0 and at most 1")
|
|
if min_price < 0 or min_value_turnover_thb < 0:
|
|
raise ValueError("price and turnover filters must be non-negative")
|
|
if market_filter not in {"none", "ew_trend_up", "ew_above_ema200"}:
|
|
raise ValueError("market_filter must be none, ew_trend_up or ew_above_ema200")
|
|
if exit_mode not in {"cross_under", "ema21_low"}:
|
|
raise ValueError("exit_mode must be cross_under or ema21_low")
|
|
if max_loss_pct is not None and not 0 < max_loss_pct < 1:
|
|
raise ValueError("max_loss_pct must be greater than 0 and less than 1")
|
|
if not features_by_symbol:
|
|
raise ValueError("features_by_symbol is empty")
|
|
|
|
strategy = strategy or StrategyConfig()
|
|
rules = rules or ThaiMarketRules()
|
|
costs = costs or TradingCosts()
|
|
members_by_date = market.attrs.get("members_by_date")
|
|
ew_close = pd.to_numeric(market.get("set100ew_close", pd.Series(dtype=float)), errors="coerce")
|
|
ew_ema200 = ew_close.ewm(span=200, adjust=False, min_periods=200).mean()
|
|
external_dividends = {
|
|
str(symbol).upper(): {
|
|
pd.Timestamp(date).normalize(): float(amount) for date, amount in events.items()
|
|
}
|
|
for symbol, events in market.attrs.get("external_dividends", {}).items()
|
|
}
|
|
|
|
indicators: dict[str, pd.DataFrame] = {}
|
|
all_dates: set[pd.Timestamp] = set(market.index)
|
|
for symbol, source in features_by_symbol.items():
|
|
frame = source.sort_index().copy()
|
|
if "close" not in frame:
|
|
raise ValueError(f"{symbol} has no close column")
|
|
close = pd.to_numeric(frame["close"], errors="coerce")
|
|
frame["_ema_fast"] = close.ewm(span=fast, adjust=False, min_periods=fast).mean()
|
|
frame["_ema_slow"] = close.ewm(span=slow, adjust=False, min_periods=slow).mean()
|
|
indicators[symbol] = frame
|
|
all_dates.update(pd.Timestamp(date).normalize() for date in frame.index)
|
|
all_dates.update(date for events in external_dividends.values() for date in events)
|
|
dates = sorted(all_dates)
|
|
if start:
|
|
dates = [date for date in dates if date >= pd.Timestamp(start).normalize()]
|
|
if end:
|
|
dates = [date for date in dates if date < pd.Timestamp(end).normalize()]
|
|
if len(dates) < 2:
|
|
raise ValueError("backtest requires at least two daily bars")
|
|
|
|
cash = float(strategy.initial_equity)
|
|
positions: dict[str, _Position] = {}
|
|
pending_entries: dict[str, pd.Timestamp] = {}
|
|
pending_exits: dict[str, pd.Timestamp] = {}
|
|
previous_close: dict[str, float] = {}
|
|
trades: list[dict[str, object]] = []
|
|
fills: list[dict[str, object]] = []
|
|
skipped: list[dict[str, str]] = []
|
|
equity_rows: list[dict[str, object]] = []
|
|
|
|
def execute_sell(position: _Position, reference_price: float, date: pd.Timestamp,
|
|
reason: str) -> None:
|
|
nonlocal cash
|
|
fill = _fill_price(reference_price, "sell", costs, rules)
|
|
position.min_low = min(position.min_low, fill)
|
|
position.max_high = max(position.max_high, fill)
|
|
notional = fill * position.quantity
|
|
sale_cost = _cost(notional, costs, sell=True)
|
|
cash += notional - sale_cost
|
|
total_pnl = notional - sale_cost - position.entry_cost + position.dividend_cash
|
|
trades.append({
|
|
"symbol": position.symbol,
|
|
"entry_date": position.entry_date.date().isoformat(),
|
|
"exit_date": date.date().isoformat(),
|
|
"entry_price": position.entry_price,
|
|
"exit_price": fill,
|
|
"shares": position.quantity,
|
|
"entry_cost": position.entry_cost,
|
|
"dividend_cash": position.dividend_cash,
|
|
"total_pnl": total_pnl,
|
|
"return_pct": total_pnl / position.entry_cost if position.entry_cost else 0.0,
|
|
"mae_pct": (position.min_low / position.entry_price - 1) if position.entry_price else 0.0,
|
|
"mfe_pct": (position.max_high / position.entry_price - 1) if position.entry_price else 0.0,
|
|
"holding_sessions": position.holding_sessions,
|
|
"exit_reason": reason,
|
|
})
|
|
fills.append({"date": date, "symbol": position.symbol, "side": "SELL",
|
|
"reason": reason, "shares": position.quantity, "price": fill,
|
|
"cost": sale_cost})
|
|
positions.pop(position.symbol, None)
|
|
|
|
for date in dates:
|
|
# Apply corporate actions to positions carried from the prior close.
|
|
for symbol, position in list(positions.items()):
|
|
frame = indicators[symbol]
|
|
bar = frame.loc[date] if date in frame.index else None
|
|
if bar is not None and not yahoo_split_adjusted:
|
|
split = _number(bar.get("stock_splits", 0.0))
|
|
if split > 0 and split != 1:
|
|
position.quantity = int(round(position.quantity * split))
|
|
position.entry_price /= split
|
|
position.min_low /= split
|
|
position.max_high /= split
|
|
if symbol in previous_close:
|
|
previous_close[symbol] /= split
|
|
dividend = external_dividends.get(symbol, {}).get(date)
|
|
if dividend is None and bar is not None:
|
|
dividend = _number(bar.get("dividends", 0.0))
|
|
if dividend and date > position.entry_date:
|
|
amount = position.quantity * float(dividend)
|
|
position.dividend_cash += amount
|
|
cash += amount
|
|
if bar is None and symbol in previous_close:
|
|
previous_close[symbol] = max(0.0, previous_close[symbol] - float(dividend))
|
|
|
|
# Cross-under exits execute before new entries at the next open.
|
|
for symbol in list(pending_exits):
|
|
if symbol not in positions:
|
|
pending_exits.pop(symbol, None)
|
|
continue
|
|
frame = indicators[symbol]
|
|
if date not in frame.index or pd.isna(frame.loc[date].get("open", np.nan)):
|
|
continue
|
|
execute_sell(positions[symbol], float(frame.loc[date, "open"]), date, "ema_cross_down_next_open")
|
|
pending_exits.pop(symbol, None)
|
|
|
|
# Spread cash equally across today's eligible cross-up signals. This avoids
|
|
# selecting simultaneous signals by arbitrary ticker ordering.
|
|
entry_orders: list[tuple[str, pd.Timestamp, float]] = []
|
|
for symbol, signal_date in sorted(pending_entries.items()):
|
|
frame = indicators[symbol]
|
|
if date not in frame.index or pd.isna(frame.loc[date].get("open", np.nan)):
|
|
skipped.append({"symbol": symbol, "date": signal_date.date().isoformat(),
|
|
"reason": "missing next open"})
|
|
continue
|
|
if symbol in positions:
|
|
continue
|
|
bar = frame.loc[date]
|
|
open_price = float(bar["open"])
|
|
# Prefer the signal bar's liquidity observation to avoid using later data.
|
|
signal_bar = frame.loc[signal_date] if signal_date in frame.index else bar
|
|
signal_turnover = _number(signal_bar.get("avg_value_turnover20", 0.0))
|
|
signal_close = _number(signal_bar.get("close", open_price))
|
|
if signal_close < min_price or signal_turnover < min_value_turnover_thb:
|
|
skipped.append({"symbol": symbol, "date": signal_date.date().isoformat(),
|
|
"reason": "price or 20-day turnover filter"})
|
|
continue
|
|
fill = _fill_price(open_price, "buy", costs, rules)
|
|
entry_orders.append((symbol, signal_date, fill))
|
|
|
|
if entry_orders:
|
|
open_market_value = 0.0
|
|
for held_symbol, held in positions.items():
|
|
held_frame = indicators[held_symbol]
|
|
if date in held_frame.index and pd.notna(held_frame.loc[date].get("open", np.nan)):
|
|
mark = float(held_frame.loc[date, "open"])
|
|
else:
|
|
mark = previous_close.get(held_symbol, held.entry_price)
|
|
open_market_value += mark * held.quantity
|
|
open_equity = cash + open_market_value
|
|
allocatable_orders = entry_orders.copy()
|
|
allocation_plan: list[tuple[str, pd.Timestamp, float, int]] = []
|
|
while allocatable_orders:
|
|
per_entry_budget = min(open_equity * max_position_pct, cash / len(allocatable_orders))
|
|
allocation_plan = []
|
|
unable_to_buy: list[tuple[str, pd.Timestamp, float]] = []
|
|
for symbol, signal_date, fill in allocatable_orders:
|
|
lot_size = (lot_sizes or {}).get(symbol, rules.default_board_lot)
|
|
target_qty = round_quantity(per_entry_budget / fill, lot_size)
|
|
if target_qty <= 0:
|
|
unable_to_buy.append((symbol, signal_date, fill))
|
|
else:
|
|
allocation_plan.append((symbol, signal_date, fill, target_qty))
|
|
if not unable_to_buy:
|
|
break
|
|
for symbol, signal_date, _ in unable_to_buy:
|
|
skipped.append({"symbol": symbol, "date": signal_date.date().isoformat(),
|
|
"reason": "equal allocation below minimum board lot"})
|
|
allocatable_orders = [
|
|
(symbol, signal_date, fill)
|
|
for symbol, signal_date, fill, _ in allocation_plan
|
|
]
|
|
|
|
for symbol, signal_date, fill, target_qty in allocation_plan:
|
|
lot_size = (lot_sizes or {}).get(symbol, rules.default_board_lot)
|
|
affordable_qty = round_quantity(
|
|
cash / (fill * (1 + costs.commission_rate + costs.fees_rate)), lot_size
|
|
)
|
|
quantity = min(target_qty, affordable_qty)
|
|
if quantity <= 0:
|
|
skipped.append({"symbol": symbol, "date": signal_date.date().isoformat(),
|
|
"reason": "cash or board lot below minimum"})
|
|
continue
|
|
buy_notional = fill * quantity
|
|
buy_cost = _cost(buy_notional, costs, sell=False)
|
|
position = _Position(symbol=symbol, entry_date=date, entry_price=fill,
|
|
quantity=quantity, entry_cost=buy_notional + buy_cost,
|
|
min_low=fill, max_high=fill)
|
|
positions[symbol] = position
|
|
cash -= buy_notional + buy_cost
|
|
fills.append({"date": date, "symbol": symbol, "side": "BUY",
|
|
"reason": f"ema_{fast}_over_{slow}", "shares": quantity,
|
|
"price": fill, "cost": buy_cost})
|
|
pending_entries.clear()
|
|
|
|
# Observe the whole session after next-open fills and check closing signals.
|
|
for symbol, position in list(positions.items()):
|
|
frame = indicators[symbol]
|
|
if date not in frame.index:
|
|
continue
|
|
bar = frame.loc[date]
|
|
if pd.notna(bar.get("low", np.nan)):
|
|
position.min_low = min(position.min_low, float(bar["low"]))
|
|
if pd.notna(bar.get("high", np.nan)):
|
|
position.max_high = max(position.max_high, float(bar["high"]))
|
|
position.holding_sessions += 1
|
|
if max_loss_pct is not None:
|
|
stop_price = position.entry_price * (1 - max_loss_pct)
|
|
low = float(bar["low"])
|
|
if low <= stop_price:
|
|
opening = float(bar["open"])
|
|
fill_reference = min(opening, stop_price) if opening < stop_price else stop_price
|
|
execute_sell(position, fill_reference, date, f"hard_stop_{max_loss_pct:.0%}")
|
|
continue
|
|
previous_close[symbol] = float(bar["close"])
|
|
|
|
for symbol, frame in indicators.items():
|
|
if symbol in positions or symbol in pending_entries or date not in frame.index:
|
|
continue
|
|
if members_by_date is not None and symbol not in members_by_date.get(date, []):
|
|
continue
|
|
index = frame.index.get_loc(date)
|
|
if isinstance(index, slice) or index < 1:
|
|
continue
|
|
current = frame.iloc[index]
|
|
prior = frame.iloc[index - 1]
|
|
values = [current.get("_ema_fast"), current.get("_ema_slow"),
|
|
prior.get("_ema_fast"), prior.get("_ema_slow")]
|
|
if any(pd.isna(value) for value in values):
|
|
continue
|
|
crossed_up = float(prior["_ema_fast"]) <= float(prior["_ema_slow"]) and float(current["_ema_fast"]) > float(current["_ema_slow"])
|
|
if crossed_up:
|
|
if market_filter == "ew_trend_up":
|
|
state = market.loc[date].get("ew_trend_state", "DOWN") if date in market.index else "DOWN"
|
|
if str(state).upper() != "UP":
|
|
continue
|
|
elif market_filter == "ew_above_ema200":
|
|
if date not in ew_close.index or pd.isna(ew_ema200.get(date)) or ew_close.get(date, np.nan) <= ew_ema200.get(date):
|
|
continue
|
|
pending_entries[symbol] = date
|
|
|
|
for symbol, frame in indicators.items():
|
|
if symbol not in positions or date not in frame.index:
|
|
continue
|
|
index = frame.index.get_loc(date)
|
|
if isinstance(index, slice) or index < 1:
|
|
continue
|
|
current = frame.iloc[index]
|
|
prior = frame.iloc[index - 1]
|
|
values = [current.get("_ema_fast"), current.get("_ema_slow"),
|
|
prior.get("_ema_fast"), prior.get("_ema_slow")]
|
|
if any(pd.isna(value) for value in values):
|
|
continue
|
|
if exit_mode == "ema21_low":
|
|
ema21_low = _number(current.get("ema21_low"), np.nan)
|
|
should_exit = pd.notna(ema21_low) and float(current["close"]) < ema21_low
|
|
else:
|
|
should_exit = float(prior["_ema_fast"]) >= float(prior["_ema_slow"]) and float(current["_ema_fast"]) < float(current["_ema_slow"])
|
|
if should_exit:
|
|
pending_exits[symbol] = date
|
|
|
|
market_value = 0.0
|
|
for symbol, position in positions.items():
|
|
frame = indicators[symbol]
|
|
close = float(frame.loc[date, "close"]) if date in frame.index else previous_close.get(symbol, position.entry_price)
|
|
market_value += close * position.quantity
|
|
equity = cash + market_value
|
|
equity_rows.append({"date": date, "equity": equity, "cash": cash,
|
|
"market_value": market_value,
|
|
"exposure": market_value / equity if equity else 0.0,
|
|
"open_positions": len(positions)})
|
|
|
|
final_date = dates[-1]
|
|
for symbol, position in list(positions.items()):
|
|
frame = indicators[symbol]
|
|
available = frame.loc[frame.index <= final_date]
|
|
if available.empty:
|
|
continue
|
|
bar = available.iloc[-1]
|
|
execute_sell(position, float(bar["close"]), pd.Timestamp(available.index[-1]), "end_of_test")
|
|
if equity_rows:
|
|
equity_rows[-1].update({"equity": cash, "cash": cash, "market_value": 0.0,
|
|
"exposure": 0.0, "open_positions": 0})
|
|
|
|
trade_frame = pd.DataFrame(trades)
|
|
curve = pd.DataFrame(equity_rows).set_index("date")
|
|
fill_frame = pd.DataFrame(fills)
|
|
return BacktestResult(_metrics(curve, trade_frame), trade_frame, curve, fill_frame, skipped)
|