'use client'; import React, { useState, useMemo, useEffect } from 'react'; import { useSandboxStore, InsiderTrade, CongressTrade, WhaleTrade } from '@/lib/store'; import { calculateRollingZScore, detectInsiderClusters, coupleBayesianRebound } from '@/lib/math/statistics'; import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts'; import 'katex/dist/katex.min.css'; import { BlockMath, InlineMath } from 'react-katex'; import InsiderMathModal from './InsiderMathModal'; import { Shield, User, Landmark, ChevronDown, ChevronUp, Radio, Building2, AlertTriangle, Percent, BookOpen } from 'lucide-react'; function estimateCongressShares(valueRange: string): number { const clean = valueRange.replace(/[$,]/g, ''); const parts = clean.split('-').map(p => parseFloat(p.trim())); if (parts.length === 2) { const mid = (parts[0] + parts[1]) / 2; return Math.round(mid / 150); // assuming $150 average share price } if (parts.length === 1 && !isNaN(parts[0])) { return Math.round(parts[0] / 150); } return 1000; // default fallback } function calculateRowMetrics( ticker: string, volume: number, insiderVolumes: Record, priorProbability: number ) { const baseline = insiderVolumes[ticker]; let volumesToUse: number[]; if (baseline && baseline.length > 0) { volumesToUse = [...baseline, volume]; } else { // Generate a dynamic seed if ticker is unrepresented const seedBase = volume > 0 ? volume : 10000; volumesToUse = []; for (let i = 0; i < 11; i++) { const factor = 0.5 + ((i * 7 + ticker.charCodeAt(0)) % 10) * 0.1; volumesToUse.push(Math.round(seedBase * factor)); } volumesToUse.push(volume > 0 ? volume : 10000); } const zResult = calculateRollingZScore(volumesToUse); const zScore = parseFloat(zResult.latest.toFixed(2)); const coupled = coupleBayesianRebound(priorProbability, zScore); return { zScore, coupledRebound: coupled }; } export default function InsiderDemo() { const { insiderTrades, congressTrades, whaleTrades, insiderVolumes, priorProbability } = useSandboxStore(); // Component local UI states const [activeSegment, setActiveSegment] = useState<'executives' | 'congress' | 'whales'>('executives'); const [searchQuery, setSearchQuery] = useState(''); const [selectedTicker, setSelectedTicker] = useState(null); const [scanning, setScanning] = useState(false); const [scanResults, setScanResults] = useState<{ ticker: string; zScore: number; clusterCount: number; multiplier: number; isAnomaly: boolean; coupledRebound: number; }[] | null>(null); const [showMathAccordion, setShowMathAccordion] = useState(false); const [isMathModalOpen, setIsMathModalOpen] = useState(false); const [isShieldActive, setIsShieldActive] = useState(false); const [loading, setLoading] = useState(false); const [errorMsg, setErrorMsg] = useState(null); // Load live data from the server-side proxy useEffect(() => { let active = true; async function loadData() { setLoading(true); setErrorMsg(null); try { const [execRes, congRes, whaleRes] = await Promise.all([ fetch('/api/insider?type=executives').then(async r => { if (!r.ok) throw new Error(`Executives API HTTP ${r.status}`); return r.json(); }), fetch('/api/insider?type=congress').then(async r => { if (!r.ok) throw new Error(`Congress API HTTP ${r.status}`); return r.json(); }), fetch('/api/insider?type=whales').then(async r => { if (!r.ok) throw new Error(`Whales API HTTP ${r.status}`); return r.json(); }) ]); if (active) { setIsShieldActive(!!execRes.isShieldActive || !!congRes.isShieldActive || !!whaleRes.isShieldActive); const unavailable: string[] = []; if (execRes.liveDataAvailable === false) unavailable.push('Executives (Form 4)'); if (congRes.liveDataAvailable === false) unavailable.push('Congress (Stock Act)'); if (whaleRes.liveDataAvailable === false) unavailable.push('Whales (13F Filings)'); if (unavailable.length > 0) { setErrorMsg(`Real-time data source temporarily busy for: ${unavailable.join(', ')}. Please try again later.`); } useSandboxStore.setState({ insiderTrades: execRes.results || [], congressTrades: congRes.results || [], whaleTrades: whaleRes.results || [] }); } } catch (err: any) { console.error('Failed to load live insider data:', err.message); if (active) { setErrorMsg(err.message || 'Real-time data source temporarily unreachable.'); } } finally { if (active) setLoading(false); } } loadData(); return () => { active = false; }; }, []); // Run Global Flow Scan const handleGlobalFlowScan = () => { setScanning(true); setTimeout(() => { // Get all tickers present in the current live feed const activeTickers = Array.from(new Set([ ...insiderTrades.map(t => t.ticker), ...congressTrades.map(c => c.ticker), ...whaleTrades.map(w => w.ticker) ])).filter(ticker => ticker && ticker !== 'UNKNOWN' && ticker !== '--'); const results = activeTickers.map((ticker) => { // Calculate the trade volume for this ticker in the current active feed to use for calculation // For Executives, we sum shares from insiderTrades. For Congress, we sum estimated shares. For Whales, we sum sharesTraded. const execVolume = insiderTrades.filter(t => t.ticker === ticker).reduce((sum, t) => sum + t.shares, 0); const congVolume = congressTrades.filter(t => t.ticker === ticker).reduce((sum, t) => sum + estimateCongressShares(t.valueRange), 0); const whaleVolume = whaleTrades.filter(t => t.ticker === ticker).reduce((sum, t) => sum + t.sharesTraded, 0); const currentVolume = execVolume + congVolume + whaleVolume; const baseline = insiderVolumes[ticker]; let volumesToUse: number[]; if (baseline && baseline.length > 0) { volumesToUse = [...baseline, currentVolume]; } else { // Generate a dynamic seed if ticker is unrepresented const seedBase = currentVolume > 0 ? currentVolume : 10000; volumesToUse = []; for (let i = 0; i < 11; i++) { const factor = 0.5 + ((i * 7 + ticker.charCodeAt(0)) % 10) * 0.1; volumesToUse.push(Math.round(seedBase * factor)); } volumesToUse.push(currentVolume > 0 ? currentVolume : 10000); } const zResult = calculateRollingZScore(volumesToUse); const zScore = parseFloat(zResult.latest.toFixed(2)); // Filter trades for this ticker to detect clusters const tickerTrades = insiderTrades.filter(t => t.ticker === ticker); const clusterResult = detectInsiderClusters(tickerTrades); // Bayesian coupling const coupled = coupleBayesianRebound(priorProbability, zScore); return { ticker, zScore, clusterCount: clusterResult.count, multiplier: parseFloat(clusterResult.multiplier.toFixed(2)), isAnomaly: zScore > 2.0 || clusterResult.isCluster, coupledRebound: coupled, }; }).filter(res => res.zScore > 2.0); // Only render cards for tickers with volumetric Z-Score > 2.0 // Sort anomalies to the top results.sort((a, b) => b.zScore - a.zScore); setScanResults(results); setScanning(false); }, 1000); }; // Perform Ticker Lookup const handleTickerLookup = (e: React.FormEvent) => { e.preventDefault(); const query = searchQuery.trim().toUpperCase(); if (query) { setSelectedTicker(query); } else { setSelectedTicker(null); } }; // Compute stats for selected ticker const tickerStats = useMemo(() => { if (!selectedTicker) return null; const volumes = insiderVolumes[selectedTicker] || [5000, 4800, 5200, 6000, 4500, 5000]; // fallback const zResult = calculateRollingZScore(volumes); const tickerTrades = insiderTrades.filter(t => t.ticker === selectedTicker); const clusterResult = detectInsiderClusters(tickerTrades); const coupled = coupleBayesianRebound(priorProbability, zResult.latest); return { zScore: zResult.latest, isAnomaly: zResult.isAnomaly, clusterCount: clusterResult.count, isCluster: clusterResult.isCluster, multiplier: clusterResult.multiplier, coupledRebound: coupled, volumes, }; }, [selectedTicker, insiderVolumes, insiderTrades, priorProbability]); // Volumes chart data for selected ticker const volumeChartData = useMemo(() => { if (!tickerStats || !selectedTicker) return []; return tickerStats.volumes.map((vol, idx) => ({ month: `M-${tickerStats.volumes.length - idx - 1}`, 'Volume (Shares)': vol, })); }, [tickerStats, selectedTicker]); return (
{/* Header */}
Element 3

Institutional & Insider Flow Tracker {isShieldActive ? ( DEV ARCHIVE ACTIVE (0 CALLS) ) : ( LIVE API ENDPOINT (FMP CORPO) )}

Bayesian Coupling

Prior Rebound: {(priorProbability * 100).toFixed(0)}%

{/* SECTION 1: Dual-Query Actions */}

Global Flow Outlier Scan

Filters the market for statistically significant purchase volumes (Z-Score > 2.0) and concerted buying (insider clusters).

Ticker Lookup (Single Evaluation)

Targeted query of insider Z-scores and Bayesian coupling updates (e.g., PLTR, RACE, AMZN, AAPL).

setSearchQuery(e.target.value)} />
{/* Ticker Stats / Lookup Section */} {selectedTicker && tickerStats && (

{selectedTicker} Single Evaluation

{tickerStats.isAnomaly && FLOW OUTLIER}
Volumetric Z-Score: Z = {tickerStats.zScore.toFixed(2)}
Concerted Cluster (14 Days): {tickerStats.isCluster ? `YES (${tickerStats.clusterCount} Insiders)` : `NO (${tickerStats.clusterCount})`}
{tickerStats.isCluster && (
Cluster Exponent Multiplier: x{tickerStats.multiplier.toFixed(2)}
)}
Coupled Rebound Prob.: {(tickerStats.coupledRebound * 100).toFixed(0)}%
{/* Volume chart */}
Insider Trading Volume (24-Month Baseline)
)} {/* Global Scan Outlier List */} {scanResults && (

Global Flow Scan Results

{scanResults.length === 0 ? (

No Significant Volume Anomalies Found

No transactions with a calculated volumetric Z-Score > 2.0 were identified in the active live feeds.

) : (
{scanResults.map((res) => (
setSelectedTicker(res.ticker)} className="p-3 rounded-xl border cursor-pointer hover:bg-slate-900/60 transition-colors border-purple-500/40 bg-purple-500/5" >
{res.ticker}
Z-Score: {res.zScore}
Cluster: {res.clusterCount} Traders
Rebound: {Math.round(res.coupledRebound * 100)}%
))}
)}
)} {/* SECTION 2: Smart Money Segment Tabs */}
{errorMsg && (
Data Load Error: {errorMsg}
)} {/* Ledger displays */}
{activeSegment === 'executives' && ( {loading && ( )} {!loading && insiderTrades.length === 0 && ( )} {!loading && insiderTrades.map((t) => { const isBuy = t.type === 'BUY'; const { zScore, coupledRebound } = calculateRowMetrics( t.ticker, t.shares, insiderVolumes, priorProbability ); return ( ); })}
Ticker Insider Name Position Transaction Shares Value ($) Volumetric Z-Score P(R|Z) Strategic Assessment
Loading live insider transactions (Form 4)...
No insider transactions loaded.
{t.ticker} {t.insiderName} {t.relation} {isBuy ? 'BUY' : 'SELL'} {t.shares.toLocaleString()} ${t.value.toLocaleString()} = 2.0 ? 'text-purple-400' : 'text-slate-350'}`}>{zScore} {(coupledRebound * 100).toFixed(0)}% {t.insight || 'Opportunistic Diversification'}
)} {activeSegment === 'congress' && (
U.S. Congress Stock Act Disclosure Lags: Representatives must disclose transactions within 30 to 45 days. The Alpha Lag in the table visualizes this reporting delay. Transactions may be priced in with a delay.
{loading && ( )} {!loading && congressTrades.length === 0 && ( )} {!loading && congressTrades.map((c) => { const isBuy = c.type === 'BUY'; const estShares = estimateCongressShares(c.valueRange); const { zScore, coupledRebound } = calculateRowMetrics( c.ticker, estShares, insiderVolumes, priorProbability ); return ( ); })}
Ticker Representative Chamber Transaction Volume Range Transaction Date Filing Date Alpha Lag Volumetric Z-Score P(R|Z) Strategic Assessment
Loading US Congress transactions...
No Congress transactions loaded.
{c.ticker} {c.representative} {c.chamber} {isBuy ? 'BUY' : 'SELL'} {c.valueRange} {c.transactionDate} {c.filingDate} {c.lagDays} Days = 2.0 ? 'text-purple-400' : 'text-slate-350'}`}>{zScore} {(coupledRebound * 100).toFixed(0)}% {c.insight || 'Opportunistic Diversification'}
)} {activeSegment === 'whales' && ( {loading && ( )} {!loading && whaleTrades.length === 0 && ( )} {!loading && whaleTrades.map((w) => { const isBuy = w.type === 'BUY' || w.type === 'NEW'; const { zScore, coupledRebound } = calculateRowMetrics( w.ticker, w.sharesTraded, insiderVolumes, priorProbability ); return ( ); })}
Ticker Institution (13F Filers) Type Shares Traded Shares Held Filing Date Estimated Value ($) Volumetric Z-Score P(R|Z) Strategic Assessment
Loading 13F whale transactions...
No institutional transactions loaded.
{w.ticker} {w.institution} {w.type} {w.sharesTraded.toLocaleString()} {w.sharesHeld.toLocaleString()} {w.filingDate} ${w.estimatedValue.toLocaleString()} = 2.0 ? 'text-purple-400' : 'text-slate-350'}`}>{zScore} {(coupledRebound * 100).toFixed(0)}% {w.insight || 'Opportunistic Rebalancing'}
)}
{/* SECTION 3: Mathematical LaTeX Accordion */}
{showMathAccordion && (

1. Volumetric Z-Score (Statistical Significance)

The Z-Score indicates how many standard deviations the current transaction volume deviates from the historical average :

A Z-Score > 2.0 is classified as an outlier (anomaly trigger), corresponding to a probability of less than 2.27% for a random spike (one-sided test under a normal distribution).

2. Bayesian Coupling (Rebound Probability)

We couple price drop sentiment (Element 2) with insider Z-Scores (Element 3) to determine the posterior probability of a true rebound:

where is the prior probability. When the Z-Score is high (buying), the likelihood increases significantly, maximizing the rebound expectation.

)}
setIsMathModalOpen(false)} />
); }