|
| 1 | +"""One-shot migration: correct broker-local-as-UTC timestamps in tick_data |
| 2 | +for XAUUSD. |
| 3 | +
|
| 4 | +Background — see quant-strategies-research/docs/RESEARCH_NOTES.md lesson #80 |
| 5 | +and docs/TZ_FIX_PHASE2_DATALAKE_RECONCILIATION.md. |
| 6 | +
|
| 7 | +The XAUUSD ticks in tick_data were originally ingested from an MT5 |
| 8 | +<DATE>/<TIME> CSV via _read_raw_tick(); that path treated broker-local |
| 9 | +clock values as UTC. This script applies a DST-aware Athens -> UTC |
| 10 | +correction in place via DuckDB's `timezone()` function. |
| 11 | +
|
| 12 | +Run on the VPS where the DuckDB file lives. Read-write transaction; |
| 13 | +backs up the affected rows to `tick_data_xauusd_backup_<run-id>` before |
| 14 | +UPDATE. Idempotent guard: refuses to run if a `tick_data_migrations` |
| 15 | +ledger already contains a matching entry. |
| 16 | +
|
| 17 | +Usage: |
| 18 | + # dry-run (default) — prints sample before/after, no writes: |
| 19 | + python scripts/migrate_tick_tz_xauusd.py |
| 20 | +
|
| 21 | + # apply: |
| 22 | + python scripts/migrate_tick_tz_xauusd.py --confirm |
| 23 | +
|
| 24 | + # ad-hoc broker tz override (default = Europe/Athens): |
| 25 | + MT5_BROKER_TZ=Europe/Bucharest python scripts/migrate_tick_tz_xauusd.py --confirm |
| 26 | +""" |
| 27 | +from __future__ import annotations |
| 28 | + |
| 29 | +import argparse |
| 30 | +import os |
| 31 | +import sys |
| 32 | +import uuid |
| 33 | +from datetime import datetime, timezone |
| 34 | +from pathlib import Path |
| 35 | + |
| 36 | +# Make sibling 'src/' importable so we share the lake's DB path config. |
| 37 | +_HERE = Path(__file__).resolve().parent |
| 38 | +sys.path.insert(0, str(_HERE.parent)) |
| 39 | + |
| 40 | +import duckdb # type: ignore |
| 41 | + |
| 42 | +# Reuse the lake's own DB path config (avoid drift). |
| 43 | +try: |
| 44 | + from src.config import DUCKDB_PATH # type: ignore |
| 45 | +except Exception: |
| 46 | + DUCKDB_PATH = Path(os.getenv("DUCKDB_PATH", str(_HERE.parent / "datalake" / "ohlc.duckdb"))) |
| 47 | + |
| 48 | + |
| 49 | +MIGRATION_ID = "tick_tz_xauusd_athens_2026_05_28" |
| 50 | + |
| 51 | + |
| 52 | +def ensure_ledger(con): |
| 53 | + con.execute(""" |
| 54 | + CREATE TABLE IF NOT EXISTS tick_data_migrations ( |
| 55 | + migration_id VARCHAR PRIMARY KEY, |
| 56 | + instrument VARCHAR, |
| 57 | + broker_tz VARCHAR, |
| 58 | + rows_affected BIGINT, |
| 59 | + backup_table VARCHAR, |
| 60 | + applied_at TIMESTAMP |
| 61 | + ) |
| 62 | + """) |
| 63 | + |
| 64 | + |
| 65 | +def already_applied(con) -> bool: |
| 66 | + r = con.execute( |
| 67 | + "SELECT COUNT(*) FROM tick_data_migrations WHERE migration_id = ?", |
| 68 | + [MIGRATION_ID], |
| 69 | + ).fetchone() |
| 70 | + return bool(r and r[0]) |
| 71 | + |
| 72 | + |
| 73 | +def sample_rows(con, n=8) -> list: |
| 74 | + return con.execute(f""" |
| 75 | + SELECT timestamp, price, bid, ask |
| 76 | + FROM tick_data |
| 77 | + WHERE instrument = 'XAUUSD' |
| 78 | + ORDER BY timestamp |
| 79 | + LIMIT {n} |
| 80 | + """).fetchall() |
| 81 | + |
| 82 | + |
| 83 | +def sample_post(con, broker_tz: str, n=8) -> list: |
| 84 | + return con.execute(f""" |
| 85 | + SELECT |
| 86 | + timestamp AS before, |
| 87 | + timezone('UTC', timezone(?, timestamp)) AS after, |
| 88 | + price, bid, ask |
| 89 | + FROM tick_data |
| 90 | + WHERE instrument = 'XAUUSD' |
| 91 | + ORDER BY timestamp |
| 92 | + LIMIT {n} |
| 93 | + """, [broker_tz]).fetchall() |
| 94 | + |
| 95 | + |
| 96 | +def main() -> int: |
| 97 | + ap = argparse.ArgumentParser() |
| 98 | + ap.add_argument("--confirm", action="store_true", help="Apply the UPDATE (default: dry-run)") |
| 99 | + ap.add_argument("--broker-tz", default=os.getenv("MT5_BROKER_TZ", "Europe/Athens")) |
| 100 | + ap.add_argument("--db", default=str(DUCKDB_PATH)) |
| 101 | + args = ap.parse_args() |
| 102 | + |
| 103 | + db_path = Path(args.db) |
| 104 | + if not db_path.exists(): |
| 105 | + print(f"DuckDB file not found: {db_path}") |
| 106 | + return 2 |
| 107 | + |
| 108 | + print(f"DB: {db_path}") |
| 109 | + print(f"broker_tz: {args.broker_tz}") |
| 110 | + print(f"migration_id: {MIGRATION_ID}") |
| 111 | + |
| 112 | + con = duckdb.connect(str(db_path)) |
| 113 | + |
| 114 | + ensure_ledger(con) |
| 115 | + if already_applied(con): |
| 116 | + print("This migration is already recorded in tick_data_migrations. Refusing to re-run.") |
| 117 | + return 0 |
| 118 | + |
| 119 | + total = con.execute("SELECT COUNT(*) FROM tick_data WHERE instrument='XAUUSD'").fetchone()[0] |
| 120 | + print(f"\nXAUUSD tick rows to migrate: {total:,}") |
| 121 | + |
| 122 | + print("\n--- BEFORE (first 8 rows) ---") |
| 123 | + for r in sample_rows(con): |
| 124 | + print(" ", r) |
| 125 | + |
| 126 | + print(f"\n--- COMPUTED AFTER (via timezone('UTC', timezone('{args.broker_tz}', ts))) ---") |
| 127 | + for r in sample_post(con, args.broker_tz): |
| 128 | + print(" ", r) |
| 129 | + |
| 130 | + if not args.confirm: |
| 131 | + print("\nDry-run. Re-run with --confirm to apply.") |
| 132 | + return 0 |
| 133 | + |
| 134 | + backup_table = f"tick_data_xauusd_backup_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}" |
| 135 | + print(f"\nBacking up to {backup_table} ...") |
| 136 | + con.execute(f"CREATE TABLE {backup_table} AS SELECT * FROM tick_data WHERE instrument='XAUUSD'") |
| 137 | + backup_count = con.execute(f"SELECT COUNT(*) FROM {backup_table}").fetchone()[0] |
| 138 | + print(f" backed up {backup_count:,} rows") |
| 139 | + assert backup_count == total, "Backup row count mismatch — aborting before UPDATE" |
| 140 | + |
| 141 | + print(f"\nApplying UPDATE ...") |
| 142 | + # DuckDB UPDATE semantics: timezone('UTC', timezone(tz, ts)) returns the |
| 143 | + # naive TIMESTAMP at UTC corresponding to interpreting `ts` as wall-clock |
| 144 | + # in `tz`. DST-aware via the IANA zone tables. |
| 145 | + con.execute(""" |
| 146 | + UPDATE tick_data |
| 147 | + SET timestamp = timezone('UTC', timezone(?, timestamp)) |
| 148 | + WHERE instrument = 'XAUUSD' |
| 149 | + """, [args.broker_tz]) |
| 150 | + # DuckDB doesn't expose row-count for UPDATE separately; the backup table |
| 151 | + # holds the authoritative pre-state count, which matches. |
| 152 | + rows = total |
| 153 | + |
| 154 | + print(f"\n--- AFTER UPDATE (first 8 rows) ---") |
| 155 | + for r in sample_rows(con): |
| 156 | + print(" ", r) |
| 157 | + |
| 158 | + new_min, new_max = con.execute( |
| 159 | + "SELECT MIN(timestamp), MAX(timestamp) FROM tick_data WHERE instrument='XAUUSD'" |
| 160 | + ).fetchone() |
| 161 | + print(f"\nNew XAUUSD tick range: {new_min} -> {new_max}") |
| 162 | + |
| 163 | + print(f"\nRecording migration in tick_data_migrations ledger ...") |
| 164 | + con.execute(""" |
| 165 | + INSERT INTO tick_data_migrations |
| 166 | + (migration_id, instrument, broker_tz, rows_affected, backup_table, applied_at) |
| 167 | + VALUES (?, ?, ?, ?, ?, ?) |
| 168 | + """, [MIGRATION_ID, "XAUUSD", args.broker_tz, rows, backup_table, datetime.now(timezone.utc)]) |
| 169 | + |
| 170 | + print(f"Done. backup={backup_table} rows_affected={rows:,}") |
| 171 | + print(f"Rollback: UPDATE tick_data SET timestamp = b.timestamp FROM {backup_table} b " |
| 172 | + f"WHERE tick_data.instrument='XAUUSD' AND tick_data.<other PK columns> = b.<same>; " |
| 173 | + f"DELETE FROM tick_data_migrations WHERE migration_id = '{MIGRATION_ID}';") |
| 174 | + return 0 |
| 175 | + |
| 176 | + |
| 177 | +if __name__ == "__main__": |
| 178 | + sys.exit(main()) |
0 commit comments