File size: 9,218 Bytes
e610a2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Durable SQLite cache for Taiwan institutional investor flow rows."""

from __future__ import annotations

import sqlite3
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable

from data.institutional_flow import FLOW_COLUMNS

ROOT = Path(__file__).resolve().parent.parent
DEFAULT_CACHE_PATH = ROOT / "data" / "cache" / "institutional_flow.sqlite"

DAILY_TABLE = "institutional_daily"
STATUS_TABLE = "institutional_fetch_status"

DAILY_COLUMNS = [
    "date",
    "stock_no",
    *FLOW_COLUMNS,
    "institutional_available",
    "institutional_source",
    "institutional_as_of",
    "institutional_carry_forward",
]


def connect(db_path: str | Path) -> sqlite3.Connection:
    """Open a SQLite connection with dict-like row access."""
    Path(db_path).parent.mkdir(parents=True, exist_ok=True)
    conn = sqlite3.connect(db_path)
    conn.row_factory = sqlite3.Row
    return conn


def init_db(db: str | Path | sqlite3.Connection) -> sqlite3.Connection:
    """Create cache tables if needed and return an initialized connection."""
    conn = db if isinstance(db, sqlite3.Connection) else connect(db)
    conn.execute(
        f"""
        CREATE TABLE IF NOT EXISTS {DAILY_TABLE} (
            date TEXT NOT NULL,
            stock_no TEXT NOT NULL,
            foreign_buy INTEGER NOT NULL DEFAULT 0,
            foreign_sell INTEGER NOT NULL DEFAULT 0,
            foreign_net INTEGER NOT NULL DEFAULT 0,
            trust_buy INTEGER NOT NULL DEFAULT 0,
            trust_sell INTEGER NOT NULL DEFAULT 0,
            trust_net INTEGER NOT NULL DEFAULT 0,
            dealer_buy INTEGER NOT NULL DEFAULT 0,
            dealer_sell INTEGER NOT NULL DEFAULT 0,
            dealer_net INTEGER NOT NULL DEFAULT 0,
            institutional_buy INTEGER NOT NULL DEFAULT 0,
            institutional_sell INTEGER NOT NULL DEFAULT 0,
            institutional_net INTEGER NOT NULL DEFAULT 0,
            institutional_available INTEGER NOT NULL DEFAULT 1,
            institutional_source TEXT NOT NULL DEFAULT '',
            institutional_as_of TEXT,
            institutional_carry_forward INTEGER NOT NULL DEFAULT 0,
            updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (stock_no, date)
        )
        """
    )
    conn.execute(
        f"""
        CREATE TABLE IF NOT EXISTS {STATUS_TABLE} (
            source TEXT NOT NULL,
            date TEXT NOT NULL,
            status TEXT NOT NULL,
            fetched_at TEXT NOT NULL,
            row_count INTEGER NOT NULL DEFAULT 0,
            error TEXT NOT NULL DEFAULT '',
            PRIMARY KEY (source, date)
        )
        """
    )
    conn.execute(
        f"CREATE INDEX IF NOT EXISTS idx_{DAILY_TABLE}_date ON {DAILY_TABLE}(date)"
    )
    conn.commit()
    return conn


def _iso_date(value: Any) -> str:
    if hasattr(value, "isoformat"):
        return value.isoformat()
    return str(value).strip()


def _int_value(value: Any, default: int = 0) -> int:
    if value is None:
        return default
    if isinstance(value, bool):
        return int(value)
    try:
        return int(value)
    except (TypeError, ValueError):
        return default


def _row_values(row: dict[str, Any]) -> dict[str, Any]:
    values: dict[str, Any] = {
        "date": _iso_date(row["date"]),
        "stock_no": str(row["stock_no"]).replace(".TW", "").replace(".TWO", "").strip(),
        "institutional_available": _int_value(row.get("institutional_available", 1), 1),
        "institutional_source": str(row.get("institutional_source") or ""),
        "institutional_as_of": (
            _iso_date(row["institutional_as_of"])
            if row.get("institutional_as_of") is not None
            else None
        ),
        "institutional_carry_forward": _int_value(row.get("institutional_carry_forward", 0)),
    }
    for column in FLOW_COLUMNS:
        values[column] = _int_value(row.get(column, 0))
    return values


def upsert_daily_rows(
    db: str | Path | sqlite3.Connection,
    rows: Iterable[dict[str, Any]],
) -> int:
    """Insert or replace institutional daily rows; return rows written."""
    conn = init_db(db)
    prepared = [_row_values(row) for row in rows]
    if not prepared:
        return 0

    placeholders = ", ".join(f":{column}" for column in DAILY_COLUMNS)
    updates = ", ".join(
        f"{column}=excluded.{column}"
        for column in DAILY_COLUMNS
        if column not in {"date", "stock_no"}
    )
    conn.executemany(
        f"""
        INSERT INTO {DAILY_TABLE} ({", ".join(DAILY_COLUMNS)})
        VALUES ({placeholders})
        ON CONFLICT(stock_no, date) DO UPDATE SET
            {updates},
            updated_at=CURRENT_TIMESTAMP
        """,
        prepared,
    )
    conn.commit()
    return len(prepared)


def fetch_daily_rows(
    db: str | Path | sqlite3.Connection,
    stock_no: str,
    start_date: Any,
    end_date: Any,
) -> list[dict[str, Any]]:
    """Fetch cached institutional rows for one stock/date range, ascending."""
    conn = init_db(db)
    code = str(stock_no).replace(".TW", "").replace(".TWO", "").strip()
    cursor = conn.execute(
        f"""
        SELECT {", ".join(DAILY_COLUMNS)}
        FROM {DAILY_TABLE}
        WHERE stock_no = ? AND date >= ? AND date <= ?
        ORDER BY date ASC
        """,
        (code, _iso_date(start_date), _iso_date(end_date)),
    )
    return [_decode_daily_row(row) for row in cursor.fetchall()]


def fetch_recent_rows_by_code(
    db: str | Path | sqlite3.Connection = DEFAULT_CACHE_PATH,
    *,
    codes: Iterable[str] | None = None,
    lookback_days: int = 120,
    end_date: Any | None = None,
) -> dict[str, list[dict[str, Any]]]:
    """
    Return recent institutional rows grouped by stock code.

    This helper intentionally uses trading rows rather than calendar-day math:
    it first finds the latest available cache dates, then returns rows whose
    date is inside that latest-N trading-date set.  The hotspot scanner can use
    it without issuing TWSE/TPEx requests at request time.
    """
    conn = init_db(db)
    params: list[Any] = []
    where = ""
    if end_date is not None:
        where = "WHERE date <= ?"
        params.append(_iso_date(end_date))
    date_rows = conn.execute(
        f"""
        SELECT DISTINCT date
        FROM {DAILY_TABLE}
        {where}
        ORDER BY date DESC
        LIMIT ?
        """,
        (*params, max(1, int(lookback_days))),
    ).fetchall()
    dates = sorted(row["date"] for row in date_rows)
    if not dates:
        return {}

    code_list = [
        str(code).replace(".TW", "").replace(".TWO", "").strip()
        for code in (codes or [])
        if str(code).strip()
    ]
    query_params: list[Any] = [dates[0], dates[-1]]
    code_clause = ""
    if code_list:
        placeholders = ", ".join("?" for _ in code_list)
        code_clause = f" AND stock_no IN ({placeholders})"
        query_params.extend(code_list)

    cursor = conn.execute(
        f"""
        SELECT {", ".join(DAILY_COLUMNS)}
        FROM {DAILY_TABLE}
        WHERE date >= ? AND date <= ? {code_clause}
        ORDER BY stock_no ASC, date ASC
        """,
        query_params,
    )
    grouped: dict[str, list[dict[str, Any]]] = {}
    valid_dates = set(dates)
    for row in cursor.fetchall():
        decoded = _decode_daily_row(row)
        if decoded["date"] not in valid_dates:
            continue
        grouped.setdefault(decoded["stock_no"], []).append(decoded)
    return grouped


def _decode_daily_row(row: sqlite3.Row) -> dict[str, Any]:
    data = dict(row)
    data["institutional_available"] = bool(data["institutional_available"])
    data["institutional_carry_forward"] = bool(data["institutional_carry_forward"])
    return data


def upsert_fetch_status(
    db: str | Path | sqlite3.Connection,
    source: str,
    date: Any,
    status: str,
    *,
    row_count: int = 0,
    error: str = "",
    fetched_at: str | None = None,
) -> None:
    """Record the fetch outcome for a source/date pair."""
    conn = init_db(db)
    conn.execute(
        f"""
        INSERT INTO {STATUS_TABLE}
            (source, date, status, fetched_at, row_count, error)
        VALUES (?, ?, ?, ?, ?, ?)
        ON CONFLICT(source, date) DO UPDATE SET
            status=excluded.status,
            fetched_at=excluded.fetched_at,
            row_count=excluded.row_count,
            error=excluded.error
        """,
        (
            source,
            _iso_date(date),
            status,
            fetched_at or datetime.now(timezone.utc).isoformat(),
            _int_value(row_count),
            error or "",
        ),
    )
    conn.commit()


def get_fetch_status(
    db: str | Path | sqlite3.Connection,
    source: str,
    date: Any,
) -> dict[str, Any] | None:
    """Return the fetch status for a source/date pair, if present."""
    conn = init_db(db)
    row = conn.execute(
        f"""
        SELECT source, date, status, fetched_at, row_count, error
        FROM {STATUS_TABLE}
        WHERE source = ? AND date = ?
        """,
        (source, _iso_date(date)),
    ).fetchone()
    return dict(row) if row is not None else None