Some checks failed
Tick / tick (push) Failing after 1s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
89 lines
4.2 KiB
TypeScript
89 lines
4.2 KiB
TypeScript
import "server-only";
|
|
import { and, eq, ne } from "drizzle-orm";
|
|
import { aiSpendSince } from "./ai";
|
|
import { getDb, schema } from "./db";
|
|
import { computeGate, maxDrawdownPct, type Criterion } from "./engine/gate";
|
|
import { computePea, type PeaResult } from "./engine/pea";
|
|
import { getBars, getFxToEur, getQuote } from "./market";
|
|
import { getPortfolioState, type PortfolioState } from "./portfolio";
|
|
import { getSettings, type Settings } from "./settings";
|
|
import { daysBetween, parisDate } from "./time";
|
|
|
|
/** Rendement de l'ETF S&P 500 (celui du PEA) depuis une date, en %. */
|
|
export async function benchmarkReturnPct(symbol: string, since: string): Promise<number> {
|
|
const bars = await getBars(symbol, since);
|
|
const first = bars.find((b) => b.date >= since);
|
|
const last = (await getQuote(symbol))?.price ?? bars.at(-1)?.close;
|
|
if (!first || !last) return 0;
|
|
return (last / first.close - 1) * 100;
|
|
}
|
|
|
|
export type GateStatus = {
|
|
unlocked: boolean; // critères remplis aujourd'hui
|
|
realActive: boolean; // mode réel en service (débloqué et pas coupé par le coupe-circuit)
|
|
criteria: Criterion[];
|
|
netReturnPct: number;
|
|
aiCostEur: number;
|
|
};
|
|
|
|
export async function getGateStatus(settings?: Settings, ai?: PortfolioState): Promise<GateStatus> {
|
|
const s = settings ?? (await getSettings());
|
|
const db = await getDb();
|
|
const aiState = ai ?? (await getPortfolioState("ai_sim"));
|
|
const closed = await db
|
|
.select({ id: schema.positions.id })
|
|
.from(schema.positions)
|
|
.where(and(eq(schema.positions.portfolioId, "ai_sim"), eq(schema.positions.status, "closed")));
|
|
const snaps = await db.select().from(schema.equitySnapshots).where(eq(schema.equitySnapshots.portfolioId, "ai_sim"));
|
|
const acts = await db.select({ status: schema.actions.status }).from(schema.actions).where(ne(schema.actions.kind, "to_pea"));
|
|
const usdToEur = (await getFxToEur("USD")) ?? 0.9;
|
|
const aiCostEur = (await aiSpendSince(s.simStartDate)) * usdToEur;
|
|
const bench = s.peaPlan ? await benchmarkReturnPct(s.peaPlan.etfSymbol, s.simStartDate) : 0;
|
|
|
|
const gate = computeGate({
|
|
simDays: daysBetween(s.simStartDate, parisDate()),
|
|
closedTrades: closed.length,
|
|
aiReturnPct: (aiState.equity / aiState.initialCash - 1) * 100,
|
|
aiCostEur,
|
|
initialCash: aiState.initialCash,
|
|
benchmarkReturnPct: bench,
|
|
maxDrawdownPct: maxDrawdownPct([...snaps.sort((a, b) => a.date.localeCompare(b.date)).map((x) => x.equity), aiState.equity]),
|
|
actionsTotal: acts.length,
|
|
actionsAnswered: acts.filter((a) => a.status !== "pending").length,
|
|
});
|
|
return {
|
|
unlocked: gate.unlocked,
|
|
realActive: Boolean(s.realUnlockedAt) && !s.realLockedReason,
|
|
criteria: gate.criteria,
|
|
netReturnPct: gate.netReturnPct,
|
|
aiCostEur,
|
|
};
|
|
}
|
|
|
|
export type Leaderboard = { label: string; pct: number; detail: string }[];
|
|
|
|
export async function getLeaderboard(settings: Settings, ai: PortfolioState, sandbox: PortfolioState): Promise<Leaderboard> {
|
|
const bench = settings.peaPlan ? await benchmarkReturnPct(settings.peaPlan.etfSymbol, settings.simStartDate) : 0;
|
|
const rows = [
|
|
{ label: "L'IA", pct: (ai.equity / ai.initialCash - 1) * 100, detail: `${ai.equity.toFixed(2)} €` },
|
|
{ label: "Toi", pct: (sandbox.equity / sandbox.initialCash - 1) * 100, detail: `${sandbox.equity.toFixed(2)} €` },
|
|
{ label: "S&P 500", pct: bench, detail: "sans rien faire" },
|
|
];
|
|
return rows.sort((a, b) => b.pct - a.pct);
|
|
}
|
|
|
|
export async function getPea(settings: Settings): Promise<(PeaResult & { etfName: string; price: number | null }) | null> {
|
|
const plan = settings.peaPlan;
|
|
if (!plan) return null;
|
|
const today = parisDate();
|
|
if (plan.startDate > today) return { shares: 0, invested: 0, value: 0, gain: 0, contributions: [], etfName: plan.etfName, price: null };
|
|
const [bars, quote] = await Promise.all([getBars(plan.etfSymbol, plan.startDate), getQuote(plan.etfSymbol)]);
|
|
return { ...computePea(plan, bars, quote?.price ?? null, today), etfName: plan.etfName, price: quote?.price ?? null };
|
|
}
|
|
|
|
export async function totalDeposited(): Promise<number> {
|
|
const db = await getDb();
|
|
const rows = await db.select().from(schema.cashFlows).where(eq(schema.cashFlows.portfolioId, "real"));
|
|
return rows.reduce((s, r) => s + r.amount, 0);
|
|
}
|