File size: 29,431 Bytes
09d5e33 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 5,
"id": "811bdabd",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/var/folders/6b/p92_dgbd07ldpbpq29vbpd_m0000gn/T/ipykernel_75834/244845463.py:4: DtypeWarning: Columns (11,13,23,24,75,76,79,80,83,84,90) have mixed types. Specify dtype option on import or set low_memory=False.\n",
" df = pd.read_csv('unique_companies.csv')\n"
]
}
],
"source": [
"import pandas as pd\n",
"\n",
"# Load the CSV file\n",
"df = pd.read_csv('unique_companies.csv')\n",
"\n",
"# Filter rows where 'Industry' is 'Copper'\n",
"filtered_df = df[df['Industry'] == 'Copper']\n",
"\n",
"# If you want to save the result to a new CSV\n",
"filtered_df.to_csv('unique_companies_copper.csv', index=False)\n"
]
},
{
"cell_type": "code",
"execution_count": 26,
"id": "261ce11e",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Found 150 tickers (including HG=F).\n",
"Downloading batch 1: 50 tickers\n",
"Downloading batch 2: 50 tickers\n",
"Downloading batch 3: 50 tickers\n",
"df_prices shape: (1307, 150)\n",
"Columns: ['HG=F', '000630.SZ', '000737.SZ', '000878.SZ', '002203.SZ', '005810.KS', '08W.F', '2009.TW', '2IK.F', '300618.SZ', '300697.SZ', '301511.SZ', '381.F', '3N4.SG', '4989.TW', '5PMA.F', '600255.SS', '600362.SS', '600490.SS', '601137.SS', '601609.SS', '603124.SS', '688102.SS', '688388.SS', '7GI.F', '7LY0.F', '97E0.F', '9CM0.F', 'ACMDY', 'ALM.AX', 'ANFGF', 'AR1.AX', 'ARJN.V', 'ARJNF', 'ARREF', 'ASCU.TO', 'ASCUF', 'ATCUF', 'ATYM.L', 'AXO.V', 'BCU.V', 'BCUFF', 'BFGFF', 'BHAGYANGR.NS', 'BP60.F', 'BRVRF', 'BZDLF', 'C730.F', 'CAEN', 'CAML.L', 'CAMLF', 'CFV0.F', 'COPR', 'CPCPF', 'CPER.V', 'CPFXF', 'CPO.AX', 'CPORF', 'CPPKF', 'CPPMF', 'CPR.JO', 'CS.TO', 'CSC.AX', 'CSCCF', 'CUBEXTUB.NS', 'CUU.V', 'CVV.AX', 'CYM.AX', 'CYPMF', 'E2E1.F', 'E9E.F', 'EMTRF', 'ERO', 'FCX', 'FCXO34.SA', 'FDY.TO', 'FG1.F', 'FPMB.F', 'FQVLF', 'GCUMF', 'GRX.AX', 'GRX.L', 'GSCU.L', 'H6F.F', 'HBM', 'HBM.TO', 'HCH.V', 'HDRSF', 'HGO.AX', 'HHLKF', 'HI.V', 'HIN.MU', 'HINDCOPPER.NS', 'HLGVF', 'HNCUF', 'IE', 'IE.TO', 'INUMF', 'IPMLF', 'JGRRF', 'JIX.F', 'KCC.V', 'KGH.WA', 'KGHPF', 'LA.V', 'LSANF', 'LUNMF', 'MAC.AX', 'MARI.TO', 'MARIF', 'MCL.NS', 'MMLTF', 'MTAL', 'MTJ3.F', 'NFM.AX', 'NRX.AX', 'NTM.AX', 'NU0.F', 'OCKA.F', 'OUW0.F', 'PMAM3.SA', 'PNTZF', 'PSGR', 'PUCOBRE.SN', 'Q.V', 'QCCUF', 'RAJMET.NS', 'RDS.AX', 'RE8.F', 'RRR.AX', 'SAGARDEEP.NS', 'SARKY.IS', 'SCCO', 'SFR.AX', 'SFRRF', 'SLMFF', 'TFM.V', 'TGB', 'TKO.L', 'TNC.AX', 'TRRCF', 'TVCCF', 'TWO.V', 'TWOSF', 'USCUF', 'VCUFF', 'WA1.AX', 'WAORF', 'WCUFF', 'XXIX.V']\n",
"Saved to 'df_prices.csv'.\n"
]
}
],
"source": [
"# ------------------------------------------------------------\n",
"# Build df_prices.csv for HG=F + tickers in unique_companies_copper.csv\n",
"# • period=\"5y\" (more reliable than start/end for some venues)\n",
"# • Prefer 'Adj Close', fallback to 'Close'\n",
"# • Re-download single tickers that are all-NaN in batch (e.g., 2IK.F)\n",
"# ------------------------------------------------------------\n",
"# pip install yfinance pandas\n",
"\n",
"import pandas as pd\n",
"import yfinance as yf\n",
"\n",
"CSV_PATH = \"unique_companies_copper.csv\"\n",
"TICKER_COL = \"PrimaryTicker\"\n",
"UNDERLYING = \"HG=F\"\n",
"BATCH_SIZE = 50\n",
"OUT_CSV = \"df_prices.csv\"\n",
"\n",
"# --- Read tickers ---\n",
"tickers = (\n",
" pd.read_csv(CSV_PATH, usecols=[TICKER_COL])[TICKER_COL]\n",
" .dropna().astype(str).str.strip().str.upper().tolist()\n",
")\n",
"tickers = sorted(set(tickers))\n",
"if UNDERLYING not in tickers:\n",
" tickers = [UNDERLYING] + tickers\n",
"\n",
"print(f\"Found {len(tickers)} tickers (including {UNDERLYING}).\")\n",
"\n",
"def _extract_adj_or_close(df_multi: pd.DataFrame) -> tuple[pd.DataFrame, list[str]]:\n",
" \"\"\"From yfinance multi-ticker frame, prefer 'Adj Close', else 'Close' per ticker.\"\"\"\n",
" if not isinstance(df_multi.columns, pd.MultiIndex):\n",
" raise ValueError(\"Expected MultiIndex columns for multi-ticker download.\")\n",
" fields = set(df_multi.columns.get_level_values(-1))\n",
" adj = df_multi.xs(\"Adj Close\", axis=1, level=-1, drop_level=True) if \"Adj Close\" in fields else pd.DataFrame(index=df_multi.index)\n",
" clo = df_multi.xs(\"Close\", axis=1, level=-1, drop_level=True) if \"Close\" in fields else pd.DataFrame(index=df_multi.index)\n",
"\n",
" cols = sorted(set(adj.columns).union(clo.columns))\n",
" out = pd.DataFrame(index=df_multi.index, columns=cols, dtype=\"float64\")\n",
" used_close = []\n",
"\n",
" for t in cols:\n",
" a = adj[t] if t in adj.columns else None\n",
" c = clo[t] if t in clo.columns else None\n",
" if a is not None and not a.dropna().empty:\n",
" out[t] = a\n",
" elif c is not None and not c.dropna().empty:\n",
" out[t] = c\n",
" used_close.append(t)\n",
" return out, used_close\n",
"\n",
"def _download_batch(batch):\n",
" df = yf.download(\n",
" tickers=batch,\n",
" period=\"5y\",\n",
" interval=\"1d\",\n",
" auto_adjust=False,\n",
" actions=False,\n",
" progress=False,\n",
" group_by=\"ticker\",\n",
" threads=True\n",
" )\n",
" if isinstance(df.columns, pd.MultiIndex):\n",
" return _extract_adj_or_close(df)\n",
" else:\n",
" # Single-ticker shape\n",
" tkr = batch[0]\n",
" adj = df.get(\"Adj Close\")\n",
" clo = df.get(\"Close\")\n",
" used_close = []\n",
" if adj is not None and not adj.dropna().empty:\n",
" out = adj.rename(tkr).to_frame()\n",
" elif clo is not None and not clo.dropna().empty:\n",
" out = clo.rename(tkr).to_frame()\n",
" used_close.append(tkr)\n",
" else:\n",
" out = pd.DataFrame(index=df.index, columns=[tkr], dtype=\"float64\")\n",
" return out, used_close\n",
"\n",
"def _download_single(tkr: str) -> pd.Series:\n",
" \"\"\"Single-ticker repair path; prefer Adj Close, else Close.\"\"\"\n",
" df = yf.download(\n",
" tickers=tkr,\n",
" period=\"5y\",\n",
" interval=\"1d\",\n",
" auto_adjust=False,\n",
" actions=False,\n",
" progress=False\n",
" )\n",
" s = df.get(\"Adj Close\")\n",
" if s is None or s.dropna().empty:\n",
" s = df.get(\"Close\")\n",
" if s is None:\n",
" return pd.Series(dtype=\"float64\", name=tkr)\n",
" return s.rename(tkr)\n",
"\n",
"# --- Batch download + merge ---\n",
"frames, used_close_all = [], []\n",
"for i in range(0, len(tickers), BATCH_SIZE):\n",
" batch = tickers[i:i+BATCH_SIZE]\n",
" print(f\"Downloading batch {i//BATCH_SIZE + 1}: {len(batch)} tickers\")\n",
" part, used_close = _download_batch(batch)\n",
" frames.append(part)\n",
" used_close_all.extend(used_close)\n",
"\n",
"df_prices = pd.concat(frames, axis=1)\n",
"df_prices = df_prices.loc[:, ~df_prices.columns.duplicated()].sort_index()\n",
"\n",
"# --- Repair tickers that are NaN-only or missing after batch ---\n",
"to_repair = [t for t in tickers if (t in df_prices.columns and df_prices[t].dropna().empty) or (t not in df_prices.columns)]\n",
"to_repair = sorted(set(to_repair))\n",
"if to_repair:\n",
" print(f\"Repairing via single-ticker fetch: {to_repair}\")\n",
" for t in to_repair:\n",
" s = _download_single(t)\n",
" if not s.dropna().empty:\n",
" df_prices = df_prices.reindex(df_prices.index.union(s.index)).sort_index()\n",
" df_prices[t] = s.reindex(df_prices.index)\n",
"\n",
"# --- Order columns; drop all-NaN tickers ---\n",
"ordered_cols = [UNDERLYING] + [t for t in tickers if t != UNDERLYING and t in df_prices.columns]\n",
"df_prices = df_prices.reindex(columns=ordered_cols)\n",
"all_nan_cols = [c for c in df_prices.columns if df_prices[c].dropna().empty]\n",
"if all_nan_cols:\n",
" print(f\"Dropping tickers with no usable data: {all_nan_cols}\")\n",
" df_prices = df_prices.drop(columns=all_nan_cols)\n",
"\n",
"# --- Report fallback usage ---\n",
"used_close_all = sorted(set([t for t in used_close_all if t in df_prices.columns]))\n",
"if used_close_all:\n",
" print(f\"Used 'Close' fallback for: {used_close_all}\")\n",
"\n",
"print(\"df_prices shape:\", df_prices.shape)\n",
"print(\"Columns:\", list(df_prices.columns))\n",
"\n",
"# --- Save ---\n",
"df_prices.to_csv(OUT_CSV, index_label=\"Date\", float_format=\"%.6f\")\n",
"print(f\"Saved to '{OUT_CSV}'.\")\n"
]
},
{
"cell_type": "code",
"execution_count": 29,
"id": "11079562",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"=== Missing % by ticker ===\n",
" missing_pct\n",
"AXO.V 97.016067\n",
"603124.SS 93.037490\n",
"NFM.AX 87.299158\n",
"WAORF 85.233359\n",
"ASCUF 81.637337\n",
"... ...\n",
"OUW0.F 2.371844\n",
"9CM0.F 2.371844\n",
"5PMA.F 2.371844\n",
"3N4.SG 2.371844\n",
"E2E1.F 2.371844\n",
"\n",
"[150 rows x 1 columns]\n",
"\n",
"Dropping 45 tickers (> 10% missing): ['AXO.V', '603124.SS', 'NFM.AX', 'WAORF', 'ASCUF', 'CSC.AX', 'MAC.AX', 'CPPMF', 'JGRRF', '301511.SZ', 'HNCUF', 'TRRCF', 'CPR.JO', 'CYPMF', '381.F', 'CPORF', 'IE', 'IE.TO', 'CPCPF', '688102.SS', 'INUMF', 'CSCCF', 'WA1.AX', '7LY0.F', 'CPER.V', 'NU0.F', 'HCH.V', 'GSCU.L', 'E9E.F', 'Q.V', 'ASCU.TO', 'H6F.F', 'AR1.AX', 'VCUFF', '97E0.F', 'MTAL', 'RRR.AX', 'CAMLF', 'CPO.AX', 'WCUFF', 'EMTRF', '7GI.F', 'QCCUF', '2IK.F', 'CPPKF']\n",
"\n",
"Shapes:\n",
"Before: (1307, 150) After: (1307, 105)\n",
"Saved to 'df_prices_final.csv'.\n"
]
}
],
"source": [
"# ------------------------------------------------------------\n",
"# Load df_prices.csv, compute missing % per ticker,\n",
"# drop columns with >50% missing, save df_prices_final.csv\n",
"# ------------------------------------------------------------\n",
"import pandas as pd\n",
"\n",
"IN_CSV = \"df_prices.csv\"\n",
"OUT_CSV = \"df_prices_final.csv\"\n",
"THRESH = 10.0 # percent\n",
"\n",
"df_prices = pd.read_csv(IN_CSV, parse_dates=[\"Date\"], index_col=\"Date\")\n",
"\n",
"# Missing % over the full DataFrame index\n",
"missing_pct = df_prices.isna().mean() * 100.0\n",
"report = (\n",
" pd.DataFrame({\"missing_pct\": missing_pct})\n",
" .sort_values(\"missing_pct\", ascending=False)\n",
")\n",
"print(\"=== Missing % by ticker ===\")\n",
"print(report)\n",
"\n",
"# Drop tickers with >50% missing\n",
"to_drop = report.index[report[\"missing_pct\"] > THRESH].tolist()\n",
"print(f\"\\nDropping {len(to_drop)} tickers (> {THRESH:.0f}% missing): {to_drop}\")\n",
"\n",
"df_prices_final = df_prices.drop(columns=to_drop, errors=\"ignore\")\n",
"\n",
"print(\"\\nShapes:\")\n",
"print(\"Before:\", df_prices.shape, \"After:\", df_prices_final.shape)\n",
"\n",
"df_prices_final.to_csv(OUT_CSV, index_label=\"Date\", float_format=\"%.6f\")\n",
"print(f\"Saved to '{OUT_CSV}'.\")\n"
]
},
{
"cell_type": "code",
"execution_count": 30,
"id": "8dc7673c",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Saved clean, rectangular prices to 'df_prices_final.csv' with shape (1208, 105).\n"
]
}
],
"source": [
"# ------------------------------------------------------------\n",
"# Clean df_prices_final: common window + bfill→ffill + final NA drop\n",
"# Input : df_prices_final.csv (your current file with some missing)\n",
"# Output: df_prices_final.csv (overwritten, rectangular, NA-free)\n",
"# ------------------------------------------------------------\n",
"import pandas as pd\n",
"\n",
"IN_CSV = \"df_prices_final.csv\"\n",
"OUT_CSV = \"df_prices_final.csv\" # overwrite in place\n",
"\n",
"df = pd.read_csv(IN_CSV, parse_dates=[\"Date\"], index_col=\"Date\").sort_index()\n",
"\n",
"# 1) Common window (everyone has started and not yet delisted)\n",
"first_valid = df.apply(pd.Series.first_valid_index)\n",
"last_valid = df.apply(pd.Series.last_valid_index)\n",
"\n",
"common_start = max(first_valid.dropna())\n",
"common_end = min(last_valid.dropna())\n",
"\n",
"df = df.loc[common_start:common_end].copy()\n",
"\n",
"# 2) Business-day index to harmonize calendars\n",
"bidx = pd.date_range(df.index.min(), df.index.max(), freq=\"B\")\n",
"df = df.reindex(bidx)\n",
"\n",
"# 3) Fill:\n",
"# - Backfill once to seed the first business day for tickers closed on common_start\n",
"# - Forward-fill for holiday gaps etc.\n",
"df = df.bfill(limit=None).ffill(limit=None)\n",
"\n",
"# 4) Final sanity check: drop any rare rows still containing NA\n",
"before_rows = df.shape[0]\n",
"df = df.dropna(how=\"any\")\n",
"after_rows = df.shape[0]\n",
"if before_rows != after_rows:\n",
" print(f\"Dropped {before_rows - after_rows} rows that still had NAs after filling.\")\n",
"\n",
"# 5) Save\n",
"df.to_csv(OUT_CSV, index_label=\"Date\", float_format=\"%.6f\")\n",
"print(f\"Saved clean, rectangular prices to '{OUT_CSV}' with shape {df.shape}.\")\n"
]
},
{
"cell_type": "code",
"execution_count": 40,
"id": "8cdec19b",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"✓ Saved corr_beta.csv, excess_summary.csv (with corr_to_copper)\n"
]
}
],
"source": [
"# ============================================================\n",
"# Copper-linked stocks vs COMEX copper (HG=F)\n",
"# • Correlation & beta\n",
"# • Rolling correlation\n",
"# • β-hedged alpha / excess-return summary\n",
"# Outputs:\n",
"# corr_beta.csv, rolling_corr_long.csv, excess_summary.csv\n",
"# (excess_summary.csv now includes corr_to_copper)\n",
"# ============================================================\n",
"\n",
"import pandas as pd\n",
"import numpy as np\n",
"import statsmodels.api as sm\n",
"\n",
"# ---------- PARAMETERS ----------\n",
"IN_CSV = \"df_prices_final.csv\" # prices, Date index\n",
"BENCH = \"HG=F\" # underlying metal\n",
"FREQ = \"W-FRI\" # 'D' for daily or 'W-FRI'\n",
"ROLL_WINDOW = None # 26 weeks ≈ 6 months; set None to skip\n",
"USE_LOG_RET = True # True = log-returns, False = pct-change\n",
"ALPHA_T_CUT = 0.9 # |t| threshold for alpha significance\n",
"SHARPE_CUT = 0.0 # >0 required for outperform label\n",
"\n",
"# Annualisation factor\n",
"PER_YEAR = 52 if FREQ.startswith(\"W\") else 252\n",
"\n",
"# ---------- LOAD PRICES ----------\n",
"px = (pd.read_csv(IN_CSV, parse_dates=[\"Date\"], index_col=\"Date\")\n",
" .sort_index())\n",
"assert BENCH in px.columns, f\"{BENCH} not found in columns.\"\n",
"\n",
"# Optional resample (weekly smooths roll/holiday noise)\n",
"if FREQ != \"D\":\n",
" px = px.resample(FREQ).last()\n",
"\n",
"# ---------- RETURNS ----------\n",
"rets = np.log(px).diff() if USE_LOG_RET else px.pct_change()\n",
"rets = rets.dropna(how=\"all\")\n",
"\n",
"bench = rets[BENCH]\n",
"stocks = [c for c in rets.columns if c != BENCH]\n",
"\n",
"# ---------- 1) CORRELATION & BETA ----------\n",
"corr = rets[stocks].corrwith(bench) # Series: index=ticker\n",
"var_b = bench.var(ddof=1)\n",
"beta = rets[stocks].apply(lambda s: s.cov(bench)) / var_b\n",
"\n",
"corr_beta = (pd.DataFrame({\"corr_to_copper\": corr,\n",
" \"beta_to_copper\": beta})\n",
" .sort_values(\"corr_to_copper\", ascending=False))\n",
"corr_beta.index.name = \"ticker\"\n",
"corr_beta.to_csv(\"corr_beta.csv\", float_format=\"%.6f\")\n",
"\n",
"# Keep maps for reuse in excess_summary\n",
"corr_map = corr.to_dict()\n",
"beta_map = beta.to_dict()\n",
"\n",
"# ---------- OPTIONAL ROLLING CORRELATION ----------\n",
"if ROLL_WINDOW:\n",
" rolling_long = (\n",
" rets[stocks]\n",
" .rolling(ROLL_WINDOW)\n",
" .corr(bench) # wide: Date × tickers\n",
" .stack() # -> Series with MultiIndex (Date, ticker)\n",
" .rename(\"rolling_corr\")\n",
" .rename_axis([\"Date\", \"ticker\"])\n",
" .reset_index()\n",
" .dropna(subset=[\"rolling_corr\"])\n",
" )\n",
" rolling_long.to_csv(\"rolling_corr_long.csv\",\n",
" index=False, float_format=\"%.6f\")\n",
"\n",
"# ---------- 2) β-HEDGED EXCESS & SELECTION ----------\n",
"def _nw_lags(freq: str) -> int:\n",
" return 4 if freq.startswith(\"W\") else 21 # ≈1 month of obs\n",
"\n",
"hac_lags = _nw_lags(FREQ)\n",
"\n",
"rows = []\n",
"for s in stocks:\n",
" # align & drop NA\n",
" df_xy = rets[[s, BENCH]].dropna()\n",
" if df_xy.empty:\n",
" continue\n",
"\n",
" y = df_xy[s]\n",
" X = sm.add_constant(df_xy[BENCH])\n",
" model = sm.OLS(y, X).fit(\n",
" cov_type=\"HAC\",\n",
" cov_kwds={\"maxlags\": hac_lags}\n",
" )\n",
"\n",
" alpha = model.params[\"const\"]\n",
" beta_i = model.params[BENCH]\n",
" t_alpha = model.tvalues[\"const\"]\n",
" alpha_ann = alpha * PER_YEAR\n",
"\n",
" # β-hedged excess series\n",
" r_excess = y - beta_i * df_xy[BENCH]\n",
" mu, sd = r_excess.mean(), r_excess.std(ddof=1)\n",
" hedged_sharpe = (mu / sd) * np.sqrt(PER_YEAR) if sd > 0 else np.nan\n",
" cum_excess_beta_log = r_excess.cumsum().iloc[-1]\n",
"\n",
" # Simple 1× copper cumulative log excess\n",
" cum_excess_1x_log = y.cumsum().iloc[-1] - df_xy[BENCH].cumsum().iloc[-1]\n",
"\n",
" # Label\n",
" if (alpha_ann > 0) and (t_alpha > ALPHA_T_CUT) and (hedged_sharpe > SHARPE_CUT):\n",
" label = \"Outperform\"\n",
" elif (alpha_ann < 0) and (t_alpha < -ALPHA_T_CUT) and (hedged_sharpe < -SHARPE_CUT):\n",
" label = \"Underperform\"\n",
" else:\n",
" label = \"Neutral\"\n",
"\n",
" rows.append({\n",
" \"ticker\": s,\n",
" \"corr_to_copper\": corr_map.get(s, np.nan), # <-- added\n",
" \"beta_to_copper\": beta_map.get(s, np.nan), # keep for consistency\n",
" \"alpha_ann\": alpha_ann,\n",
" \"t_alpha\": t_alpha,\n",
" \"hedged_sharpe\": hedged_sharpe,\n",
" \"cum_excess_beta_log\": cum_excess_beta_log,\n",
" \"cum_excess_1x_log\": cum_excess_1x_log,\n",
" \"label\": label\n",
" })\n",
"\n",
"excess_summary = (pd.DataFrame(rows)\n",
" .set_index(\"ticker\")\n",
" .sort_values([\"label\", \"alpha_ann\", \"hedged_sharpe\"],\n",
" ascending=[True, False, False]))\n",
"excess_summary.to_csv(\"excess_summary.csv\", float_format=\"%.6f\")\n",
"\n",
"print(\"✓ Saved corr_beta.csv,\",\n",
" \"rolling_corr_long.csv,\" if ROLL_WINDOW else \"\",\n",
" \"excess_summary.csv (with corr_to_copper)\")\n"
]
},
{
"cell_type": "code",
"execution_count": 42,
"id": "a651e4d4",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"✓ Saved corr_beta.csv, excess_summary.csv (with corr_to_copper, vol_ann, bench_vol_ann)\n"
]
}
],
"source": [
"# ============================================================\n",
"# Copper-linked stocks vs COMEX copper (HG=F)\n",
"# • Correlation & beta\n",
"# • Rolling correlation\n",
"# • β-hedged alpha / excess-return summary\n",
"# • Annualized volatility (each stock + HG=F)\n",
"# Outputs:\n",
"# corr_beta.csv, rolling_corr_long.csv, excess_summary.csv\n",
"# ============================================================\n",
"\n",
"import pandas as pd\n",
"import numpy as np\n",
"import statsmodels.api as sm\n",
"\n",
"# ---------- PARAMETERS ----------\n",
"IN_CSV = \"df_prices_final.csv\" # prices, Date index\n",
"BENCH = \"HG=F\" # underlying metal\n",
"FREQ = \"W-FRI\" # 'D' for daily or 'W-FRI' (recommended)\n",
"ROLL_WINDOW = None # 26 weeks ≈ 6 months; set None to skip\n",
"USE_LOG_RET = True # True = log-returns, False = pct-change\n",
"ALPHA_T_CUT = 0.8 # |t| threshold for alpha significance\n",
"SHARPE_CUT = 0.0 # >0 required for outperform label\n",
"\n",
"# Annualisation factor\n",
"PER_YEAR = 52 if FREQ.startswith(\"W\") else 252\n",
"\n",
"# ---------- LOAD PRICES ----------\n",
"px = (pd.read_csv(IN_CSV, parse_dates=[\"Date\"], index_col=\"Date\")\n",
" .sort_index())\n",
"assert BENCH in px.columns, f\"{BENCH} not found in columns.\"\n",
"\n",
"# Optional resample (weekly smooths roll/holiday noise)\n",
"if FREQ != \"D\":\n",
" px = px.resample(FREQ).last()\n",
"\n",
"# ---------- RETURNS ----------\n",
"rets = np.log(px).diff() if USE_LOG_RET else px.pct_change()\n",
"rets = rets.dropna(how=\"all\")\n",
"\n",
"bench = rets[BENCH]\n",
"stocks = [c for c in rets.columns if c != BENCH]\n",
"\n",
"# ---------- 1) CORRELATION & BETA ----------\n",
"corr = rets[stocks].corrwith(bench)\n",
"var_b = bench.var(ddof=1)\n",
"beta = rets[stocks].apply(lambda s: s.cov(bench)) / var_b\n",
"\n",
"corr_beta = (pd.DataFrame({\"corr_to_copper\": corr,\n",
" \"beta_to_copper\": beta})\n",
" .sort_values(\"corr_to_copper\", ascending=False))\n",
"corr_beta.index.name = \"ticker\"\n",
"corr_beta.to_csv(\"corr_beta.csv\", float_format=\"%.6f\")\n",
"\n",
"# Maps to reuse\n",
"corr_map = corr.to_dict()\n",
"beta_map = beta.to_dict()\n",
"\n",
"# ---------- OPTIONAL ROLLING CORRELATION ----------\n",
"if ROLL_WINDOW:\n",
" rolling_long = (\n",
" rets[stocks]\n",
" .rolling(ROLL_WINDOW)\n",
" .corr(bench) # wide: Date × tickers\n",
" .stack() # -> Series with MultiIndex (Date, ticker)\n",
" .rename(\"rolling_corr\")\n",
" .rename_axis([\"Date\", \"ticker\"])\n",
" .reset_index()\n",
" .dropna(subset=[\"rolling_corr\"])\n",
" )\n",
" rolling_long.to_csv(\"rolling_corr_long.csv\",\n",
" index=False, float_format=\"%.6f\")\n",
"\n",
"# ---------- 2) β-HEDGED EXCESS, VOLATILITY & SELECTION ----------\n",
"def _nw_lags(freq: str) -> int:\n",
" return 4 if freq.startswith(\"W\") else 21 # ≈1 month of obs\n",
"\n",
"hac_lags = _nw_lags(FREQ)\n",
"\n",
"# Benchmark annualized volatility (on full return series at chosen frequency)\n",
"bench_vol_ann = bench.std(ddof=1) * np.sqrt(PER_YEAR)\n",
"\n",
"rows = []\n",
"for s in stocks:\n",
" # Align series to common non-NA dates for regression & stats\n",
" df_xy = rets[[s, BENCH]].dropna()\n",
" if df_xy.empty:\n",
" continue\n",
"\n",
" y = df_xy[s]\n",
" X = sm.add_constant(df_xy[BENCH])\n",
" model = sm.OLS(y, X).fit(\n",
" cov_type=\"HAC\",\n",
" cov_kwds={\"maxlags\": hac_lags}\n",
" )\n",
"\n",
" alpha = model.params[\"const\"]\n",
" beta_i = model.params[BENCH]\n",
" t_alpha = model.tvalues[\"const\"]\n",
" alpha_ann = alpha * PER_YEAR\n",
"\n",
" # β-hedged excess series\n",
" r_excess = y - beta_i * df_xy[BENCH]\n",
" mu, sd = r_excess.mean(), r_excess.std(ddof=1)\n",
" hedged_sharpe = (mu / sd) * np.sqrt(PER_YEAR) if sd > 0 else np.nan\n",
" cum_excess_beta_log = r_excess.cumsum().iloc[-1]\n",
"\n",
" # Simple 1× copper cumulative log excess\n",
" cum_excess_1x_log = y.cumsum().iloc[-1] - df_xy[BENCH].cumsum().iloc[-1]\n",
"\n",
" # Annualized volatility for this stock (aligned sample)\n",
" vol_ann = y.std(ddof=1) * np.sqrt(PER_YEAR)\n",
"\n",
" # Label\n",
" if (alpha_ann > 0) and (t_alpha > ALPHA_T_CUT) and (hedged_sharpe > SHARPE_CUT):\n",
" label = \"Outperform\"\n",
" elif (alpha_ann < 0) and (t_alpha < -ALPHA_T_CUT) and (hedged_sharpe < -SHARPE_CUT):\n",
" label = \"Underperform\"\n",
" else:\n",
" label = \"Neutral\"\n",
"\n",
" rows.append({\n",
" \"ticker\": s,\n",
" \"corr_to_copper\": corr_map.get(s, np.nan),\n",
" \"beta_to_copper\": beta_map.get(s, np.nan),\n",
" \"alpha_ann\": alpha_ann,\n",
" \"t_alpha\": t_alpha,\n",
" \"hedged_sharpe\": hedged_sharpe,\n",
" \"cum_excess_beta_log\": cum_excess_beta_log,\n",
" \"cum_excess_1x_log\": cum_excess_1x_log,\n",
" \"vol_ann\": vol_ann, # stock annualized volatility\n",
" \"bench_vol_ann\": bench_vol_ann, # HG=F annualized volatility (same for all rows)\n",
" \"label\": label\n",
" })\n",
"\n",
"excess_summary = (pd.DataFrame(rows)\n",
" .set_index(\"ticker\")\n",
" .sort_values([\"label\", \"alpha_ann\", \"hedged_sharpe\"],\n",
" ascending=[True, False, False]))\n",
"excess_summary.to_csv(\"excess_summary.csv\", float_format=\"%.6f\")\n",
"\n",
"print(\"✓ Saved corr_beta.csv,\",\n",
" \"rolling_corr_long.csv,\" if ROLL_WINDOW else \"\",\n",
" \"excess_summary.csv (with corr_to_copper, vol_ann, bench_vol_ann)\")\n"
]
},
{
"cell_type": "code",
"execution_count": 43,
"id": "13fb4bda",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Found 20 outperformers; price matrix shape: (1208, 20)\n"
]
}
],
"source": [
"import pandas as pd\n",
"\n",
"# Load prices and labels\n",
"prices = pd.read_csv(\"df_prices_final.csv\", parse_dates=[\"Date\"], index_col=\"Date\")\n",
"labels = pd.read_csv(\"excess_summary.csv\", index_col=0)\n",
"\n",
"# Select tickers labeled as OUTPERFORM (case-insensitive)\n",
"op_tickers = (\n",
" labels.assign(_lab=labels[\"label\"].astype(str).str.upper())\n",
" .query(\"_lab == 'OUTPERFORM'\")\n",
" .index.tolist()\n",
")\n",
"\n",
"# Keep only those tickers that exist in the price matrix\n",
"op_tickers = [t for t in op_tickers if t in prices.columns]\n",
"\n",
"# Slice prices → new DataFrame\n",
"outperforming_stocks = prices.loc[:, op_tickers].copy()\n",
"\n",
"print(f\"Found {len(op_tickers)} outperformers; price matrix shape: {outperforming_stocks.shape}\")\n",
"\n",
"# Optional: include the benchmark column too\n",
"# outperforming_with_bench = prices.loc[:, ['HG=F'] + op_tickers].copy()\n",
"\n",
"# Save to CSV (optional)\n",
"outperforming_stocks.to_csv(\"outperforming_stocks.csv\", index_label=\"Date\", float_format=\"%.6f\")\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
}
|