Visualize strategy decision trees and analyze trade patterns with graph-based analysis
The Graph Analyzer is a powerful tool for understanding how your strategy makes decisions. It builds a directed graph of market conditions and tracks the probability of profitable outcomes from each state.
Visualize strategy logic
Win rates by condition
Find market regimes
from rlxbt import TradingEngine
from rlxbt.analysis import GraphAnalyzer
import pandas as pd
# Run backtest first
df = pd.read_csv("BTCUSDT_1h.csv")
df["signal"] = 0
df.loc[df["RSI_14"] < 30, "signal"] = 1
df.loc[df["RSI_14"] > 70, "signal"] = -1
engine = TradingEngine(initial_capital=100_000)
result = engine.run_backtest(df)
# Create graph analyzer
analyzer = GraphAnalyzer(
result=result,
features=["RSI_14", "MACD", "close_vs_sma"]
)
# Build decision graph
graph = analyzer.build_graph()
# Get summary statistics
print(analyzer.summary())Define custom market states based on indicator values. The analyzer will track transitions and outcomes.
# Define market states
state_definitions = {
"rsi_state": {
"oversold": lambda x: x["RSI_14"] < 30,
"neutral": lambda x: (x["RSI_14"] >= 30) & (x["RSI_14"] <= 70),
"overbought": lambda x: x["RSI_14"] > 70
},
"trend_state": {
"bullish": lambda x: x["close"] > x["SMA_200"],
"bearish": lambda x: x["close"] <= x["SMA_200"]
},
"volatility_state": {
"low": lambda x: x["ATR_14"] < x["ATR_14"].quantile(0.33),
"medium": lambda x: (x["ATR_14"] >= x["ATR_14"].quantile(0.33)) &
(x["ATR_14"] < x["ATR_14"].quantile(0.67)),
"high": lambda x: x["ATR_14"] >= x["ATR_14"].quantile(0.67)
}
}
analyzer = GraphAnalyzer(
result=result,
state_definitions=state_definitions
)
graph = analyzer.build_graph()Analyze how the market transitions between states and what happens to trades during each transition.
# Get transition matrix
transitions = analyzer.get_transitions()
print("State Transition Probabilities:")
print(transitions)
# Win rates by transition
win_rates = analyzer.get_win_rates_by_transition()
print("\\nWin Rates by State Transition:")
for (from_state, to_state), wr in win_rates.items():
print(f" {from_state} → {to_state}: {wr:.1%}")
# Expected returns by path
paths = analyzer.get_profitable_paths(min_trades=10)
print("\\nMost Profitable State Paths:")
for path in paths[:5]:
print(f" {path.states}: {path.avg_return:.2%} ({path.n_trades} trades)")| From State | To State | Probability | Win Rate | Avg Return |
|---|---|---|---|---|
| Oversold + Bullish | Neutral + Bullish | 45% | 68% | +2.1% |
| Overbought + Bearish | Neutral + Bearish | 38% | 72% | +1.8% |
| Oversold + Bearish | Oversold + Bearish | 62% | 35% | -1.5% |
# Generate interactive graph visualization
analyzer.plot_graph(
output="strategy_graph.html",
node_size="trade_count", # Size by number of trades
node_color="win_rate", # Color by profitability
edge_width="probability", # Edge width by transition prob
show_labels=True
)
# Export to various formats
analyzer.export_graph("graph.gexf") # For Gephi
analyzer.export_graph("graph.json") # For D3.js
analyzer.export_graph("graph.dot") # For GraphViz
# Heatmap of win rates
analyzer.plot_heatmap(
x="rsi_state",
y="trend_state",
value="win_rate",
output="heatmap.png"
)Interactive graph visualization opens in browser
Automatically discover profitable patterns in the graph.
# Find recurring profitable patterns
patterns = analyzer.discover_patterns(
min_occurrences=20,
min_win_rate=0.60,
max_path_length=4
)
print("Discovered Profitable Patterns:")
for pattern in patterns:
print(f"\\n Pattern: {pattern.sequence}")
print(f" Occurrences: {pattern.count}")
print(f" Win Rate: {pattern.win_rate:.1%}")
print(f" Avg Return: {pattern.avg_return:.2%}")
print(f" Sharpe: {pattern.sharpe:.2f}")
# Generate strategy rules from patterns
rules = analyzer.patterns_to_rules(patterns)
print("\\nGenerated Rules:")
print(rules.to_json())Understand why your strategy loses in certain market conditions. Identify which state transitions lead to losses.
Automatically detect market regimes and adapt strategy parameters based on current state probabilities.
Generate entry/exit filters based on discovered patterns. Only trade when in profitable states.
Adjust position sizing based on current state's historical win rate and expected return.