{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Z-Bot Quantitative Strategy Backtester & Signal Generator\n",
    "### Professional Walk-Forward Backtesting for EMA 9/20, VWAP Reversion & Regime Filtering\n",
    "\n",
    "This notebook demonstrates how to load historical market telemetry, compute algorithmic indicators, generate high-expectancy signals ($EV_{net} > +0.05\\%$), and execute a walk-forward vectorized backtest with transaction fee and slippage models."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "from datetime import datetime, timedelta\n",
    "\n",
    "print(\"Z-Bot Quant Engine initialized successfully.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Load Historical OHLCV Telemetry Data\n",
    "We generate or load continuous hourly OHLCV bars with volume."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generate realistic geometric Brownian motion sample OHLCV data\n",
    "np.random.seed(42)\n",
    "n_bars = 2000\n",
    "dates = [datetime(2026, 1, 1) + timedelta(hours=i) for i in range(n_bars)]\n",
    "\n",
    "returns = np.random.normal(0.0003, 0.012, n_bars)\n",
    "price_path = 60000 * np.exp(np.cumsum(returns))\n",
    "\n",
    "df = pd.DataFrame({\n",
    "    'timestamp': dates,\n",
    "    'open': price_path * (1 + np.random.normal(0, 0.002, n_bars)),\n",
    "    'high': price_path * (1 + np.abs(np.random.normal(0.004, 0.003, n_bars))),\n",
    "    'low': price_path * (1 - np.abs(np.random.normal(0.004, 0.003, n_bars))),\n",
    "    'close': price_path,\n",
    "    'volume': np.random.lognormal(mean=4.5, sigma=0.8, size=n_bars) * 10\n",
    "})\n",
    "df.set_index('timestamp', inplace=True)\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Quantitative Feature Engineering: EMA 9/20 & VWAP"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Compute Exponential Moving Averages (EMA 9 and EMA 20)\n",
    "df['ema_9'] = df['close'].ewm(span=9, adjust=False).mean()\n",
    "df['ema_20'] = df['close'].ewm(span=20, adjust=False).mean()\n",
    "\n",
    "# Compute Rolling Anchored Volume-Weighted Average Price (VWAP)\n",
    "typical_price = (df['high'] + df['low'] + df['close']) / 3\n",
    "df['cum_pv'] = (typical_price * df['volume']).cumsum()\n",
    "df['cum_v'] = df['volume'].cumsum()\n",
    "df['vwap'] = df['cum_pv'] / df['cum_v']\n",
    "\n",
    "# Market Volatility & Regime Detection (ATR & Volatility Bands)\n",
    "df['tr'] = np.maximum(\n",
    "    df['high'] - df['low'],\n",
    "    np.maximum(\n",
    "        np.abs(df['high'] - df['close'].shift(1)),\n",
    "        np.abs(df['low'] - df['close'].shift(1))\n",
    "    )\n",
    ")\n",
    "df['atr_14'] = df['tr'].rolling(14).mean()\n",
    "df['regime_bull'] = (df['close'] > df['vwap']) & (df['ema_9'] > df['ema_20'])\n",
    "df.dropna(inplace=True)\n",
    "df[['close', 'ema_9', 'ema_20', 'vwap', 'regime_bull']].tail()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. High-Expectancy Signal Generation ($EV_{net} > +0.05\\%$)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generate binary entry/exit positions based on EMA Crossover + VWAP filter\n",
    "df['signal'] = 0\n",
    "df.loc[(df['ema_9'] > df['ema_20']) & (df['close'] > df['vwap']), 'signal'] = 1\n",
    "df.loc[(df['ema_9'] < df['ema_20']) | (df['close'] < df['vwap']), 'signal'] = 0\n",
    "\n",
    "# Shift position by 1 bar to prevent lookahead bias\n",
    "df['position'] = df['signal'].shift(1).fillna(0)\n",
    "\n",
    "# Compute strategy returns with fee & slippage friction (10 bps round-trip)\n",
    "FEE_RATE = 0.0006\n",
    "SLIPPAGE_RATE = 0.0004\n",
    "ROUND_TRIP_FRICTION = FEE_RATE + SLIPPAGE_RATE\n",
    "\n",
    "df['bar_return'] = df['close'].pct_change().fillna(0)\n",
    "df['trades'] = df['position'].diff().abs().fillna(0)\n",
    "df['strategy_return'] = (df['position'] * df['bar_return']) - (df['trades'] * ROUND_TRIP_FRICTION)\n",
    "\n",
    "# Cumulative returns\n",
    "df['cum_benchmark'] = (1 + df['bar_return']).cumprod()\n",
    "df['cum_strategy'] = (1 + df['strategy_return']).cumprod()\n",
    "\n",
    "print(f\"Total Trades Executed: {int(df['trades'].sum())}\")\n",
    "print(f\"Final Benchmark Return: {(df['cum_benchmark'].iloc[-1] - 1) * 100:.2f}%\")\n",
    "print(f\"Final Strategy Return: {(df['cum_strategy'].iloc[-1] - 1) * 100:.2f}%\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Key Performance Indicators (KPIs) & Risk Metrics"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Annualized Sharpe Ratio (assuming 8760 hourly bars/yr)\n",
    "strat_ret = df['strategy_return']\n",
    "sharpe = (strat_ret.mean() / (strat_ret.std() + 1e-9)) * np.sqrt(8760)\n",
    "\n",
    "# Maximum Drawdown\n",
    "cum = df['cum_strategy']\n",
    "peak = cum.cummax()\n",
    "drawdown = (cum - peak) / peak\n",
    "max_drawdown = drawdown.min()\n",
    "\n",
    "# Win Rate\n",
    "active_bars = df[df['position'] > 0]\n",
    "win_rate = (active_bars['bar_return'] > 0).mean() * 100\n",
    "\n",
    "print(\"=\" * 40)\n",
    "print(\"Z-BOT STRATEGY PERFORMANCE METRICS\")\n",
    "print(\"=\" * 40)\n",
    "print(f\"Sharpe Ratio:       {sharpe:.2f}\")\n",
    "print(f\"Max Drawdown:       {max_drawdown * 100:.2f}%\")\n",
    "print(f\"Bar Win Rate:       {win_rate:.2f}%\")\n",
    "print(f\"Net Profit Factor:  {(df[df['strategy_return'] > 0]['strategy_return'].sum() / np.abs(df[df['strategy_return'] < 0]['strategy_return'].sum() + 1e-9)):.2f}\")\n",
    "print(\"=\" * 40)"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python",
   "version": "3.10.0"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
