{ "cells": [ { "cell_type": "code", "execution_count": 4, "id": "ddec01d9", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Table 4 – Augmented Dickey-Fuller\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Level pDiff p
Building construction copper0.00000.0000
US copper production0.00000.0000
Copper mining cost0.00000.0000
Commodity speculation0.00000.0000
Chile copper production0.00000.0000
.........
COVID0.79200.0000
Terrorist attack0.80970.0000
Electronics manufacturing0.87760.0000
China US trade tensions0.99890.0002
Copper tariff1.00000.0000
\n", "

98 rows × 2 columns

\n", "
" ], "text/plain": [ " Level p Diff p\n", "Building construction copper 0.0000 0.0000\n", "US copper production 0.0000 0.0000\n", "Copper mining cost 0.0000 0.0000\n", "Commodity speculation 0.0000 0.0000\n", "Chile copper production 0.0000 0.0000\n", "... ... ...\n", "COVID 0.7920 0.0000\n", "Terrorist attack 0.8097 0.0000\n", "Electronics manufacturing 0.8776 0.0000\n", "China US trade tensions 0.9989 0.0002\n", "Copper tariff 1.0000 0.0000\n", "\n", "[98 rows x 2 columns]" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Table 5 – Cointegration\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
tp
Series
Iran Iraq War-2.89430.1375
5G technology-2.81660.1605
Electronics manufacturing-2.79110.1685
Copper ore reserves-2.76750.1762
Currency exchange rates-2.70400.1981
Copper concentrate-2.65450.2164
Middle East conflicts-2.62400.2281
Mining sanctions-2.58740.2420
Yahoo finance-2.57750.2460
RMB exchange rate-2.57580.2467
Energy crisis-2.56180.2525
Scrap copper prices-2.55810.2541
Manufacturing PMI-2.55480.2554
COVID-2.54030.2616
Extreme weather-2.53260.2649
Euro exchange rate-2.52890.2665
Copper tariff-2.52630.2676
China US trade tensions-2.51210.2738
COVID copper-2.51160.2740
Electric vehicle demand-2.47230.2914
Bloomberg-2.39200.3286
Copper price forecast-2.36620.3410
Terrorist attack-2.32570.3608
Trade war-2.30100.3731
Global GDP growth-2.26840.3894
World GDP by country-2.25330.3970
Inflation expectations-2.23040.4087
\n", "
" ], "text/plain": [ " t p\n", "Series \n", "Iran Iraq War -2.8943 0.1375\n", "5G technology -2.8166 0.1605\n", "Electronics manufacturing -2.7911 0.1685\n", "Copper ore reserves -2.7675 0.1762\n", "Currency exchange rates -2.7040 0.1981\n", "Copper concentrate -2.6545 0.2164\n", "Middle East conflicts -2.6240 0.2281\n", "Mining sanctions -2.5874 0.2420\n", "Yahoo finance -2.5775 0.2460\n", "RMB exchange rate -2.5758 0.2467\n", "Energy crisis -2.5618 0.2525\n", "Scrap copper prices -2.5581 0.2541\n", "Manufacturing PMI -2.5548 0.2554\n", "COVID -2.5403 0.2616\n", "Extreme weather -2.5326 0.2649\n", "Euro exchange rate -2.5289 0.2665\n", "Copper tariff -2.5263 0.2676\n", "China US trade tensions -2.5121 0.2738\n", "COVID copper -2.5116 0.2740\n", "Electric vehicle demand -2.4723 0.2914\n", "Bloomberg -2.3920 0.3286\n", "Copper price forecast -2.3662 0.3410\n", "Terrorist attack -2.3257 0.3608\n", "Trade war -2.3010 0.3731\n", "Global GDP growth -2.2684 0.3894\n", "World GDP by country -2.2533 0.3970\n", "Inflation expectations -2.2304 0.4087" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Table 6 – Granger causality (all lags)\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
SeriesLagp
245G technology10.9159
255G technology20.4953
265G technology30.4765
275G technology40.5444
285G technology50.3709
............
211Yahoo finance200.1242
212Yahoo finance210.1664
213Yahoo finance220.2101
214Yahoo finance230.2764
215Yahoo finance240.3186
\n", "

648 rows × 3 columns

\n", "
" ], "text/plain": [ " Series Lag p\n", "24 5G technology 1 0.9159\n", "25 5G technology 2 0.4953\n", "26 5G technology 3 0.4765\n", "27 5G technology 4 0.5444\n", "28 5G technology 5 0.3709\n", ".. ... ... ...\n", "211 Yahoo finance 20 0.1242\n", "212 Yahoo finance 21 0.1664\n", "213 Yahoo finance 22 0.2101\n", "214 Yahoo finance 23 0.2764\n", "215 Yahoo finance 24 0.3186\n", "\n", "[648 rows x 3 columns]" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Feature Selection Results:\n", "\n", "p-value < 0.01: 6 series\n", "['Copper ore reserves', 'Mining sanctions', 'Extreme weather', 'Euro exchange rate', 'Copper tariff', 'Terrorist attack']\n", "\n", "p-value < 0.05: 12 series\n", "['Iran Iraq War', 'Electronics manufacturing', 'Copper ore reserves', 'Mining sanctions', 'Yahoo finance', 'Scrap copper prices', 'Extreme weather', 'Euro exchange rate', 'Copper tariff', 'China US trade tensions', 'Terrorist attack', 'Trade war']\n", "\n", "p-value < 0.10: 13 series\n", "['Iran Iraq War', 'Electronics manufacturing', 'Copper ore reserves', 'Middle East conflicts', 'Mining sanctions', 'Yahoo finance', 'Scrap copper prices', 'Extreme weather', 'Euro exchange rate', 'Copper tariff', 'China US trade tensions', 'Terrorist attack', 'Trade war']\n", "\n", "Table 7 – Granger-causal summary\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Min pBest Lagp<0.01p<0.05p<0.10
Series
Extreme weather0.00077TrueTrueTrue
Terrorist attack0.000815TrueTrueTrue
Euro exchange rate0.00249TrueTrueTrue
Copper tariff0.00406TrueTrueTrue
Copper ore reserves0.004421TrueTrueTrue
Mining sanctions0.005724TrueTrueTrue
Trade war0.01219FalseTrueTrue
Scrap copper prices0.019621FalseTrueTrue
China US trade tensions0.02631FalseTrueTrue
Yahoo finance0.035615FalseTrueTrue
Electronics manufacturing0.03712FalseTrueTrue
Iran Iraq War0.03946FalseTrueTrue
Middle East conflicts0.05808FalseFalseTrue
Copper concentrate0.117415FalseFalseFalse
COVID0.132523FalseFalseFalse
Currency exchange rates0.14201FalseFalseFalse
Global GDP growth0.169416FalseFalseFalse
COVID copper0.170723FalseFalseFalse
Inflation expectations0.27266FalseFalseFalse
RMB exchange rate0.277615FalseFalseFalse
Manufacturing PMI0.35991FalseFalseFalse
Bloomberg0.369817FalseFalseFalse
5G technology0.37095FalseFalseFalse
World GDP by country0.43473FalseFalseFalse
Energy crisis0.56805FalseFalseFalse
Copper price forecast0.75066FalseFalseFalse
Electric vehicle demand0.79062FalseFalseFalse
\n", "
" ], "text/plain": [ " Min p Best Lag p<0.01 p<0.05 p<0.10\n", "Series \n", "Extreme weather 0.0007 7 True True True\n", "Terrorist attack 0.0008 15 True True True\n", "Euro exchange rate 0.0024 9 True True True\n", "Copper tariff 0.0040 6 True True True\n", "Copper ore reserves 0.0044 21 True True True\n", "Mining sanctions 0.0057 24 True True True\n", "Trade war 0.0121 9 False True True\n", "Scrap copper prices 0.0196 21 False True True\n", "China US trade tensions 0.0263 1 False True True\n", "Yahoo finance 0.0356 15 False True True\n", "Electronics manufacturing 0.0371 2 False True True\n", "Iran Iraq War 0.0394 6 False True True\n", "Middle East conflicts 0.0580 8 False False True\n", "Copper concentrate 0.1174 15 False False False\n", "COVID 0.1325 23 False False False\n", "Currency exchange rates 0.1420 1 False False False\n", "Global GDP growth 0.1694 16 False False False\n", "COVID copper 0.1707 23 False False False\n", "Inflation expectations 0.2726 6 False False False\n", "RMB exchange rate 0.2776 15 False False False\n", "Manufacturing PMI 0.3599 1 False False False\n", "Bloomberg 0.3698 17 False False False\n", "5G technology 0.3709 5 False False False\n", "World GDP by country 0.4347 3 False False False\n", "Energy crisis 0.5680 5 False False False\n", "Copper price forecast 0.7506 6 False False False\n", "Electric vehicle demand 0.7906 2 False False False" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Accuracy comparison – direction prediction\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Scenario0.050.10without
Model
DecTree46.67%57.78%46.67%
HMM55.56%55.56%55.56%
LogReg44.44%48.89%51.11%
RandForest46.67%44.44%46.67%
SVM51.11%48.89%62.22%
Stack44.44%40.00%55.56%
Voting48.89%48.89%46.67%
\n", "
" ], "text/plain": [ "Scenario 0.05 0.10 without\n", "Model \n", "DecTree 46.67% 57.78% 46.67%\n", "HMM 55.56% 55.56% 55.56%\n", "LogReg 44.44% 48.89% 51.11%\n", "RandForest 46.67% 44.44% 46.67%\n", "SVM 51.11% 48.89% 62.22%\n", "Stack 44.44% 40.00% 55.56%\n", "Voting 48.89% 48.89% 46.67%" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# ================================================================\n", "# Copper-Price Direction-of-Move Classification\n", "# • Baseline (“without”), tier 0·05, tier 0·10\n", "# • Models: LogReg, DecisionTree, RandomForest, SVM, HMM\n", "# + Ensembles: Voting, Stacking\n", "# ================================================================\n", "import pathlib, warnings, numpy as np, pandas as pd\n", "from statsmodels.tsa.stattools import adfuller, coint, grangercausalitytests\n", "from sklearn.model_selection import TimeSeriesSplit, KFold\n", "from sklearn.preprocessing import StandardScaler\n", "from sklearn.pipeline import make_pipeline\n", "from sklearn.linear_model import LogisticRegression\n", "from sklearn.tree import DecisionTreeClassifier\n", "from sklearn.ensemble import (RandomForestClassifier, VotingClassifier,\n", " StackingClassifier)\n", "from sklearn.svm import SVC\n", "from hmmlearn.hmm import GaussianHMM\n", "from sklearn.metrics import accuracy_score\n", "\n", "warnings.filterwarnings(\"ignore\")\n", "pd.set_option(\"display.float_format\", \"{:,.4f}\".format)\n", "np.random.seed(42)\n", "\n", "# ── 1. Load copper price and Google-Trends data ------------------\n", "ROOT = pathlib.Path(\".\")\n", "def load_copper(fp=ROOT / \"Copper Prices.csv\"):\n", " df = (pd.read_csv(fp)\n", " .assign(Date=lambda d: pd.to_datetime(d[\"Date\"]))\n", " .set_index(\"Date\")\n", " .asfreq(\"W-SUN\"))\n", " return df[\"Price\"].rename(\"Copper_Price\")\n", "\n", "def load_trends():\n", " def one_folder(folder):\n", " frames = []\n", " for fp in (ROOT / folder).glob(\"*.csv\"):\n", " key = fp.stem.replace(\",\", \"\")\n", " t = pd.read_csv(fp); t.columns = [c.strip() for c in t.columns]\n", " val = t.columns[1]\n", " frames.append(t.assign(Date=lambda d: pd.to_datetime(d[t.columns[0]]))\n", " .set_index(\"Date\")\n", " .asfreq(\"W-SUN\")\n", " .rename(columns={val: key}))\n", " return pd.concat(frames, axis=1) if frames else pd.DataFrame()\n", " cats = [\"Supply Factors\", \"Demand Factors\",\n", " \"Speculative Factors\", \"Sudden Factors\"]\n", " return pd.concat([one_folder(c) for c in cats], axis=1).sort_index()\n", "\n", "copper, trends = load_copper(), load_trends()\n", "data_raw = pd.concat([copper, trends], axis=1).dropna()\n", "\n", "# ── 2. ADF to find I(1) series -----------------------------------\n", "ALPHA_ADF, ALPHA_COINT, MAX_LAG_GC = 0.01, 0.50, 24\n", "adf_p = lambda s: adfuller(s.dropna(), autolag=\"AIC\")[1]\n", "i1 = [c for c in data_raw.columns\n", " if adf_p(data_raw[c]) > ALPHA_ADF and\n", " adf_p(data_raw[c].diff()) < ALPHA_ADF and\n", " c != \"Copper_Price\"]\n", "\n", "# ── 3. Cointegration filter --------------------------------------\n", "cands = [s for s in i1\n", " if coint(data_raw[\"Copper_Price\"], data_raw[s])[1] < ALPHA_COINT]\n", "\n", "# ── 4. Granger causality tiers -----------------------------------\n", "gc_rows = []\n", "for s in cands:\n", " if data_raw[s].nunique() <= 1: continue\n", " for lag in range(1, MAX_LAG_GC + 1):\n", " try:\n", " p = grangercausalitytests(\n", " data_raw[[\"Copper_Price\", s]].dropna().values,\n", " maxlag=lag, verbose=False)[lag][0][\"ssr_ftest\"][1]\n", " gc_rows.append({\"Series\": s, \"Lag\": lag, \"p\": p})\n", " except Exception:\n", " continue\n", "df_gc = pd.DataFrame(gc_rows)\n", "\n", "TIERS = {0.05: [s for s in cands if df_gc.loc[df_gc[\"Series\"] == s, \"p\"].min() < 0.05],\n", " 0.10: [s for s in cands if df_gc.loc[df_gc[\"Series\"] == s, \"p\"].min() < 0.10]}\n", "\n", "# ────────────────────────────────────────────────────────────────\n", "# Tables 4 → 7 + Feature Selection Results (no CSV, no .style)\n", "# ────────────────────────────────────────────────────────────────\n", "from IPython.display import display\n", "from statsmodels.tools.sm_exceptions import InfeasibleTestError\n", "\n", "# ── Table 4 – Augmented Dickey-Fuller ----------------------------\n", "tab4 = pd.DataFrame(\n", " {\n", " \"Level p\": [adf_p(data_raw[c]) for c in data_raw.columns],\n", " \"Diff p\": [adf_p(data_raw[c].diff()) for c in data_raw.columns],\n", " },\n", " index=data_raw.columns,\n", ").sort_values(\"Level p\")\n", "\n", "print(\"\\nTable 4 – Augmented Dickey-Fuller\")\n", "display(tab4)\n", "\n", "# Identify I(1) candidates\n", "i1 = tab4.index[\n", " (tab4[\"Level p\"] > ALPHA_ADF) & (tab4[\"Diff p\"] < ALPHA_ADF)\n", "]\n", "\n", "# ── Table 5 – Engle-Granger cointegration ------------------------\n", "rows = []\n", "for s in i1:\n", " if s == \"Copper_Price\":\n", " continue\n", " t_stat, p_val, *_ = coint(data_raw[\"Copper_Price\"], data_raw[s])\n", " rows.append({\"Series\": s, \"t\": t_stat, \"p\": p_val})\n", "\n", "df_coint = pd.DataFrame(rows).set_index(\"Series\").sort_values(\"p\")\n", "\n", "print(\"\\nTable 5 – Cointegration\")\n", "display(df_coint)\n", "\n", "cointegrated = df_coint.index[df_coint[\"p\"] < ALPHA_COINT]\n", "\n", "# ── Table 6 – full Granger matrix --------------------------------\n", "gc_records = []\n", "for s in cointegrated:\n", " if data_raw[s].nunique() <= 1:\n", " continue\n", " for lag in range(1, MAX_LAG_GC + 1):\n", " try:\n", " p = grangercausalitytests(\n", " data_raw[[\"Copper_Price\", s]].dropna().values,\n", " maxlag=lag,\n", " verbose=False,\n", " )[lag][0][\"ssr_ftest\"][1]\n", " gc_records.append({\"Series\": s, \"Lag\": lag, \"p\": p})\n", " except InfeasibleTestError:\n", " continue\n", "\n", "df_gc = pd.DataFrame(gc_records).sort_values([\"Series\", \"Lag\"])\n", "\n", "print(\"\\nTable 6 – Granger causality (all lags)\")\n", "display(df_gc)\n", "\n", "# ── Feature Selection Results ------------------------------------\n", "tiers = {\n", " a: [\n", " s\n", " for s in cointegrated\n", " if df_gc.loc[df_gc[\"Series\"] == s, \"p\"].min() < a\n", " ]\n", " for a in TIERS_TO_BUILD\n", "}\n", "\n", "print(\"\\nFeature Selection Results:\")\n", "for a in TIERS_TO_BUILD:\n", " print(f\"\\np-value < {a:.2f}: {len(tiers[a])} series\")\n", " print(tiers[a])\n", "\n", "# ── Table 7 – Granger-causal summary -----------------------------\n", "summary_rows = []\n", "for series in cointegrated:\n", " subset = df_gc.loc[df_gc[\"Series\"] == series, [\"Lag\", \"p\"]]\n", " best = subset.loc[subset[\"p\"].idxmin()]\n", " summary_rows.append(\n", " {\n", " \"Series\": series,\n", " \"Min p\": float(best[\"p\"]),\n", " \"Best Lag\":int(best[\"Lag\"]),\n", " \"p<0.01\": best[\"p\"] < 0.01,\n", " \"p<0.05\": best[\"p\"] < 0.05,\n", " \"p<0.10\": best[\"p\"] < 0.10,\n", " }\n", " )\n", "\n", "df_summary = pd.DataFrame(summary_rows).set_index(\"Series\").sort_values(\"Min p\")\n", "\n", "print(\"\\nTable 7 – Granger-causal summary\")\n", "display(df_summary)\n", "\n", "\n", "# ── 5. Helper: build lag-1 feature frame --------------------------\n", "def lag_df(feats, lag=1):\n", " base = {\"Copper_Price\": data_raw[\"Copper_Price\"]}\n", " base.update({f\"{f}_lag{lag}\": data_raw[f].shift(lag) for f in feats})\n", " return pd.DataFrame(base).dropna()\n", "\n", "# ── 6. Scenarios --------------------------------------------------\n", "SCENARIOS = {\n", " \"without\": [], # copper-only baseline\n", " \"0.05\" : TIERS[0.05],\n", " \"0.10\" : TIERS[0.10],\n", "}\n", "\n", "# ── 7. Model factories -------------------------------------------\n", "MODEL_FNS = {\n", " \"LogReg\" : lambda: make_pipeline(StandardScaler(),\n", " LogisticRegression(max_iter=1000,\n", " random_state=42)),\n", " \"DecTree\" : lambda: DecisionTreeClassifier(random_state=42),\n", " \"RandForest\":lambda: RandomForestClassifier(n_estimators=500,\n", " random_state=42),\n", " \"SVM\" : lambda: make_pipeline(StandardScaler(),\n", " SVC(kernel=\"rbf\",\n", " probability=True,\n", " random_state=42)),\n", "}\n", "\n", "records = []\n", "\n", "# ── 8. Run classification for each scenario ----------------------\n", "for scen, feats in SCENARIOS.items():\n", " # A. dataset\n", " if scen == \"without\":\n", " df = (pd.concat([data_raw[\"Copper_Price\"],\n", " data_raw[\"Copper_Price\"].shift(1)\n", " .rename(\"Copper_Price_lag1\")],\n", " axis=1)\n", " .dropna())\n", " else:\n", " df = lag_df(feats, lag=1)\n", " # label\n", " df[\"y\"] = (df[\"Copper_Price\"].diff().shift(-1) > 0).astype(int)\n", " df.dropna(inplace=True)\n", "\n", " X, y = df.drop(columns=[\"Copper_Price\", \"y\"]), df[\"y\"]\n", " cut = int(len(X) * 0.83)\n", " X_tr, X_te, y_tr, y_te = X.iloc[:cut], X.iloc[cut:], y.iloc[:cut], y.iloc[cut:]\n", "\n", " # B. supervised models\n", " fitted = {n: fn() for n, fn in MODEL_FNS.items()}\n", " for n, clf in fitted.items():\n", " clf.fit(X_tr, y_tr)\n", "\n", " # C. HMM\n", " rets = df[\"Copper_Price\"].pct_change().dropna().values.reshape(-1, 1)\n", " split_pt = cut - 1\n", " hmm = GaussianHMM(n_components=2, covariance_type=\"full\",\n", " n_iter=100, random_state=42).fit(rets[:split_pt])\n", " states = hmm.predict(rets[split_pt:]) # length == len(y_te)\n", " state_map = {s: int(mu > 0) for s, mu in enumerate(hmm.means_.flatten())}\n", " y_pred_hmm = pd.Series([state_map[s] for s in states[:len(y_te)]],\n", " index=y_te.index)\n", "\n", " # D. ensembles (use KFold to satisfy cross_val_predict)\n", " kf = KFold(n_splits=5, shuffle=False)\n", " voting = VotingClassifier([(n, c) for n, c in fitted.items()],\n", " voting=\"hard\").fit(X_tr, y_tr)\n", " stack = StackingClassifier([(n, c) for n, c in fitted.items()],\n", " final_estimator=LogisticRegression(max_iter=1000,\n", " random_state=42),\n", " cv=kf, n_jobs=-1).fit(X_tr, y_tr)\n", "\n", " # E. accuracy scores\n", " scores = {n: accuracy_score(y_te, c.predict(X_te)) for n, c in fitted.items()}\n", " scores[\"HMM\"] = accuracy_score(y_te, y_pred_hmm)\n", " scores[\"Voting\"] = accuracy_score(y_te, voting.predict(X_te))\n", " scores[\"Stack\"] = accuracy_score(y_te, stack.predict(X_te))\n", "\n", " for mdl, acc in scores.items():\n", " records.append({\"Model\": mdl, \"Scenario\": scen, \"Accuracy\": acc})\n", "\n", "# ── 9. Show comparison table -------------------------------------\n", "acc_df = (pd.DataFrame(records)\n", " .pivot_table(index=\"Model\", columns=\"Scenario\", values=\"Accuracy\")\n", " .applymap(\"{:.2%}\".format)\n", " .sort_index())\n", "\n", "print(\"\\nAccuracy comparison – direction prediction\")\n", "display(acc_df)\n" ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "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.12.11" } }, "nbformat": 4, "nbformat_minor": 5 }