Files
stock_chart_site/web/lib/api.ts
tkrmagid 5e6ce11491 feat(weights): shadow chronos/lgbm 예측 + ensemble_weights 자동 보정
- ensemble.predict() 가 chronos_raw / lgbm_raw 를 함께 반환
- predict_and_store() 가 매 호출마다 3종 행 적재:
    model='ensemble' (user_triggered=인자)
    model='chronos'  (user_triggered=FALSE, shadow)
    model='lgbm'     (user_triggered=FALSE, shadow)
- retrain_weekly.adjust_weights(): 최근 30일 prediction_outcomes 의
  chronos vs lgbm hit_rate 로 ensemble_weights upsert
    w_chronos = clamp(0.1, hr_c/(hr_c+hr_l), 0.9), w_lgbm = 1 - w_chronos
  모델별 표본 < 10 이면 기본값(0.6/0.4) 유지
- API 응답에 saved_shadow_ids 추가 (TS 타입도 동기화)
- README: 동작 모델 메모 섹션을 실제 구현과 일치하도록 갱신

리뷰어 지적 3번 (ensemble_weights 가 영원히 갱신 안됨, upsert_weights 미호출) 해결.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-20 16:27:21 +09:00

180 lines
4.4 KiB
TypeScript

// Backend API client.
// NEXT_PUBLIC_API_BASE 는 docker-compose 에서 http://localhost:8000 으로 주입됨.
const RAW_BASE = process.env.NEXT_PUBLIC_API_BASE ?? "http://localhost:8000";
export const API_BASE = RAW_BASE.replace(/\/$/, "");
export type Symbol = {
code: string;
name: string;
market: string;
sector: string | null;
is_seed: boolean;
};
export type SymbolSearch = {
q: string;
count: number;
items: Symbol[];
};
export type OhlcvPoint = {
date: string;
open: number | null;
high: number | null;
low: number | null;
close: number | null;
volume: number | null;
};
export type SentimentPoint = {
date: string;
n_articles: number;
mean_score: number | null;
weighted_score: number | null;
};
export type TradingValuePoint = {
date: string;
foreign_net: number | null;
institution_net: number | null;
individual_net: number | null;
};
export type ChartPayload = {
code: string;
name: string;
market: string;
range: { from: string; to: string };
ohlcv: OhlcvPoint[];
sentiment: SentimentPoint[];
trading_value: TradingValuePoint[];
};
export type PredictionStep = {
horizon: number;
target_idx?: number;
point_close: number;
ci_low: number;
ci_high: number;
prob_up: number;
prob_flat: number;
prob_down: number;
direction: "up" | "flat" | "down";
expected_return: number;
target_date?: string;
};
export type PredictResponse = {
code: string;
base_date: string;
base_close: number;
sources_used: string[];
steps: PredictionStep[];
saved_prediction_ids: number[];
saved_shadow_ids?: { chronos: number[]; lgbm: number[] };
user_triggered: boolean;
};
export type LatestPredictionStep = {
predicted_at: string | null;
target_date: string;
horizon: number;
direction: "up" | "flat" | "down" | string;
prob_up: number | null;
prob_flat: number | null;
prob_down: number | null;
expected_return: number | null;
point_close: number | null;
ci_low: number | null;
ci_high: number | null;
user_triggered: boolean;
features_snapshot: unknown;
};
export type LatestPredictionResponse = {
code: string;
name?: string;
found: boolean;
base_date?: string;
base_close?: number | null;
steps: LatestPredictionStep[];
};
export type MetricsRow = {
model: string;
horizon: number;
n: number;
hit_rate: number | null;
mae: number | null;
};
export type MetricsResponse = {
code?: string;
name?: string;
window_days: number;
range: { from: string; to: string };
by_model_horizon: MetricsRow[];
};
export type NewsItem = {
source: string;
published_at: string | null;
title: string;
url: string;
sentiment_score: number | null;
sentiment_label: string | null;
};
export type NewsResponse = {
code: string;
name: string;
count: number;
items: NewsItem[];
};
async function getJson<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(`${API_BASE}${path}`, {
...init,
headers: {
Accept: "application/json",
...(init?.headers ?? {}),
},
cache: "no-store",
});
if (!res.ok) {
const text = await res.text().catch(() => "");
throw new Error(`API ${path}${res.status} ${text || res.statusText}`);
}
return (await res.json()) as T;
}
export const api = {
search: (q: string, seedOnly = false, limit = 20) =>
getJson<SymbolSearch>(
`/api/symbols/search?q=${encodeURIComponent(q)}&limit=${limit}&seed_only=${seedOnly}`,
),
getSymbol: (code: string) => getJson<Symbol>(`/api/symbols/${encodeURIComponent(code)}`),
getChart: (code: string, days = 180) =>
getJson<ChartPayload>(`/api/chart/${encodeURIComponent(code)}?days=${days}`),
predict: (code: string, horizons = "1,3,5") =>
getJson<PredictResponse>(
`/api/predict/${encodeURIComponent(code)}?horizons=${encodeURIComponent(horizons)}`,
{ method: "POST" },
),
latestPrediction: (code: string) =>
getJson<LatestPredictionResponse>(`/api/predict/${encodeURIComponent(code)}/latest`),
metrics: (code: string, windowDays = 30) =>
getJson<MetricsResponse>(
`/api/metrics/${encodeURIComponent(code)}?window_days=${windowDays}`,
),
overallMetrics: (windowDays = 30) =>
getJson<MetricsResponse>(`/api/metrics?window_days=${windowDays}`),
news: (code: string, limit = 20, source?: string) =>
getJson<NewsResponse>(
`/api/news/${encodeURIComponent(code)}?limit=${limit}${
source ? `&source=${encodeURIComponent(source)}` : ""
}`,
),
};