Three Gemini Personas Debate a Losing Volatility Breakout Strategy
A backtest of a volatility breakout strategy on high-beta stocks tuned by a Quant, a Risk Manager and an Execution persona, with what improved and what still lagged SPY.
This article is published in English.
Volatility breakouts tempt nearly every quant who owns a Python script and a market-data wrapper. High-beta stocks trend happily until they reverse hard, and a single afternoon can wipe out an account. Optimizers aimed at one number, usually the Sharpe ratio, twist parameters until historical noise looks like alpha. Live markets don't care about an overfitted grid search.
Conventional tuning also treats risk as an afterthought, a static stop or a fixed position size added at the end. That fails because generating alpha and surviving call for opposite mindsets. A quantitative analyst wants strong exposure to momentum, while an experienced risk manager wants the hatches battened before volatility jumps.
This experiment tries to bridge the two with a multi-agent debate among three Gemini personas: a Quant Analyst, a Risk Manager and an Execution Strategist. They critique, revise and validate a volatility breakout strategy over a portfolio of fifteen high-beta equities plus SPY as the benchmark. They won't always agree, and the friction is intentional. Averaging parameter suggestions across personas with different priorities steadies the result.
Here's where the run ended after three rounds of structured debate:
{
"strategy_version": "v2.0-optimized",
"final_sharpe_ratio": -0.6822300207528283,
"consensus_rationale": "Iteration 1 consensus achieved superior Sharpe ratio through optimized ATR multiplier and volume threshold refinement.",
"max_drawdown_delta": 0.00687485272186061,
"total_iterations_run": 3
}
The baseline began at a dreadful Sharpe ratio of negative 2.68 with a negative cumulative return. The debate pulled the strategy out of that hole, and it also delivered a sobering comparison with the broader market. The build needed careful data handling and a modular backtester, so the walkthrough starts with the market universe and historical data.
Data and market universe
The high-beta universe
Picking single tech stocks on social-media hype isn't a method, and a structured universe is the starting point. The test uses fifteen high-beta equities with SPY alongside. High-beta names supply the sharp price dispersion that breakout rules need, while SPY is the baseline that separates real alpha from beta-driven noise.
Before any breakout logic exists, imports and global configuration have to be defined cleanly. Imports cover pandas and numpy for the math, yfinance for prices, and Google's Gen AI SDK, which drives the personas. Keeping the settings in one place makes later experiments easy to repeat.
import os
import json
import logging
from datetime import datetime, timezone
import pandas as pd
import numpy as np
import yfinance as yf
import matplotlib.pyplot as plt
from google import genai
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
Missing data and MultiIndex alignment
Financial data is messy. Yahoo Finance may return MultiIndex columns or scattered NaN values caused by halts, different listing dates or corporate actions. Feed misaligned DataFrames into a breakout backtester and position calculations drift apart, which turns portfolio returns into fiction.
The MarketDataLoader class deals with this by wrapping the download. It forces auto_adjust=True so prices are corrected for splits and dividends, applies forward filling, and safely drops any leading NaN rows left by staggered IPO dates, which keeps the shape uniform.
class MarketDataLoader:
def __init__(self, tickers: list[str], benchmark: str):
self.tickers = tickers
self.all_symbols = tickers + [benchmark]
self.benchmark = benchmark
def fetch_data(self) -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame]:
end_date = datetime.now(timezone.utc).strftime('%Y-%m-%d')
start_date = (datetime.now(timezone.utc) -
pd.Timedelta(days=365 * 3)).strftime('%Y-%m-%d')
logging.info(
f"Fetching historical data from {start_date} to {end_date} for {len(self.all_symbols)} symbols.")
data = yf.download(self.all_symbols, start=start_date,
end=end_date, auto_adjust=True, progress=False)
if data.empty:
logging.error(
f"Failed to download data for symbols: {self.all_symbols}")
raise ValueError(
f"Failed to download data for symbols: {self.all_symbols}")
if isinstance(data.columns, pd.MultiIndex):
close = data['Close'] if 'Close' in data.columns.levels[0] else data.xs(
'Close', level=1, axis=1)
high = data['High'] if 'High' in data.columns.levels[0] else data.xs(
'High', level=1, axis=1)
low = data['Low'] if 'Low' in data.columns.levels[0] else data.xs(
'Low', level=1, axis=1)
volume = data['Volume'] if 'Volume' in data.columns.levels[0] else data.xs(
'Volume', level=1, axis=1)
else:
close = data[['Close']]
high = data[['High']]
low = data[['Low']]
volume = data[['Volume']]
close = close.ffill().dropna(how='all')
high = high.ffill().dropna(how='all')
low = low.ffill().dropna(how='all')
volume = volume.ffill().fillna(0.0)
if close.empty:
logging.error(
"Cleaned price data DataFrame is empty after processing.")
raise ValueError(
"Cleaned price data DataFrame is empty after processing.")
logging.info(
f"Data checkpoint - Shape: {close.shape}, Column sample: {list(close.columns[:3])}, NaN count: {close.isna().sum().sum()}, Date range: {close.index[0]} to {close.index[-1]}")
return close, high, low, volume
When the pipeline runs, the loader pulls three years of daily data for all sixteen symbols and confirms alignment before any math touches it:
INFO - Fetching historical data from 2023-08-10 to 2026-08-09 for 16 symbols.
INFO - Data checkpoint - Shape: (751, 16), Column sample: ['AMD', 'COIN', 'DKNG'], NaN count: 0, Date range: 2023-08-10 00:00:00 to 2026-08-07 00:00:00
The log shows 751 trading days by 16 symbols, from August 2023 to August 2026, with zero NaN values. With the panel synchronized and verified, attention can move from data engineering to the strategy.
The breakout engine
Momentum and volatility together
Breakouts attract retail traders because they promise instant momentum. In practice, many breakout signals in high-beta names are false moves that trap liquidity before a reversal. A price crossing a threshold means little without volume expansion and volatility scaling to confirm it.
A dependable backtester therefore has to look at how price interacts with rolling volume and volatility bands. When price clears a rolling high while volume surges past its moving average, the signal has real weight. Otherwise it's noise.
Simulating portfolio returns
The VolatilityStrategyBacktester class holds this logic. It takes the clean price and volume frames from the loader, computes the indicators and simulates daily portfolio returns from configurable parameters such as lookback windows and volatility thresholds. The implementation below runs simulations across the multi-symbol portfolio with no state leaking between runs.
class VolatilityStrategyBacktester:
def __init__(self, close_df: pd.DataFrame, high_df: pd.DataFrame, low_df: pd.DataFrame, volume_df: pd.DataFrame, benchmark: str):
self.close_df = close_df
self.high_df = high_df
self.low_df = low_df
self.volume_df = volume_df
self.benchmark = benchmark
self.asset_columns = [c for c in close_df.columns if c != benchmark]
def backtest(self, params: dict) -> tuple[pd.Series, pd.Series]:
lookback = int(params.get("lookback", 20))
atr_mult = float(params.get("atr_multiplier", 2.0))
vol_thresh = float(params.get("volume_threshold", 1.5))
asset_returns_dict = {}
for ticker in self.asset_columns:
if ticker not in self.close_df.columns:
continue
c = self.close_df[ticker]
h = self.high_df[ticker]
l = self.low_df[ticker]
v = self.volume_df[ticker]
tr1 = h - l
tr2 = (h - c.shift(1)).abs()
tr3 = (l - c.shift(1)).abs()
tr = pd.concat([tr1, tr2, tr3], axis=1).max(axis=1)
atr = tr.rolling(window=lookback).mean()
rolling_high = c.rolling(window=lookback).max()
avg_vol = v.rolling(window=lookback).mean()
breakout = (c > rolling_high.shift(1) + atr_mult *
atr) & (v > vol_thresh * avg_vol)
asset_ret = c.pct_change()
strat_ret = asset_ret * breakout.shift(1).fillna(False)
trades = breakout & (~breakout.shift(1).fillna(False))
strat_ret = strat_ret - (trades.astype(float) * 0.001)
asset_returns_dict[ticker] = strat_ret
strategy_df = pd.DataFrame(asset_returns_dict)
portfolio_returns = strategy_df.mean(axis=1).fillna(0.0)
benchmark_returns = self.close_df[self.benchmark].pct_change().fillna(
0.0)
return portfolio_returns, benchmark_returns
Running it across the fifteen stocks and SPY before any agent involvement, using the untuned parameters, gives a harsh result:
INFO - Baseline Metrics: Sharpe=-2.68, Return=-2.79%
A Sharpe of negative 2.68 and a cumulative return of negative 2.79 percent show how quickly static parameters in a high-beta basket can wreck an account. That failure is what the debate architecture is meant to repair, after a naive grid search made things worse.
Persona design and the debate loop
Using the model as a reasoner, not an oracle
Many attempts at LLMs in quantitative finance fail because the model is treated as an oracle asked to predict tomorrow's price, which is a quick way to lose capital. Here the model works as a linguistic reasoner inside a structured optimization loop. It judges how sensitive the parameters are and makes no attempt to forecast prices.
A configuration class holds the base hyperparameters and the model identifiers needed to reach the Google Gen AI SDK:
class Config:
TICKERS = [
"TSLA", "NVDA", "AMD", "PLTR", "COIN",
"MARA", "RIOT", "MSTR", "HOOD", "ROKU",
"UBER", "SHOP", "SNAP", "PTON", "DKNG"
]
BENCHMARK = "SPY"
MAX_ITERATIONS = 3
INITIAL_PARAMS = {
"lookback": 20,
"atr_multiplier": 2.0,
"volume_threshold": 1.5,
"stop_loss_pct": 0.05
}
To make the debate productive, three specialized personas are created. The Quant Analyst watches alpha decay and threshold sensitivity. The Risk Manager is preoccupied with drawdown limits and volatility metrics. The Execution Strategist looks at turnover and slippage.
class GeminiAgentPersona:
def __init__(self, name: str, role: str, system_prompt: str):
self.name = name
self.role = role
self.system_prompt = system_prompt
self.client = genai.Client()
def evaluate(self, current_params: dict, metrics: dict, iteration: int) -> dict:
prompt = f"""
You are {self.name}, a specialized {self.role} in a multi-agent quantitative trading system.
Current Iteration: {iteration}
Current Strategy Parameters: {json.dumps(current_params, indent=2)}
Current Backtest Performance Metrics: {json.dumps(metrics, indent=2)}
Analyze the performance and parameters from your professional perspective. Provide your critique and propose specific parameter adjustments (lookback, atr_multiplier, volume_threshold, stop_loss_pct) to improve the Sharpe ratio and reduce max drawdown.
You MUST return a valid JSON object with keys:
- "critique": Detailed analytical critique from your persona's perspective.
- "proposed_adjustment": Dictionary of recommended parameter changes (e.g., ).
- "confidence_score": Float between 0 and 1 representing your confidence in this adjustment.
"""
response = self.client.models.generate_content(
model="gemini-3.5-flash-lite",
contents=prompt
)
text = response.text
clean_text = text.strip()
if clean_text.startswith("```json"):
clean_text = clean_text[7:]
if clean_text.endswith("```"):
clean_text = clean_text[:-3]
try:
parsed = json.loads(clean_text.strip())
except json.JSONDecodeError:
parsed = {
"critique": text[:500],
"proposed_adjustment": current_params,
"confidence_score": 0.6
}
return parsed
The debate coordinator
When the personas meet, they don't just trade opinions. The PersonaDebateCoordinator runs a disciplined critique loop. It takes the previous iteration's backtest results, passes the metrics to each persona and gathers structured JSON answers containing critiques and proposed parameter changes.
To stop the model from inventing oversized position sizes or endless lookback windows, the coordinator applies strict parameter clipping. It also averages the personas' recommendations, which smooths convergence between iterations.
class PersonaDebateCoordinator:
def __init__(self, backtester: VolatilityStrategyBacktester, initial_params: dict, max_iterations: int):
self.backtester = backtester
self.current_params = initial_params.copy()
self.max_iterations = max_iterations
self.quant = GeminiAgentPersona(
"QuantAnalyst",
"Quantitative Strategist",
"Focuses on alpha generation, indicator sensitivity, and statistical edge."
)
self.risk = GeminiAgentPersona(
"RiskManager",
"Risk Officer",
"Focuses on drawdowns, tail risk, position sizing, and volatility caps."
)
self.execution = GeminiAgentPersona(
"ExecutionStrategist",
"Execution Trading Specialist",
"Focuses on liquidity, volume confirmation, slippage, and practical execution friction."
)
self.audit_log = []
self.parameter_history = []
def run_iterative_loop(self) -> dict:
best_sharpe = -999.0
consensus_rationale = "Initial baseline strategy evaluation."
p_ret, b_ret = self.backtester.backtest(self.current_params)
baseline_metrics = calculate_performance_metrics(p_ret, b_ret)
current_metrics = baseline_metrics
logging.info(
f"Baseline Metrics: Sharpe={baseline_metrics['sharpe_ratio']:.2f}, Return={baseline_metrics['cumulative_return']*100:.2f}%")
for i in range(1, self.max_iterations + 1):
logging.debug(
f"--- Starting Debate Iteration {i}/{self.max_iterations} ---")
q_eval = self.quant.evaluate(
self.current_params, current_metrics, i)
r_eval = self.risk.evaluate(
self.current_params, current_metrics, i)
e_eval = self.execution.evaluate(
self.current_params, current_metrics, i)
for persona_name, eval_data in [("QuantAnalyst", q_eval), ("RiskManager", r_eval), ("ExecutionStrategist", e_eval)]:
self.audit_log.append({
"iteration_number": i,
"persona_name": persona_name,
"critique_text": eval_data.get("critique", ""),
"proposed_adjustment": eval_data.get("proposed_adjustment", {}),
"confidence_score": eval_data.get("confidence_score", 0.8)
})
q_adj = q_eval.get("proposed_adjustment", {})
r_adj = r_eval.get("proposed_adjustment", {})
e_adj = e_eval.get("proposed_adjustment", {})
new_lookback = int(np.mean([
float(q_adj.get("lookback",
self.current_params["lookback"])),
float(r_adj.get("lookback",
self.current_params["lookback"])),
float(e_adj.get("lookback",
self.current_params["lookback"]))
]))
new_atr = float(np.mean([
float(q_adj.get("atr_multiplier",
self.current_params["atr_multiplier"])),
float(r_adj.get("atr_multiplier",
self.current_params["atr_multiplier"])),
float(e_adj.get("atr_multiplier",
self.current_params["atr_multiplier"]))
]))
new_vol_thresh = float(np.mean([
float(q_adj.get("volume_threshold",
self.current_params["volume_threshold"])),
float(r_adj.get("volume_threshold",
self.current_params["volume_threshold"])),
float(e_adj.get("volume_threshold",
self.current_params["volume_threshold"]))
]))
new_sl = float(np.mean([
float(q_adj.get("stop_loss_pct",
self.current_params["stop_loss_pct"])),
float(r_adj.get("stop_loss_pct",
self.current_params["stop_loss_pct"])),
float(e_adj.get("stop_loss_pct",
self.current_params["stop_loss_pct"]))
]))
self.current_params = {
"lookback": max(5, min(60, new_lookback)),
"atr_multiplier": max(1.0, min(4.0, new_atr)),
"volume_threshold": max(1.0, min(3.0, new_vol_thresh)),
"stop_loss_pct": max(0.01, min(0.15, new_sl))
}
p_ret_new, b_ret_new = self.backtester.backtest(
self.current_params)
current_metrics = calculate_performance_metrics(
p_ret_new, b_ret_new)
logging.debug(
f"Iteration {i} Results: Sharpe={current_metrics['sharpe_ratio']:.2f}, Return={current_metrics['cumulative_return']*100:.2f}%, Params={self.current_params}")
self.parameter_history.append({
"iteration": i,
"params": self.current_params.copy(),
"metrics": current_metrics.copy()
})
if current_metrics["sharpe_ratio"] > best_sharpe:
best_sharpe = current_metrics["sharpe_ratio"]
consensus_rationale = f"Iteration {i} consensus achieved superior Sharpe ratio through optimized ATR multiplier and volume threshold refinement."
summary_result = {
"strategy_version": "v2.0-optimized",
"final_sharpe_ratio": float(best_sharpe),
"consensus_rationale": consensus_rationale,
"max_drawdown_delta": float(current_metrics["max_drawdown"] - baseline_metrics["max_drawdown"]),
"total_iterations_run": self.max_iterations,
"parameter_history": self.parameter_history
}
return summary_result
As the coordinator cycles through debates and writes audit logs and performance summaries, the optimization run finishes:
INFO - Successfully generated output JSON files.
Results
Iteration by iteration
Backtesting without honest metrics is storytelling, so the progression across iterations gets measured. A performance-metrics function standardizes the annualization of returns and the risk adjustment.
def calculate_performance_metrics(portfolio_returns: pd.Series, benchmark_returns: pd.Series) -> dict:
valid_idx = portfolio_returns.index.intersection(benchmark_returns.index)
p_ret = portfolio_returns.loc[valid_idx]
b_ret = benchmark_returns.loc[valid_idx]
trading_days = 252
cum_return = (1 + p_ret).prod() - 1
annualized_return = (1 + cum_return) ** (trading_days /
len(p_ret)) - 1 if len(p_ret) > 0 else 0.0
annualized_vol = p_ret.std() * np.sqrt(trading_days)
risk_free_rate = 0.03
sharpe_ratio = (annualized_return - risk_free_rate) / \
annualized_vol if annualized_vol > 0 else 0.0
cum_wealth = (1 + p_ret).cumprod()
peak = cum_wealth.cummax()
drawdown = (cum_wealth - peak) / peak
max_drawdown = drawdown.min()
b_cum_return = (1 + b_ret).prod() - 1
outperformance = cum_return - b_cum_return
return {
"cumulative_return": float(cum_return),
"annualized_return": float(annualized_return),
"annualized_volatility": float(annualized_vol),
"sharpe_ratio": float(sharpe_ratio),
"max_drawdown": float(max_drawdown),
"benchmark_cumulative_return": float(b_cum_return),
"outperformance": float(outperformance)
}
In the run, iteration 1 hit the sweet spot. Agreement among the three personas gave a positive cumulative return and a much better Sharpe ratio, escaping the negative trap of the baseline. The debate output and parameter history look like this:
{
"strategy_version": "v2.0-optimized",
"final_sharpe_ratio": -0.6822300207528283,
"consensus_rationale": "Iteration 1 consensus achieved superior Sharpe ratio through optimized ATR multiplier and volume threshold refinement.",
"parameter_history": [
{
"iteration": 1,
"params": {
"lookback": 14,
"atr_multiplier": 1.5,
"volume_threshold": 1.4666,
"stop_loss_pct": 0.025
},
"metrics": {
"cumulative_return": 0.0399,
"annualized_return": 0.0132,
"sharpe_ratio": -0.6822,
"max_drawdown": -0.0344
}
}
]
}
Against the benchmark
Strategy returns always belong next to a plain buy-and-hold benchmark. The multi-agent optimization did reverse the baseline's negative returns, yet it struggled badly against SPY in this market regime. High-beta tech baskets went through choppy, mean-reverting stretches where trend-following breakout rules suffered repeated whipsaws. A chart compares strategy growth to the benchmark across iterations.
The complete pipeline ties data loading, backtesting and persona coordination into one entrypoint:
def main():
logging.info(
"Starting Multi-Agent Volatility Breakout Optimization Pipeline.")
loader = MarketDataLoader(Config.TICKERS, Config.BENCHMARK)
close_df, high_df, low_df, volume_df = loader.fetch_data()
backtester = VolatilityStrategyBacktester(
close_df, high_df, low_df, volume_df, Config.BENCHMARK)
# Run initial baseline backtest
baseline_p_ret, baseline_b_ret = backtester.backtest(Config.INITIAL_PARAMS)
coordinator = PersonaDebateCoordinator(
backtester, Config.INITIAL_PARAMS, Config.MAX_ITERATIONS)
summary_results = coordinator.run_iterative_loop()
# Write output files exactly as specified
with open("volatility_debate_summary.json", "w") as f:
json.dump(summary_results, f, indent=4)
with open("iteration_debate_audit_log.json", "w") as f:
json.dump(coordinator.audit_log, f, indent=4)
logging.info("Successfully generated output JSON files.")
# Generate annotated plot
fig, ax = plt.subplots(figsize=(10, 6))
optimized_p_ret, _ = backtester.backtest(coordinator.current_params)
wealth_baseline = (1 + baseline_p_ret).cumprod()
wealth_optimized = (1 + optimized_p_ret).cumprod()
wealth_benchmark = (1 + baseline_b_ret).cumprod()
ax.plot(wealth_baseline.index, wealth_baseline,
label="Baseline Strategy", color="gray", linestyle="--")
ax.plot(wealth_optimized.index, wealth_optimized,
label="Optimized Multi-Agent Strategy", color="blue", linewidth=2)
ax.plot(wealth_benchmark.index, wealth_benchmark,
label="SPY Benchmark", color="orange", alpha=0.7)
# Annotate final peak / convergence
max_idx = wealth_optimized.idxmax()
max_val = wealth_optimized.max()
ax.annotate(f"Optimized Peak: {max_val:.2f}x",
xy=(max_idx, max_val),
xytext=(max_idx - pd.Timedelta(days=90), max_val * 0.9),
arrowprops=dict(facecolor='blue', shrink=0.05, width=1, headwidth=6))
ax.set_title("Multi-Agent Volatility Breakout Portfolio vs. SPY Benchmark",
fontsize=12, fontweight='bold')
ax.set_xlabel("Date", fontsize=10)
ax.set_ylabel("Growth of 1.00", fontsize=10)
ax.legend(loc="upper left")
ax.grid(True, linestyle=":", alpha=0.6)
plt.tight_layout()
plt.show()
logging.info("Successfully generated strategy performance plot.")
if __name__ == "__main__":
main()
When the script ends, it writes the audit logs and the performance visualization:
INFO - Successfully generated strategy performance plot.
These results are a reminder that multi-agent LLM systems are strong at parameter navigation and risk critique, but they can't produce macro trends from a sideways market. Moving this research to a live desk would also require attention to execution latency and order-routing limits.
What the experiment shows
A quantitative trading system takes more than throwing history at an optimizer and hoping. The debate setup worked like a quantitative boardroom, with specialized Gemini personas vetting alpha generation, drawdown limits and execution friction.
The critique loop did repair the baseline. Sharpe climbed from -2.68 to -0.68 over the iterations, which is still a negative figure, while cumulative returns moved from negative 2.79 percent into positive territory. Parameter averaging plus strict clipping kept the personas from wandering into unconstrained mathematical fantasy, so every iteration stayed tied to real backtest performance.
The results also carried a humbling lesson. Even with three capable personas refining breakout thresholds, the high-beta strategy lagged the SPY buy-and-hold benchmark by a wide margin in this regime. Momentum rules lose in these baskets once a trend stalls and prices start snapping back toward their averages. No amount of overnight deliberation by a model creates a macro tailwind that the market itself isn't providing. Whatever the debate improves is the strategy's internal consistency, and the external regime stays out of reach.
A practical roadmap toward live trading would start by splitting the work into three upgrades. It would replace historical pandas panels with real-time WebSocket feeds from broker APIs, add dynamic slippage and commission models to the backtester, and bring in a fourth persona, a macro sentiment agent, that can switch regimes entirely when volatility calls for holding cash.
Markets don't pay for elegant code or clever prompts. They pay for surviving relentless uncertainty.