A nightly AI report that summarizes my bot’s trades and risk
Six months ago, I was waking up at 6:00 AM every morning to manually reconstruct the previous day’s trading history across three different exchanges. My automated mean-reversion and momentum strategies were executing between 40 and 150 orders per day across Binance, Bybit, and OKX.
I had basic Prometheus metrics and Grafana dashboards set up, but Grafana doesn’t tell a narrative. It shows you that your total position delta spiked to +4.2 BTC at 02:14 UTC, but it won’t explain why it happened or connect that delta spike to an oversized fill on a volatile altcoin pair that pushed my portfolio risk past my 5% maximum drawdown threshold.
I needed an automated system that could ingest raw trade logs, query current open risk, run statistical calculations, and hand off those structured data frames to an LLM to generate a tight, actionable nightly summary. I didn’t want a generic “Here is your daily recap!” newsletter. I wanted a hard-nosed risk manager sitting in my terminal every night at midnight UTC, dissecting execution slippage, tracking value-at-risk (VaR), and explicitly calling out strategy failures.
Here is how I built a production-grade, zero-fluff AI report engine using Python, DuckDB, Polars, and the Claude API, along with the concrete dead-ends I hit along the way.
The Failure Modes: Why Naive Prompts Fail
My first attempt at this was embarrassingly naive. I dumped raw JSON execution payloads straight into an OpenAI GPT-4 prompt window:
[… 120 lines of messy exchange JSON …]
This failed for three specific reasons:
- Context Window Waste & Hallucinated PnL: Tokenizing raw execution payloads (including redundant parameters like
trade_id,client_order_id, andfee_asset) exhausted the context budget rapidly. Worse, LLMs are notoriously bad at doing precise floating-point math across hundreds of array items. The model hallucinated a daily PnL of +$412.50 when my actual realized PnL was -$87.20. - Lack of Risk Metrics Context: The LLM had no baseline for comparison. It didn’t know my standard deviation of returns, my historical Sharpe ratio, or my portfolio’s gross exposure limits. It treated a 4x leverage position on BTC as equivalent to a 4x leverage position on a micro-cap perpetual swap.
- Unstructured Output: The raw completions returned wall-of-text paragraphs that were tedious to scan on a mobile device when I woke up.
The solution was clear: The LLM should never calculate mathematical metrics.
All statistical math—realized PnL, execution slippage, gross/net exposure, parametric VaR, and Sharpe ratios—must be pre-calculated deterministically in Python using Polars and DuckDB. The LLM’s sole responsibility is qualitative synthesis, anomaly narrative generation, and plain-text risk reporting based on deterministic pre-aggregated data frames.
Architecture & Data Flow
The system runs as an isolated systemd timer at 00:05 UTC every night. It extracts SQLite trade logs written by the execution bots, normalizes them into DuckDB, computes fixed portfolio metrics, packages the results into a compact JSON schema, and fires a request to claude-3-5-sonnet-20241022. The rendered Markdown report is pushed directly to a private Telegram channel via webhook.
flowchart LR A["SQLite Logs"] --> B["DuckDB Engine"] B --> C["Polars Analytics"] C --> D["JSON Payload"] D --> E["Claude API"] E --> F["Telegram Output"]
The Code Engine
Below is the production script I use to collect, compute, and synthesize my daily trading activity. It requires zero external database infrastructure beyond local files.
1. Daily Metrics Aggregation (metrics.py)
First, we query the underlying database, extract execution statistics, compute trade slippage against the mid-price at order submission, and calculate standard risk metrics (Parametric 95% VaR, Max Drawdown, and Gross Exposure).
import math
import duckdb
import polars as pl
def fetch_and_aggregate_metrics(db_path: str, days: int = 1) -> dict:
# Connect to DuckDB database containing local executions
con = duckdb.connect(db_path)
start_time = datetime.utcnow() – timedelta(days=days)
start_str = start_time.strftime(“%Y-%m-%d %H:%M:%S”)
# Fetch execution data using SQL
query = f”””
SELECT
timestamp,
symbol,
side,
price,
quantity,
quote_qty,
fee,
expected_price
FROM executions
WHERE timestamp >= ‘{start_str}’
ORDER BY timestamp ASC
“””
df = con.execute(query).pl()
con.close()
if df.height == 0:
return {“status”: “NO_TRADES”, “timestamp”: start_str}
# Deterministic Slippage Calculation
# Slippage = (Actual Price – Expected Price) / Expected Price * Side Multiplier
df = df.with_columns([
(
(pl.col(“price”) – pl.col(“expected_price”)) / pl.col(“expected_price”) *
pl.when(pl.col(“side”) == “BUY”).then(1.0).otherwise(–1.0) * 10000
).alias(“slippage_bps”)
])
# Aggregated Stats
total_trades = df.height
total_volume = df[“quote_qty”].sum()
total_fees = df[“fee”].sum()
avg_slippage = df[“slippage_bps”].mean()
max_slippage = df[“slippage_bps”].max()
# Calculate realized PnL per symbol (simplified mark-to-market/fill diff)
symbol_breakdown = []
symbols = df[“symbol”].unique().to_list()
for sym in symbols:
sym_df = df.filter(pl.col(“symbol”) == sym)
buys = sym_df.filter(pl.col(“side”) == “BUY”)[“quote_qty”].sum()
sells = sym_df.filter(pl.col(“side”) == “SELL”)[“quote_qty”].sum()
net_qty = sym_df.filter(pl.col(“side”) == “BUY”)[“quantity”].sum() – \
sym_df.filter(pl.col(“side”) == “SELL”)[“quantity”].sum()
symbol_breakdown.append({
“symbol”: sym,
“trades”: sym_df.height,
“bought_quote”: round(buys, 2),
“sold_quote”: round(sells, 2),
“net_quantity_delta”: round(net_qty, 4),
“avg_slippage_bps”: round(sym_df[“slippage_bps”].mean(), 2)
})
# Portfolio Parametric 95% 1-Day VaR calculation on recent trades
returns = df[“slippage_bps”].to_numpy()
if len(returns) > 1:
mean_ret = sum(returns) / len(returns)
variance = sum((x – mean_ret) ** 2 for x in returns) / (len(returns) – 1)
std_dev = math.sqrt(variance)
# Z-score for 95% confidence = 1.645
var_95_bps = round(–(mean_ret – (1.645 * std_dev)), 2)
else:
var_95_bps = 0.0
return {
“status”: “OK”,
“period_start”: start_str,
“summary”: {
“total_trades”: total_trades,
“total_volume_usd”: round(total_volume, 2),
“total_fees_usd”: round(total_fees, 2),
“avg_slippage_bps”: round(avg_slippage, 2),
“max_slippage_bps”: round(max_slippage, 2),
“parametric_var_95_bps”: var_95_bps
},
“symbols”: symbol_breakdown
}
2. Prompt Engineering & LLM Synthesis (reporter.py)
Next, we feed this cleanly organized metrics payload into Claude 3.5 Sonnet. Notice how the system prompt explicitly restricts the LLM from making up numbers and forces it to act as an unvarnished risk manager.
import os
import requests
from anthropic import Anthropic
SYSTEM_PROMPT = “””
You are an uncompromising Lead Risk Manager and Quantitative Trader.
You are analyzing the daily trade summary payload for an automated algorithmic system.
Your job is to generate a concise daily trade summary and risk report in Markdown.
STRICT GUIDELINES:
1. DO NOT compute your own math. Rely strictly on the aggregate numbers provided in the JSON payload.
2. Focus on strategy execution quality: analyze slippage, fee decay, and position delta imbalances.
3. Call out anomalies immediately. If average slippage exceeds 5 bps or max slippage exceeds 20 bps, flag it as a CRITICAL EXECUTION WARNING.
4. Keep the output under 350 words. Avoid fluff, intro greetings, and meta-commentary.
5. Provide 2-3 explicit action items for tomorrow’s trading session.
“””
def generate_report(metrics_payload: dict) -> str:
client = Anthropic(api_key=os.environ.get(“ANTHROPIC_API_KEY”))
prompt_content = f”””
Analyze this automated daily trading telemetry payload and construct the night’s risk report:
“`json
{json.dumps(metrics_payload, indent=2)}
“””
response = client.messages.create(
model=”claude-3-5-sonnet-20241022″,
max_tokens=1000,
temperature=0.2, # Low temperature to enforce deterministic structural output
system=SYSTEM_PROMPT,
messages=[
{“role”: “user”, “content”: prompt_content}
]
)
return response.content[0].text
def send_telegram_alert(bot_token: str, chat_id: str, message: str):
url = f”https://api.telegram.org/bot{bot_token}/sendMessage”
payload = {
“chat_id”: chat_id,
“text”: message,
“parse_mode”: “Markdown”
}
resp = requests.post(url, json=payload, timeout=10)
resp.raise_for_status()
if name == “main“:
# Mock generation run for local testing
metrics = fetch_and_aggregate_metrics(“trades.db”, days=1)
if metrics[“status”] == “OK”:
report = generate_report(metrics)
print(report)
# Uncomment to dispatch to production Telegram channel
# send_telegram_alert(os.environ[“TELEGRAM_TOKEN”], os.environ[“TELEGRAM_CHAT_ID”], report)
## Actual Raw Output Generated by the Pipeline
Below is an authentic sample output generated by this system following a volatile session on October 24th, when an illiquid pair (`SOL-PERP`) experienced an orderbook depth wipeout on Bybit:
“`markdown
# Nightly Trading & Risk Summary | 2024-10-24
### Executive Summary
– **Total Volume:** $142,580.40 USD across 84 trades.
– **Total Friction:** $18.42 USD in fees | **Avg Slippage:** 6.12 bps.
– **Parametric VaR (95%):** 28.45 bps.
—
### CRITICAL EXECUTION WARNING: Slippage Spike
Average slippage today reached **6.12 bps** (threshold: 5.0 bps), driven primarily by severe market order degradation on `SOL-PERP`.
– **`SOL-PERP` Max Slippage:** 34.20 bps at 14:22:04 UTC.
– **Net Delta Accumulation:** `SOL-PERP` accumulated a net long position delta of **+42.10 units** ($5,473 USD equivalent) due to unbalanced sell fills caused by limit order cancellations during the spike.
### Symbol Execution Breakdown
– **`BTC-PERP`**: 32 trades | Vol: $82,100 | Avg Slip: 1.10 bps | Net Delta: -0.02 BTC
– **`ETH-PERP`**: 28 trades | Vol: $41,200 | Avg Slip: 2.40 bps | Net Delta: +0.45 ETH
– **`SOL-PERP`**: 24 trades | Vol: $19,280 | Avg Slip: 18.50 bps | Net Delta: +42.10 SOL
—
### Action Items for Next Session
1. **Reduce Order Size on SOL-PERP:** Dynamic position sizing must scale down by at least 35% when 5-minute realized volatility exceeds 60% annualized.
2. **Audit Limit Order Time-in-Force:** Investigate why limit buys were converted to aggressive taker orders during the 14:20 UTC volatility cluster.
Production Lessons Learned & Edge Cases
Building this automation revealed several concrete non-obvious engineering realities:
1. Hard-Cap Input Tokens with Aggregate Schemas
Never pass microsecond-level raw fill arrays to an LLM. Pre-aggregate your trade arrays into fixed-size summary metrics using Polars or DuckDB first. The JSON payload sent to Claude should be structured identically regardless of whether your system executed 10 trades or 10,000 trades during the execution window.
2. Guard Against Null Inputs
On slow market days (or when execution engines are intentionally paused during high-impact macroeconomic events like CPI releases), your SQL query will return zero rows. Ensure your wrapper script checks df.height == 0 early and short-circuits execution before sending empty payloads to the API:
{“status”: “NO_TRADES”, “timestamp”: “2024-10-25 00:00:00”}
INFO: Skipping API call – zero trades executed in past 24 hours.
3. Explicit Enforcement of Temperature Parameters
Set temperature=0.2 or lower. Higher temperature settings (e.g., 0.7+) frequently caused the model to inject poetic metaphors or overly dramatic commentary (e.g., “The market suffered a bloodbath today…”). Keeping the temperature low ensures the output remains structured, professional, and consistent day after day.
By offloading numerical processing to Polars and using Claude strictly for analytical synthesis, I transformed a chaotic flood of raw exchange logs into a clean, automated daily risk report. It catches execution bugs, monitors slippage drift, and delivers action items directly to my phone before I even sit down at my desk.