Kabutsurayuki commited on
Commit
3173979
·
1 Parent(s): fe50eff

feat: add HF Jobs-based data refresh flow

Browse files
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
README.md CHANGED
@@ -36,4 +36,8 @@ short_description: 米国市場の終値から翌日の日本市場業種ETFの
36
 
37
  ## 参考文献
38
 
39
- 中川ら (2026) 「部分空間正則化付き主成分分析を用いた日米業種リードラグ投資戦略」, SIG-FIN-036
 
 
 
 
 
36
 
37
  ## 参考文献
38
 
39
+ 中川ら (2026) 「部分空間正則化付き主成分分析を用いた日米業種リードラグ投資戦略」, SIG-FIN-036
40
+
41
+ ## Maintenance
42
+
43
+ Scheduled refresh setup is documented in `docs/hf-jobs-setup.md`.
app.py CHANGED
@@ -278,26 +278,12 @@ st.sidebar.caption(
278
  # ---------------------------------------------------------------------------
279
 
280
  if not _data_files_exist():
281
- st.info("初回起動: データをダウンロード中...(1〜2分かかります)")
282
- with st.spinner("データ取得中..."):
283
- try:
284
- from src.data.fetch_jp_etf import fetch_jp_etf
285
- from src.data.fetch_us_etf import fetch_us_etf
286
- from src.data.fetch_ff_factors import fetch_ff_factors
287
- from src.data.preprocess import preprocess_returns
288
- from src.data.build_calendar import build_calendar
289
-
290
- fetch_jp_etf()
291
- fetch_us_etf()
292
- fetch_ff_factors()
293
- us_ret, jp_ret = preprocess_returns()
294
- jp_cc = jp_ret.xs("cc", axis=1, level="ReturnType")
295
- build_calendar(us_ret.index, jp_cc.index)
296
- st.success("データ取得完了! ページを再読み込みします...")
297
- st.rerun()
298
- except Exception as e:
299
- st.error(f"データ取得に失敗しました: {e}")
300
- st.stop()
301
 
302
  # Load base data (cheap, cached)
303
  us_ret, jp_ret_full, date_map = load_data()
 
278
  # ---------------------------------------------------------------------------
279
 
280
  if not _data_files_exist():
281
+ st.error(
282
+ "Required data files are missing. Run the scheduled HF update job "
283
+ "to regenerate data for this Space."
284
+ )
285
+ st.caption("Setup instructions: docs/hf-jobs-setup.md")
286
+ st.stop()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
 
288
  # Load base data (cheap, cached)
289
  us_ret, jp_ret_full, date_map = load_data()
data/processed/jp_returns.csv CHANGED
The diff for this file is too large to render. See raw diff
 
data/processed/us_returns.csv CHANGED
The diff for this file is too large to render. See raw diff
 
data/raw/jp_etf_ohlc.csv CHANGED
The diff for this file is too large to render. See raw diff
 
data/raw/us_etf_ohlc.csv CHANGED
The diff for this file is too large to render. See raw diff
 
docs/hf-jobs-setup.md ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HF Jobs Setup
2
+
3
+ This Space stays read-only at runtime. Data refresh should happen through scheduled Hugging Face Jobs that update the Space repository and trigger a rebuild only when the data changed.
4
+
5
+ ## Prerequisites
6
+
7
+ - Hugging Face account with Jobs access
8
+ - `hf` CLI installed and logged in
9
+ - a token with permission to push to `spaces/Kabutsurayuki/sector-leadlag`
10
+
11
+ Official references:
12
+
13
+ - Jobs overview: https://huggingface.co/docs/huggingface_hub/guides/jobs
14
+ - Jobs CLI: https://huggingface.co/docs/huggingface_hub/guides/cli
15
+
16
+ ## Required secret
17
+
18
+ Create the scheduled jobs with:
19
+
20
+ - `--secrets HF_TOKEN`
21
+
22
+ The CLI docs describe this flag as the way to inject local secrets into a Job environment.
23
+
24
+ ## Schedule
25
+
26
+ The jobs are defined in UTC:
27
+
28
+ - JP close refresh: `45 6 * * *` -> `15:45 JST`
29
+ - US close refresh: `0 22 * * *` -> `07:00 JST`
30
+
31
+ ## Scheduled Job Commands
32
+
33
+ These commands clone the Space repo with token-backed auth, install dependencies, run the update script, and push only when the data changed.
34
+
35
+ ### JP close job
36
+
37
+ ```bash
38
+ hf jobs scheduled run "45 6 * * *" --secrets HF_TOKEN python:3.10 bash -lc "apt-get update && apt-get install -y git && git clone https://Kabutsurayuki:${HF_TOKEN}@huggingface.co/spaces/Kabutsurayuki/sector-leadlag repo && cd repo && pip install -r requirements.txt && python scripts/update_data.py --mode jp --commit --push"
39
+ ```
40
+
41
+ ### US close job
42
+
43
+ ```bash
44
+ hf jobs scheduled run "0 22 * * *" --secrets HF_TOKEN python:3.10 bash -lc "apt-get update && apt-get install -y git && git clone https://Kabutsurayuki:${HF_TOKEN}@huggingface.co/spaces/Kabutsurayuki/sector-leadlag repo && cd repo && pip install -r requirements.txt && python scripts/update_data.py --mode us --commit --push"
45
+ ```
46
+
47
+ ## Expected behavior
48
+
49
+ - If data refresh fails, the job exits non-zero and the current Space stays on the last good commit.
50
+ - If the raw or processed CSV files did not change, the script exits successfully without committing or rebuilding the Space.
51
+ - If data changed, the script commits only `data/raw` and `data/processed`, then pushes to `origin`.
52
+
53
+ ## Useful follow-up commands
54
+
55
+ ```bash
56
+ hf jobs scheduled ps
57
+ hf jobs scheduled inspect <scheduled_job_id>
58
+ hf jobs scheduled suspend <scheduled_job_id>
59
+ hf jobs scheduled resume <scheduled_job_id>
60
+ hf jobs scheduled delete <scheduled_job_id>
61
+ ```
scripts/update_data.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import logging
5
+ import subprocess
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ import pandas as pd
10
+
11
+
12
+ LOGGER = logging.getLogger("update_data")
13
+
14
+
15
+ def parse_args() -> argparse.Namespace:
16
+ parser = argparse.ArgumentParser(
17
+ description="Refresh market data and derived CSVs for the HF Space.",
18
+ )
19
+ parser.add_argument(
20
+ "--mode",
21
+ choices=("jp", "us", "all"),
22
+ required=True,
23
+ help="Which market data source to refresh before rebuilding derived files.",
24
+ )
25
+ parser.add_argument(
26
+ "--repo-dir",
27
+ type=Path,
28
+ default=Path(__file__).resolve().parents[1],
29
+ help="Path to the cloned Space repository.",
30
+ )
31
+ parser.add_argument(
32
+ "--commit",
33
+ action="store_true",
34
+ help="Create a git commit when data files changed.",
35
+ )
36
+ parser.add_argument(
37
+ "--push",
38
+ action="store_true",
39
+ help="Push the commit to origin. Requires --commit.",
40
+ )
41
+ parser.add_argument(
42
+ "--message",
43
+ help="Override the default git commit message.",
44
+ )
45
+ return parser.parse_args()
46
+
47
+
48
+ def ensure_repo_root(repo_dir: Path) -> Path:
49
+ repo_root = repo_dir.resolve()
50
+ expected = (
51
+ repo_root / "app.py",
52
+ repo_root / "src",
53
+ repo_root / "data",
54
+ )
55
+ missing = [str(path) for path in expected if not path.exists()]
56
+ if missing:
57
+ raise FileNotFoundError(
58
+ f"Repository root looks incomplete: missing {', '.join(missing)}"
59
+ )
60
+ return repo_root
61
+
62
+
63
+ def configure_import_path(repo_root: Path) -> None:
64
+ root_str = str(repo_root)
65
+ if root_str not in sys.path:
66
+ sys.path.insert(0, root_str)
67
+
68
+
69
+ def refresh_market_data(mode: str) -> None:
70
+ from src.data.build_calendar import build_calendar
71
+ from src.data.fetch_jp_etf import fetch_jp_etf
72
+ from src.data.fetch_us_etf import fetch_us_etf
73
+ from src.data.preprocess import preprocess_returns
74
+
75
+ if mode in {"jp", "all"}:
76
+ LOGGER.info("Refreshing JP ETF data")
77
+ fetch_jp_etf()
78
+
79
+ if mode in {"us", "all"}:
80
+ LOGGER.info("Refreshing US ETF data")
81
+ fetch_us_etf()
82
+
83
+ LOGGER.info("Rebuilding processed returns")
84
+ us_returns, jp_returns = preprocess_returns()
85
+ jp_cc = jp_returns.xs("cc", axis=1, level="ReturnType")
86
+
87
+ LOGGER.info("Rebuilding US-JP trading calendar map")
88
+ build_calendar(us_returns.index, jp_cc.index)
89
+
90
+
91
+ def validate_outputs(repo_root: Path) -> None:
92
+ # The Streamlit app expects these files and schemas to exist before startup.
93
+ raw_dir = repo_root / "data" / "raw"
94
+ processed_dir = repo_root / "data" / "processed"
95
+
96
+ required_raw = [
97
+ raw_dir / "jp_etf_ohlc.csv",
98
+ raw_dir / "us_etf_ohlc.csv",
99
+ ]
100
+ required_processed = [
101
+ processed_dir / "jp_returns.csv",
102
+ processed_dir / "us_returns.csv",
103
+ processed_dir / "us_jp_date_map.csv",
104
+ ]
105
+
106
+ for path in required_raw + required_processed:
107
+ if not path.exists():
108
+ raise FileNotFoundError(f"Required output file is missing: {path}")
109
+
110
+ us_returns = pd.read_csv(
111
+ processed_dir / "us_returns.csv",
112
+ index_col=0,
113
+ parse_dates=True,
114
+ )
115
+ jp_returns = pd.read_csv(
116
+ processed_dir / "jp_returns.csv",
117
+ header=[0, 1],
118
+ index_col=0,
119
+ parse_dates=True,
120
+ )
121
+ date_map = pd.read_csv(
122
+ processed_dir / "us_jp_date_map.csv",
123
+ parse_dates=["us_date", "jp_next_date"],
124
+ )
125
+
126
+ if us_returns.empty:
127
+ raise ValueError("us_returns.csv is empty")
128
+ if jp_returns.empty:
129
+ raise ValueError("jp_returns.csv is empty")
130
+ if date_map.empty:
131
+ raise ValueError("us_jp_date_map.csv is empty")
132
+
133
+ return_types = set(jp_returns.columns.get_level_values(1))
134
+ if {"cc", "oc"} - return_types:
135
+ raise ValueError("jp_returns.csv is missing expected return types")
136
+
137
+ if us_returns.index.isna().any():
138
+ raise ValueError("us_returns.csv contains null dates")
139
+ if jp_returns.index.isna().any():
140
+ raise ValueError("jp_returns.csv contains null dates")
141
+ if date_map[["us_date", "jp_next_date"]].isna().any().any():
142
+ raise ValueError("us_jp_date_map.csv contains null dates")
143
+
144
+ LOGGER.info(
145
+ "Validated outputs: latest US=%s latest JP=%s latest map=(%s -> %s)",
146
+ us_returns.index.max().date(),
147
+ jp_returns.index.max().date(),
148
+ date_map["us_date"].max().date(),
149
+ date_map["jp_next_date"].max().date(),
150
+ )
151
+
152
+
153
+ def run_git(repo_root: Path, *args: str) -> subprocess.CompletedProcess[str]:
154
+ return subprocess.run(
155
+ ["git", *args],
156
+ cwd=repo_root,
157
+ check=True,
158
+ text=True,
159
+ capture_output=True,
160
+ )
161
+
162
+
163
+ def read_git_config(repo_root: Path, key: str) -> str:
164
+ try:
165
+ result = run_git(repo_root, "config", "--get", key)
166
+ except subprocess.CalledProcessError:
167
+ return ""
168
+ return result.stdout.strip()
169
+
170
+
171
+ def ensure_git_identity(repo_root: Path) -> None:
172
+ if not read_git_config(repo_root, "user.name"):
173
+ run_git(repo_root, "config", "user.name", "hf-jobs-bot")
174
+ if not read_git_config(repo_root, "user.email"):
175
+ run_git(
176
+ repo_root,
177
+ "config",
178
+ "user.email",
179
+ "hf-jobs-bot@users.noreply.huggingface.co",
180
+ )
181
+
182
+
183
+ def data_diff_status(repo_root: Path) -> str:
184
+ result = run_git(repo_root, "status", "--short", "--", "data/raw", "data/processed")
185
+ return result.stdout.strip()
186
+
187
+
188
+ def default_commit_message(mode: str) -> str:
189
+ if mode == "jp":
190
+ return "chore: refresh JP market data"
191
+ if mode == "us":
192
+ return "chore: refresh US market data"
193
+ return "chore: refresh market data"
194
+
195
+
196
+ def commit_and_push(repo_root: Path, mode: str, message: str | None, push: bool) -> None:
197
+ ensure_git_identity(repo_root)
198
+ run_git(repo_root, "add", "data/raw", "data/processed")
199
+ run_git(repo_root, "commit", "-m", message or default_commit_message(mode))
200
+
201
+ if push:
202
+ LOGGER.info("Pushing updated data to origin")
203
+ run_git(repo_root, "push")
204
+
205
+
206
+ def main() -> int:
207
+ args = parse_args()
208
+ if args.push and not args.commit:
209
+ raise SystemExit("--push requires --commit")
210
+
211
+ logging.basicConfig(
212
+ level=logging.INFO,
213
+ format="%(asctime)s %(levelname)s %(message)s",
214
+ )
215
+
216
+ repo_root = ensure_repo_root(args.repo_dir)
217
+ configure_import_path(repo_root)
218
+
219
+ LOGGER.info("Repository root: %s", repo_root)
220
+ LOGGER.info("Refresh mode: %s", args.mode)
221
+
222
+ refresh_market_data(args.mode)
223
+ validate_outputs(repo_root)
224
+
225
+ diff = data_diff_status(repo_root)
226
+ if not diff:
227
+ LOGGER.info("No changes detected in data/raw or data/processed")
228
+ return 0
229
+
230
+ LOGGER.info("Changed files:\n%s", diff)
231
+ if args.commit:
232
+ commit_and_push(repo_root, args.mode, args.message, args.push)
233
+ else:
234
+ LOGGER.info("Changes detected, but --commit was not requested")
235
+
236
+ return 0
237
+
238
+
239
+ if __name__ == "__main__":
240
+ try:
241
+ raise SystemExit(main())
242
+ except Exception as exc:
243
+ LOGGER.exception("Data refresh failed: %s", exc)
244
+ raise SystemExit(1) from exc