continuation

This commit is contained in:
Boki 2026-10-20 16:57:59 -04:00
parent 32e43c9243
commit 879e9b4228
42 changed files with 2607 additions and 1306 deletions

View file

@ -20,7 +20,7 @@ interface ExtendedTrade {
price: number;
commission: number;
pnl?: number;
positionAfter: number;
positionAfter?: number;
entryPrice?: number;
entryDate?: string;
date?: string;

View file

@ -37,27 +37,13 @@ export const BacktestPlayback = memo(function BacktestPlayback({
const openPositions: Position[] = [];
const closedPositions: Position[] = [];
if (result.positions) {
if (Array.isArray(result.positions)) {
result.positions.forEach(p => {
if (p.quantity !== 0) {
openPositions.push(p);
} else if (p.realizedPnl !== 0) {
closedPositions.push(p);
}
});
} else if (typeof result.positions === 'object') {
// Convert positions object to array
Object.entries(result.positions).forEach(([symbol, position]) => {
const pos = { symbol, ...position };
if (position.quantity !== 0) {
openPositions.push(pos);
} else if (position.realizedPnl !== 0) {
closedPositions.push(pos);
}
});
result.positions.forEach(position => {
if (position.quantity !== 0) {
openPositions.push(position);
} else if (position.realizedPnl !== 0) {
closedPositions.push(position);
}
}
});
return (
<div className="h-full flex flex-col gap-4">

View file

@ -1,8 +1,8 @@
import type { ColumnDef } from '@tanstack/react-table';
import type { BacktestRunTrade as Trade } from '@stock-bot/types';
import { DataTable } from '@/components/ui/DataTable';
import { browserLog } from '@/utils/browserLog';
import type { RunResult } from '../services/backtestApiV2';
import type { Trade } from '../types/backtest.types';
interface BacktestTradesProps {
result: RunResult | null;
@ -66,7 +66,7 @@ export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
size: 180,
cell: ({ row }) => {
const trade = row.original;
const date = trade.timestamp || trade.entryDate || trade.date;
const date = trade.timestamp;
return (
<span className="text-sm text-text-secondary">
{date ? new Date(date).toLocaleString() : '-'}
@ -112,7 +112,7 @@ export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
size: 100,
cell: ({ row }) => {
const trade = row.original;
const pnl = trade.pnl || trade.realizedPnl || 0;
const pnl = trade.pnl ?? 0;
return (
<span className={`text-sm font-medium ${pnl >= 0 ? 'text-success' : 'text-error'}`}>
${pnl.toFixed(2)}
@ -125,7 +125,7 @@ export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
// Calculate trade statistics
const tradeStats = result.trades.reduce(
(stats, trade) => {
const pnl = trade.pnl || trade.realizedPnl || 0;
const pnl = trade.pnl ?? 0;
if (pnl > 0) {
stats.wins++;
stats.totalWin += pnl;
@ -139,14 +139,14 @@ export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
{ wins: 0, losses: 0, totalWin: 0, totalLoss: 0, totalPnL: 0 }
);
const winRate = result.trades.length > 0 ? (tradeStats.wins / result.trades.length) * 100 : 0;
const winRate = result.metrics.winRate * 100;
return (
<div>
<div className="mb-4 grid grid-cols-1 md:grid-cols-5 gap-4">
<div className="bg-surface-secondary rounded-lg border border-border p-3">
<p className="text-xs text-text-secondary">Total Trades</p>
<p className="text-lg font-medium text-text-primary">{result.trades.length}</p>
<p className="text-xs text-text-secondary">Closed Trades</p>
<p className="text-lg font-medium text-text-primary">{result.metrics.totalTrades}</p>
</div>
<div className="bg-surface-secondary rounded-lg border border-border p-3">
<p className="text-xs text-text-secondary">Win Rate</p>
@ -180,10 +180,7 @@ export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
{result.positions &&
Object.keys(result.positions).length > 0 &&
(() => {
const positionsArray = Object.entries(result.positions).map(([symbol, position]) => ({
symbol,
...position,
}));
const positionsArray = result.positions;
const positionColumns: ColumnDef<(typeof positionsArray)[0]>[] = [
{

View file

@ -82,21 +82,21 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
return status.charAt(0).toUpperCase() + status.slice(1);
};
const formatPercentage = (value: number | undefined, decimals = 2) => {
const formatPercentage = (value: number | null | undefined, decimals = 2) => {
if (value === undefined || value === null) {
return '-';
}
return `${(value * 100).toFixed(decimals)}%`;
};
const formatNumber = (value: number | undefined, decimals = 2) => {
const formatNumber = (value: number | null | undefined, decimals = 2) => {
if (value === undefined || value === null) {
return '-';
}
return value.toFixed(decimals);
};
const formatCurrency = (value: number | undefined) => {
const formatCurrency = (value: number | null | undefined) => {
if (value === undefined || value === null) {
return '-';
}
@ -169,7 +169,7 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
return (
<span
className={`text-sm font-medium ${
value === undefined
value === undefined || value === null
? 'text-text-secondary'
: value >= 0
? 'text-success'
@ -191,7 +191,7 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
return (
<span
className={`text-sm font-medium ${
value === undefined
value === undefined || value === null
? 'text-text-secondary'
: value > 1
? 'text-success'
@ -215,7 +215,7 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
return (
<span
className={`text-sm font-medium ${
value === undefined
value === undefined || value === null
? 'text-text-secondary'
: value > -0.1
? 'text-success'
@ -239,7 +239,7 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
return (
<span
className={`text-sm font-medium ${
value === undefined
value === undefined || value === null
? 'text-text-secondary'
: value > 0.5
? 'text-success'
@ -261,7 +261,7 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
return (
<span
className={`text-sm font-medium ${
value === undefined
value === undefined || value === null
? 'text-text-secondary'
: value > 1.5
? 'text-success'
@ -285,7 +285,7 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
return (
<span
className={`text-sm font-medium ${
value === undefined
value === undefined || value === null
? 'text-text-secondary'
: value >= 0
? 'text-success'

View file

@ -1,5 +1,5 @@
import type { BacktestRunResult } from '@stock-bot/types';
import { browserLog } from '@/utils/browserLog';
import type { BacktestMetrics, Position, Trade } from '../types/backtest.types';
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:2003';
@ -46,39 +46,7 @@ export interface CreateRunRequest {
speedMultiplier?: number | null;
}
export interface RunResult {
runId: string;
backtestId: string;
status: 'completed';
completedAt: string;
config: {
name: string;
strategy: string;
symbols: string[];
startDate: string;
endDate: string;
initialCapital: number;
commission: number;
slippage: number;
dataFrequency: string;
};
metrics: BacktestMetrics;
equity: { date: string; value: number }[];
ohlcData: Record<
string,
{ timestamp: number; open: number; high: number; low: number; close: number; volume?: number }[]
>;
trades: Trade[];
positions: Position[] | Record<string, Omit<Position, 'symbol'>>;
analytics: {
exposureTime?: number;
drawdownSeries?: { timestamp: number; value: number }[];
dailyReturns?: number[];
monthlyReturns?: Record<string, number>;
riskMetrics?: Record<string, number>;
};
executionTime: number;
}
export type RunResult = BacktestRunResult;
export const backtestApiV2 = {
// Backtest operations

View file

@ -60,7 +60,7 @@ export interface Trade {
entryPrice?: number;
date?: string;
realizedPnl?: number;
positionAfter: number; // Position size after this trade
positionAfter?: number; // Position size after this trade
}
export interface PerformanceDataPoint {