{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f6d67a08-68fc-4a58-b282-04734560df08",
   "metadata": {},
   "source": [
    "## Brent crude  macro & geopolitical data pull\n",
    "\n",
    "**Stage:** Data ingestion (stage 1 of the causal-filter pipeline)\n",
    "\n",
    "Pulls Brent crude price alongside macro and geopolitical variables that will be screened for Granger causality in the next stage, before any feature engineering or model training.\n",
    "\n",
    "**Sources**\n",
    "- **Brent futures (`BZ=F`)** — daily close, via `yfinance`\n",
    "- **Real rates (`DFII10`)** — 10Y TIPS yield, via FRED\n",
    "- **USD trade-weighted index (`DTWEXBGS`)** — via FRED\n",
    "- **Industrial production (`INDPRO`)** — via FRED\n",
    "- **US crude oil stocks, ex-SPR (`WCESTUS1`)** — weekly petroleum status report, via EIA API\n",
    "- **Geopolitical risk (`GPRD`)** — Caldara-Iacoviello daily GPR index\n",
    "\n",
    "**Output**\n",
    "All series are resampled and aligned to weekly frequency (Friday close) and saved to `brent_macro_weekly.csv`. This is the raw, unfiltered dataset — causal screening (Granger tests, lag selection) and stationarity transforms happen in the next notebook stage, not here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "b1e12167-fa64-46a0-b2f6-e7456cb85f20",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: yfinance in c:\\users\\hp\\anaconda3\\lib\\site-packages (0.2.66)\n",
      "Collecting fredapi\n",
      "  Downloading fredapi-0.5.2-py3-none-any.whl.metadata (5.0 kB)\n",
      "Requirement already satisfied: pandas in c:\\users\\hp\\anaconda3\\lib\\site-packages (3.0.0)\n",
      "Requirement already satisfied: requests in c:\\users\\hp\\anaconda3\\lib\\site-packages (2.32.5)\n",
      "Requirement already satisfied: openpyxl in c:\\users\\hp\\anaconda3\\lib\\site-packages (3.1.5)\n",
      "Requirement already satisfied: numpy>=1.16.5 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from yfinance) (2.2.6)\n",
      "Requirement already satisfied: multitasking>=0.0.7 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from yfinance) (0.0.12)\n",
      "Requirement already satisfied: platformdirs>=2.0.0 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from yfinance) (4.3.7)\n",
      "Requirement already satisfied: pytz>=2022.5 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from yfinance) (2025.2)\n",
      "Requirement already satisfied: frozendict>=2.3.4 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from yfinance) (2.4.2)\n",
      "Requirement already satisfied: peewee>=3.16.2 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from yfinance) (3.18.3)\n",
      "Requirement already satisfied: beautifulsoup4>=4.11.1 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from yfinance) (4.12.3)\n",
      "Requirement already satisfied: curl_cffi>=0.7 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from yfinance) (0.13.0)\n",
      "Requirement already satisfied: protobuf>=3.19.0 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from yfinance) (5.29.3)\n",
      "Requirement already satisfied: websockets>=13.0 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from yfinance) (16.0)\n",
      "Requirement already satisfied: python-dateutil>=2.8.2 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from pandas) (2.9.0.post0)\n",
      "Requirement already satisfied: tzdata in c:\\users\\hp\\anaconda3\\lib\\site-packages (from pandas) (2025.2)\n",
      "Requirement already satisfied: charset_normalizer<4,>=2 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from requests) (3.3.2)\n",
      "Requirement already satisfied: idna<4,>=2.5 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from requests) (3.7)\n",
      "Requirement already satisfied: urllib3<3,>=1.21.1 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from requests) (1.26.20)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from requests) (2025.4.26)\n",
      "Requirement already satisfied: et-xmlfile in c:\\users\\hp\\anaconda3\\lib\\site-packages (from openpyxl) (1.1.0)\n",
      "Requirement already satisfied: soupsieve>1.2 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from beautifulsoup4>=4.11.1->yfinance) (2.5)\n",
      "Requirement already satisfied: cffi>=1.12.0 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from curl_cffi>=0.7->yfinance) (1.17.1)\n",
      "Requirement already satisfied: pycparser in c:\\users\\hp\\anaconda3\\lib\\site-packages (from cffi>=1.12.0->curl_cffi>=0.7->yfinance) (2.21)\n",
      "Requirement already satisfied: six>=1.5 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from python-dateutil>=2.8.2->pandas) (1.17.0)\n",
      "Downloading fredapi-0.5.2-py3-none-any.whl (11 kB)\n",
      "Installing collected packages: fredapi\n",
      "Successfully installed fredapi-0.5.2\n"
     ]
    }
   ],
   "source": [
    "! pip install yfinance fredapi pandas requests openpyxl"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "bdc51d5a-362c-4858-8579-be7a50a7c43e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting xlrd\n",
      "  Downloading xlrd-2.0.2-py2.py3-none-any.whl.metadata (3.5 kB)\n",
      "Downloading xlrd-2.0.2-py2.py3-none-any.whl (96 kB)\n",
      "Installing collected packages: xlrd\n",
      "Successfully installed xlrd-2.0.2\n"
     ]
    }
   ],
   "source": [
    "!pip install xlrd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "10bfb46d-d1d0-44c1-977f-3ce06edaaabf",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\hp\\AppData\\Local\\Temp\\ipykernel_6384\\3657498532.py:32: FutureWarning: YF.download() has changed argument auto_adjust default to True\n",
      "  df = yf.download(\"BZ=F\", start=START_DATE, progress=False)[[\"Close\"]]\n",
      "C:\\Users\\hp\\anaconda3\\Lib\\site-packages\\yfinance\\scrapers\\history.py:147: Pandas4Warning: Timestamp.utcnow is deprecated and will be removed in a future version. Use Timestamp.now('UTC') instead.\n",
      "  end_dt = pd.Timestamp.utcnow().tz_convert(tz)\n",
      "C:\\Users\\hp\\anaconda3\\Lib\\site-packages\\yfinance\\scrapers\\history.py:204: Pandas4Warning: Timestamp.utcnow is deprecated and will be removed in a future version. Use Timestamp.now('UTC') instead.\n",
      "  dt_now = pd.Timestamp.utcnow()\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Saved 2177 rows to brent_macro_weekly.csv\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\hp\\AppData\\Local\\Temp\\ipykernel_6384\\3657498532.py:106: Pandas4Warning: Sorting by default when concatenating all DatetimeIndex is deprecated.  In the future, pandas will respect the default of `sort=False`. Specify `sort=True` or `sort=False` to silence this message. If you see this warnings when not directly calling concat, report a bug to pandas.\n",
      "  weekly = pd.concat(\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>brent_close</th>\n",
       "      <th>real_rate_10y</th>\n",
       "      <th>usd_index</th>\n",
       "      <th>industrial_production</th>\n",
       "      <th>crude_stocks</th>\n",
       "      <th>gpr_daily</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>date</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2026-08-21</th>\n",
       "      <td>94.389999</td>\n",
       "      <td>2.40</td>\n",
       "      <td>118.0628</td>\n",
       "      <td>NaN</td>\n",
       "      <td>428910</td>\n",
       "      <td>133.967634</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2026-08-28</th>\n",
       "      <td>89.309998</td>\n",
       "      <td>2.42</td>\n",
       "      <td>118.7479</td>\n",
       "      <td>NaN</td>\n",
       "      <td>424460</td>\n",
       "      <td>149.529170</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2026-09-04</th>\n",
       "      <td>96.279999</td>\n",
       "      <td>2.43</td>\n",
       "      <td>118.0732</td>\n",
       "      <td>NaN</td>\n",
       "      <td>424069</td>\n",
       "      <td>149.310905</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2026-09-11</th>\n",
       "      <td>104.610001</td>\n",
       "      <td>2.60</td>\n",
       "      <td>118.2126</td>\n",
       "      <td>NaN</td>\n",
       "      <td>423429</td>\n",
       "      <td>162.268873</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2026-09-18</th>\n",
       "      <td>99.639999</td>\n",
       "      <td>2.62</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>142.915278</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            brent_close  real_rate_10y  usd_index  industrial_production  \\\n",
       "date                                                                       \n",
       "2026-08-21    94.389999           2.40   118.0628                    NaN   \n",
       "2026-08-28    89.309998           2.42   118.7479                    NaN   \n",
       "2026-09-04    96.279999           2.43   118.0732                    NaN   \n",
       "2026-09-11   104.610001           2.60   118.2126                    NaN   \n",
       "2026-09-18    99.639999           2.62        NaN                    NaN   \n",
       "\n",
       "           crude_stocks   gpr_daily  \n",
       "date                                 \n",
       "2026-08-21       428910  133.967634  \n",
       "2026-08-28       424460  149.529170  \n",
       "2026-09-04       424069  149.310905  \n",
       "2026-09-11       423429  162.268873  \n",
       "2026-09-18          NaN  142.915278  "
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"\"\"\n",
    "Pull Brent crude price + macro / geopolitical data for the causal-filter pipeline.\n",
    "\n",
    "Sources:\n",
    "  - Brent futures price   -> yfinance (ticker BZ=F)\n",
    "  - Real rates            -> FRED (DFII10)\n",
    "  - USD trade-weighted idx-> FRED (DTWEXBGS)\n",
    "  - Industrial production -> FRED (INDPRO)\n",
    "  - US crude inventories  -> EIA API (weekly petroleum status report)\n",
    "  - Geopolitical risk     -> Caldara-Iacoviello GPR daily index (free CSV/XLS)\n",
    "\n",
    "Requires:\n",
    "  pip install yfinance pandas requests openpyxl\n",
    "\n",
    "You need free API keys for:\n",
    "  - FRED:  https://fred.stlouisfed.org/docs/api/api_key.html\n",
    "  - EIA:   https://www.eia.gov/opendata/register.php\n",
    "\"\"\"\n",
    "\n",
    "import pandas as pd\n",
    "import requests\n",
    "import yfinance as yf\n",
    "\n",
    "FRED_API_KEY = \"YOUR_FRED_API_KEY\"\n",
    "EIA_API_KEY = \"YOUR_EIA_API_KEY\"\n",
    "\n",
    "START_DATE = \"2010-01-01\"\n",
    "\n",
    "\n",
    "def fetch_brent() -> pd.DataFrame:\n",
    "    \"\"\"Brent crude futures, daily close.\"\"\"\n",
    "    df = yf.download(\"BZ=F\", start=START_DATE, progress=False)[[\"Close\"]]\n",
    "    df.columns = [\"brent_close\"]\n",
    "    df.index.name = \"date\"\n",
    "    return df\n",
    "\n",
    "\n",
    "def fetch_fred_series(series_id: str, api_key: str) -> pd.Series:\n",
    "    \"\"\"Fetch one FRED series via the REST API (requests, not fredapi/urllib).\"\"\"\n",
    "    url = \"https://api.stlouisfed.org/fred/series/observations\"\n",
    "    params = {\n",
    "        \"series_id\": series_id,\n",
    "        \"api_key\": api_key,\n",
    "        \"file_type\": \"json\",\n",
    "        \"observation_start\": START_DATE,\n",
    "    }\n",
    "    resp = requests.get(url, params=params, timeout=30)\n",
    "    resp.raise_for_status()\n",
    "    obs = resp.json()[\"observations\"]\n",
    "    df = pd.DataFrame(obs)[[\"date\", \"value\"]]\n",
    "    df[\"date\"] = pd.to_datetime(df[\"date\"])\n",
    "    df[\"value\"] = pd.to_numeric(df[\"value\"], errors=\"coerce\")\n",
    "    return df.set_index(\"date\")[\"value\"]\n",
    "\n",
    "\n",
    "def fetch_fred_macro(api_key: str) -> pd.DataFrame:\n",
    "    \"\"\"Real rates, USD index, industrial production.\"\"\"\n",
    "    series = {\n",
    "        \"real_rate_10y\": \"DFII10\",\n",
    "        \"usd_index\": \"DTWEXBGS\",\n",
    "        \"industrial_production\": \"INDPRO\",\n",
    "    }\n",
    "    frames = {name: fetch_fred_series(code, api_key) for name, code in series.items()}\n",
    "    df = pd.DataFrame(frames)\n",
    "    df.index.name = \"date\"\n",
    "    return df\n",
    "\n",
    "\n",
    "def fetch_eia_crude_stocks(api_key: str) -> pd.DataFrame:\n",
    "    \"\"\"Weekly US crude oil stocks (excluding SPR), thousand barrels.\"\"\"\n",
    "    url = \"https://api.eia.gov/v2/petroleum/stoc/wstk/data/\"\n",
    "    params = {\n",
    "        \"api_key\": api_key,\n",
    "        \"frequency\": \"weekly\",\n",
    "        \"data[0]\": \"value\",\n",
    "        \"facets[series][]\": \"WCESTUS1\",\n",
    "        \"start\": START_DATE,\n",
    "        \"sort[0][column]\": \"period\",\n",
    "        \"sort[0][direction]\": \"asc\",\n",
    "    }\n",
    "    resp = requests.get(url, params=params, timeout=30)\n",
    "    resp.raise_for_status()\n",
    "    records = resp.json()[\"response\"][\"data\"]\n",
    "    df = pd.DataFrame(records)[[\"period\", \"value\"]]\n",
    "    df[\"period\"] = pd.to_datetime(df[\"period\"])\n",
    "    df = df.rename(columns={\"period\": \"date\", \"value\": \"crude_stocks\"}).set_index(\"date\")\n",
    "    return df\n",
    "\n",
    "\n",
    "def fetch_gpr() -> pd.DataFrame:\n",
    "    \"\"\"Caldara-Iacoviello daily geopolitical risk index.\"\"\"\n",
    "    url = \"https://www.matteoiacoviello.com/gpr_files/data_gpr_daily_recent.xls\"\n",
    "    df = pd.read_excel(url)\n",
    "    df[\"date\"] = pd.to_datetime(df[\"date\"])\n",
    "    df = df.set_index(\"date\")[[\"GPRD\"]].rename(columns={\"GPRD\": \"gpr_daily\"})\n",
    "    return df\n",
    "\n",
    "\n",
    "def build_dataset() -> pd.DataFrame:\n",
    "    brent = fetch_brent()\n",
    "    macro = fetch_fred_macro(FRED_API_KEY)\n",
    "    inventories = fetch_eia_crude_stocks(EIA_API_KEY)\n",
    "    gpr = fetch_gpr()\n",
    "\n",
    "    # Align everything to weekly frequency (Friday close)\n",
    "    weekly = pd.concat(\n",
    "        [\n",
    "            brent.resample(\"W-FRI\").last(),\n",
    "            macro.resample(\"W-FRI\").ffill(),\n",
    "            inventories.resample(\"W-FRI\").ffill(),\n",
    "            gpr.resample(\"W-FRI\").mean(),\n",
    "        ],\n",
    "        axis=1,\n",
    "    )\n",
    "    weekly = weekly.dropna(how=\"all\")\n",
    "    return weekly\n",
    "\n",
    "\n",
    "data = build_dataset()\n",
    "data.to_csv(\"brent_macro_weekly.csv\")\n",
    "print(f\"Saved {len(data)} rows to brent_macro_weekly.csv\")\n",
    "data.tail()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "1c704c8d-e586-452a-a185-929d24af7e39",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: pandas in c:\\users\\hp\\anaconda3\\lib\\site-packages (3.0.0)\n",
      "Requirement already satisfied: numpy in c:\\users\\hp\\anaconda3\\lib\\site-packages (2.2.6)\n",
      "Requirement already satisfied: statsmodels in c:\\users\\hp\\anaconda3\\lib\\site-packages (0.14.6)\n",
      "Requirement already satisfied: python-dateutil>=2.8.2 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from pandas) (2.9.0.post0)\n",
      "Requirement already satisfied: tzdata in c:\\users\\hp\\anaconda3\\lib\\site-packages (from pandas) (2025.2)\n",
      "Requirement already satisfied: scipy!=1.9.2,>=1.8 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from statsmodels) (1.15.3)\n",
      "Requirement already satisfied: patsy>=0.5.6 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from statsmodels) (1.0.1)\n",
      "Requirement already satisfied: packaging>=21.3 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from statsmodels) (24.2)\n",
      "Requirement already satisfied: six>=1.5 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from python-dateutil>=2.8.2->pandas) (1.17.0)\n"
     ]
    }
   ],
   "source": [
    "!pip install pandas numpy statsmodels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "87abd9ae-689d-45f9-bea2-717f67acf603",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Non-null counts per column (out of 2177 rows):\n",
      "brent_close               872\n",
      "real_rate_10y             846\n",
      "usd_index                 846\n",
      "industrial_production      30\n",
      "crude_stocks              872\n",
      "gpr_daily                2177\n",
      "dtype: int64\n",
      "\n",
      "                brent_ret | ADF p-value = 0.0000 -> stationary\n",
      "            real_rate_10y | ADF p-value = 0.0000 -> stationary\n",
      "                usd_index | ADF p-value = 0.0000 -> stationary\n",
      "    industrial_production | SKIPPED - only 0 usable data points after differencing\n",
      "             crude_stocks | ADF p-value = 0.0000 -> stationary\n",
      "                gpr_daily | ADF p-value = 0.0000 -> stationary\n",
      "\n",
      "Best lag per variable (lowest p-value):\n",
      "        variable  lag   p_value  passes\n",
      "0      gpr_daily    1  0.030811    True\n",
      "1      usd_index    5  0.119014   False\n",
      "2   crude_stocks    4  0.131519   False\n",
      "3  real_rate_10y    5  0.275831   False\n",
      "\n",
      "Variables that Granger-cause Brent returns (p < 0.05): ['gpr_daily']\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\hp\\anaconda3\\Lib\\site-packages\\statsmodels\\tsa\\stattools.py:1556: FutureWarning: verbose is deprecated since functions should not print results\n",
      "  warnings.warn(\n",
      "C:\\Users\\hp\\anaconda3\\Lib\\site-packages\\statsmodels\\tsa\\stattools.py:1556: FutureWarning: verbose is deprecated since functions should not print results\n",
      "  warnings.warn(\n",
      "C:\\Users\\hp\\anaconda3\\Lib\\site-packages\\statsmodels\\tsa\\stattools.py:1556: FutureWarning: verbose is deprecated since functions should not print results\n",
      "  warnings.warn(\n",
      "C:\\Users\\hp\\anaconda3\\Lib\\site-packages\\statsmodels\\tsa\\stattools.py:1556: FutureWarning: verbose is deprecated since functions should not print results\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "\"\"\"\n",
    "Causal filter stage: test whether each macro variable Granger-causes\n",
    "Brent returns, and at what lag. Only variables that pass get carried\n",
    "forward into feature engineering / the model.\n",
    "\n",
    "Input:  brent_macro_weekly.csv (output of the data-pull stage)\n",
    "Output: granger_causality_results.csv\n",
    "\n",
    "Requires:\n",
    "  pip install pandas numpy statsmodels\n",
    "\"\"\"\n",
    "\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from statsmodels.tsa.stattools import adfuller, grangercausalitytests\n",
    "\n",
    "MAX_LAG = 8          # weeks of lag to test, adjust as needed\n",
    "SIGNIFICANCE = 0.05   # p-value threshold to call a variable \"causal\"\n",
    "\n",
    "df = pd.read_csv(\"brent_macro_weekly.csv\", index_col=\"date\", parse_dates=True)\n",
    "\n",
    "MACRO_COLS = [\n",
    "    \"real_rate_10y\",\n",
    "    \"usd_index\",\n",
    "    \"industrial_production\",\n",
    "    \"crude_stocks\",\n",
    "    \"gpr_daily\",\n",
    "]\n",
    "\n",
    "print(\"Non-null counts per column (out of\", len(df), \"rows):\")\n",
    "print(df.notna().sum())\n",
    "print()\n",
    "\n",
    "\n",
    "def make_stationary(series: pd.Series, log_diff: bool = True) -> pd.Series:\n",
    "    \"\"\"Log-difference (for strictly positive series) or first-difference otherwise.\"\"\"\n",
    "    if log_diff and (series > 0).all():\n",
    "        return np.log(series).diff()\n",
    "    return series.diff()\n",
    "\n",
    "\n",
    "def check_stationary(series: pd.Series, name: str) -> bool:\n",
    "    \"\"\"Quick ADF check, printed for sanity. Returns False (and skips) if too little data.\"\"\"\n",
    "    clean = series.dropna()\n",
    "    if len(clean) < MAX_LAG + 10:\n",
    "        print(f\"{name:>25s} | SKIPPED - only {len(clean)} usable data points after differencing\")\n",
    "        return False\n",
    "    result = adfuller(clean)\n",
    "    p_value = result[1]\n",
    "    flag = \"stationary\" if p_value < SIGNIFICANCE else \"NOT stationary\"\n",
    "    print(f\"{name:>25s} | ADF p-value = {p_value:.4f} -> {flag}\")\n",
    "    return True\n",
    "\n",
    "\n",
    "def run_granger(brent_ret: pd.Series, macro_diff: pd.Series, var_name: str) -> pd.DataFrame:\n",
    "    \"\"\"Run Granger causality (macro -> brent) across lags 1..MAX_LAG.\"\"\"\n",
    "    pair = pd.concat([brent_ret, macro_diff], axis=1).dropna()\n",
    "    pair.columns = [\"brent_ret\", var_name]\n",
    "\n",
    "    results = grangercausalitytests(pair[[\"brent_ret\", var_name]], maxlag=MAX_LAG, verbose=False)\n",
    "\n",
    "    rows = []\n",
    "    for lag, res in results.items():\n",
    "        p_value = res[0][\"ssr_ftest\"][1]\n",
    "        rows.append({\"variable\": var_name, \"lag\": lag, \"p_value\": p_value})\n",
    "    return pd.DataFrame(rows)\n",
    "\n",
    "\n",
    "# Build stationary series\n",
    "brent_ret = make_stationary(df[\"brent_close\"], log_diff=True).rename(\"brent_ret\")\n",
    "check_stationary(brent_ret, \"brent_ret\")\n",
    "\n",
    "macro_stationary = {}\n",
    "valid_cols = []\n",
    "for col in MACRO_COLS:\n",
    "    diffed = make_stationary(df[col], log_diff=(df[col] > 0).all())\n",
    "    macro_stationary[col] = diffed\n",
    "    if check_stationary(diffed, col):\n",
    "        valid_cols.append(col)\n",
    "\n",
    "if not valid_cols:\n",
    "    raise RuntimeError(\"No macro columns had enough usable data — check brent_macro_weekly.csv for gaps.\")\n",
    "\n",
    "# Run Granger causality test for each surviving macro variable against Brent returns\n",
    "all_results = []\n",
    "for col in valid_cols:\n",
    "    res = run_granger(brent_ret, macro_stationary[col], col)\n",
    "    all_results.append(res)\n",
    "\n",
    "granger_results = pd.concat(all_results, ignore_index=True)\n",
    "granger_results.to_csv(\"granger_causality_results.csv\", index=False)\n",
    "\n",
    "# Best (lowest p-value) lag per variable, and whether it passes the threshold\n",
    "best_per_var = granger_results.loc[granger_results.groupby(\"variable\")[\"p_value\"].idxmin()]\n",
    "best_per_var = best_per_var.sort_values(\"p_value\").reset_index(drop=True)\n",
    "best_per_var[\"passes\"] = best_per_var[\"p_value\"] < SIGNIFICANCE\n",
    "\n",
    "print(\"\\nBest lag per variable (lowest p-value):\")\n",
    "print(best_per_var)\n",
    "\n",
    "surviving_vars = best_per_var.loc[best_per_var[\"passes\"], \"variable\"].tolist()\n",
    "print(f\"\\nVariables that Granger-cause Brent returns (p < {SIGNIFICANCE}): {surviving_vars}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "013c13f0-43de-45d6-9c01-e45b0a6544c2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Surviving variables and their best lag:\n",
      " variable  lag  p_value\n",
      "gpr_daily    1 0.030811\n",
      "\n",
      "Feature matrix: 1 features, 2150 usable rows\n",
      "Train: 1720 rows (1985-07-12 00:00:00 to 2018-06-22 00:00:00)\n",
      "Test:  430 rows (2018-06-29 00:00:00 to 2026-09-18 00:00:00)\n",
      "Target balance (train): 13.31% up\n"
     ]
    }
   ],
   "source": [
    "\"\"\"\n",
    "Feature engineering stage: turn the Granger-surviving macro variables into\n",
    "a lagged, normalized feature matrix, and build the prediction target.\n",
    "\n",
    "Inputs:\n",
    "  brent_macro_weekly.csv          (stage 1 output)\n",
    "  granger_causality_results.csv   (stage 2 output)\n",
    "\n",
    "Outputs:\n",
    "  X_train.csv, X_test.csv, y_train.csv, y_test.csv\n",
    "\n",
    "Requires:\n",
    "  pip install pandas numpy\n",
    "\"\"\"\n",
    "\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "SIGNIFICANCE = 0.05\n",
    "ROLLING_WINDOW = 52   # weeks (~1 year) for rolling z-score normalization\n",
    "TEST_FRACTION = 0.2   # last 20% of the timeline held out, no shuffling\n",
    "\n",
    "df = pd.read_csv(\"brent_macro_weekly.csv\", index_col=\"date\", parse_dates=True)\n",
    "granger_results = pd.read_csv(\"granger_causality_results.csv\")\n",
    "\n",
    "\n",
    "def make_stationary(series: pd.Series, log_diff: bool = True) -> pd.Series:\n",
    "    \"\"\"Same transform used in the causal-filter stage — must match exactly.\"\"\"\n",
    "    if log_diff and (series > 0).all():\n",
    "        return np.log(series).diff()\n",
    "    return series.diff()\n",
    "\n",
    "\n",
    "def rolling_zscore(series: pd.Series, window: int) -> pd.Series:\n",
    "    \"\"\"Causal rolling z-score — uses only data up to and including t.\"\"\"\n",
    "    roll_mean = series.rolling(window, min_periods=window // 2).mean()\n",
    "    roll_std = series.rolling(window, min_periods=window // 2).std()\n",
    "    return (series - roll_mean) / roll_std\n",
    "\n",
    "\n",
    "# 1. Find which variables survived the Granger filter, and their best lag\n",
    "best_per_var = granger_results.loc[granger_results.groupby(\"variable\")[\"p_value\"].idxmin()]\n",
    "surviving = best_per_var[best_per_var[\"p_value\"] < SIGNIFICANCE]\n",
    "\n",
    "if surviving.empty:\n",
    "    raise RuntimeError(\"No variables passed the Granger filter — nothing to build features from.\")\n",
    "\n",
    "print(\"Surviving variables and their best lag:\")\n",
    "print(surviving[[\"variable\", \"lag\", \"p_value\"]].to_string(index=False))\n",
    "\n",
    "# 2. Rebuild the stationary series for Brent and each surviving variable\n",
    "brent_ret = make_stationary(df[\"brent_close\"], log_diff=True).rename(\"brent_ret\")\n",
    "\n",
    "feature_frames = {}\n",
    "for _, row in surviving.iterrows():\n",
    "    var, lag = row[\"variable\"], int(row[\"lag\"])\n",
    "    stationary = make_stationary(df[var], log_diff=(df[var] > 0).all())\n",
    "    lagged = stationary.shift(lag)                       # apply each variable's own best lag\n",
    "    scaled = rolling_zscore(lagged, ROLLING_WINDOW)       # normalize\n",
    "    feature_frames[f\"{var}_lag{lag}\"] = scaled\n",
    "\n",
    "X = pd.DataFrame(feature_frames)\n",
    "\n",
    "# 3. Build the target: direction of Brent's next-period return (features at t predict t+1)\n",
    "y = (brent_ret.shift(-1) > 0).astype(int).rename(\"target_up\")\n",
    "\n",
    "# 4. Align, drop rows with any NaN from lagging/rolling/shifting\n",
    "data = pd.concat([X, y], axis=1).dropna()\n",
    "X = data.drop(columns=\"target_up\")\n",
    "y = data[\"target_up\"]\n",
    "\n",
    "# 5. Time-respecting split — no shuffling, clean cutoff\n",
    "split_idx = int(len(data) * (1 - TEST_FRACTION))\n",
    "X_train, X_test = X.iloc[:split_idx], X.iloc[split_idx:]\n",
    "y_train, y_test = y.iloc[:split_idx], y.iloc[split_idx:]\n",
    "\n",
    "X_train.to_csv(\"X_train.csv\")\n",
    "X_test.to_csv(\"X_test.csv\")\n",
    "y_train.to_csv(\"y_train.csv\")\n",
    "y_test.to_csv(\"y_test.csv\")\n",
    "\n",
    "print(f\"\\nFeature matrix: {X.shape[1]} features, {len(X)} usable rows\")\n",
    "print(f\"Train: {len(X_train)} rows ({X_train.index.min()} to {X_train.index.max()})\")\n",
    "print(f\"Test:  {len(X_test)} rows ({X_test.index.min()} to {X_test.index.max()})\")\n",
    "print(f\"Target balance (train): {y_train.mean():.2%} up\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "37157bcb-9ddd-445c-a450-7a1f1ed684f3",
   "metadata": {},
   "source": [
    "## Model architecture : Brent direction signal MLP\n",
    "\n",
    "**Input layer**\n",
    "- Size: N features (dynamic  equal to however many macro variables survived the Granger filter, each already lagged and rolling-z-scored)\n",
    "\n",
    "**Hidden layer 1**\n",
    "- Dense, 24 units\n",
    "- Activation: ReLU\n",
    "- Dropout: 0.3\n",
    "\n",
    "**Hidden layer 2**\n",
    "- Dense, 16 units\n",
    "- Activation: ReLU\n",
    "- Dropout: 0.2\n",
    "\n",
    "**Output layer**\n",
    "- Dense, 1 unit, raw logit (sigmoid applied only at evaluation time, not during training)\n",
    "- Interpreted as: probability Brent's next-period return is positive\n",
    "\n",
    "**Loss function**\n",
    "- Binary cross-entropy with logits (`BCEWithLogitsLoss`)\n",
    "- `pos_weight` set to the train-set negative/positive class ratio, so an imbalanced up/down split doesn't bias the model toward the majority class\n",
    "\n",
    "**Optimizer**\n",
    "- Adam, learning rate 1e-3\n",
    "- `weight_decay = 1e-4` (this is the L2 regularization term)\n",
    "\n",
    "**Training regime**\n",
    "- Full-batch gradient descent (dataset is small enough that mini-batching isn't necessary)\n",
    "- Up to 300 epochs, with early stopping: training halts if validation loss hasn't improved in 15 consecutive epochs, and the best-validation-loss weights are restored at the end\n",
    "- Validation slice is the last 15% of the training period (time-respecting, not shuffled)\n",
    "\n",
    "**Evaluation (on held-out test set)**\n",
    "- Accuracy / hit rate\n",
    "- Information coefficient — Pearson correlation between predicted probability and actual direction\n",
    "- Compared against a majority-class baseline, so you can see if the model is actually adding anything over just guessing \"up\" (or \"down\") every time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "278f4994-22b3-482a-bf30-088f650c30d1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: torch in c:\\users\\hp\\anaconda3\\lib\\site-packages (2.10.0)\n",
      "Requirement already satisfied: pandas in c:\\users\\hp\\anaconda3\\lib\\site-packages (3.0.0)\n",
      "Requirement already satisfied: numpy in c:\\users\\hp\\anaconda3\\lib\\site-packages (2.2.6)\n",
      "Requirement already satisfied: filelock in c:\\users\\hp\\anaconda3\\lib\\site-packages (from torch) (3.20.3)\n",
      "Requirement already satisfied: typing-extensions>=4.10.0 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from torch) (4.12.2)\n",
      "Requirement already satisfied: sympy>=1.13.3 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from torch) (1.13.3)\n",
      "Requirement already satisfied: networkx>=2.5.1 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from torch) (3.4.2)\n",
      "Requirement already satisfied: jinja2 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from torch) (3.1.6)\n",
      "Requirement already satisfied: fsspec>=0.8.5 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from torch) (2025.3.2)\n",
      "Requirement already satisfied: setuptools in c:\\users\\hp\\anaconda3\\lib\\site-packages (from torch) (72.1.0)\n",
      "Requirement already satisfied: python-dateutil>=2.8.2 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from pandas) (2.9.0.post0)\n",
      "Requirement already satisfied: tzdata in c:\\users\\hp\\anaconda3\\lib\\site-packages (from pandas) (2025.2)\n",
      "Requirement already satisfied: six>=1.5 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from python-dateutil>=2.8.2->pandas) (1.17.0)\n",
      "Requirement already satisfied: mpmath<1.4,>=1.1.0 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from sympy>=1.13.3->torch) (1.3.0)\n",
      "Requirement already satisfied: MarkupSafe>=2.0 in c:\\users\\hp\\anaconda3\\lib\\site-packages (from jinja2->torch) (3.0.2)\n"
     ]
    }
   ],
   "source": [
    "! pip install torch pandas numpy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "3ab11887-d045-46b0-b82f-5933e1bab65b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Early stopping at epoch 15, best val loss = 4.9857\n",
      "\n",
      "Test accuracy / hit rate: 52.79%\n",
      "Information coefficient (predicted prob vs actual direction): 0.0465\n",
      "Baseline (always predict majority class): 53.72%\n"
     ]
    }
   ],
   "source": [
    "\"\"\"\n",
    "Model stage: small MLP signal generator for Brent direction, trained on the\n",
    "feature matrix from the feature-engineering stage.\n",
    "\n",
    "Inputs:  X_train.csv, X_test.csv, y_train.csv, y_test.csv\n",
    "Output:  printed accuracy, hit rate, and information coefficient on the test set\n",
    "\n",
    "Runs comfortably on any modern laptop, CPU only — a few hundred parameters,\n",
    "a few hundred rows of data, full-batch training. No GPU needed.\n",
    "\n",
    "Requires:\n",
    "  pip install torch pandas numpy\n",
    "\"\"\"\n",
    "\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "\n",
    "torch.manual_seed(42)\n",
    "\n",
    "X_train = pd.read_csv(\"X_train.csv\", index_col=0, parse_dates=True)\n",
    "X_test = pd.read_csv(\"X_test.csv\", index_col=0, parse_dates=True)\n",
    "y_train = pd.read_csv(\"y_train.csv\", index_col=0, parse_dates=True).iloc[:, 0]\n",
    "y_test = pd.read_csv(\"y_test.csv\", index_col=0, parse_dates=True).iloc[:, 0]\n",
    "\n",
    "# Carve a validation slice off the END of the training period (time-respecting, no shuffling)\n",
    "VAL_FRACTION = 0.15\n",
    "val_split = int(len(X_train) * (1 - VAL_FRACTION))\n",
    "X_tr, X_val = X_train.iloc[:val_split], X_train.iloc[val_split:]\n",
    "y_tr, y_val = y_train.iloc[:val_split], y_train.iloc[val_split:]\n",
    "\n",
    "\n",
    "def to_tensor(data) -> torch.Tensor:\n",
    "    return torch.tensor(data.values, dtype=torch.float32)\n",
    "\n",
    "\n",
    "X_tr_t, X_val_t, X_test_t = to_tensor(X_tr), to_tensor(X_val), to_tensor(X_test)\n",
    "y_tr_t = to_tensor(y_tr).unsqueeze(1)\n",
    "y_val_t = to_tensor(y_val).unsqueeze(1)\n",
    "\n",
    "\n",
    "class SignalMLP(nn.Module):\n",
    "    \"\"\"Input -> 24 (ReLU, dropout 0.3) -> 16 (ReLU, dropout 0.2) -> 1 logit.\"\"\"\n",
    "\n",
    "    def __init__(self, n_features: int):\n",
    "        super().__init__()\n",
    "        self.net = nn.Sequential(\n",
    "            nn.Linear(n_features, 24),\n",
    "            nn.ReLU(),\n",
    "            nn.Dropout(0.3),\n",
    "            nn.Linear(24, 16),\n",
    "            nn.ReLU(),\n",
    "            nn.Dropout(0.2),\n",
    "            nn.Linear(16, 1),   # raw logit — sigmoid applied at evaluation time\n",
    "        )\n",
    "\n",
    "    def forward(self, x):\n",
    "        return self.net(x)\n",
    "\n",
    "\n",
    "model = SignalMLP(n_features=X_tr.shape[1])\n",
    "\n",
    "# Class imbalance handling — weight the minority class in the loss\n",
    "n_pos = y_tr.sum()\n",
    "n_neg = len(y_tr) - n_pos\n",
    "pos_weight = torch.tensor([n_neg / max(n_pos, 1)], dtype=torch.float32)\n",
    "criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weight)\n",
    "\n",
    "optimizer = torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-4)  # weight_decay = L2\n",
    "\n",
    "# Training loop with early stopping on validation loss\n",
    "MAX_EPOCHS = 300\n",
    "PATIENCE = 15\n",
    "best_val_loss = float(\"inf\")\n",
    "best_state = None\n",
    "patience_counter = 0\n",
    "\n",
    "for epoch in range(MAX_EPOCHS):\n",
    "    model.train()\n",
    "    optimizer.zero_grad()\n",
    "    loss = criterion(model(X_tr_t), y_tr_t)\n",
    "    loss.backward()\n",
    "    optimizer.step()\n",
    "\n",
    "    model.eval()\n",
    "    with torch.no_grad():\n",
    "        val_loss = criterion(model(X_val_t), y_val_t).item()\n",
    "\n",
    "    if val_loss < best_val_loss:\n",
    "        best_val_loss = val_loss\n",
    "        best_state = {k: v.clone() for k, v in model.state_dict().items()}\n",
    "        patience_counter = 0\n",
    "    else:\n",
    "        patience_counter += 1\n",
    "        if patience_counter >= PATIENCE:\n",
    "            print(f\"Early stopping at epoch {epoch}, best val loss = {best_val_loss:.4f}\")\n",
    "            break\n",
    "\n",
    "model.load_state_dict(best_state)\n",
    "\n",
    "# Evaluate on the held-out test set\n",
    "model.eval()\n",
    "with torch.no_grad():\n",
    "    test_probs = torch.sigmoid(model(X_test_t)).squeeze().numpy()\n",
    "\n",
    "test_preds = (test_probs > 0.5).astype(int)\n",
    "y_test_arr = y_test.values\n",
    "\n",
    "accuracy = (test_preds == y_test_arr).mean()\n",
    "ic = np.corrcoef(test_probs, y_test_arr)[0, 1]\n",
    "baseline = max(y_test_arr.mean(), 1 - y_test_arr.mean())\n",
    "\n",
    "print(f\"\\nTest accuracy / hit rate: {accuracy:.2%}\")\n",
    "print(f\"Information coefficient (predicted prob vs actual direction): {ic:.4f}\")\n",
    "print(f\"Baseline (always predict majority class): {baseline:.2%}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "c762dcc1-6250-45e3-ab47-0e581e07a2c9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=== Walk-forward validation ===\n",
      "Fold 1: train= 360  test= 358  accuracy=100.00%  IC=nan\n",
      "Fold 2: train= 718  test= 358  accuracy=100.00%  IC=nan\n",
      "Fold 3: train=1076  test= 358  accuracy=75.14%  IC=0.0438\n",
      "Fold 4: train=1434  test= 358  accuracy=49.72%  IC=-0.0543\n",
      "Fold 5: train=1792  test= 358  accuracy=54.47%  IC=-0.0213\n",
      "\n",
      "Mean IC across folds: -0.0106  (std 0.0408)\n",
      "Mean accuracy across folds: 75.87%\n",
      "\n",
      "=== Permutation test ===\n",
      "Real model: accuracy=46.98%  IC=-0.0136\n",
      "  50/200 permutations done\n",
      "  100/200 permutations done\n",
      "  150/200 permutations done\n",
      "  200/200 permutations done\n",
      "\n",
      "Permutation null distribution: mean IC=-0.0028, std=0.0379\n",
      "Empirical p-value (real IC vs shuffled-label IC): 0.5920\n",
      "Signal does NOT clearly pass — real IC is not distinguishable from noise.\n"
     ]
    }
   ],
   "source": [
    "\"\"\"\n",
    "Validation stage: walk-forward testing across the whole timeline, plus a\n",
    "permutation test to check the signal isn't just noise the model overfit to.\n",
    "\n",
    "Inputs:  X_train.csv, X_test.csv, y_train.csv, y_test.csv (stage 3 output)\n",
    "Output:  printed walk-forward IC/accuracy per fold, and permutation p-value\n",
    "\n",
    "Requires:\n",
    "  pip install torch pandas numpy scikit-learn\n",
    "\"\"\"\n",
    "\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "from sklearn.model_selection import TimeSeriesSplit\n",
    "\n",
    "N_SPLITS = 5           # walk-forward folds\n",
    "N_PERMUTATIONS = 200    # shuffles for the permutation test\n",
    "VAL_FRACTION = 0.15     # slice of each fold's train portion used for early stopping\n",
    "MAX_EPOCHS = 300\n",
    "PATIENCE = 15\n",
    "\n",
    "\n",
    "# --- Load and recombine into one continuous, time-ordered series -----------\n",
    "X_train = pd.read_csv(\"X_train.csv\", index_col=0, parse_dates=True)\n",
    "X_test = pd.read_csv(\"X_test.csv\", index_col=0, parse_dates=True)\n",
    "y_train = pd.read_csv(\"y_train.csv\", index_col=0, parse_dates=True).iloc[:, 0]\n",
    "y_test = pd.read_csv(\"y_test.csv\", index_col=0, parse_dates=True).iloc[:, 0]\n",
    "\n",
    "X_full = pd.concat([X_train, X_test]).sort_index()\n",
    "y_full = pd.concat([y_train, y_test]).sort_index()\n",
    "\n",
    "\n",
    "# --- Same architecture as the model stage — must match exactly -------------\n",
    "class SignalMLP(nn.Module):\n",
    "    def __init__(self, n_features: int):\n",
    "        super().__init__()\n",
    "        self.net = nn.Sequential(\n",
    "            nn.Linear(n_features, 24),\n",
    "            nn.ReLU(),\n",
    "            nn.Dropout(0.3),\n",
    "            nn.Linear(24, 16),\n",
    "            nn.ReLU(),\n",
    "            nn.Dropout(0.2),\n",
    "            nn.Linear(16, 1),\n",
    "        )\n",
    "\n",
    "    def forward(self, x):\n",
    "        return self.net(x)\n",
    "\n",
    "\n",
    "def to_tensor(data) -> torch.Tensor:\n",
    "    return torch.tensor(np.asarray(data), dtype=torch.float32)\n",
    "\n",
    "\n",
    "def train_model(X_tr: np.ndarray, y_tr: np.ndarray, X_val: np.ndarray, y_val: np.ndarray) -> SignalMLP:\n",
    "    \"\"\"Train one MLP with early stopping on the given train/val arrays.\"\"\"\n",
    "    X_tr_t, X_val_t = to_tensor(X_tr), to_tensor(X_val)\n",
    "    y_tr_t = to_tensor(y_tr).unsqueeze(1)\n",
    "    y_val_t = to_tensor(y_val).unsqueeze(1)\n",
    "\n",
    "    model = SignalMLP(n_features=X_tr.shape[1])\n",
    "\n",
    "    n_pos = y_tr.sum()\n",
    "    n_neg = len(y_tr) - n_pos\n",
    "    pos_weight = torch.tensor([n_neg / max(n_pos, 1)], dtype=torch.float32)\n",
    "    criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weight)\n",
    "    optimizer = torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-4)\n",
    "\n",
    "    best_val_loss = float(\"inf\")\n",
    "    best_state = None\n",
    "    patience_counter = 0\n",
    "\n",
    "    for _ in range(MAX_EPOCHS):\n",
    "        model.train()\n",
    "        optimizer.zero_grad()\n",
    "        loss = criterion(model(X_tr_t), y_tr_t)\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "\n",
    "        model.eval()\n",
    "        with torch.no_grad():\n",
    "            val_loss = criterion(model(X_val_t), y_val_t).item()\n",
    "\n",
    "        if val_loss < best_val_loss:\n",
    "            best_val_loss = val_loss\n",
    "            best_state = {k: v.clone() for k, v in model.state_dict().items()}\n",
    "            patience_counter = 0\n",
    "        else:\n",
    "            patience_counter += 1\n",
    "            if patience_counter >= PATIENCE:\n",
    "                break\n",
    "\n",
    "    model.load_state_dict(best_state)\n",
    "    return model\n",
    "\n",
    "\n",
    "def evaluate(model: SignalMLP, X_eval: np.ndarray, y_eval: np.ndarray):\n",
    "    \"\"\"Return (predicted probabilities, accuracy, IC) on an eval set.\"\"\"\n",
    "    model.eval()\n",
    "    with torch.no_grad():\n",
    "        probs = torch.sigmoid(model(to_tensor(X_eval))).squeeze().numpy()\n",
    "    preds = (probs > 0.5).astype(int)\n",
    "    accuracy = (preds == y_eval).mean()\n",
    "    ic = np.corrcoef(probs, y_eval)[0, 1] if len(np.unique(y_eval)) > 1 else np.nan\n",
    "    return probs, accuracy, ic\n",
    "\n",
    "\n",
    "def train_val_split(X: np.ndarray, y: np.ndarray, val_fraction: float):\n",
    "    \"\"\"Time-respecting split of a fold's training portion into train/val for early stopping.\"\"\"\n",
    "    split = int(len(X) * (1 - val_fraction))\n",
    "    return X[:split], y[:split], X[split:], y[split:]\n",
    "\n",
    "\n",
    "# --- 1. Walk-forward validation across the whole timeline ------------------\n",
    "print(\"=== Walk-forward validation ===\")\n",
    "tscv = TimeSeriesSplit(n_splits=N_SPLITS)\n",
    "X_arr, y_arr = X_full.values, y_full.values\n",
    "\n",
    "fold_ics, fold_accs = [], []\n",
    "for fold, (train_idx, test_idx) in enumerate(tscv.split(X_arr), start=1):\n",
    "    X_tr_fold, y_tr_fold = X_arr[train_idx], y_arr[train_idx]\n",
    "    X_te_fold, y_te_fold = X_arr[test_idx], y_arr[test_idx]\n",
    "\n",
    "    X_tr, y_tr, X_val, y_val = train_val_split(X_tr_fold, y_tr_fold, VAL_FRACTION)\n",
    "    model = train_model(X_tr, y_tr, X_val, y_val)\n",
    "    _, acc, ic = evaluate(model, X_te_fold, y_te_fold)\n",
    "\n",
    "    fold_ics.append(ic)\n",
    "    fold_accs.append(acc)\n",
    "    print(f\"Fold {fold}: train={len(train_idx):>4d}  test={len(test_idx):>4d}  \"\n",
    "          f\"accuracy={acc:.2%}  IC={ic:.4f}\")\n",
    "\n",
    "fold_ics_arr = np.array(fold_ics)\n",
    "print(f\"\\nMean IC across folds: {np.nanmean(fold_ics_arr):.4f}  \"\n",
    "      f\"(std {np.nanstd(fold_ics_arr):.4f})\")\n",
    "print(f\"Mean accuracy across folds: {np.mean(fold_accs):.2%}\")\n",
    "\n",
    "\n",
    "# --- 2. Permutation test on the original stage-3 train/test split ----------\n",
    "print(\"\\n=== Permutation test ===\")\n",
    "X_tr_orig, y_tr_orig = X_train.values, y_train.values\n",
    "X_te_orig, y_te_orig = X_test.values, y_test.values\n",
    "\n",
    "X_tr_real, y_tr_real, X_val_real, y_val_real = train_val_split(X_tr_orig, y_tr_orig, VAL_FRACTION)\n",
    "real_model = train_model(X_tr_real, y_tr_real, X_val_real, y_val_real)\n",
    "_, real_acc, real_ic = evaluate(real_model, X_te_orig, y_te_orig)\n",
    "print(f\"Real model: accuracy={real_acc:.2%}  IC={real_ic:.4f}\")\n",
    "\n",
    "rng = np.random.default_rng(42)\n",
    "permuted_ics = []\n",
    "for i in range(N_PERMUTATIONS):\n",
    "    y_shuffled = rng.permutation(y_tr_orig)\n",
    "    X_tr_p, y_tr_p, X_val_p, y_val_p = train_val_split(X_tr_orig, y_shuffled, VAL_FRACTION)\n",
    "    perm_model = train_model(X_tr_p, y_tr_p, X_val_p, y_val_p)\n",
    "    _, _, perm_ic = evaluate(perm_model, X_te_orig, y_te_orig)\n",
    "    permuted_ics.append(perm_ic if not np.isnan(perm_ic) else 0.0)\n",
    "\n",
    "    if (i + 1) % 50 == 0:\n",
    "        print(f\"  {i + 1}/{N_PERMUTATIONS} permutations done\")\n",
    "\n",
    "permuted_ics = np.array(permuted_ics)\n",
    "p_value = (np.sum(permuted_ics >= real_ic) + 1) / (N_PERMUTATIONS + 1)\n",
    "\n",
    "print(f\"\\nPermutation null distribution: mean IC={permuted_ics.mean():.4f}, \"\n",
    "      f\"std={permuted_ics.std():.4f}\")\n",
    "print(f\"Empirical p-value (real IC vs shuffled-label IC): {p_value:.4f}\")\n",
    "\n",
    "if p_value < 0.05:\n",
    "    print(\"Signal passes the permutation test — real IC is unlikely under the null.\")\n",
    "else:\n",
    "    print(\"Signal does NOT clearly pass — real IC is not distinguishable from noise.\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d25e2d32-86ad-4041-a5e4-fe1e025d159c",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
