|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import csv |
| 4 | +import datetime as dt |
| 5 | +from dataclasses import dataclass |
| 6 | +from pathlib import Path |
| 7 | + |
| 8 | + |
| 9 | +DATE_COLUMNS = ("date", "as_of") |
| 10 | + |
| 11 | + |
| 12 | +@dataclass(frozen=True) |
| 13 | +class PriceRow: |
| 14 | + date: dt.date |
| 15 | + symbol: str |
| 16 | + close: float |
| 17 | + |
| 18 | + |
| 19 | +@dataclass(frozen=True) |
| 20 | +class PriceExtractionSummary: |
| 21 | + source: str |
| 22 | + target: str |
| 23 | + input_rows: int |
| 24 | + output_rows: int |
| 25 | + symbols: list[str] |
| 26 | + start_date: str | None |
| 27 | + end_date: str | None |
| 28 | + |
| 29 | + |
| 30 | +def parse_price_date(value: object) -> dt.date: |
| 31 | + text = str(value or "").strip() |
| 32 | + if not text: |
| 33 | + raise ValueError("price date is required") |
| 34 | + if text.endswith("Z"): |
| 35 | + text = f"{text[:-1]}+00:00" |
| 36 | + try: |
| 37 | + return dt.date.fromisoformat(text) |
| 38 | + except ValueError: |
| 39 | + return dt.datetime.fromisoformat(text).date() |
| 40 | + |
| 41 | + |
| 42 | +def _resolve_date_column(fieldnames: list[str] | None) -> str: |
| 43 | + fields = set(fieldnames or []) |
| 44 | + for column in DATE_COLUMNS: |
| 45 | + if column in fields: |
| 46 | + return column |
| 47 | + expected = " or ".join(DATE_COLUMNS) |
| 48 | + raise ValueError(f"price history missing date column: expected {expected}") |
| 49 | + |
| 50 | + |
| 51 | +def _normalize_symbols(symbols: list[str] | tuple[str, ...] | set[str] | str) -> list[str]: |
| 52 | + if isinstance(symbols, str): |
| 53 | + raw_symbols = symbols.split(",") |
| 54 | + else: |
| 55 | + raw_symbols = list(symbols) |
| 56 | + normalized: list[str] = [] |
| 57 | + for symbol in raw_symbols: |
| 58 | + text = str(symbol or "").strip().upper() |
| 59 | + if text and text not in normalized: |
| 60 | + normalized.append(text) |
| 61 | + if not normalized: |
| 62 | + raise ValueError("at least one symbol is required") |
| 63 | + return normalized |
| 64 | + |
| 65 | + |
| 66 | +def read_price_rows( |
| 67 | + path: str | Path, |
| 68 | + *, |
| 69 | + symbols: list[str] | tuple[str, ...] | set[str] | str, |
| 70 | + start_date: str | None = None, |
| 71 | + end_date: str | None = None, |
| 72 | +) -> list[PriceRow]: |
| 73 | + selected_symbols = set(_normalize_symbols(symbols)) |
| 74 | + start = parse_price_date(start_date) if start_date else None |
| 75 | + end = parse_price_date(end_date) if end_date else None |
| 76 | + rows_by_key: dict[tuple[dt.date, str], PriceRow] = {} |
| 77 | + |
| 78 | + with Path(path).open(newline="", encoding="utf-8") as handle: |
| 79 | + reader = csv.DictReader(handle) |
| 80 | + required = {"symbol", "close"} |
| 81 | + missing = required.difference(reader.fieldnames or ()) |
| 82 | + if missing: |
| 83 | + raise ValueError(f"price history missing columns: {', '.join(sorted(missing))}") |
| 84 | + date_column = _resolve_date_column(reader.fieldnames) |
| 85 | + |
| 86 | + for raw_row in reader: |
| 87 | + symbol = str(raw_row["symbol"]).strip().upper() |
| 88 | + if symbol not in selected_symbols: |
| 89 | + continue |
| 90 | + row_date = parse_price_date(raw_row[date_column]) |
| 91 | + if start and row_date < start: |
| 92 | + continue |
| 93 | + if end and row_date > end: |
| 94 | + continue |
| 95 | + close = float(raw_row["close"]) |
| 96 | + if close <= 0: |
| 97 | + raise ValueError(f"close must be positive for {symbol} on {row_date.isoformat()}") |
| 98 | + rows_by_key[(row_date, symbol)] = PriceRow(date=row_date, symbol=symbol, close=close) |
| 99 | + |
| 100 | + return [rows_by_key[key] for key in sorted(rows_by_key)] |
| 101 | + |
| 102 | + |
| 103 | +def write_filtered_price_history( |
| 104 | + source: str | Path, |
| 105 | + target: str | Path, |
| 106 | + *, |
| 107 | + symbols: list[str] | tuple[str, ...] | set[str] | str, |
| 108 | + start_date: str | None = None, |
| 109 | + end_date: str | None = None, |
| 110 | +) -> PriceExtractionSummary: |
| 111 | + selected_symbols = _normalize_symbols(symbols) |
| 112 | + start = parse_price_date(start_date) if start_date else None |
| 113 | + end = parse_price_date(end_date) if end_date else None |
| 114 | + rows_by_key: dict[tuple[dt.date, str], PriceRow] = {} |
| 115 | + input_rows = 0 |
| 116 | + |
| 117 | + with Path(source).open(newline="", encoding="utf-8") as handle: |
| 118 | + reader = csv.DictReader(handle) |
| 119 | + required = {"symbol", "close"} |
| 120 | + missing = required.difference(reader.fieldnames or ()) |
| 121 | + if missing: |
| 122 | + raise ValueError(f"price history missing columns: {', '.join(sorted(missing))}") |
| 123 | + date_column = _resolve_date_column(reader.fieldnames) |
| 124 | + |
| 125 | + for raw_row in reader: |
| 126 | + input_rows += 1 |
| 127 | + symbol = str(raw_row["symbol"]).strip().upper() |
| 128 | + if symbol not in selected_symbols: |
| 129 | + continue |
| 130 | + row_date = parse_price_date(raw_row[date_column]) |
| 131 | + if start and row_date < start: |
| 132 | + continue |
| 133 | + if end and row_date > end: |
| 134 | + continue |
| 135 | + close = float(raw_row["close"]) |
| 136 | + if close <= 0: |
| 137 | + raise ValueError(f"close must be positive for {symbol} on {row_date.isoformat()}") |
| 138 | + rows_by_key[(row_date, symbol)] = PriceRow(date=row_date, symbol=symbol, close=close) |
| 139 | + |
| 140 | + output_path = Path(target) |
| 141 | + output_path.parent.mkdir(parents=True, exist_ok=True) |
| 142 | + rows = [rows_by_key[key] for key in sorted(rows_by_key)] |
| 143 | + with output_path.open("w", newline="", encoding="utf-8") as handle: |
| 144 | + writer = csv.DictWriter(handle, fieldnames=["date", "symbol", "close"]) |
| 145 | + writer.writeheader() |
| 146 | + for row in rows: |
| 147 | + writer.writerow({"date": row.date.isoformat(), "symbol": row.symbol, "close": row.close}) |
| 148 | + |
| 149 | + return PriceExtractionSummary( |
| 150 | + source=str(source), |
| 151 | + target=str(target), |
| 152 | + input_rows=input_rows, |
| 153 | + output_rows=len(rows), |
| 154 | + symbols=selected_symbols, |
| 155 | + start_date=start.isoformat() if start else None, |
| 156 | + end_date=end.isoformat() if end else None, |
| 157 | + ) |
0 commit comments