Files
stock_chart_site/web/lib/api.ts
tkrmagid 4fb6cec383 feat(phase-6): Next.js UI + TypeScript strict + 백엔드 mypy 설정
UI:
- web/lib/api.ts: 백엔드 모든 엔드포인트의 클라이언트 + 타입 (Symbol,
  ChartPayload, PredictResponse, LatestPredictionResponse, MetricsResponse,
  NewsResponse). NEXT_PUBLIC_API_BASE 자동 정규화.
- web/components/SearchBox: 디바운스 검색, seed_only 토글, trigram + prefix.
- web/components/StockChart: lightweight-charts 캔들 + 예측 overlay
  (median dashed + q10/q90 점선). base_date 에서 target_date 까지 이어 붙임.
- web/components/PredictionPanel: "예상차트 보기" 버튼 → POST /api/predict
  → user_triggered=TRUE 저장 → onResult 콜백으로 StockChart 에 반영.
  표로 +1/+3/+5거래일 direction, prob_up/flat/down, expected_return,
  ci_low~ci_high 표시.
- web/components/MetricsPanel: 최근 30일 hit_rate / mae.
- web/components/NewsList: 최근 뉴스 + 감성 라벨/점수.
- web/app/page.tsx: 검색 페이지.
- web/app/[code]/page.tsx: 종목 상세 (차트 + 패널 + 메트릭 + 뉴스).

TypeScript 보강 (사용자 요청 "typescript도 추가해서 나중에 수정하기 쉽게"):
- tsconfig.json: strict 외에 forceConsistentCasingInFileNames,
  noFallthroughCasesInSwitch, noImplicitOverride 추가.
- package.json: typecheck (tsc --noEmit), check (typecheck + lint) 스크립트,
  eslint + eslint-config-next 14.2.3.
- .eslintrc.json: next/core-web-vitals.
- package-lock.json 커밋 (재현 가능한 dep).

백엔드:
- pyproject.toml: [tool.mypy] 추가. strict_optional, no_implicit_optional,
  check_untyped_defs. 3rd-party stub 없는 pykrx/chronos 등은 ignore.

검증: `npx tsc --noEmit` 통과 (exit=0).

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

179 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[];
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)}` : ""
}`,
),
};