### Fast Trade Geometry Analysis Configuration in Python Source: https://github.com/alihaskar/signal_analyzer/blob/master/docs/quickstart.md An example of configuring the Trade Geometry Analyzer for a faster analysis by focusing only on geometry and frontiers and disabling path storage. ```python config = AnalysisConfig( H=10, sections=['A', 'B'], store_paths=False, # Faster ) ``` -------------------------------- ### Import and Verify signal_analyzer Installation Source: https://github.com/alihaskar/signal_analyzer/blob/master/docs/installation.md Demonstrates how to import the signal_analyzer library in Python and verify the installation by printing its version and creating a basic AnalysisConfig object. This confirms that the package is accessible and functional. ```python import signal_analyzer print(signal_analyzer.__version__) # Should print version number # Quick test from signal_analyzer import AnalysisConfig config = AnalysisConfig(H=10) print(f"Horizon: {config.H} bars") ``` -------------------------------- ### Full Trade Geometry Analysis with Custom Settings in Python Source: https://github.com/alihaskar/signal_analyzer/blob/master/docs/quickstart.md An example of a comprehensive analysis configuration for the Trade Geometry Analyzer, including all sections, custom outlier trimming, volatility normalization, and regime splitting. ```python config = AnalysisConfig( H=30, # 30-bar horizon sections=['A', 'B', 'C', 'D', 'E', 'F'], # All sections trim_k=3.0, # More permissive outlier removal store_paths=True, vol_col='atr_14', # Use 14-period ATR n_regimes=3, # Split into 3 volatility regimes ) ``` -------------------------------- ### Minimal Trade Geometry Analysis Example in Python Source: https://github.com/alihaskar/signal_analyzer/blob/master/docs/quickstart.md A basic example demonstrating how to perform signal analysis using the Trade Geometry Analyzer library. It requires a pandas DataFrame with OHLC data and signals, and configures the analysis parameters. ```python import pandas as pd from signal_analyzer import analyze, AnalysisConfig # Your OHLC data with signals df = pd.DataFrame({ 'Open': [...], 'High': [...], 'Low': [...], 'Close': [...], 'sig': [1, -1, 0, 1, ...], # +1=long, -1=short, 0=neutral }) # Configure analysis config = AnalysisConfig( H=20, # 20-bar forward horizon sections=['A', 'B', 'C', 'D'], # Run these sections store_paths=True, # Required for Section D ) # Run analysis result = analyze(df, sig_col='sig', config=config) # Access results print(result.section_a['long']['metrics']) print(result.section_d['long']['best_zones'][:5]) # Show plots import matplotlib.pyplot as plt plt.show() ``` -------------------------------- ### Install Trade Geometry Analyzer from Source Source: https://github.com/alihaskar/signal_analyzer/blob/master/docs/installation.md Installs the Trade Geometry Analyzer package from its source code repository. This method is intended for developers who wish to contribute to or modify the codebase. It requires Git and Poetry. ```bash git clone git@github.com:alihaskar/signal_analyzer.git cd signal_analyzer poetry install ``` -------------------------------- ### Install Trade Geometry Analyzer using pip Source: https://github.com/alihaskar/signal_analyzer/blob/master/docs/installation.md Installs the Trade Geometry Analyzer package from the Python Package Index (PyPI). This is the recommended method for most users. It automatically handles all necessary dependencies. ```bash pip install trade-geometry-analyzer ``` -------------------------------- ### Configure Signal Analyzer with AnalysisConfig Source: https://context7.com/alihaskar/signal_analyzer/llms.txt Shows how to instantiate and configure the AnalysisConfig object for the Signal Analyzer. It covers setting core parameters like horizon and sections, as well as detailed options for outlier trimming, frontier quantiles, TP/SL grids, volatility normalization, and clustering. Includes examples for both full and minimal configurations. ```python from signal_analyzer import AnalysisConfig import numpy as np # Full configuration with all options config = AnalysisConfig( # Core settings H=20, # Forward horizon in bars sections=['A', 'B', 'C', 'D', 'E', 'F'], # All sections # Section A: Geometry (outlier trimming) trim_method='iqr', # 'iqr', 'percentile', or None trim_k=1.5, # IQR multiplier (higher = more permissive) # Section B: Frontiers risk_q=0.9, # Quantile for risk-constrained frontier opp_q=0.8, # Quantile for opportunity-constrained frontier # Section D: TP/SL Feasibility tp_grid=np.linspace(0.1, 5.0, 25), # Take-profit levels to test sl_grid=np.linspace(0.1, 5.0, 25), # Stop-loss levels to test store_paths=True, # Required for Section D # Section E: Volatility Normalization vol_col='atr', # Column name for volatility (e.g., ATR) n_regimes=3, # Number of vol regimes (low/mid/high) # Section F: Clustering n_clusters=None, # Auto-select if None ) # Minimal configuration for quick analysis quick_config = AnalysisConfig( H=10, sections=['A', 'B'], # Only geometry and frontiers store_paths=False, # Skip path storage (faster) ) print(f"Default horizon: {AnalysisConfig().H}") print(f"Default sections: {AnalysisConfig().sections}") ``` -------------------------------- ### Viewing and Saving Plots from Trade Geometry Analysis in Python Source: https://github.com/alihaskar/signal_analyzer/blob/master/docs/quickstart.md Provides examples of how to display and save plots generated by the Trade Geometry Analyzer. This includes showing all plots, a specific plot, or saving a plot to a file. ```python # Show all plots import matplotlib.pyplot as plt plt.show() # Show specific plot result.plots['scatter'].show() # Save plot result.plots['heatmap_prob'].savefig('tp_sl_heatmap.png', dpi=150) ``` -------------------------------- ### Generate Example Plots using Python Script Source: https://github.com/alihaskar/signal_analyzer/blob/master/docs/examples.md This script regenerates all example plots for the EMA regression strategy. It loads data, calculates the strategy, runs a full analysis, and saves the plots. Dependencies include 'poetry' for package management. ```bash cd signal_analyzer poetry run python generate_examples.py ``` -------------------------------- ### Accessing Trade Geometry Analysis Results in Python Source: https://github.com/alihaskar/signal_analyzer/blob/master/docs/quickstart.md Shows how to access and interpret the results from the `analyze()` function, including trade sets, section-specific data (metrics, best zones, proportions), and plots. ```python # Trade sets # result.long_trades # TradeSet for long entries # result.short_trades # TradeSet for short entries # Section results (dicts with 'long' and 'short' keys) # result.section_a # Geometry metrics # result.section_b # Frontier analysis # result.section_c # Ordering analysis # result.section_d # TP/SL feasibility # result.section_e # Vol normalization # result.section_f # Cluster analysis # All plots # result.plots # Dict of matplotlib figures # Geometry metrics (Section A) metrics = result.section_a['long']['metrics'] print(f"Median MFE: {metrics['median_mfe']:.2f}%") print(f"Win Rate: {metrics['win_rate']*100:.1f}%") # Best TP/SL zones (Section D) best_zones = result.section_d['long']['best_zones'] for zone in best_zones[:3]: print(f"TP={zone['tp']:.2f}%, SL={zone['sl']:.2f}%, EV={zone['ev']:.2f}%") # Ordering proportions (Section C) props = result.section_c['long']['proportions'] print(f"MFE-first: {props['mfe_first']*100:.1f}%") print(f"MAE-first: {props['mae_first']*100:.1f}%") ``` -------------------------------- ### Advanced Usage API Source: https://github.com/alihaskar/signal_analyzer/blob/master/README.md Provides examples for advanced usage patterns, including custom signal modes and manual creation of TradeSet objects. ```APIDOC ## Advanced Usage API ### Description Demonstrates advanced usage patterns for the signal_analyzer library, including custom signal processing modes and manual trade set creation. ### Method Various (Python functions) ### Endpoints - `signal_to_events(df, sig_col='sig', mode='transitions')` - `compute_trade_paths(df, entries, H, side, vol_col='atr', store_paths=False)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - `df` (DataFrame) - The input data frame. - `sig_col` (str) - The name of the signal column in the DataFrame. - `mode` (str) - The signal processing mode ('transitions' or 'levels'). - `entries` (array) - Indices of trade entries. - `H` (int) - The lookahead period. - `side` (str) - The trade side ('long' or 'short'). - `vol_col` (str) - The name of the volatility column (e.g., 'atr'). - `store_paths` (bool) - Whether to store raw MFE/MAE paths. ### Request Example ```python from signal_analyzer.core.events import signal_to_events from signal_analyzer.core.trades import compute_trade_paths import numpy as np # Custom Signal Modes # Transitions mode (default): Fire on state changes events_trans = signal_to_events(df, sig_col='sig', mode='transitions') # Returns: enter_long, enter_short, exit_long, exit_short # Levels mode: Fire on all long/short bars events_levels = signal_to_events(df, sig_col='sig', mode='levels') # Returns: enter_long, enter_short (every bar signal is active) # Manual TradeSet Creation # Get entry indices however you want long_entries = np.where(df['my_condition'])[0] # Compute trade paths manually trades = compute_trade_paths( df, entries=long_entries, H=20, side='long', vol_col='atr', store_paths=True # If you need Section D ) # Accessing Raw Paths mfe_paths = trades.mfe_path # Shape: (n_trades, H) mae_paths = trades.mae_path ``` ### Response #### Success Response (200) - `signal_to_events`: Returns event arrays based on the specified mode. - `compute_trade_paths`: Returns a TradeSet object with computed trade paths. - Accessing Raw Paths: Returns numpy arrays of MFE and MAE paths. #### Response Example ```json { "signal_to_events_transitions": { "enter_long": [10, 50, 100], "exit_long": [20, 60, 110] }, "signal_to_events_levels": { "enter_long": [10, 11, 12, 50, 51], "enter_short": [] }, "compute_trade_paths": { "trade_set_info": "..." }, "raw_paths": { "mfe_path_shape": [100, 20], "mae_path_shape": [100, 20] } } ``` ``` -------------------------------- ### Analyze Trade Ordering Proportions (Python) Source: https://github.com/alihaskar/signal_analyzer/blob/master/README.md Determines the time-sequencing of profit and pain in trades (MFE-first vs MAE-first). It returns ordering proportions, trailing suitability metrics, and 'needs room' analysis to guide stop-loss strategies. ```python from signal_analyzer.analysis.ordering import ( ordering_proportions, trailing_suitability, needs_room ) props = ordering_proportions(trades) # Returns: {'mfe_first': 0.6, 'mae_first': 0.35, 'tie': 0.05} trailing = trailing_suitability(trades) # Returns: suitability rate for trailing stops needs = needs_room(trades, mfe_threshold=1.0) # Returns: success rate of MAE-first trades ``` -------------------------------- ### Trade Geometry Analysis with ATR Normalization in Python Source: https://github.com/alihaskar/signal_analyzer/blob/master/docs/quickstart.md Demonstrates how to perform volatility-adjusted analysis by incorporating an ATR (Average True Range) column into the DataFrame. This enables Section E of the analysis. ```python # Add ATR column to your data df['atr'] = calculate_atr(df) # Your ATR calculation config = AnalysisConfig( H=20, sections=['A', 'B', 'C', 'D', 'E'], # Include Section E vol_col='atr', # Enable vol normalization store_paths=True, ) result = analyze(df, sig_col='sig', config=config) ``` -------------------------------- ### Configure Analysis Run Source: https://github.com/alihaskar/signal_analyzer/blob/master/README.md Defines the parameters for an analysis run, including horizon, sections to process, outlier trimming methods, and risk/opportunity quantiles. It also allows specifying TP/SL grids and volatility columns. ```python config = AnalysisConfig( H=30, # 30-bar horizon sections=['A', 'D'], # Only geometry and TP/SL trim_k=3.0, # More permissive outlier removal store_paths=True, vol_col='atr_14', # Use 14-period ATR ) ``` -------------------------------- ### Compute Marginal Distributions (Python) Source: https://github.com/alihaskar/signal_analyzer/blob/master/README.md Calculates histogram bins, counts, and Kernel Density Estimation (KDE) for Maximum Favorable Excursion (MFE) and Maximum Adverse Excursion (MAE) from trade data. This helps in understanding the distribution of potential profits and losses. ```python marg = marginals(trades, bins=50, use_kde=True) # Returns: histogram bins/counts and KDE for MFE and MAE ``` -------------------------------- ### Manual Step-by-Step Analysis Source: https://github.com/alihaskar/signal_analyzer/blob/master/docs/api/overview.md Illustrates a custom analysis workflow by manually calling core functions. This involves converting signals to events, computing trade paths, and then calculating geometry metrics. ```python from signal_analyzer.core import signal_to_events, compute_trade_paths from signal_analyzer.analysis.geometry import geometry_metrics # Step-by-step manual analysis events = signal_to_events(df.sig) trades = compute_trade_paths(df, events['enter_long'], side='long', H=20) metrics = geometry_metrics(trades) ``` -------------------------------- ### Compute TP/SL Hit Matrix (Python) Source: https://github.com/alihaskar/signal_analyzer/blob/master/README.md Performs a probabilistic analysis of hitting take-profit (TP) targets versus stop-loss (SL) levels, considering path dependency. It generates hit probability matrices and expected value maps to identify optimal TP/SL zones. ```python from signal_analyzer.analysis.feasibility import hit_matrix, ev_proxy, find_best_zones import numpy as np # Compute hit probabilities hit_data = hit_matrix( trades, tp_grid=np.linspace(0.1, 5, 25), sl_grid=np.linspace(0.1, 5, 25) ) prob = hit_data['prob_matrix'] # Shape: (n_tp, n_sl) # Compute expected values ev_data = ev_proxy(hit_data, slippage=0.05, commission=0.02) # Find best zones best = find_best_zones(ev_data, top_n=5) print(f"Best TP/SL: {best[0]['tp']:.2f}% / {best[0]['sl']:.2f}%") print(f"Expected Value: {best[0]['ev']:.2f}%") ``` -------------------------------- ### Run Section A Analysis and Access Metrics (Python) Source: https://github.com/alihaskar/signal_analyzer/blob/master/docs/guide/section-a-geometry.md This snippet demonstrates how to run Section A of the signal analysis using the `analyze` function and `AnalysisConfig`. It shows how to access calculated metrics such as median MFE, median MAE, win rate, and percentiles from the analysis results. ```python from signal_analyzer import analyze, AnalysisConfig # Run Section A config = AnalysisConfig(H=20, sections=['A']) result = analyze(df, sig_col='sig', config=config) # Access metrics metrics = result.section_a['long']['metrics'] print(f"Median MFE: {metrics['median_mfe']:.2f}%") print(f"Median MAE: {metrics['median_mae']:.2f}%") print(f"Win Rate: {metrics['win_rate']*100:.1f}%") print(f"MFE 95th: {metrics['mfe_p95']:.2f}%") print(f"MAE 5th: {metrics['mae_p5']:.2f}%") ``` -------------------------------- ### Manual TradeSet Creation Source: https://github.com/alihaskar/signal_analyzer/blob/master/README.md Enables manual creation of TradeSet objects, allowing users to define entry points and trade parameters outside the library's automatic detection. This is useful for integrating custom entry logic or analyzing specific trade sequences. It requires specifying entry indices, trade side, lookahead period (H), and optionally volatility columns and path storage. ```python from signal_analyzer.core.trades import compute_trade_paths # Get entry indices however you want long_entries = np.where(df['my_condition'])[0] # Compute trade paths manually trades = compute_trade_paths( df, entries=long_entries, H=20, side='long', vol_col='atr', store_paths=True # If you need Section D ) ``` -------------------------------- ### Accessing Raw MFE/MAE Paths Source: https://github.com/alihaskar/signal_analyzer/blob/master/README.md Allows direct access to the raw Maximum Favorable Excursion (MFE) and Maximum Adverse Excursion (MAE) paths for each trade. This feature is valuable for advanced, custom analysis where users need to perform detailed examination of trade performance trajectories beyond the aggregated metrics provided by default. ```python # Get full MFE/MAE paths for custom analysis mfe_paths = trades.mfe_path # Shape: (n_trades, H) mae_paths = trades.mae_path ``` -------------------------------- ### Analyze TP/SL Feasibility with Python Source: https://context7.com/alihaskar/signal_analyzer/llms.txt Computes path-dependent probability heatmaps for hitting take-profit (TP) before stop-loss (SL) across a grid of TP/SL combinations. It includes expected value (EV) calculation and identification of optimal trading zones. Requires trade paths to be stored using `store_paths=True` in `compute_trade_paths`. Uses functions like `hit_matrix`, `ev_proxy`, and `find_best_zones`. ```python from signal_analyzer.analysis.feasibility import hit_matrix, ev_proxy, find_best_zones from signal_analyzer import compute_trade_paths import pandas as pd import numpy as np # Create sample trades with stored paths np.random.seed(42) df = pd.DataFrame({ 'Open': 100 + np.cumsum(np.random.randn(300) * 0.5), 'High': 100 + np.cumsum(np.random.randn(300) * 0.5) + 1.0, 'Low': 100 + np.cumsum(np.random.randn(300) * 0.5) - 1.0, 'Close': 100 + np.cumsum(np.random.randn(300) * 0.5), }) entries = np.arange(0, 250, 3) trades = compute_trade_paths(df, entries, H=20, side='long', store_paths=True) # Define TP/SL grids tp_grid = np.linspace(0.5, 4.0, 15) sl_grid = np.linspace(0.5, 4.0, 15) # Compute hit probability matrix hit_data = hit_matrix(trades, tp_grid, sl_grid, min_sample=5) print(f"Probability matrix shape: {hit_data['prob_matrix'].shape}") print(f"Max P(TP before SL): {np.nanmax(hit_data['prob_matrix']):.2f}") # Compute expected values ev_data = ev_proxy(hit_data, slippage=0.05, commission=0.02) print(f"EV matrix shape: {ev_data['ev_matrix'].shape}") print(f"Max EV: {np.nanmax(ev_data['ev_matrix']):.2f}%") # Find best TP/SL zones best_zones = find_best_zones(ev_data, top_n=5) for i, zone in enumerate(best_zones): print(f"Zone {i+1}: TP={zone['tp']:.2f}%, SL={zone['sl']:.2f}%, " f"EV={zone['ev']:.2f}%, RR={zone['rr']:.2f}") ``` -------------------------------- ### Running Specific Analysis Sections Source: https://github.com/alihaskar/signal_analyzer/blob/master/docs/api/overview.md Demonstrates how to configure the analysis to run only a subset of sections, such as 'A' (geometry) and 'B' (frontiers), by modifying the `sections` parameter in `AnalysisConfig`. This can speed up analysis. ```python # Only geometry and frontiers (fast) config = AnalysisConfig(H=10, sections=['A', 'B'], store_paths=False) result = analyze(df, sig_col='sig', config=config) ``` -------------------------------- ### TP/SL Feasibility API Source: https://github.com/alihaskar/signal_analyzer/blob/master/README.md Performs probabilistic analysis of hitting Take Profit (TP) targets versus Stop Loss (SL) levels, generating heatmaps for probabilities and expected values, and identifying optimal TP/SL zones. ```APIDOC ## POST /api/feasibility ### Description Analyzes the feasibility of hitting Take Profit (TP) targets before Stop Loss (SL) levels, providing probability heatmaps, expected value maps, and identifying optimal TP/SL zones. ### Method POST ### Endpoint /api/feasibility ### Parameters #### Request Body - **trades** (list) - Required - A list of trade objects. - **tp_grid** (list) - Optional - A list of TP levels to evaluate. Defaults to a grid from 0.1 to 5 in 25 steps. - **sl_grid** (list) - Optional - A list of SL levels to evaluate. Defaults to a grid from 0.1 to 5 in 25 steps. - **slippage** (float) - Optional - The assumed slippage for calculating expected value. Defaults to 0.05. - **commission** (float) - Optional - The assumed commission for calculating expected value. Defaults to 0.02. ### Request Example ```json { "trades": [ {"mfe": 1.5, "mae": -0.5, ...}, {"mfe": -0.2, "mae": -1.0, ...} ], "tp_grid": [0.5, 1.0, 1.5, 2.0], "sl_grid": [0.2, 0.4, 0.6, 0.8], "slippage": 0.05, "commission": 0.02 } ``` ### Response #### Success Response (200) - **hit_matrix** (dict) - Contains 'prob_matrix' (shape: [n_tp, n_sl]) showing P(TP before SL) and 'hit_data' (raw data used for calculation). - **ev_proxy** (dict) - Contains 'ev_matrix' (shape: [n_tp, n_sl]) showing expected value for each TP/SL combination. - **best_zones** (list) - A list of the top N (default 5) best TP/SL zones, ranked by expected value, each containing 'tp', 'sl', and 'ev'. #### Response Example ```json { "hit_matrix": { "prob_matrix": [[0.7, 0.6], [0.5, 0.4]], "hit_data": {...} }, "ev_proxy": { "ev_matrix": [[1.2, 0.8], [0.5, 0.1]] }, "best_zones": [ {"tp": 1.0, "sl": 0.4, "ev": 1.2}, {"tp": 0.5, "sl": 0.2, "ev": 0.8} ] } ``` ``` -------------------------------- ### Configuration for Analysis Source: https://github.com/alihaskar/signal_analyzer/blob/master/docs/api/overview.md Defines parameters for the analysis, including the forward horizon (H), specific sections to execute, whether to store trade paths, and the column for volatility normalization. ```python from signal_analyzer import AnalysisConfig config = AnalysisConfig( H=20, # Forward horizon sections=['A', 'B', 'C', 'D'], # Sections to run store_paths=True, # Required for Section D vol_col='atr', # Enable vol normalization ) ``` -------------------------------- ### Convert Trading Signals to Events (Python) Source: https://context7.com/alihaskar/signal_analyzer/llms.txt Converts continuous trading signals into discrete entry/exit events. Supports 'transitions' mode (fires on state changes) and 'levels' mode (fires on all long/short signals). This is the first step in the analysis pipeline. ```python from signal_analyzer import signal_to_events import pandas as pd df = pd.DataFrame({ 'Close': [100, 101, 102, 101, 100, 99, 100, 101], 'sig': [0, 1, 1, 1, 0, -1, -1, 0], # Signal: +1=long, -1=short, 0=neutral }) # Transitions mode (default): Fire events only on state changes events = signal_to_events(df, sig_col='sig', mode='transitions') print(f"Long entries at bars: {events['enter_long']}") # [1] print(f"Short entries at bars: {events['enter_short']}") # [5] print(f"Long exits at bars: {events['exit_long']}") # [4] print(f"Short exits at bars: {events['exit_short']}") # [7] # Levels mode: Fire on all long/short bars events_levels = signal_to_events(df, sig_col='sig', mode='levels') print(f"All long bars: {events_levels['enter_long']}") # [1, 2, 3] print(f"All short bars: {events_levels['enter_short']}") # [5, 6] ``` -------------------------------- ### Compute Risk/Reward Frontiers (Python) Source: https://github.com/alihaskar/signal_analyzer/blob/master/README.md Analyzes risk/reward boundaries and diminishing returns. It computes risk-constrained and opportunity-constrained frontiers, identifying 'knee points' which represent optimal stop sizing. Dependencies include the 'trades' data structure. ```python from signal_analyzer.analysis.frontiers import compute_frontiers frontiers = compute_frontiers( trades, dd_grid=None, # Auto-generate risk_q=0.9, # 90th percentile MFE opp_q=0.8 # 80th percentile DD ) knee_dd, knee_mfe = frontiers['risk_constrained']['knee'] print(f"Optimal stop: {knee_dd:.2f}%") ``` -------------------------------- ### Configure Outlier Removal for Analysis (Python) Source: https://github.com/alihaskar/signal_analyzer/blob/master/docs/guide/section-a-geometry.md This snippet shows how to configure outlier removal methods for Section A analysis using `AnalysisConfig`. It demonstrates setting the `trim_method` to 'iqr' or 'percentile', and adjusting the `trim_k` parameter to control the extent of trimming. It also shows how to disable trimming entirely. ```python # IQR method (default) config = AnalysisConfig(trim_method='iqr', trim_k=1.5) # More permissive (keep more outliers) config = AnalysisConfig(trim_method='iqr', trim_k=3.0) # Percentile method config = AnalysisConfig(trim_method='percentile', trim_k=5) # Remove top/bottom 5% # No trimming config = AnalysisConfig(trim_method=None) ``` -------------------------------- ### Accessing Raw Trade Path Data Source: https://github.com/alihaskar/signal_analyzer/blob/master/docs/api/overview.md Shows how to retrieve detailed trade path data, including MFE and MAE paths, by setting `store_paths=True` in `AnalysisConfig`. This raw data can be used for custom analysis. ```python # Get TradeSet with full paths config = AnalysisConfig(H=20, store_paths=True) result = analyze(df, sig_col='sig', config=config) # Access MFE paths (shape: n_trades × H) mfe_paths = result.long_trades.mfe_path mae_paths = result.long_trades.mae_path # Custom analysis on paths quick_winners = np.any(mfe_paths[:, :5] >= 1.0, axis=1) ``` -------------------------------- ### Marginal Distributions API Source: https://github.com/alihaskar/signal_analyzer/blob/master/README.md Computes and returns histogram bins/counts and Kernel Density Estimation (KDE) for MFE (Maximum Favorable Excursion) and MAE (Maximum Adverse Excursion) from trade data. ```APIDOC ## POST /api/marginals ### Description Computes marginal distributions (histograms and KDE) for MFE and MAE from a list of trades. ### Method POST ### Endpoint /api/marginals ### Parameters #### Request Body - **trades** (list) - Required - A list of trade objects. - **bins** (int) - Optional - The number of bins to use for the histogram. Defaults to 50. - **use_kde** (bool) - Optional - Whether to compute Kernel Density Estimation. Defaults to True. ### Request Example ```json { "trades": [ {"mfe": 1.5, "mae": -0.5, ...}, {"mfe": -0.2, "mae": -1.0, ...} ], "bins": 50, "use_kde": true } ``` ### Response #### Success Response (200) - **median_mfe** (float) - The median MFE across all trades. - **median_mae** (float) - The median MAE across all trades. - **win_rate** (float) - The win rate of the trades. - **tail_stats** (dict) - Statistics for the tails of MFE and MAE distributions. - **correlation** (float) - The correlation between MFE and MAE. - **histogram_mfe** (dict) - Bins and counts for the MFE histogram. - **kde_mfe** (list) - Points for the MFE Kernel Density Estimation. - **histogram_mae** (dict) - Bins and counts for the MAE histogram. - **kde_mae** (list) - Points for the MAE Kernel Density Estimation. #### Response Example ```json { "median_mfe": 0.8, "median_mae": -0.3, "win_rate": 0.55, "tail_stats": {"mfe_right": 1.2, "mae_left": -1.5}, "correlation": 0.2, "histogram_mfe": {"bins": [0, 1, 2], "counts": [10, 5]}, "kde_mfe": [[0.5, 0.2], [1.5, 0.1]], "histogram_mae": {"bins": [-1, 0, 1], "counts": [8, 7]}, "kde_mae": [[-0.5, 0.3], [-1.5, 0.15]] } ``` ``` -------------------------------- ### Analyze Trading Signals with Trade Geometry Analyzer (Python) Source: https://github.com/alihaskar/signal_analyzer/blob/master/docs/index.md Demonstrates how to use the trade-geometry-analyzer library to analyze trading signals. It involves loading OHLC data with signal indicators, configuring analysis parameters, running the analysis, and accessing the results. Requires pandas for data manipulation and matplotlib for plotting. ```python import pandas as pd from signal_analyzer import analyze, AnalysisConfig import matplotlib.pyplot as plt # Your OHLC data with signals df = pd.DataFrame({ 'Open': [...], 'High': [...], 'Low': [...], 'Close': [...], 'sig': [1, -1, 0, 1, ...], # +1=long, -1=short, 0=neutral }) # Configure analysis config = AnalysisConfig( H=20, # 20-bar forward horizon sections=['A', 'B', 'C', 'D'], # Run these sections store_paths=True, # Required for Section D ) # Run analysis result = analyze(df, sig_col='sig', config=config) # Access results print(result.section_a['long']['metrics']) print(result.section_d['long']['best_zones'][:5]) # Show plots plt.show() ``` -------------------------------- ### Find Quick Winners in Trades Source: https://github.com/alihaskar/signal_analyzer/blob/master/README.md Identifies trades that achieved a 1% profit within the first 5 bars. It uses NumPy for efficient array operations and prints the count of quick winners against the total number of trades. ```python quick_winners = np.any(mfe_paths[:, :5] >= 1.0, axis=1) print(f"Quick winners: {quick_winners.sum()} / {trades.n_trades}") ``` -------------------------------- ### Main Entry Point for Signal Analysis Source: https://github.com/alihaskar/signal_analyzer/blob/master/docs/api/overview.md Initiates the trade geometry analysis process using the `analyze` function. It requires a pandas DataFrame and a signal column name, along with an optional `AnalysisConfig` object for customization. ```python from signal_analyzer import analyze, AnalysisConfig result = analyze(df, sig_col='sig', config=AnalysisConfig(H=20)) ```