feat: add backtest pages and API endpoints
- Backtest list/create page with strategy-specific params - Backtest result page with metrics, holdings, transactions - Polling for async backtest status Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
parent
99bd08c68a
commit
1a3a0cf5a0
428
frontend/src/app/backtest/[id]/page.tsx
Normal file
428
frontend/src/app/backtest/[id]/page.tsx
Normal file
@ -0,0 +1,428 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useEffect, useState, useCallback } from 'react';
|
||||||
|
import { useRouter, useParams } from 'next/navigation';
|
||||||
|
import Sidebar from '@/components/layout/Sidebar';
|
||||||
|
import Header from '@/components/layout/Header';
|
||||||
|
import { api } from '@/lib/api';
|
||||||
|
|
||||||
|
interface User {
|
||||||
|
id: number;
|
||||||
|
username: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BacktestMetrics {
|
||||||
|
total_return: number;
|
||||||
|
cagr: number;
|
||||||
|
mdd: number;
|
||||||
|
sharpe_ratio: number;
|
||||||
|
volatility: number;
|
||||||
|
benchmark_return: number;
|
||||||
|
excess_return: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BacktestDetail {
|
||||||
|
id: number;
|
||||||
|
strategy_type: string;
|
||||||
|
strategy_params: Record<string, unknown>;
|
||||||
|
start_date: string;
|
||||||
|
end_date: string;
|
||||||
|
rebalance_period: string;
|
||||||
|
initial_capital: number;
|
||||||
|
commission_rate: number;
|
||||||
|
slippage_rate: number;
|
||||||
|
benchmark: string;
|
||||||
|
status: string;
|
||||||
|
created_at: string;
|
||||||
|
completed_at: string | null;
|
||||||
|
error_message: string | null;
|
||||||
|
result: BacktestMetrics | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface EquityCurvePoint {
|
||||||
|
date: string;
|
||||||
|
portfolio_value: number;
|
||||||
|
benchmark_value: number;
|
||||||
|
drawdown: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface HoldingItem {
|
||||||
|
ticker: string;
|
||||||
|
name: string;
|
||||||
|
weight: number;
|
||||||
|
shares: number;
|
||||||
|
price: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RebalanceHoldings {
|
||||||
|
rebalance_date: string;
|
||||||
|
holdings: HoldingItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TransactionItem {
|
||||||
|
id: number;
|
||||||
|
date: string;
|
||||||
|
ticker: string;
|
||||||
|
action: string;
|
||||||
|
shares: number;
|
||||||
|
price: number;
|
||||||
|
commission: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const strategyLabels: Record<string, string> = {
|
||||||
|
multi_factor: '멀티 팩터',
|
||||||
|
quality: '슈퍼 퀄리티',
|
||||||
|
value_momentum: '밸류 모멘텀',
|
||||||
|
};
|
||||||
|
|
||||||
|
const periodLabels: Record<string, string> = {
|
||||||
|
monthly: '월별',
|
||||||
|
quarterly: '분기별',
|
||||||
|
semi_annual: '반기별',
|
||||||
|
annual: '연별',
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function BacktestDetailPage() {
|
||||||
|
const router = useRouter();
|
||||||
|
const params = useParams();
|
||||||
|
const backtestId = params.id as string;
|
||||||
|
|
||||||
|
const [user, setUser] = useState<User | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [backtest, setBacktest] = useState<BacktestDetail | null>(null);
|
||||||
|
const [equityCurve, setEquityCurve] = useState<EquityCurvePoint[]>([]);
|
||||||
|
const [holdings, setHoldings] = useState<RebalanceHoldings[]>([]);
|
||||||
|
const [transactions, setTransactions] = useState<TransactionItem[]>([]);
|
||||||
|
const [activeTab, setActiveTab] = useState<'holdings' | 'transactions'>('holdings');
|
||||||
|
const [selectedRebalance, setSelectedRebalance] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const fetchBacktest = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const data = await api.get<BacktestDetail>(`/api/backtest/${backtestId}`);
|
||||||
|
setBacktest(data);
|
||||||
|
|
||||||
|
if (data.status === 'completed') {
|
||||||
|
const [curveData, holdingsData, txData] = await Promise.all([
|
||||||
|
api.get<EquityCurvePoint[]>(`/api/backtest/${backtestId}/equity-curve`),
|
||||||
|
api.get<RebalanceHoldings[]>(`/api/backtest/${backtestId}/holdings`),
|
||||||
|
api.get<TransactionItem[]>(`/api/backtest/${backtestId}/transactions`),
|
||||||
|
]);
|
||||||
|
setEquityCurve(curveData);
|
||||||
|
setHoldings(holdingsData);
|
||||||
|
setTransactions(txData);
|
||||||
|
if (holdingsData.length > 0) {
|
||||||
|
setSelectedRebalance(holdingsData[holdingsData.length - 1].rebalance_date);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to fetch backtest:', err);
|
||||||
|
}
|
||||||
|
}, [backtestId]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const init = async () => {
|
||||||
|
try {
|
||||||
|
const userData = await api.getCurrentUser() as User;
|
||||||
|
setUser(userData);
|
||||||
|
await fetchBacktest();
|
||||||
|
} catch {
|
||||||
|
router.push('/login');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
init();
|
||||||
|
}, [router, fetchBacktest]);
|
||||||
|
|
||||||
|
// Poll for status if pending/running
|
||||||
|
useEffect(() => {
|
||||||
|
if (!backtest) return;
|
||||||
|
if (backtest.status === 'pending' || backtest.status === 'running') {
|
||||||
|
const interval = setInterval(() => {
|
||||||
|
fetchBacktest();
|
||||||
|
}, 3000);
|
||||||
|
return () => clearInterval(interval);
|
||||||
|
}
|
||||||
|
}, [backtest, fetchBacktest]);
|
||||||
|
|
||||||
|
const formatNumber = (value: number | null | undefined, decimals: number = 2) => {
|
||||||
|
if (value === null || value === undefined) return '-';
|
||||||
|
return value.toFixed(decimals);
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatCurrency = (value: number) => {
|
||||||
|
return new Intl.NumberFormat('ko-KR').format(value);
|
||||||
|
};
|
||||||
|
|
||||||
|
const getStatusBadge = (status: string) => {
|
||||||
|
const styles: Record<string, string> = {
|
||||||
|
pending: 'bg-yellow-100 text-yellow-800',
|
||||||
|
running: 'bg-blue-100 text-blue-800',
|
||||||
|
completed: 'bg-green-100 text-green-800',
|
||||||
|
failed: 'bg-red-100 text-red-800',
|
||||||
|
};
|
||||||
|
const labels: Record<string, string> = {
|
||||||
|
pending: '대기중',
|
||||||
|
running: '실행중',
|
||||||
|
completed: '완료',
|
||||||
|
failed: '실패',
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<span className={`px-2 py-1 rounded text-xs ${styles[status] || 'bg-gray-100'}`}>
|
||||||
|
{labels[status] || status}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center">
|
||||||
|
<div className="text-gray-500">Loading...</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!backtest) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center">
|
||||||
|
<div className="text-gray-500">Backtest not found</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const selectedHoldings = holdings.find((h) => h.rebalance_date === selectedRebalance);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen">
|
||||||
|
<Sidebar />
|
||||||
|
<div className="flex-1">
|
||||||
|
<Header username={user?.username} />
|
||||||
|
<main className="p-6">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex justify-between items-center mb-6">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold text-gray-800">
|
||||||
|
{strategyLabels[backtest.strategy_type] || backtest.strategy_type} 백테스트
|
||||||
|
</h1>
|
||||||
|
<p className="text-sm text-gray-500">
|
||||||
|
{backtest.start_date} ~ {backtest.end_date} | {periodLabels[backtest.rebalance_period]}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
{getStatusBadge(backtest.status)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Status Messages */}
|
||||||
|
{backtest.status === 'pending' && (
|
||||||
|
<div className="bg-yellow-50 border border-yellow-200 text-yellow-800 px-4 py-3 rounded mb-6">
|
||||||
|
백테스트가 대기 중입니다...
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{backtest.status === 'running' && (
|
||||||
|
<div className="bg-blue-50 border border-blue-200 text-blue-800 px-4 py-3 rounded mb-6">
|
||||||
|
백테스트가 실행 중입니다... 잠시만 기다려주세요.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{backtest.status === 'failed' && (
|
||||||
|
<div className="bg-red-50 border border-red-200 text-red-800 px-4 py-3 rounded mb-6">
|
||||||
|
백테스트 실패: {backtest.error_message}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Results (only show when completed) */}
|
||||||
|
{backtest.status === 'completed' && backtest.result && (
|
||||||
|
<>
|
||||||
|
{/* Metrics Cards */}
|
||||||
|
<div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4 mb-6">
|
||||||
|
<div className="bg-white rounded-lg shadow p-4">
|
||||||
|
<div className="text-sm text-gray-500">총 수익률</div>
|
||||||
|
<div className={`text-xl font-bold ${backtest.result.total_return >= 0 ? 'text-green-600' : 'text-red-600'}`}>
|
||||||
|
{formatNumber(backtest.result.total_return)}%
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="bg-white rounded-lg shadow p-4">
|
||||||
|
<div className="text-sm text-gray-500">CAGR</div>
|
||||||
|
<div className={`text-xl font-bold ${backtest.result.cagr >= 0 ? 'text-green-600' : 'text-red-600'}`}>
|
||||||
|
{formatNumber(backtest.result.cagr)}%
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="bg-white rounded-lg shadow p-4">
|
||||||
|
<div className="text-sm text-gray-500">MDD</div>
|
||||||
|
<div className="text-xl font-bold text-red-600">
|
||||||
|
{formatNumber(backtest.result.mdd)}%
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="bg-white rounded-lg shadow p-4">
|
||||||
|
<div className="text-sm text-gray-500">샤프 비율</div>
|
||||||
|
<div className="text-xl font-bold text-gray-800">
|
||||||
|
{formatNumber(backtest.result.sharpe_ratio)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="bg-white rounded-lg shadow p-4">
|
||||||
|
<div className="text-sm text-gray-500">변동성</div>
|
||||||
|
<div className="text-xl font-bold text-gray-800">
|
||||||
|
{formatNumber(backtest.result.volatility)}%
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="bg-white rounded-lg shadow p-4">
|
||||||
|
<div className="text-sm text-gray-500">벤치마크</div>
|
||||||
|
<div className={`text-xl font-bold ${backtest.result.benchmark_return >= 0 ? 'text-green-600' : 'text-red-600'}`}>
|
||||||
|
{formatNumber(backtest.result.benchmark_return)}%
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="bg-white rounded-lg shadow p-4">
|
||||||
|
<div className="text-sm text-gray-500">초과 수익</div>
|
||||||
|
<div className={`text-xl font-bold ${backtest.result.excess_return >= 0 ? 'text-green-600' : 'text-red-600'}`}>
|
||||||
|
{formatNumber(backtest.result.excess_return)}%
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Equity Curve */}
|
||||||
|
<div className="bg-white rounded-lg shadow p-6 mb-6">
|
||||||
|
<h2 className="text-lg font-semibold mb-4">자산 추이</h2>
|
||||||
|
<div className="h-64 flex items-center justify-center text-gray-400">
|
||||||
|
{equityCurve.length > 0 ? (
|
||||||
|
<div className="w-full">
|
||||||
|
<div className="flex justify-between text-sm text-gray-500 mb-2">
|
||||||
|
<span>시작: {formatCurrency(equityCurve[0]?.portfolio_value || 0)}원</span>
|
||||||
|
<span>종료: {formatCurrency(equityCurve[equityCurve.length - 1]?.portfolio_value || 0)}원</span>
|
||||||
|
</div>
|
||||||
|
<div className="text-center text-gray-400">
|
||||||
|
(차트 라이브러리 연동 필요 - {equityCurve.length}개 데이터 포인트)
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
'데이터 없음'
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tabs */}
|
||||||
|
<div className="bg-white rounded-lg shadow">
|
||||||
|
<div className="border-b">
|
||||||
|
<nav className="flex">
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('holdings')}
|
||||||
|
className={`px-6 py-3 text-sm font-medium ${
|
||||||
|
activeTab === 'holdings'
|
||||||
|
? 'border-b-2 border-blue-600 text-blue-600'
|
||||||
|
: 'text-gray-500 hover:text-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
리밸런싱 이력
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('transactions')}
|
||||||
|
className={`px-6 py-3 text-sm font-medium ${
|
||||||
|
activeTab === 'transactions'
|
||||||
|
? 'border-b-2 border-blue-600 text-blue-600'
|
||||||
|
: 'text-gray-500 hover:text-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
거래 내역
|
||||||
|
</button>
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Holdings Tab */}
|
||||||
|
{activeTab === 'holdings' && (
|
||||||
|
<div className="p-4">
|
||||||
|
<div className="mb-4">
|
||||||
|
<label htmlFor="rebalance-date" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
리밸런싱 날짜
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
id="rebalance-date"
|
||||||
|
value={selectedRebalance || ''}
|
||||||
|
onChange={(e) => setSelectedRebalance(e.target.value)}
|
||||||
|
className="px-3 py-2 border rounded"
|
||||||
|
>
|
||||||
|
{holdings.map((h) => (
|
||||||
|
<option key={h.rebalance_date} value={h.rebalance_date}>
|
||||||
|
{h.rebalance_date}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
{selectedHoldings && (
|
||||||
|
<table className="w-full">
|
||||||
|
<thead className="bg-gray-50">
|
||||||
|
<tr>
|
||||||
|
<th scope="col" className="px-4 py-3 text-left text-sm font-medium text-gray-600">종목</th>
|
||||||
|
<th scope="col" className="px-4 py-3 text-right text-sm font-medium text-gray-600">비중</th>
|
||||||
|
<th scope="col" className="px-4 py-3 text-right text-sm font-medium text-gray-600">수량</th>
|
||||||
|
<th scope="col" className="px-4 py-3 text-right text-sm font-medium text-gray-600">가격</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y">
|
||||||
|
{selectedHoldings.holdings.map((h) => (
|
||||||
|
<tr key={h.ticker} className="hover:bg-gray-50">
|
||||||
|
<td className="px-4 py-3">
|
||||||
|
<div className="font-medium">{h.ticker}</div>
|
||||||
|
<div className="text-xs text-gray-500">{h.name}</div>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-right">{formatNumber(h.weight)}%</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-right">{formatCurrency(h.shares)}</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-right">{formatCurrency(h.price)}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Transactions Tab */}
|
||||||
|
{activeTab === 'transactions' && (
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full">
|
||||||
|
<thead className="bg-gray-50">
|
||||||
|
<tr>
|
||||||
|
<th scope="col" className="px-4 py-3 text-left text-sm font-medium text-gray-600">날짜</th>
|
||||||
|
<th scope="col" className="px-4 py-3 text-left text-sm font-medium text-gray-600">종목</th>
|
||||||
|
<th scope="col" className="px-4 py-3 text-center text-sm font-medium text-gray-600">구분</th>
|
||||||
|
<th scope="col" className="px-4 py-3 text-right text-sm font-medium text-gray-600">수량</th>
|
||||||
|
<th scope="col" className="px-4 py-3 text-right text-sm font-medium text-gray-600">가격</th>
|
||||||
|
<th scope="col" className="px-4 py-3 text-right text-sm font-medium text-gray-600">수수료</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y">
|
||||||
|
{transactions.map((t) => (
|
||||||
|
<tr key={t.id} className="hover:bg-gray-50">
|
||||||
|
<td className="px-4 py-3 text-sm">{t.date}</td>
|
||||||
|
<td className="px-4 py-3 text-sm font-medium">{t.ticker}</td>
|
||||||
|
<td className="px-4 py-3 text-center">
|
||||||
|
<span className={`px-2 py-1 rounded text-xs ${
|
||||||
|
t.action === 'buy' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
|
||||||
|
}`}>
|
||||||
|
{t.action === 'buy' ? '매수' : '매도'}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-right">{formatCurrency(t.shares)}</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-right">{formatCurrency(t.price)}</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-right">{formatCurrency(t.commission)}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
{transactions.length === 0 && (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={6} className="px-4 py-8 text-center text-gray-500">
|
||||||
|
거래 내역이 없습니다.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
502
frontend/src/app/backtest/page.tsx
Normal file
502
frontend/src/app/backtest/page.tsx
Normal file
@ -0,0 +1,502 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { useRouter } from 'next/navigation';
|
||||||
|
import Link from 'next/link';
|
||||||
|
import Sidebar from '@/components/layout/Sidebar';
|
||||||
|
import Header from '@/components/layout/Header';
|
||||||
|
import { api } from '@/lib/api';
|
||||||
|
|
||||||
|
interface User {
|
||||||
|
id: number;
|
||||||
|
username: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BacktestListItem {
|
||||||
|
id: number;
|
||||||
|
strategy_type: string;
|
||||||
|
start_date: string;
|
||||||
|
end_date: string;
|
||||||
|
rebalance_period: string;
|
||||||
|
status: string;
|
||||||
|
created_at: string;
|
||||||
|
total_return: number | null;
|
||||||
|
cagr: number | null;
|
||||||
|
mdd: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const strategyOptions = [
|
||||||
|
{ value: 'multi_factor', label: '멀티 팩터' },
|
||||||
|
{ value: 'quality', label: '슈퍼 퀄리티' },
|
||||||
|
{ value: 'value_momentum', label: '밸류 모멘텀' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const periodOptions = [
|
||||||
|
{ value: 'monthly', label: '월별' },
|
||||||
|
{ value: 'quarterly', label: '분기별' },
|
||||||
|
{ value: 'semi_annual', label: '반기별' },
|
||||||
|
{ value: 'annual', label: '연별' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function BacktestPage() {
|
||||||
|
const router = useRouter();
|
||||||
|
const [user, setUser] = useState<User | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [backtests, setBacktests] = useState<BacktestListItem[]>([]);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Form state
|
||||||
|
const [strategyType, setStrategyType] = useState('multi_factor');
|
||||||
|
const [startDate, setStartDate] = useState('2020-01-01');
|
||||||
|
const [endDate, setEndDate] = useState('2024-12-31');
|
||||||
|
const [rebalancePeriod, setRebalancePeriod] = useState('quarterly');
|
||||||
|
const [initialCapital, setInitialCapital] = useState(100000000);
|
||||||
|
const [topN, setTopN] = useState(30);
|
||||||
|
const [showAdvanced, setShowAdvanced] = useState(false);
|
||||||
|
const [commissionRate, setCommissionRate] = useState(0.00015);
|
||||||
|
const [slippageRate, setSlippageRate] = useState(0.001);
|
||||||
|
|
||||||
|
// Strategy-specific params
|
||||||
|
const [valueWeight, setValueWeight] = useState(0.33);
|
||||||
|
const [qualityWeight, setQualityWeight] = useState(0.33);
|
||||||
|
const [momentumWeight, setMomentumWeight] = useState(0.34);
|
||||||
|
const [minFscore, setMinFscore] = useState(7);
|
||||||
|
const [vmValueWeight, setVmValueWeight] = useState(0.5);
|
||||||
|
const [vmMomentumWeight, setVmMomentumWeight] = useState(0.5);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const init = async () => {
|
||||||
|
try {
|
||||||
|
const userData = await api.getCurrentUser() as User;
|
||||||
|
setUser(userData);
|
||||||
|
await fetchBacktests();
|
||||||
|
} catch {
|
||||||
|
router.push('/login');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
init();
|
||||||
|
}, [router]);
|
||||||
|
|
||||||
|
const fetchBacktests = async () => {
|
||||||
|
try {
|
||||||
|
const data = await api.get<BacktestListItem[]>('/api/backtest');
|
||||||
|
setBacktests(data);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to fetch backtests:', err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setSubmitting(true);
|
||||||
|
setError(null);
|
||||||
|
|
||||||
|
try {
|
||||||
|
let strategyParams = {};
|
||||||
|
if (strategyType === 'multi_factor') {
|
||||||
|
strategyParams = {
|
||||||
|
weights: {
|
||||||
|
value: valueWeight,
|
||||||
|
quality: qualityWeight,
|
||||||
|
momentum: momentumWeight,
|
||||||
|
low_vol: 0,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} else if (strategyType === 'quality') {
|
||||||
|
strategyParams = { min_fscore: minFscore };
|
||||||
|
} else if (strategyType === 'value_momentum') {
|
||||||
|
strategyParams = {
|
||||||
|
value_weight: vmValueWeight,
|
||||||
|
momentum_weight: vmMomentumWeight,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await api.post<{ id: number }>('/api/backtest', {
|
||||||
|
strategy_type: strategyType,
|
||||||
|
strategy_params: strategyParams,
|
||||||
|
start_date: startDate,
|
||||||
|
end_date: endDate,
|
||||||
|
rebalance_period: rebalancePeriod,
|
||||||
|
initial_capital: initialCapital,
|
||||||
|
commission_rate: commissionRate,
|
||||||
|
slippage_rate: slippageRate,
|
||||||
|
top_n: topN,
|
||||||
|
});
|
||||||
|
|
||||||
|
router.push(`/backtest/${response.id}`);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Failed to create backtest');
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getStatusBadge = (status: string) => {
|
||||||
|
const styles: Record<string, string> = {
|
||||||
|
pending: 'bg-yellow-100 text-yellow-800',
|
||||||
|
running: 'bg-blue-100 text-blue-800',
|
||||||
|
completed: 'bg-green-100 text-green-800',
|
||||||
|
failed: 'bg-red-100 text-red-800',
|
||||||
|
};
|
||||||
|
const labels: Record<string, string> = {
|
||||||
|
pending: '대기중',
|
||||||
|
running: '실행중',
|
||||||
|
completed: '완료',
|
||||||
|
failed: '실패',
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<span className={`px-2 py-1 rounded text-xs ${styles[status] || 'bg-gray-100'}`}>
|
||||||
|
{labels[status] || status}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatNumber = (value: number | null, decimals: number = 2) => {
|
||||||
|
if (value === null) return '-';
|
||||||
|
return value.toFixed(decimals);
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatCurrency = (value: number) => {
|
||||||
|
return new Intl.NumberFormat('ko-KR').format(value);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center">
|
||||||
|
<div className="text-gray-500">Loading...</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen">
|
||||||
|
<Sidebar />
|
||||||
|
<div className="flex-1">
|
||||||
|
<Header username={user?.username} />
|
||||||
|
<main className="p-6">
|
||||||
|
<h1 className="text-2xl font-bold text-gray-800 mb-6">백테스트</h1>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* New Backtest Form */}
|
||||||
|
<div className="bg-white rounded-lg shadow p-6 mb-6">
|
||||||
|
<h2 className="text-lg font-semibold mb-4">새 백테스트</h2>
|
||||||
|
<form onSubmit={handleSubmit}>
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
|
||||||
|
<div>
|
||||||
|
<label htmlFor="strategy" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
전략
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
id="strategy"
|
||||||
|
value={strategyType}
|
||||||
|
onChange={(e) => setStrategyType(e.target.value)}
|
||||||
|
className="w-full px-3 py-2 border rounded"
|
||||||
|
>
|
||||||
|
{strategyOptions.map((opt) => (
|
||||||
|
<option key={opt.value} value={opt.value}>
|
||||||
|
{opt.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label htmlFor="start-date" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
시작일
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="start-date"
|
||||||
|
type="date"
|
||||||
|
value={startDate}
|
||||||
|
onChange={(e) => setStartDate(e.target.value)}
|
||||||
|
className="w-full px-3 py-2 border rounded"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label htmlFor="end-date" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
종료일
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="end-date"
|
||||||
|
type="date"
|
||||||
|
value={endDate}
|
||||||
|
onChange={(e) => setEndDate(e.target.value)}
|
||||||
|
className="w-full px-3 py-2 border rounded"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
|
||||||
|
<div>
|
||||||
|
<label htmlFor="period" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
리밸런싱 주기
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
id="period"
|
||||||
|
value={rebalancePeriod}
|
||||||
|
onChange={(e) => setRebalancePeriod(e.target.value)}
|
||||||
|
className="w-full px-3 py-2 border rounded"
|
||||||
|
>
|
||||||
|
{periodOptions.map((opt) => (
|
||||||
|
<option key={opt.value} value={opt.value}>
|
||||||
|
{opt.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label htmlFor="capital" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
초기 자본금
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="capital"
|
||||||
|
type="number"
|
||||||
|
value={initialCapital}
|
||||||
|
onChange={(e) => setInitialCapital(parseInt(e.target.value))}
|
||||||
|
className="w-full px-3 py-2 border rounded"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label htmlFor="top-n" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
종목 수
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="top-n"
|
||||||
|
type="number"
|
||||||
|
min="1"
|
||||||
|
max="100"
|
||||||
|
value={topN}
|
||||||
|
onChange={(e) => setTopN(parseInt(e.target.value))}
|
||||||
|
className="w-full px-3 py-2 border rounded"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Strategy-specific params */}
|
||||||
|
{strategyType === 'multi_factor' && (
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
|
||||||
|
<div>
|
||||||
|
<label htmlFor="value-weight" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
밸류 가중치
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="value-weight"
|
||||||
|
type="number"
|
||||||
|
step="0.01"
|
||||||
|
min="0"
|
||||||
|
max="1"
|
||||||
|
value={valueWeight}
|
||||||
|
onChange={(e) => setValueWeight(parseFloat(e.target.value))}
|
||||||
|
className="w-full px-3 py-2 border rounded"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label htmlFor="quality-weight" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
퀄리티 가중치
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="quality-weight"
|
||||||
|
type="number"
|
||||||
|
step="0.01"
|
||||||
|
min="0"
|
||||||
|
max="1"
|
||||||
|
value={qualityWeight}
|
||||||
|
onChange={(e) => setQualityWeight(parseFloat(e.target.value))}
|
||||||
|
className="w-full px-3 py-2 border rounded"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label htmlFor="momentum-weight" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
모멘텀 가중치
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="momentum-weight"
|
||||||
|
type="number"
|
||||||
|
step="0.01"
|
||||||
|
min="0"
|
||||||
|
max="1"
|
||||||
|
value={momentumWeight}
|
||||||
|
onChange={(e) => setMomentumWeight(parseFloat(e.target.value))}
|
||||||
|
className="w-full px-3 py-2 border rounded"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{strategyType === 'quality' && (
|
||||||
|
<div className="mb-4">
|
||||||
|
<label htmlFor="min-fscore" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
최소 F-Score
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="min-fscore"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
max="9"
|
||||||
|
value={minFscore}
|
||||||
|
onChange={(e) => setMinFscore(parseInt(e.target.value))}
|
||||||
|
className="w-32 px-3 py-2 border rounded"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{strategyType === 'value_momentum' && (
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
|
||||||
|
<div>
|
||||||
|
<label htmlFor="vm-value" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
밸류 가중치
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="vm-value"
|
||||||
|
type="number"
|
||||||
|
step="0.1"
|
||||||
|
min="0"
|
||||||
|
max="1"
|
||||||
|
value={vmValueWeight}
|
||||||
|
onChange={(e) => setVmValueWeight(parseFloat(e.target.value))}
|
||||||
|
className="w-full px-3 py-2 border rounded"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label htmlFor="vm-momentum" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
모멘텀 가중치
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="vm-momentum"
|
||||||
|
type="number"
|
||||||
|
step="0.1"
|
||||||
|
min="0"
|
||||||
|
max="1"
|
||||||
|
value={vmMomentumWeight}
|
||||||
|
onChange={(e) => setVmMomentumWeight(parseFloat(e.target.value))}
|
||||||
|
className="w-full px-3 py-2 border rounded"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Advanced options */}
|
||||||
|
<div className="mb-4">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowAdvanced(!showAdvanced)}
|
||||||
|
className="text-sm text-blue-600 hover:underline"
|
||||||
|
>
|
||||||
|
{showAdvanced ? '고급 옵션 숨기기' : '고급 옵션 보기'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{showAdvanced && (
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
|
||||||
|
<div>
|
||||||
|
<label htmlFor="commission" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
수수료율
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="commission"
|
||||||
|
type="number"
|
||||||
|
step="0.00001"
|
||||||
|
value={commissionRate}
|
||||||
|
onChange={(e) => setCommissionRate(parseFloat(e.target.value))}
|
||||||
|
className="w-full px-3 py-2 border rounded"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label htmlFor="slippage" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
슬리피지율
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="slippage"
|
||||||
|
type="number"
|
||||||
|
step="0.0001"
|
||||||
|
value={slippageRate}
|
||||||
|
onChange={(e) => setSlippageRate(parseFloat(e.target.value))}
|
||||||
|
className="w-full px-3 py-2 border rounded"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={submitting}
|
||||||
|
className="px-6 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:bg-blue-400"
|
||||||
|
>
|
||||||
|
{submitting ? '실행 중...' : '백테스트 실행'}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Backtest List */}
|
||||||
|
<div className="bg-white rounded-lg shadow">
|
||||||
|
<div className="p-4 border-b">
|
||||||
|
<h2 className="text-lg font-semibold">백테스트 목록</h2>
|
||||||
|
</div>
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full">
|
||||||
|
<thead className="bg-gray-50">
|
||||||
|
<tr>
|
||||||
|
<th scope="col" className="px-4 py-3 text-left text-sm font-medium text-gray-600">전략</th>
|
||||||
|
<th scope="col" className="px-4 py-3 text-left text-sm font-medium text-gray-600">기간</th>
|
||||||
|
<th scope="col" className="px-4 py-3 text-left text-sm font-medium text-gray-600">주기</th>
|
||||||
|
<th scope="col" className="px-4 py-3 text-right text-sm font-medium text-gray-600">수익률</th>
|
||||||
|
<th scope="col" className="px-4 py-3 text-right text-sm font-medium text-gray-600">CAGR</th>
|
||||||
|
<th scope="col" className="px-4 py-3 text-right text-sm font-medium text-gray-600">MDD</th>
|
||||||
|
<th scope="col" className="px-4 py-3 text-center text-sm font-medium text-gray-600">상태</th>
|
||||||
|
<th scope="col" className="px-4 py-3 text-left text-sm font-medium text-gray-600">생성일</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y">
|
||||||
|
{backtests.map((bt) => (
|
||||||
|
<tr key={bt.id} className="hover:bg-gray-50">
|
||||||
|
<td className="px-4 py-3">
|
||||||
|
<Link href={`/backtest/${bt.id}`} className="text-blue-600 hover:underline">
|
||||||
|
{strategyOptions.find((s) => s.value === bt.strategy_type)?.label || bt.strategy_type}
|
||||||
|
</Link>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-sm">
|
||||||
|
{bt.start_date} ~ {bt.end_date}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-sm">
|
||||||
|
{periodOptions.find((p) => p.value === bt.rebalance_period)?.label || bt.rebalance_period}
|
||||||
|
</td>
|
||||||
|
<td className={`px-4 py-3 text-sm text-right ${(bt.total_return ?? 0) >= 0 ? 'text-green-600' : 'text-red-600'}`}>
|
||||||
|
{bt.total_return !== null ? `${formatNumber(bt.total_return)}%` : '-'}
|
||||||
|
</td>
|
||||||
|
<td className={`px-4 py-3 text-sm text-right ${(bt.cagr ?? 0) >= 0 ? 'text-green-600' : 'text-red-600'}`}>
|
||||||
|
{bt.cagr !== null ? `${formatNumber(bt.cagr)}%` : '-'}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-right text-red-600">
|
||||||
|
{bt.mdd !== null ? `${formatNumber(bt.mdd)}%` : '-'}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-center">
|
||||||
|
{getStatusBadge(bt.status)}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-sm text-gray-500">
|
||||||
|
{new Date(bt.created_at).toLocaleDateString('ko-KR')}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
{backtests.length === 0 && (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={8} className="px-4 py-8 text-center text-gray-500">
|
||||||
|
아직 백테스트가 없습니다.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user