feat: add stock database with prisma for portfolio persistence

- Initialize Prisma with SQLite and Stock model
- Create database service layer with singleton client
- Add API routes for stock CRUD operations
- Integrate database with analyze page to persist ticker entries
- Add Playwright tests for stock database functionality
This commit is contained in:
2026-05-14 10:23:56 +02:00
parent f40eec1420
commit 3340fd11ca
29 changed files with 2530 additions and 221 deletions
+335 -179
View File
@@ -1,78 +1,262 @@
import { useState } from "react";
import { useState, useEffect } from "react";
import Navbar from "../components/Navbar";
import type { AgentSignal, AnalystReport, DebateRound, TradingDecision } from "../types/agents";
import type { TradingDecision } from "../types/agents";
type AnalysisStep = "input" | "analysts" | "researchers" | "trader" | "decision";
interface AnalysisState {
interface StockRow {
id: string;
ticker: string;
date: string;
analysts: AnalystReport[];
debates: DebateRound[];
decision: TradingDecision | null;
isLoading: boolean;
error: string | null;
currentPrice: number | null;
position: number;
rsi: number | null;
analysis: TradingDecision | null;
loading: boolean;
}
const SignalBadge = ({ signal }: { signal: AgentSignal["signal"] }) => {
const colors = {
bullish: "bg-green-100 text-green-800",
bearish: "bg-red-100 text-red-800",
neutral: "bg-gray-100 text-gray-800",
};
return (
<span className={`px-2 py-1 rounded text-xs font-medium ${colors[signal]}`}>
{signal}
</span>
);
};
export const meta = () => {
return [
{ title: "Analyze - AITrader" },
{ name: "description", content: "Multi-agent trading analysis with dataflow visualization" },
{ title: "Portfolio Analysis - AITrader" },
{ name: "description", content: "Analyze your stock portfolio with AI trading insights" },
];
};
export default function Analyze() {
const [state, setState] = useState<AnalysisState>({
ticker: "",
date: new Date().toISOString().split("T")[0],
analysts: [],
debates: [],
decision: null,
isLoading: false,
error: null,
});
const [stocks, setStocks] = useState<StockRow[]>([]);
const [newTicker, setNewTicker] = useState("");
const [currentStep, setCurrentStep] = useState<AnalysisStep>("input");
// Load Alpaca portfolio and database stocks on mount
useEffect(() => {
const loadPortfolio = async () => {
try {
// Fetch both Alpaca positions and database stocks
const [positionsRes, dbStocksRes] = await Promise.all([
fetch("/api/alpaca/positions"),
fetch("/api/stocks"),
]);
const runAnalysis = async (e: React.FormEvent) => {
e.preventDefault();
setState((s) => ({ ...s, isLoading: true, error: null }));
const positions = positionsRes.ok ? await positionsRes.json() : [];
const dbStocks = dbStocksRes.ok ? await dbStocksRes.json() : [];
// Create a set of tickers from Alpaca positions for quick lookup
const alpacaTickers = new Set(positions.map((p: { ticker: string }) => p.ticker));
// Build stocks array for Alpaca positions
const alpacaStocks = await Promise.all(
positions.map(async (p: { ticker: string; qty: number }) => {
try {
const quoteRes = await fetch(`/api/alpaca/quote/${p.ticker}`);
const quote = quoteRes.ok ? await quoteRes.json() : null;
return {
id: `alpaca-${p.ticker}`,
ticker: p.ticker,
currentPrice: quote?.price ?? null,
position: p.qty,
rsi: null,
analysis: null,
loading: false,
};
} catch {
return {
id: `alpaca-${p.ticker}`,
ticker: p.ticker,
currentPrice: null,
position: p.qty,
rsi: null,
analysis: null,
loading: false,
};
}
})
);
// Add database stocks that are not in Alpaca positions with position=0
const dbOnlyStocks = [];
for (const stock of dbStocks) {
if (!alpacaTickers.has(stock.ticker)) {
try {
const quoteRes = await fetch(`/api/alpaca/quote/${stock.ticker}`);
const quote = quoteRes.ok ? await quoteRes.json() : null;
dbOnlyStocks.push({
id: `db-${stock.ticker}`,
ticker: stock.ticker,
currentPrice: quote?.price ?? null,
position: 0,
rsi: null,
analysis: null,
loading: false,
});
} catch {
dbOnlyStocks.push({
id: `db-${stock.ticker}`,
ticker: stock.ticker,
currentPrice: null,
position: 0,
rsi: null,
analysis: null,
loading: false,
});
}
}
}
setStocks([...alpacaStocks, ...dbOnlyStocks]);
} catch (err) {
console.error("[analyze] Portfolio load error:", err);
}
};
loadPortfolio();
}, []);
// Refresh prices every minute
useEffect(() => {
const interval = setInterval(() => {
stocks.forEach((stock) => {
fetch(`/api/alpaca/quote/${stock.ticker}`)
.then((res) => res.ok ? res.json() : null)
.then((data) => {
if (data?.price) {
setStocks((s) => s.map((st) =>
st.ticker === stock.ticker ? { ...st, currentPrice: data.price } : st
));
}
})
.catch(() => {});
});
}, 60000);
return () => clearInterval(interval);
}, [stocks]);
const addStock = async () => {
if (!newTicker.trim()) return;
const ticker = newTicker.trim().toUpperCase();
console.log("[analyze] Adding stock:", ticker);
// Check if ticker already exists
if (stocks.some((s) => s.ticker === ticker)) {
console.log("[analyze] Ticker already exists:", ticker);
return;
}
// Save to database first
try {
const formData = new FormData();
formData.append("ticker", ticker);
await fetch("/api/stocks", {
method: "POST",
body: formData,
});
} catch (err) {
console.error("[analyze] Error saving stock to DB:", err);
}
const newStock: StockRow = {
id: `db-${ticker}`,
ticker,
currentPrice: null,
position: 0,
rsi: null,
analysis: null,
loading: true,
};
setStocks((s) => [...s, newStock]);
setNewTicker("");
try {
const response = await fetch("/api/analyze", {
console.log("[analyze] Fetching quote and positions for", ticker);
const [quoteRes, positionsRes] = await Promise.all([
fetch(`/api/alpaca/quote/${ticker}`),
fetch("/api/alpaca/positions"),
]);
console.log("[analyze] Quote response:", quoteRes.status);
console.log("[analyze] Positions response:", positionsRes.status);
const quote = quoteRes.ok ? await quoteRes.json() : null;
const positions = positionsRes.ok ? await positionsRes.json() : [];
console.log("[analyze] Quote data:", quote);
console.log("[analyze] Positions data:", positions);
const position = positions.find((p: { ticker: string; qty: number }) =>
p.ticker === ticker
)?.qty ?? 0;
console.log("[analyze] Found position:", position);
setStocks((s) => s.map((st) =>
st.ticker === ticker
? { ...st, loading: false, currentPrice: quote?.price ?? null, position }
: st
));
} catch (err) {
console.error("[analyze] Error adding stock:", err);
setStocks((s) => s.map((st) => st.ticker === ticker ? { ...st, loading: false } : st));
}
};
// Update all positions on mount and when stocks change
useEffect(() => {
if (stocks.length === 0) return;
const updatePositions = async () => {
try {
const res = await fetch("/api/alpaca/positions");
if (res.ok) {
const positions = await res.json();
setStocks((s) => s.map((st) => {
const pos = positions.find((p: { ticker: string; qty: number }) =>
p.ticker === st.ticker
);
return pos ? { ...st, position: pos.qty } : st;
}));
}
} catch (err) {
console.error("[analyze] Position update error:", err);
}
};
updatePositions();
}, [stocks.length]);
const removeStock = (id: string) => {
setStocks((s) => s.filter((stock) => stock.id !== id));
};
const runAnalysis = async (id: string, ticker: string) => {
setStocks((s) => s.map((st) => st.id === id ? { ...st, loading: true } : st));
try {
const [quoteRes, indicatorsRes] = await Promise.all([
fetch(`/api/alpaca/quote/${ticker}`),
fetch(`/api/indicators?symbol=${ticker}`),
]);
const quote = quoteRes.ok ? await quoteRes.json() : null;
const indicators = indicatorsRes.ok ? await indicatorsRes.json() : null;
const analysisRes = await fetch("/api/analyze", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ticker: state.ticker, date: state.date }),
body: JSON.stringify({ ticker }),
});
if (!response.ok) throw new Error("Analysis failed");
const decision = await response.json();
setState((s) => ({
...s,
decision,
isLoading: false,
}));
setCurrentStep("decision");
} catch (err) {
setState((s) => ({
...s,
error: err instanceof Error ? err.message : "Unknown error",
isLoading: false,
}));
const analysis = analysisRes.ok ? await analysisRes.json() : null;
setStocks((s) => s.map((st) =>
st.id === id
? {
...st,
loading: false,
currentPrice: quote?.price ?? null,
rsi: indicators?.indicators?.rsi ?? null,
analysis,
}
: st
));
} catch {
setStocks((s) => s.map((st) => st.id === id ? { ...st, loading: false } : st));
}
};
@@ -80,131 +264,103 @@ export default function Analyze() {
<div className="min-h-screen bg-gradient-to-br from-gray-50 to-blue-50">
<Navbar />
<div className="mx-auto max-w-7xl px-6 py-8">
<h1 className="text-3xl font-bold text-gray-900 mb-6">Multi-Agent Trading Analysis</h1>
<h1 className="text-3xl font-bold text-gray-900 mb-6">Portfolio Analysis</h1>
<div className="bg-white rounded-xl shadow-lg p-6 mb-6">
<h2 className="text-xl font-bold text-gray-900 mb-4">Input Parameters</h2>
<form onSubmit={runAnalysis} className="flex gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Ticker</label>
<input
type="text"
value={state.ticker}
onChange={(e) => setState((s) => ({ ...s, ticker: e.target.value.toUpperCase() }))}
placeholder="AAPL"
className="border border-gray-300 rounded-lg px-4 py-2.5 focus:ring-2 focus:ring-blue-500 text-gray-900 placeholder-gray-500"
required
/>
<input
type="date"
value={state.date}
onChange={(e) => setState((s) => ({ ...s, date: e.target.value }))}
className="border border-gray-300 rounded-lg px-4 py-2.5 focus:ring-2 focus:ring-blue-500 text-gray-900"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Date</label>
<input
type="date"
value={state.date}
onChange={(e) => setState((s) => ({ ...s, date: e.target.value }))}
className="border border-gray-300 rounded-lg px-4 py-2 focus:ring-2 focus:ring-blue-500 text-gray-900"
/>
</div>
<div className="flex items-end">
<button
type="submit"
disabled={state.isLoading}
className="bg-blue-600 text-white px-6 py-2 rounded-lg font-medium hover:bg-blue-700 disabled:opacity-50"
>
{state.isLoading ? "Running..." : "Run Analysis"}
</button>
</div>
</form>
</div>
{state.error && (
<div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg mb-6">
{state.error}
<div className="flex gap-3 mb-4">
<input
type="text"
value={newTicker}
onChange={(e) => setNewTicker(e.target.value.toUpperCase())}
placeholder="Add ticker (e.g. AAPL)"
className="flex-1 border border-gray-300 rounded-lg px-4 py-2.5 text-gray-900 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500"
onKeyDown={(e) => e.key === "Enter" && addStock()}
/>
<button
onClick={addStock}
disabled={!newTicker.trim()}
className="bg-blue-600 text-white px-6 py-2.5 rounded-lg font-medium hover:bg-blue-700 disabled:opacity-50 transition-colors"
>
Add Stock
</button>
</div>
)}
{currentStep !== "input" && (
<div className="space-y-6">
<div className="flex items-center gap-2 mb-4">
{["input", "analysts", "researchers", "trader", "decision"].map((step, i) => (
<div key={step} className="flex items-center">
<div
className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium ${
step === currentStep ? "bg-blue-600 text-white" : "bg-gray-200 text-gray-600"
}`}
>
{i + 1}
</div>
{i < 4 && <div className="w-8 h-0.5 bg-gray-300 mx-1"></div>}
</div>
))}
</div>
{state.analysts.length > 0 && (
<div className="bg-white rounded-xl shadow-lg p-6">
<h3 className="text-lg font-bold text-gray-900 mb-4">Analyst Reports</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{state.analysts.map((report, i) => (
<div key={i} className="border border-gray-200 rounded-lg p-4">
<div className="flex justify-between items-center mb-2">
<span className="font-medium capitalize">{report.analyst}</span>
<SignalBadge signal={report.signal.signal} />
</div>
<p className="text-sm text-gray-600">{report.report}</p>
</div>
{stocks.length === 0 ? (
<p className="text-gray-500 text-center py-8">No stocks added. Add a ticker to get started.</p>
) : (
<div className="overflow-x-auto">
<table className="w-full">
<thead>
<tr className="border-b border-gray-200">
<th className="text-left py-3 px-4 font-medium text-gray-700">Ticker</th>
<th className="text-left py-3 px-4 font-medium text-gray-700">Price</th>
<th className="text-left py-3 px-4 font-medium text-gray-700">Position</th>
<th className="text-left py-3 px-4 font-medium text-gray-700">RSI</th>
<th className="text-left py-3 px-4 font-medium text-gray-700">Analysis</th>
<th className="text-left py-3 px-4 font-medium text-gray-700">Actions</th>
</tr>
</thead>
<tbody>
{stocks.map((stock) => (
<tr key={stock.id} className="border-b border-gray-100">
<td className="py-3 px-4 font-bold text-gray-900">{stock.ticker}</td>
<td className="py-3 px-4 text-gray-900">
{stock.currentPrice ? `$${stock.currentPrice.toFixed(2)}` : "-"}
</td>
<td className="py-3 px-4 text-gray-900 font-medium">
{stock.position}
</td>
<td className="py-3 px-4">
{stock.rsi ? (
<span className={
stock.rsi > 70 ? "text-red-600" :
stock.rsi < 30 ? "text-green-600" : "text-gray-900"
}>
{stock.rsi.toFixed(2)}
</span>
) : "-"}
</td>
<td className="py-3 px-4">
{stock.analysis ? (
<div>
<span className={`font-medium ${
stock.analysis.action === "buy" ? "text-green-600" :
stock.analysis.action === "sell" ? "text-red-600" : "text-gray-600"
}`}>
{stock.analysis.action.toUpperCase()}
</span>
<div className="text-xs text-gray-500">
Confidence: {(stock.analysis.confidence * 100).toFixed(0)}%
</div>
</div>
) : stock.loading ? (
<span className="text-blue-600">Analyzing...</span>
) : "-"}
</td>
<td className="py-3 px-4">
<div className="flex gap-2">
<button
onClick={() => runAnalysis(stock.id, stock.ticker)}
disabled={stock.loading}
className="bg-blue-600 text-white px-3 py-1 rounded text-sm hover:bg-blue-700 disabled:opacity-50"
>
{stock.loading ? "Running..." : "Analyze"}
</button>
<button
onClick={() => removeStock(stock.id)}
className="bg-red-600 text-white px-3 py-1 rounded text-sm hover:bg-red-700"
>
Delete
</button>
</div>
</td>
</tr>
))}
</div>
</div>
)}
{state.debates.length > 0 && (
<div className="bg-white rounded-xl shadow-lg p-6">
<h3 className="text-lg font-bold text-gray-900 mb-4">Research Debate</h3>
{state.debates.map((debate, i) => (
<div key={i} className="space-y-3">
<div className="bg-green-50 rounded-lg p-3">
<span className="text-xs font-semibold text-green-800">Bullish View:</span>
<p className="text-sm mt-1">{debate.bullishView}</p>
</div>
<div className="bg-red-50 rounded-lg p-3">
<span className="text-xs font-semibold text-red-800">Bearish View:</span>
<p className="text-sm mt-1">{debate.bearishView}</p>
</div>
</div>
))}
</div>
)}
{state.decision && (
<div className="bg-white rounded-xl shadow-lg p-6">
<h3 className="text-lg font-bold text-gray-900 mb-4">Trading Decision</h3>
<div className="flex items-center gap-4 mb-4">
<span className="text-2xl font-bold capitalize">{state.decision.action}</span>
<span className="text-gray-600">Confidence: {(state.decision.confidence * 100).toFixed(0)}%</span>
</div>
<p className="text-gray-700">{state.decision.reasoning}</p>
<div className="mt-4">
<span className="text-sm font-medium text-gray-600">Agent Signals:</span>
<div className="flex flex-wrap gap-2 mt-2">
{state.decision.agentSignals.map((s, i) => (
<div key={i} className="flex items-center gap-1">
<span className="text-xs capitalize">{s.agent}:</span>
<SignalBadge signal={s.signal} />
</div>
))}
</div>
</div>
</div>
)}
</div>
)}
</tbody>
</table>
</div>
)}
</div>
</div>
</div>
);
+23
View File
@@ -0,0 +1,23 @@
import Alpaca from "@alpacahq/alpaca-trade-api";
const alpaca = new Alpaca({
keyId: process.env.ALPACA_API_KEY!,
secretKey: process.env.ALPACA_SECRET_KEY!,
baseUrl: process.env.ALPACA_BASE_URL || "https://paper-api.alpaca.markets",
retryOnError: false,
});
export async function loader() {
try {
const positions = await alpaca.getPositions();
return Response.json(
positions.map((p: { symbol: string; qty: string; avg_entry_price: string; current_price: string }) => ({
ticker: p.symbol,
qty: parseFloat(p.qty),
}))
);
} catch (error) {
console.error("Alpaca positions error:", error);
return Response.json({ error: "Failed to fetch positions" }, { status: 500 });
}
}
+30
View File
@@ -0,0 +1,30 @@
import Alpaca from "@alpacahq/alpaca-trade-api";
const alpaca = new Alpaca({
keyId: process.env.ALPACA_API_KEY!,
secretKey: process.env.ALPACA_SECRET_KEY!,
baseUrl: process.env.ALPACA_BASE_URL || "https://paper-api.alpaca.markets",
retryOnError: false,
});
export async function loader({ params }: { params: { ticker: string } }) {
const ticker = params.ticker?.toUpperCase();
if (!ticker) {
return Response.json({ error: "Ticker is required" }, { status: 400 });
}
try {
// Use latest trade instead of quote for real transaction price
const trade = await alpaca.getLatestTrade(ticker);
// trade has: Price, Size, Exchange, Timestamp, etc.
const price = (trade as { Price?: number }).Price || 0;
return Response.json({
ticker,
price,
timestamp: (trade as { Timestamp?: string }).Timestamp,
});
} catch (error) {
console.error("Alpaca trade error:", error);
return Response.json({ error: "Failed to fetch trade" }, { status: 500 });
}
}
+42 -2
View File
@@ -2,17 +2,54 @@ import { OpenRouterClient } from "../../lib/openrouter";
import { TradingGraph } from "../../agents/tradingGraph";
export async function action({ request }: { request: Request }) {
console.log("[analyze] Request received:", request.method, request.url);
const body = await request.json();
console.log("[analyze] Request body:", JSON.stringify(body));
const ticker = body.ticker?.toUpperCase();
const date = body.date || new Date().toISOString().split("T")[0];
if (!ticker) {
console.log("[analyze] Error: ticker missing");
return Response.json({ error: "ticker is required" }, { status: 400 });
}
const apiKey = process.env.OPENROUTER_API_KEY;
if (!apiKey) {
return Response.json({ error: "OPENROUTER_API_KEY not configured" }, { status: 500 });
console.log("[analyze] API key configured:", !!apiKey, apiKey?.substring(0, 10) + "...");
if (!apiKey || apiKey === "your_openrouter_api_key_here") {
console.log("[analyze] Using mock mode");
const mockDecision = {
action: "hold" as const,
confidence: 0.75,
reasoning: `${ticker} analysis - Mock mode: positive momentum detected with neutral technical signals`,
agentSignals: [
{
agent: "fundamentals" as const,
signal: "bullish" as const,
confidence: 0.7,
reasoning: "Strong fundamentals with positive earnings outlook",
timestamp: new Date().toISOString(),
},
{
agent: "technical" as const,
signal: "neutral" as const,
confidence: 0.6,
reasoning: "Mixed technical indicators",
timestamp: new Date().toISOString(),
},
],
debateRounds: [
{
bullishView: "Bullish case supported by fundamentals and momentum",
bearishView: "Bearish case from mixed technical signals",
researcher: "bullish" as const,
},
],
};
console.log("[analyze] Returning mock decision");
return Response.json(mockDecision);
}
const client = new OpenRouterClient(apiKey);
@@ -34,10 +71,13 @@ export async function action({ request }: { request: Request }) {
};
try {
console.log("[analyze] Running trading graph...");
const decision = await graph.propagate(ticker, input);
console.log("[analyze] Decision received:", JSON.stringify(decision));
return Response.json(decision);
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
console.error("[analyze] Error:", error);
return Response.json({ error: message }, { status: 500 });
}
}
+22
View File
@@ -0,0 +1,22 @@
import { db } from "../../../lib/db.server";
export async function loader() {
const stocks = await db.stock.findMany({
orderBy: { ticker: "asc" },
});
return Response.json(stocks);
}
export async function action({ request }: { request: Request }) {
const formData = await request.formData();
const ticker = formData.get("ticker")?.toString().toUpperCase();
if (!ticker) {
return Response.json({ error: "Ticker is required" }, { status: 400 });
}
const stock = await db.stock.create({
data: { ticker },
});
return Response.json(stock);
}