How to Use the show_reasoning Flag in AI Hedge Fund to Display Agent Reasoning
The --show-reasoning flag in the virattt/ai-hedge-fund repository enables verbose output of LLM agent logic during both live trading simulations and backtesting, exposing the step-by-step rationale behind buy, sell, and hold decisions.
The AI Hedge Fund project orchestrates multiple LLM agents through LangGraph to simulate quantitative trading strategies. When debugging agent behavior or validating investment theses, understanding why an analyst reached a specific conclusion is as critical as the signal itself. The show_reasoning flag provides this transparency by surfacing intermediate reasoning steps from the valuation, sentiment, growth, and risk management agents.
What is the show_reasoning Flag?
The show_reasoning flag is a boolean command-line argument defined in src/cli/input.py that controls whether the application prints detailed reasoning traces from each analyst agent. When enabled, the system outputs the LLM's chain-of-thought analysis before finalizing trade decisions in the portfolio manager.
By default, agents return compact signals (bullish/bearish/neutral) with confidence scores. Activating this flag expands the output to include the qualitative justification generated during the agent's execution in src/agents/valuation.py, src/agents/sentiment.py, and other analyst modules.
Enabling show_reasoning in Live Trading
To display agent reasoning during an interactive trading session, append --show-reasoning to the main execution command in src/main.py. This triggers verbose logging as the LangGraph workflow (StateGraph) executes the selected analyst nodes.
python -m src.main \
--tickers AAPL,MSFT,TSLA \
--initial-cash 200000 \
--margin-requirement 0.5 \
--model gpt-4o \
--analysts valuation,growth \
--show-reasoning
When invoked, the run_hedge_fund function receives this flag through the CLIInputs dataclass and propagates it through the agent graph. Each analyst node in src/agents/ then emits its reasoning to src/utils/display.py, which formats the output with colors and indentation for readability.
Enabling show_reasoning in Backtesting
The same flag functions identically in the backtesting engine (src/backtesting/engine.py), allowing you to inspect daily agent decisions across historical date ranges. This is critical for debugging why specific trades occurred on specific days during simulation.
python -m src.backtester \
--tickers AAPL,MSFT \
--start-date 2023-01-01 \
--end-date 2023-12-31 \
--initial-cash 150000 \
--model gpt-4o \
--show-reasoning
The BacktestEngine class passes this configuration through its run_backtest method, ensuring that each daily iteration of the agent graph outputs reasoning before the TradeExecutor in src/backtesting/trader.py processes portfolio updates.
Implementation Architecture
CLI Argument Parsing
In src/cli/input.py, the flag is parsed alongside other parameters like --tickers, --model, and --initial-cash. The parser stores this as a boolean attribute in the CLIInputs dataclass, which src/main.py consumes when initializing the workflow.
State Management and Reasoning Display
The AgentState dictionary defined in src/graph/state.py carries messages and analyst_signals through the LangGraph execution. When show_reasoning is active, the system extracts reasoning content from the message history and passes it to src/utils/display.py, where print_backtest_results and related functions format the output for the console.
Agent-Level Integration
Individual analysts leverage the progress tracker in src/utils/progress.py to emit status updates. When reasoning display is enabled, agents append their qualitative analysis to the state object, which the portfolio manager in src/agents/portfolio_manager.py can reference when making final trade decisions.
Practical Usage Examples
Debugging Valuation Logic
To isolate and inspect the valuation agent's DCF calculations or Owner Earnings analysis:
python -m src.main \
--tickers AAPL \
--analysts valuation \
--show-reasoning \
--model gpt-4o
This outputs the specific financial metrics fetched via src/tools/api.py (such as get_financial_metrics and search_line_items) and the agent's interpretation of EV/EBITDA or P/E ratios before generating the final signal.
Capturing Reasoning Programmatically
When extending the system, you can check the reasoning flag within custom agents using the pattern shown in src/agents/valuation.py:
from src.graph.state import AgentState, show_agent_reasoning
def custom_analyst_agent(state: AgentState, agent_id: str = "custom"):
# ... analysis logic ...
# Conditionally display reasoning based on global config
show_agent_reasoning(state, agent_id, reasoning_content)
return {"messages": [...], "data": state["data"]}
Summary
- The
--show-reasoningflag activates verbose LLM output in both live trading (src/main.py) and backtest modes (src/backtesting/engine.py) - Configuration originates in
src/cli/input.pyand propagates through theCLIInputsdataclass to the LangGraph workflow - Output formatting relies on
src/utils/display.pyfor structured, color-coded console presentation - All analyst agents in
src/agents/support reasoning output, exposing their data sources fromsrc/tools/api.pyand calculation logic - Essential for debugging signal generation and validating that agents correctly interpret financial metrics
Frequently Asked Questions
Does the show_reasoning flag slow down execution?
The performance impact is minimal. The flag primarily affects I/O operations by printing additional content to stdout via src/utils/display.py. The underlying LLM calls in src/agents/ execute identically regardless of this setting; only the visibility of the reasoning text changes.
Can I redirect reasoning output to a file instead of the console?
Yes. Since the output flows through standard console printing in src/utils/display.py, you can redirect stdout when running the CLI command: python -m src.main --show-reasoning [...] > reasoning.log 2>&1. For structured logging, modify src/utils/display.py to write to a file handle alongside console output.
Is show_reasoning available in the web UI frontend?
The optional Vite + React frontend in app/frontend/ primarily interfaces with the backend routes. While the CLI flag is specific to the terminal interface in src/cli/, you can expose reasoning data programmatically by accessing the AgentState messages after graph execution and returning them via the API layer.
Which agents support detailed reasoning output?
All analyst agents support reasoning display, including valuation (src/agents/valuation.py), sentiment, growth, and technical analysts. The risk manager in src/agents/risk_manager.py and portfolio manager in src/agents/portfolio_manager.py also output their consolidation logic when the flag is enabled, showing how conflicting analyst signals are resolved into final trading decisions.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →