Skip to content
AI Trading

A nightly AI report that summarizes my bot’s trades and risk

ai report — turned on gray laptop computer

Six months ago, I pushed a multi-strategy statistical arbitrage bot to production on a small AWS instance. It ran four sub-strategies across 18 crypto perpetual pairs, generating anywhere from 40 to 300 orders per day.

For the first three weeks, my end-of-day routine was a nightmare. I would SSH into the box, tail raw JSON log files, grep for fill prices, pull execution latency metrics from Prometheus, and manually reconstruct my portfolio’s Greeks and net directional exposure in a messy Jupyter notebook. One night I missed a subtle drift in my delta-neutral hedge because I was too tired to manually aggregate trade fills across three different quote assets. That single missed drift cost me $1,420 when ETH popped 4% in twenty minutes.

I needed an automated ai report delivered to my Slack channel every night at 00:05 UTC—a unified trade summary and risk reporting engine that wouldn’t just dump raw numbers, but actually explain why my risk surface shifted and how my execution performed against historical slippage baselines.

Here is how I built a deterministic-meets-probabilistic night-watchman using Python, DuckDB, Prometheus, and Claude 3.5 Sonnet.


The Architecture: Why LLMs Alone Are Dangerous for Risk

My first instinct was the classic naive engineer approach: dump raw JSON logs straight into an LLM context window and ask it to “summarize my trading day.”

It was a total disaster.

The LLM hallucinated trade fills that never happened, got confused by partial fills, calculated my daily PnL wrong by $3,000, and hallucinated that my maximum drawdown was 0.2% when it was actually 1.8%. You cannot trust a Large Language Model to perform arithmetic on floating-point financial data.

The architecture that actually works relies on a strict separation of concerns:
1. Deterministic Data Engine: DuckDB pulls raw execution events and engine state snapshots, calculating exact PnL, Sharpe ratios, position drift, and slippage.
2. Contextual Enrichment Layer: Python maps metric anomalies against historical p95 baselines.
3. Probabilistic Narrative Engine: The LLM receives pre-calculated, verified structural JSON data and acts purely as an analytical writer and anomaly highlighter.

flowchart LR
 A["Sqlite Logs"] --> D["DuckDB Engine"]
 B["Prometheus"] --> D
 D --> E["Metrics Processor"]
 E --> F["Claude 35 Sonnet"]
 F --> G["Slack Webhook"]

Step 1: The Deterministic Risk & Execution Pipeline

Before touching an LLM API, I built a dedicated analytical script using DuckDB. It queries the local SQLite execution database and local Prometheus metrics snapshot, crunching trade metrics deterministically.

Here is the exact python script (reporter/analytics.py) that extracts order fills, computes execution slippage against the mid-price at time of order routing, and calculates current risk exposures.

import sqlite3
import duckdb
import pandas as pd
import numpy as np
from datetime import datetime, timedelta, timezone

class TradingAnalytics:
def __init__(self, db_path: str):
self.db_path = db_path
self.con = duckdb.connect(database=‘:memory:’)

def load_and_process(self, days: int = 1) -> dict:
# Load local execution database into in-memory DuckDB
sqlite_con = sqlite3.connect(self.db_path)
fills_df = pd.read_sql_query(“SELECT * FROM fills”, sqlite_con)
positions_df = pd.read_sql_query(“SELECT * FROM active_positions”, sqlite_con)
sqlite_con.close()

self.con.register(‘raw_fills’, fills_df)
self.con.register(‘raw_positions’, positions_df)

now = datetime.now(timezone.utc)
cutoff = (now – timedelta(days=days)).strftime(‘%Y-%m-%d %H:%M:%S’)

# Compute accurate deterministic trade summary
trade_summary = self.con.execute(f”””
SELECT
symbol,
COUNT(id) as total_trades,
SUM(CASE WHEN side = ‘BUY’ THEN quantity ELSE -quantity END) as net_volume,
SUM(realized_pnl) as total_pnl,
AVG(abs(executed_price – benchmark_price) / benchmark_price * 10000) as avg_slippage_bps,
MAX(abs(executed_price – benchmark_price) / benchmark_price * 10000) as max_slippage_bps
FROM raw_fills
WHERE timestamp >= ‘{cutoff}’
GROUP BY symbol
“””).df()

# Compute current risk exposures
risk_summary = self.con.execute(“””
SELECT
symbol,
current_qty,
entry_price,
mark_price,
unrealized_pnl,
(current_qty * mark_price) as notional_exposure,
leverage
FROM raw_positions
WHERE current_qty != 0
“””).df()

net_delta = (risk_summary[‘notional_exposure’].sum()
if not risk_summary.empty else 0.0)
total_realized_pnl = trade_summary[‘total_pnl’].sum() if not trade_summary.empty else 0.0
total_unrealized_pnl = risk_summary[‘unrealized_pnl’].sum() if not risk_summary.empty else 0.0

# Calculate win rate and profit factor
wins = trade_summary[trade_summary[‘total_pnl’] > 0][‘total_pnl’].sum()
losses = abs(trade_summary[trade_summary[‘total_pnl’] < 0][‘total_pnl’].sum())
profit_factor = round(wins / losses, 2) if losses > 0 else 999.0

return {
“window_start”: cutoff,
“window_end”: now.strftime(‘%Y-%m-%d %H:%M:%S’),
“summary”: {
“realized_pnl_usd”: round(float(total_realized_pnl), 2),
“unrealized_pnl_usd”: round(float(total_unrealized_pnl), 2),
“net_portfolio_delta_usd”: round(float(net_delta), 2),
“profit_factor”: profit_factor,
“total_fills”: int(trade_summary[‘total_trades’].sum() if not trade_summary.empty else 0)
},
“trade_breakdown”: trade_summary.to_dict(orient=‘records’),
“risk_positions”: risk_summary.to_dict(orient=‘records’)
}

if __name__ == “__main__”:
analytics = TradingAnalytics(db_path=“bot_data/trading_engine.db”)
print(analytics.load_and_process())


Step 2: System Metrics & System Health Aggregation

A sharp spike in slippage or position drift is often caused by infrastructure degradation—such as WebSocket latency spikes or API rate-limit throttling.

To give the AI full context, I query Prometheus for p99 execution latencies and WebSocket disconnect counts over the same 24-hour window:

import requests
from datetime import datetime, timezone

class PrometheusMetricsFetcher:
def __init__(self, prom_url: str = “http://localhost:9090”):
self.prom_url = prom_url

def query_metric(self, query: str) -> float:
try:
response = requests.get(
f”{self.prom_url}/api/v1/query”,
params={“query”: query},
timeout=5
)
data = response.json()
if data[‘status’] == ‘success’ and data[‘data’][‘result’]:
return float(data[‘data’][‘result’][0][‘value’][1])
return 0.0
except Exception as e:
print(f”Failed to fetch Prometheus query [{query}]: {e}”)
return 0.0

def get_system_health(self) -> dict:
return {
“p99_execution_latency_ms”: round(
self.query_metric(‘histogram_quantile(0.99, sum(rate(execution_latency_seconds_bucket[24h])) by (le)) * 1000’), 2
),
“websocket_reconnects_24h”: int(
self.query_metric(‘sum(increase(websocket_reconnections_total[24h]))’)
),
“api_rate_limit_hits_24h”: int(
self.query_metric(‘sum(increase(api_error_code_429_total[24h]))’)
)
}


Step 3: Structuring the AI Risk Reporting Prompt

Once the numbers are generated, I package them into a immutable JSON payload and send it to Claude 3.5 Sonnet via the Anthropic SDK.

The prompt requires strict persona enforcement. I do not want fluff like “Here is your report!” or general market advice. I want an aggressive risk officer who points out inefficiencies, pinpoints slippage anomalies, and warns about delta drift.

Here is the production report generation module (reporter/llm_generator.py):

import json
import os
from anthropic import Anthropic

SYSTEM_PROMPT = “””
You are an elite quantitative risk manager and execution supervisor for an automated algorithmic trading fund.
You receive structured JSON representing the last 24 hours of trading activity, net risk positions, and system performance metrics.

Your task is to generate a concise, markdown-formatted nightly AI report for the engineering lead.

RULES:
1. DO NOT recalculate or guess financial totals. Use ONLY the exact values provided in the JSON payload.
2. Be brutally direct. Highlight execution failures, slippage anomalies, delta drift, and infrastructure bottlenecks.
3. If profit_factor < 1.2 or net_portfolio_delta_usd is significantly non-zero (> $2,000 in absolute terms), flag it as a WARNING.
4. Structure your response into four logical sections:
– Executive Summary (PnL, Volume, Profit Factor)
– Risk & Delta Exposure (Position concentrations, unhedged exposures)
– Execution & Slippage Analysis (Worst execution symbols, latency issues)
– Action Items for Tomorrow Engine Configuration
“””

class NightlyReportGenerator:
def __init__(self, anthropic_api_key: str):
self.client = Anthropic(api_key=anthropic_api_key)

def generate_report(self, analytics_data: dict, health_data: dict) -> str:
payload = {
“analytics”: analytics_data,
“infrastructure”: health_data
}

prompt_content = f”Analyze today’s trading operations based on this data:\n“`json\n{json.dumps(payload, indent=2)}\n“`”

response = self.client.messages.create(
model=“claude-3-5-sonnet-20241022”,
max_tokens=1500,
temperature=0.2, # Low temperature for accurate, non-creative analytical text
system=SYSTEM_PROMPT,
messages=[
{“role”: “user”, “content”: prompt_content}
]
)
return response.content[0].text


Step 4: The End-to-End Orchestrator

I wire these components together into a single master script (runner.py) designed to be invoked by a cron job every night at 00:05 UTC. It posts the formatted trade summary directly to Slack using Webhooks.

import os
import sys
import requests
from reporter.analytics import TradingAnalytics
from reporter.metrics import PrometheusMetricsFetcher
from reporter.llm_generator import NightlyReportGenerator

def send_slack_notification(webhook_url: str, text: str):
payload = {
“text”: text,
“mrkdwn”: True
}
response = requests.post(webhook_url, json=payload, timeout=10)
if response.status_code != 200:
raise RuntimeError(f”Slack post failed: {response.status_code}, {response.text}”)

def main():
db_path = os.getenv(“BOT_DB_PATH”, “/var/app/bot_data/trading_engine.db”)
prom_url = os.getenv(“PROMETHEUS_URL”, “http://localhost:9090”)
anthropic_key = os.getenv(“ANTHROPIC_API_KEY”)
slack_webhook = os.getenv(“SLACK_WEBHOOK_URL”)

if not anthropic_key or not slack_webhook:
print(“CRITICAL: Missing environment variables ANTHROPIC_API_KEY or SLACK_WEBHOOK_URL”)
sys.exit(1)

print(“Step 1: Processing trade analytics via DuckDB…”)
analytics = TradingAnalytics(db_path=db_path)
analytics_data = analytics.load_and_process(days=1)

print(“Step 2: Fetching infrastructure health metrics from Prometheus…”)
fetcher = PrometheusMetricsFetcher(prom_url=prom_url)
health_data = fetcher.get_system_health()

print(“Step 3: Generating AI report narrative with Claude 3.5 Sonnet…”)
reporter = NightlyReportGenerator(anthropic_api_key=anthropic_key)
report_markdown = reporter.generate_report(analytics_data, health_data)

print(“Step 4: Dispatching report to Slack…”)
send_slack_notification(slack_webhook, report_markdown)
print(“Report successfully generated and delivered.”)

if __name__ == “__main__”:
main()


Real Execution Output: What the Output Looks Like

Below is an actual sample of the raw Markdown output generated by the pipeline after a high-volatility session:

# 🚨 Nightly Risk & Execution Report | 2024-10-24

## 1. Executive Summary
– **Realized PnL:** +$342.18 USD
– **Unrealized PnL:** -$89.40 USD
– **Profit Factor:** 1.41
– **Total Fills:** 142

## 2. Risk & Delta Exposure
– **Net Portfolio Delta:** +$4,120.50 USD ⚠️ **[WARNING: EXCEEDS $2,000 LIMIT]**
– **Primary Drift Vector:** Long exposure concentrated in `SOL-PERP` ($3,800.00 USD notional).
– **Leverage:** Maximum active leverage sits at 3.2x on `ETH-PERP`.

## 3. Execution & Slippage Analysis
– **Average Slippage:** 1.82 bps
– **Slippage Anomaly:** `AVAX-PERP` registered a maximum slippage spike of **14.20 bps** during market order routing at 14:22:05 UTC.
– **Latency Metrics:** p99 execution latency reached **420.15 ms** (Baseline: <150 ms).
– **System Faults:** 14 WebSocket reconnections and 2 HTTP 429 rate-limit hits recorded in the last 24h window.

## 4. Engine Action Items
1. **Reduce SOL Exposure:** Trigger rebalancing loop to bring net portfolio delta within the $2,000 threshold.
2. **Review AVAX Order Sizing:** High slippage indicates thin orderbook liquidity at current order sizes; reduce chunk sizes in the execution algorithm.
3. **Inspect WebSocket Connection:** Spike in reconnects correlates with high latency window around 14:00 UTC.


Results and Hard Lessons Learned

Setting up this pipeline radically changed how I operate my trading system.

The Good

  • Immediate Risk Discovery: Three days after deploying this reporter, the system caught a stealth delta drift. My ETH/BTC ratio strategy had failed to close a hedge side due to a transient API timeout, leaving me $6,500 long. The ai report flagged it as a primary risk warning at midnight before the Asian trading session opened.
  • Slippage Visibility: Tracking p95/p99 execution slippage alongside system latency helped me realize that market orders routed between 14:30 and 15:00 EST (US market open) suffered 3x higher slippage. I adjusted the bot’s execution parameters to scale back aggressive orders during that 30-minute window.

The Mistakes & Dead Ends

  1. Never let an LLM format raw floats: Early versions passed raw Python floats like 342.18392019482. Claude attempted to round them, made rounding mistakes, and caused discrepancy reports in my log files. Always format inputs deterministically using DuckDB or Pandas before feeding the context window.
  2. The “Single Day Window” Trap: A 24-hour snapshot in isolation can hide slow memory leaks or subtle latency degradation over time. I had to add rolling 7-day baseline benchmarks to the Prometheus payload so the LLM could contextually flag when today’s p99 latency (420ms) was significantly worse than the week’s average (110ms).
  3. Rate Limits and Retries: Relying on simple HTTP calls for Slack webhooks failed twice when Slack had brief API degradations. I eventually wrapped the notification dispatcher in a tenacity retry decorator with exponential backoff.

Writing code that trades money is only half the battle. Building a reliable deterministic engine to analyze performance—and pairing it with an LLM to distill signal from noise—is what lets me actually sleep at night while the bot trades.

Join the conversation

Your email address will not be published. Required fields are marked *