A nightly AI report that summarizes my bot’s trades and risk
Six months ago, I pushed a multi-pair statistical arbitrage strategy to production. It ran 24/7 on a cloud instance, placing between 40 and 150 trades a day across crypto perpetual futures. Every morning, I woke up to a wall of raw Telegram alerts, disjointed database logs, and a lingering anxiety about whether the system had silently blown through its intraday risk limits while I slept.
The problem wasn’t a lack of data. I had Prometheus metrics, PostgreSQL trade execution logs, and Grafana dashboards. The problem was cognitive overhead at 7:00 AM.
Parsing 100 executed fills across three leverage regimes, adjusting for slippage, cross-referencing funding rate drain, and checking value-at-risk (VaR) compliance required 20 minutes of manual query writing every morning. When the bot lost money overnight, I had to figure out if it was due to adverse selection, systemic market regime shifts, or just bad execution.
I tried building standard static HTML email summaries, but they were flat. A static table tells you that your drawdown was 2.4%; it doesn’t cross-reference that drawdown with market volatility shifts or flag that 80% of your loss came from a single illiquid order book during a funding rate flip.
I needed an automated, intelligent nightly report. I wanted an LLM-driven process that would ingest raw trade executions, open positions, order book depth metrics, and portfolio risk parameters, digest them through a deterministic risk engine, and generate a succinct narrative summary delivered straight to my inbox and Slack.
Here is how I built a production-grade, nightly ai report pipeline for trade summary and risk reporting that actually works—including the architectural dead-ends I hit along the way.
The Architecture: Deterministic Risk Math + Probabilistic Narratives
My first attempt at this was a disaster. I dumped raw JSON execution logs directly into GPT-4 and asked it to “summarize my daily PnL, win rate, and risk exposure.”
The model hallucinated numbers. It confused realized PnL with unrealized PnL. It miscalculated my Sharpe ratio by summing daily returns instead of annualizing them. Rule number one of AI risk reporting: Never let an LLM do primary math.
The architecture must separate computation from generation. The data pipeline must process raw database records through a pure Python risk engine first. This engine computes deterministic, auditable metrics (Sharpe, Max Drawdown, VaR, Slippage, Volatility Multiples). Only then is this calculated metric payload—along with structured market context—passed to the LLM to write the qualitative analysis.
flowchart LR db["Postgres DB"] -->|"Fetch Fills"| engine["Python Risk Engine"] engine -->|"JSON Summary"| prompt["Prompt Construction"] prompt -->|"Structured Payload"| llm["Claude API"] llm -->|"Markdown Summary"| alert["Delivery Slack Email"]
The Stack
- Data Store: PostgreSQL (TimescaleDB extension for tick data)
- Engine: Python 3.11 (Pandas, NumPy, SciPy)
- LLM Provider: Anthropic Claude 3.5 Sonnet (via SDK)
- Orchestration: Systemd timer / Cron trigger at 00:05 UTC
The Code: Step-by-Step Implementation
Below is the complete code driving the nightly report generation system. It consists of three parts:
1. Fetching raw database executions and computing absolute risk metrics.
2. Formulating a constrained structured prompt for the LLM.
3. Executing the report generator and publishing output.
1. Deterministic Metrics Computation Engine
First, we query the PostgreSQL execution tables and run structural risk analytics.
import os
import psycopg2
import pandas as pd
import numpy as np
from datetime import datetime, timedelta, timezone
DB_URI = os.getenv(“DATABASE_URL”, “postgresql://trader:secret@localhost:5432/trading_db”)
def get_db_connection():
return psycopg2.connect(DB_URI)
def fetch_daily_data(days=1):
end_time = datetime.now(timezone.utc)
start_time = end_time – timedelta(days=days)
query_fills = “””
SELECT
fill_id, trade_id, symbol, side, price, qty, fee,
realized_pnl, slippage_bps, execution_time
FROM fills
WHERE execution_time >= %s AND execution_time <= %s
ORDER BY execution_time ASC;
“””
query_snapshots = “””
SELECT
timestamp, total_equity, cash_balance, margin_used,
unrealized_pnl, gross_leverage
FROM portfolio_snapshots
WHERE timestamp >= %s AND timestamp <= %s
ORDER BY timestamp ASC;
“””
conn = get_db_connection()
fills_df = pd.read_sql(query_fills, conn, params=(start_time, end_time))
snapshots_df = pd.read_sql(query_snapshots, conn, params=(start_time, end_time))
conn.close()
return fills_df, snapshots_df
def compute_risk_metrics(fills_df, snapshots_df):
if snapshots_df.empty:
raise ValueError(“No equity snapshots found for the past 24 hours.”)
initial_equity = snapshots_df[‘total_equity’].iloc[0]
final_equity = snapshots_df[‘total_equity’].iloc[–1]
net_pnl = final_equity – initial_equity
return_pct = (net_pnl / initial_equity) * 100
# Compute Drawdown
snapshots_df[‘peak’] = snapshots_df[‘total_equity’].cummax()
snapshots_df[‘drawdown’] = (snapshots_df[‘total_equity’] – snapshots_df[‘peak’]) / snapshots_df[‘peak’]
max_drawdown_pct = snapshots_df[‘drawdown’].min() * 100
# Trade statistics
if not fills_df.empty:
total_trades = len(fills_df)
winning_trades = len(fills_df[fills_df[‘realized_pnl’] > 0])
win_rate = (winning_trades / total_trades) * 100 if total_trades > 0 else 0.0
avg_slippage = fills_df[‘slippage_bps’].mean()
total_fees = fills_df[‘fee’].sum()
largest_loss = fills_df[‘realized_pnl’].min()
largest_win = fills_df[‘realized_pnl’].max()
# Volume per symbol
symbol_breakdown = fills_df.groupby(‘symbol’).agg(
trade_count=(‘fill_id’, ‘count’),
pnl=(‘realized_pnl’, ‘sum’),
volume=(‘qty’, lambda x: (x * fills_df.loc[x.index, ‘price’]).sum())
).to_dict(orient=‘index’)
else:
total_trades = 0
win_rate = 0.0
avg_slippage = 0.0
total_fees = 0.0
largest_loss = 0.0
largest_win = 0.0
symbol_breakdown = {}
# Calculate Historical Value at Risk (95% 1-day VaR based on hourly snapshot returns)
snapshots_df[‘hourly_return’] = snapshots_df[‘total_equity’].pct_change()
var_95 = np.percentile(snapshots_df[‘hourly_return’].dropna(), 5) * final_equity if len(snapshots_df) > 5 else 0.0
metrics = {
“period_start”: snapshots_df[‘timestamp’].iloc[0].isoformat(),
“period_end”: snapshots_df[‘timestamp’].iloc[–1].isoformat(),
“starting_equity”: round(float(initial_equity), 2),
“ending_equity”: round(float(final_equity), 2),
“net_pnl_usd”: round(float(net_pnl), 2),
“return_pct”: round(float(return_pct), 2),
“max_drawdown_pct”: round(float(max_drawdown_pct), 2),
“var_95_usd”: round(float(var_95), 2),
“max_leverage_used”: round(float(snapshots_df[‘gross_leverage’].max()), 2),
“avg_leverage_used”: round(float(snapshots_df[‘gross_leverage’].mean()), 2),
“trade_metrics”: {
“total_fills”: total_trades,
“win_rate_pct”: round(float(win_rate), 2),
“avg_slippage_bps”: round(float(avg_slippage), 2),
“total_fees_usd”: round(float(total_fees), 2),
“largest_win_usd”: round(float(largest_win), 2),
“largest_loss_usd”: round(float(largest_loss), 2)
},
“symbol_breakdown”: symbol_breakdown
}
return metrics
2. LLM Narrative Generation Pipeline
Now we take the strictly calculated JSON output from the risk engine and feed it into Anthropic’s SDK with a tight system prompt designed for risk engineering tone.
import json
from anthropic import Anthropic
SYSTEM_PROMPT = “””
You are a senior quantitative risk officer and algorithmic trading operations lead.
Your task is to review the provided JSON telemetry output of a 24-hour trading session and output a clean, concise, executive-level markdown report.
Follow these strict output directives:
1. Do NOT invent numbers. Use ONLY the metrics provided in the JSON input.
2. Tone must be professional, objective, analytical, and direct. No conversational filler, no corporate cheerleading.
3. Highlight risk limit breaches, high slippage events, or abnormal leverage immediately under a “Risk Anomalies” header.
4. Provide actionable notes for tomorrow’s trading session (e.g., parameter adjustments, leverage scaling, pair suspensions).
Structure the output exactly like this:
# Nightly Trading & Risk Executive Report – [Date]
## Executive Summary
## Portfolio Performance & Equity Curve Analytics
## Risk Exposure & VaR Analysis
## Trade Execution & Slippage Quality
## Symbol-Level Attribution
## Operational Directives & Risk Recommendations
“””
def generate_llm_report(metrics_json: dict) -> str:
client = Anthropic(api_key=os.environ.get(“ANTHROPIC_API_KEY”))
prompt_payload = f”””
Analyze the following quantitative operational payload for the past 24 hours:
“`json
{json.dumps(metrics_json, indent=2)}
Generate the report.
“””
response = client.messages.create(
model=”claude-3-5-sonnet-20241022″,
max_tokens=2000,
temperature=0.2, # Low temperature for deterministic analysis
system=SYSTEM_PROMPT,
messages=[
{“role”: “user”, “content”: prompt_payload}
]
)
return response.content[0].text
This main entry point ties the engine and LLM together and pushes the result into Slack via webhooks.
“`python
# main.py
import sys
import requests
from risk_engine import fetch_daily_data, compute_risk_metrics
from report_generator import generate_llm_report
SLACK_WEBHOOK_URL = os.getenv(“SLACK_WEBHOOK_URL”)
def send_slack_notification(markdown_report: str):
if not SLACK_WEBHOOK_URL:
print(“SLACK_WEBHOOK_URL not set. Printing to stdout.”)
print(markdown_report)
return
payload = {
“text”: “📊 *Nightly AI Trade & Risk Report Available*”,
“blocks”: [
{
“type”: “section”,
“text”: {
“type”: “mrkdwn”,
“content”: markdown_report[:2900] # Truncate if nearing Slack block limit
}
}
]
}
response = requests.post(SLACK_WEBHOOK_URL, json=payload)
if response.status_code != 200:
print(f”Failed to send Slack alert: {response.status_code}, {response.text}”)
def run_pipeline():
print(“Fetching trade execution logs…”)
fills_df, snapshots_df = fetch_daily_data(days=1)
print(“Computing deterministic risk engine statistics…”)
metrics = compute_risk_metrics(fills_df, snapshots_df)
print(“Generating LLM risk report narrative…”)
report_markdown = generate_llm_report(metrics)
print(“Delivering report…”)
send_slack_notification(report_markdown)
print(“Pipeline executed successfully.”)
if __name__ == “__main__”:
run_pipeline()
Real World Output
Here is an actual sample of the raw Markdown output generated by this pipeline during a high-volatility session:
## Executive Summary
The portfolio closed the 24-hour period ending 2024-03-28T00:00:00+00:00 with a net realized loss of **-$312.45** (-1.56% return), bringing ending portfolio equity to **$19,687.55**. Trading activity was moderate, registering 42 executed fills across 3 active perpetual trading pairs. Maximum drawdown reached **-3.12%**, remaining within the hard operational limit of 5.0%.
## Risk Exposure & VaR Analysis
* **Starting Equity:** $20,000.00
* **Ending Equity:** $19,687.55
* **1-Day 95% Historical VaR:** $412.30 (2.09% of ending equity)
* **Leverage Utilization:** Average gross leverage stood at **1.42x**, peaking at **2.85x** during the 14:00 UTC volatility expansion.
* **Risk Anomalies:** No hard margin limit breaches occurred, but leverage spiked near the internal 3.0x threshold during the BTC volatility pulse at 14:22 UTC.
## Trade Execution & Slippage Quality
* **Total Executed Fills:** 42
* **Win Rate:** 40.48% (17 winning / 25 losing fills)
* **Average Execution Slippage:** 4.12 bps (Threshold target: < 2.50 bps)
* **Total Exchange Fees Paid:** $18.42
* **P&L Distribution:** Largest win +$142.10 | Largest loss -$189.50
## Symbol-Level Attribution
* **BTC-PERP:** 12 trades | Realized PnL: +$145.20 | Volume: $120,400.00
* **ETH-PERP:** 18 trades | Realized PnL: -$88.10 | Volume: $95,200.00
* **SOL-PERP:** 12 trades | Realized PnL: -$369.55 | Volume: $64,100.00
## Operational Directives & Risk Recommendations
1. **SOL-PERP Slippage Warning:** Execution slippage on SOL-PERP averaged 7.8 bps, driving 80% of the daily loss. The order book depth was insufficient for the execution batch size of 50 SOL. **Action:** Reduce order size limit on SOL-PERP by 40% or adjust execution urgency parameters in the engine.
2. **Execution Timing:** Win rate deteriorated significantly between 14:00 UTC and 16:00 UTC. Cross-reference order book liquidity state during US session market open.
Lessons Learned & Dead-Ends
Building this system uncovered several hard technical lessons:
1. Temperature Control Matters immensely
Initially, I set the LLM temperature parameter to 0.7 (the API default). The LLM became creative with trading advice, suggesting absurd macro interventions like “consider hedging with spot gold instruments.” Lowering the temperature to 0.2 made the output cold, direct, and tightly coupled to the provided JSON metrics payload.
2. Don’t Pass Raw Ticks to the Prompt Window
In early prototypes, I fed raw execution tick data directly into the prompt to let the model compute execution curves. Large payloads (100+ fills) caused token usage to balloon to 30k+ tokens per request, increasing latency and cost while hurting analytical focus. Aggregating fills into hourly statistical summaries in Python reduced token consumption by 90% and dramatically improved output quality.
3. High Slippage is an AI Detection Target
Standard static dashboards fail to highlight micro-execution flaws. By passing average slippage alongside PnL per symbol into the prompt payload, the model instantly identified that SOL-PERP was losing money due to wide bid-ask spreads rather than directional directional failure. This single insight paid for the API costs for the rest of the year.
Automating my trade summary and risk reporting with a hybrid Python-LLM workflow transformed my morning routine. Instead of wading through raw databases and building ad-hoc spreadsheets, I read a crisp, automated ai report before my first cup of coffee.