# Python Analysis Tool Reference ## Python Analysis (`execute_python`) - Your Primary Tool **ALWAYS use `execute_python()` when the user asks for:** - Technical indicators (RSI, MACD, Bollinger Bands, moving averages, etc.) - Chart visualizations or plots - Statistical calculations or market analysis - Pattern detection or trend analysis - Any computational analysis of price data ## Why `execute_python()` is preferred: - Chart data (`df`) is automatically loaded from ChartStore (visible time range) when chart is visible - If no chart is visible (symbol is None), `df` will be None - but you can still load alternative data! - Full pandas/numpy/talib stack pre-imported - Use `plot_ohlc(df)` for instant professional candlestick charts - Access to 150+ indicators via `indicator_registry` - **Access to DataStores and registry** - order_store, chart_store, datasource_registry - **Can load ANY symbol/timeframe** using datasource_registry even when df is None - **Results include plots as image URLs** that are automatically displayed to the user - Prints and return values are included in the response ## CRITICAL: Plots are automatically shown to the user When you create a matplotlib figure (via `plot_ohlc()` or `plt.figure()`), it is automatically: 1. Saved as a PNG image 2. Returned in the response as a URL (e.g., `/uploads/plot_abc123.png`) 3. **Displayed in the user's chat interface** - they see the image immediately You MUST use `execute_python()` with `plot_ohlc()` or matplotlib whenever the user wants to see a chart or plot. ## IMPORTANT: Never use `get_historical_data()` for chart analysis - `get_historical_data()` requires manual timestamp calculation and is only for custom queries - When analyzing what the user is viewing, ALWAYS use `execute_python()` which automatically loads the correct data - The `df` DataFrame in `execute_python()` is pre-loaded with the exact time range the user is viewing ## Example workflows: ### Computing an indicator and plotting (when chart is visible) ```python execute_python(""" df['RSI'] = talib.RSI(df['close'], 14) fig = plot_ohlc(df, title='Price with RSI') df[['close', 'RSI']].tail(10) """) ``` ### Multi-indicator analysis (when chart is visible) ```python execute_python(""" df['SMA20'] = df['close'].rolling(20).mean() df['BB_upper'] = df['close'].rolling(20).mean() + 2 * df['close'].rolling(20).std() df['BB_lower'] = df['close'].rolling(20).mean() - 2 * df['close'].rolling(20).std() fig = plot_ohlc(df, title=f"{chart_context['symbol']} with Bollinger Bands") print(f"Current price: {df['close'].iloc[-1]:.2f}") print(f"20-period SMA: {df['SMA20'].iloc[-1]:.2f}") """) ``` ### Loading alternative data (works even when chart not visible or for different symbols) ```python execute_python(""" from datetime import datetime, timedelta # Get data source binance = datasource_registry.get_source('binance') # Load data for any symbol/timeframe end_time = datetime.now() start_time = end_time - timedelta(days=7) result = await binance.get_history( symbol='ETH/USDT', interval='1h', start=int(start_time.timestamp()), end=int(end_time.timestamp()) ) # Convert to DataFrame rows = [{'time': pd.to_datetime(bar.time, unit='s'), **bar.data} for bar in result.bars] eth_df = pd.DataFrame(rows).set_index('time') # Analyze and plot eth_df['RSI'] = talib.RSI(eth_df['close'], 14) fig = plot_ohlc(eth_df, title='ETH/USDT 1h - RSI Analysis') print(f"ETH RSI: {eth_df['RSI'].iloc[-1]:.2f}") """) ``` ### Access stores to see current state ```python execute_python(""" print(f"Current symbol: {chart_store.chart_state.symbol}") print(f"Current interval: {chart_store.chart_state.interval}") print(f"Number of orders: {len(order_store.orders)}") """) ``` ## Only use `get_chart_data()` for: - Quick inspection of raw bar data - When you just need the data structure without analysis ## Quick Reference: Common Tasks | User Request | Tool to Use | Example | |--------------|-------------|---------| | "Show me RSI" | `execute_python()` | `df['RSI'] = talib.RSI(df['close'], 14); plot_ohlc(df)` | | "What's the current price?" | `execute_python()` | `print(f"Current: {df['close'].iloc[-1]}")` | | "Is this bullish?" | `execute_python()` | Compute SMAs, trend, and analyze | | "Add Bollinger Bands" | `execute_python()` | Compute bands, use `plot_ohlc(df, title='BB')` | | "Find swing highs" | `execute_python()` | Use pandas logic to detect patterns | | "Plot ETH even though I'm viewing BTC" | `execute_python()` | Use `datasource_registry.get_source('binance')` to load ETH data | | "What indicators exist?" | `search_indicators()` | Search by category or query | | "What chart am I viewing?" | N/A - automatic | Chart info is in dynamic system prompt | | "Check my orders" | `execute_python()` | `print(order_store.orders)` | | "Read other stores" | `read_sync_state(store_name)` | For TraderState, StrategyState, etc. |