Spaces:
Sleeping
Sleeping
Download engine/vbt_engine.py from Darshanpurohit/StratoTest: direct link, hf CLI and curl.
- Browser
- Download file 7.49 kB
-
https://huggingface.co/spaces/Darshanpurohit/StratoTest/resolve/main/engine/vbt_engine.py
- Command line
-
hf download hf://spaces/Darshanpurohit/StratoTest/engine/vbt_engine.py
-
curl -L -o vbt_engine.py https://huggingface.co/spaces/Darshanpurohit/StratoTest/resolve/main/engine/vbt_engine.py
7.49 kB
| # engine/vbt_engine.py | |
| # vectorbt-powered analytics layer | |
| # Runs AFTER the existing engine β purely additive, never breaks existing flow. | |
| # | |
| # How it works: | |
| # 1. Takes the entry signals already generated by the existing strategy | |
| # 2. Builds a vbt Portfolio from those signals + price data | |
| # 3. Extracts richer metrics the manual tearsheet doesn't compute | |
| # 4. Returns a dict β {} on any failure (graceful degradation) | |
| import pandas as pd | |
| import numpy as np | |
| def run_vbt_analysis( | |
| df: pd.DataFrame, | |
| signals: pd.Series, | |
| initial_capital: float = 100_000 | |
| ) -> dict: | |
| """ | |
| Run vectorbt portfolio analytics on the existing strategy signals. | |
| Parameters | |
| ---------- | |
| df : OHLCV DataFrame (same one used by the strategy) | |
| signals : Boolean Series where True = entry signal (from generate_signals) | |
| initial_capital : Starting capital (same as strategy) | |
| Returns | |
| ------- | |
| dict with enhanced analytics, or {} if vectorbt is unavailable / fails | |
| """ | |
| try: | |
| import vectorbt as vbt | |
| close = df["Close"] | |
| # Align signals index to close β drop any NaN signals | |
| entries = signals.reindex(close.index).fillna(False).astype(bool) | |
| # ββ Build Portfolio ββββββββββββββββββββββββββββββββββββββββ | |
| # sl_stop / tp_stop: use 2% SL and 4% TP as reasonable defaults | |
| # (the existing engine handles exact SL/TP β vbt is for analytics enrichment) | |
| pf = vbt.Portfolio.from_signals( | |
| close=close, | |
| entries=entries, | |
| sl_stop=0.02, # 2% stop-loss | |
| tp_stop=0.04, # 4% take-profit (β 1:2 RR) | |
| init_cash=initial_capital, | |
| freq="D", | |
| fees=0.001, # 0.1% commission per trade | |
| slippage=0.001, # 0.1% slippage | |
| ) | |
| # ββ Core metrics via properties ββ | |
| sortino = _safe_float(pf.sortino_ratio) | |
| omega = _safe_float(pf.omega_ratio) | |
| profit_factor = _safe_float(pf.stats().get('Profit Factor', 0.0)) | |
| max_dd = _safe_float(pf.stats().get('Max Drawdown [%]', 0.0)) | |
| # Recovery Factor = Total Profit / Max Drawdown | |
| total_pnl = pf.total_profit() if callable(getattr(pf, "total_profit", None)) else pf.stats().get('Total Return [%]', 0.0) | |
| recovery_factor = _safe_float(total_pnl / abs(max_dd)) if max_dd != 0 else 0.0 | |
| # Drawdown Duration | |
| try: | |
| mdd = pf.stats().get('Max Drawdown Duration', 0) | |
| if hasattr(mdd, 'days'): | |
| max_dd_duration = int(mdd.days) | |
| elif hasattr(mdd, 'astype'): | |
| max_dd_duration = int(mdd.astype('timedelta64[D]') / np.timedelta64(1, 'D')) | |
| else: | |
| max_dd_duration = int(mdd) | |
| except: | |
| max_dd_duration = 0 | |
| # ββ Trade-level metrics via MappedArray ββββββββββββββββββββ | |
| n_trades = len(pf.trades.records) | |
| best_trade = 0.0 | |
| worst_trade = 0.0 | |
| avg_duration = 0.0 | |
| expectancy = 0.0 | |
| if n_trades > 0: | |
| # .values gives raw numpy array from MappedArray | |
| trade_returns = pf.trades.returns.values | |
| trade_duration = pf.trades.duration.values | |
| trade_pnl = pf.trades.pnl.values | |
| best_trade = _safe_float(trade_returns.max() * 100) | |
| worst_trade = _safe_float(trade_returns.min() * 100) | |
| # Safely handle timedelta arrays | |
| try: | |
| mean_dur = np.mean(trade_duration) | |
| if hasattr(mean_dur, 'days'): | |
| avg_duration = float(mean_dur.days) | |
| elif hasattr(mean_dur, 'astype'): | |
| avg_duration = float(mean_dur.astype('timedelta64[D]') / np.timedelta64(1, 'D')) | |
| else: | |
| avg_duration = _safe_float(float(mean_dur)) | |
| except: | |
| avg_duration = 0.0 | |
| expectancy = _safe_float(float(np.mean(trade_pnl))) | |
| # ββ vbt equity curve (timestamped) βββββββββββββββββββββββββ | |
| eq_series = pf.value() | |
| vbt_equity = [ | |
| {"time": str(t), "value": round(float(v), 2)} | |
| for t, v in eq_series.items() | |
| if not np.isnan(v) | |
| ] | |
| # ββ Monte Carlo simulation βββββββββββββββββββββββββββββββββ | |
| monte_carlo = _run_monte_carlo(pf, initial_capital, n_sims=100) | |
| return { | |
| "sortino_ratio": round(sortino, 3), | |
| "omega_ratio": round(omega, 3), | |
| "profit_factor": round(profit_factor, 3), | |
| "max_drawdown_pct": round(max_dd, 3), | |
| "recovery_factor": round(recovery_factor, 3), | |
| "max_dd_duration": max_dd_duration, | |
| "expectancy": round(expectancy, 2), | |
| "best_trade_pct": round(best_trade, 3), | |
| "worst_trade_pct": round(worst_trade, 3), | |
| "avg_trade_duration": round(avg_duration, 1), | |
| "vbt_equity_curve": vbt_equity, | |
| "monte_carlo": monte_carlo, | |
| } | |
| except ImportError: | |
| print("[vbt_engine] vectorbt not installed β skipping enhanced analytics") | |
| return {} | |
| except Exception as e: | |
| print(f"[vbt_engine] Error during vbt analysis: {e}") | |
| return {} | |
| # ββ Private helpers βββββββββββββββββββββββββββββββββββββββββββ | |
| def _safe_float(val) -> float: | |
| """Convert any numeric value to float, returning 0 on NaN/None.""" | |
| try: | |
| f = float(val) | |
| return 0.0 if (np.isnan(f) or np.isinf(f)) else f | |
| except Exception: | |
| return 0.0 | |
| def _run_monte_carlo(pf, initial_capital: float, n_sims: int = 100) -> dict: | |
| """ | |
| Bootstrap daily returns from the portfolio n_sims times over | |
| the same number of days, then return p10 / p50 / p90 equity paths. | |
| """ | |
| try: | |
| returns = pf.returns().dropna().values | |
| if len(returns) < 5: | |
| return {} | |
| n_steps = len(returns) | |
| sim_results = np.zeros((n_sims, n_steps + 1)) | |
| sim_results[:, 0] = initial_capital | |
| rng = np.random.default_rng(seed=42) | |
| # Vectorized bootstrap sampling | |
| # sampled shape: (n_sims, n_steps) | |
| sampled = rng.choice(returns, size=(n_sims, n_steps), replace=True) | |
| # Calculate equity paths using log returns for numerical stability and speed | |
| # equity = initial_capital * exp(cumsum(log(1 + r))) | |
| log_returns = np.log1p(sampled) | |
| cum_log_returns = np.cumsum(log_returns, axis=1) | |
| sim_results[:, 1:] = initial_capital * np.exp(cum_log_returns) | |
| p10 = np.percentile(sim_results, 10, axis=0).tolist() | |
| p50 = np.percentile(sim_results, 50, axis=0).tolist() | |
| p90 = np.percentile(sim_results, 90, axis=0).tolist() | |
| return { | |
| "p10": [round(v, 2) for v in p10], | |
| "p50": [round(v, 2) for v in p50], | |
| "p90": [round(v, 2) for v in p90], | |
| "n_sims": n_sims, | |
| } | |
| except Exception as e: | |
| print(f"[vbt_engine] Monte Carlo failed: {e}") | |
| return {} | |