Volatility Cone & Analog Path ProjectionVolatility Cone & Analog Path Projection — Forward Price Envelope with Fractal Replay and Terminal Probability Distribution
Overview
Nearly every overlay on PulseWire describes the past: where price has been, where volume traded, where structure broke. This tool points in the other direction. It builds a forward projection zone from the current bar using three independent layers — a realized-volatility cone, a replay of the historically most similar price fractals, and a terminal probability profile that combines both into a distribution of possible outcomes at the projection horizon.
The result is not a forecast. It is a bounded expectation: a visual answer to "given how this instrument has actually been moving, what range is normal over the next N bars, and where has price historically ended up after conditions that looked like this?"
Conceptual Framework
Price uncertainty grows with the square root of time, not linearly. A 24-bar projection is not 24 times as wide as a 1-bar projection — it is roughly 4.9 times as wide. Traders who size targets and stops on a straight-line mental model consistently misjudge what is achievable in a given number of bars.
The cone makes that curvature visible. Its width at each future bar is sigma * sqrt(t), where sigma is the standard deviation of log returns over the volatility window. Three nested bands are drawn, so you can immediately see which targets sit inside the ordinary range, which sit at the statistical edge, and which would require an exceptional move.
The Gaussian model alone, however, is a poor description of real markets: returns have fat tails, and volatility clusters. The analog layer addresses this by ignoring models entirely and asking an empirical question instead — what actually happened, historically, after the market printed this exact shape?
How It Works
Volatility estimation. Log returns are computed bar to bar. Their standard deviation over the volatility window gives the per-bar sigma; their mean gives the drift. Drift can be included or excluded from the cone's centerline.
Cone construction. For each future bar t from 1 to the horizon, the upper and lower bounds are close * exp(drift*t ± k*sigma*sqrt(t)) for each of the three band multipliers. Each band is rendered as a closed polygon with layered transparency, producing depth from the centerline outward.
Fingerprint extraction. The most recent N bars of log returns are z-scored — mean removed, divided by their own standard deviation. This makes the pattern scale-invariant: the same shape is recognised whether it happened during a quiet range or a volatile expansion, and at any price level.
Historical scan. Every candidate window inside the scan depth is z-scored the same way and compared to the current fingerprint by summed squared difference. Lower distance means a closer shape match. Candidates that overlap an already-selected match without improving on it are rejected, so the top results are not five copies of the same event shifted by one bar.
Forward replay. For each of the top matches, the bars that followed it are converted into a relative path and re-anchored to the current close. The path each analog is drawing forward is exactly the move that occurred after that historical fingerprint — nothing is fitted or optimised. Paths ending above the current price are drawn bullish, below bearish, and a thick median line traces the bar-by-bar median across all analogs.
Terminal probability profile. At the projection horizon a horizontal distribution is built across the cone's full range. Each row's density blends the Gaussian probability implied by the volatility model with an empirical kernel centred on each analog's endpoint. The Model Weight input controls that mix: 1.0 is purely theoretical, 0.0 is purely historical, and the default sits between them. The widest row — the mode of the blended distribution — is marked as the most probable zone.
Interpretation
Cone bands define what is statistically ordinary. A target beyond the outer band within the horizon is not impossible, it is simply rare — treat it accordingly when planning holding time.
Cone width itself is information. A narrow cone means compressed volatility, which historically resolves into expansion. A wide cone means the market is already moving; chasing inside it carries a worse risk profile.
Analog dispersion matters more than analog direction. Five paths that fan out in all directions means the current shape carried no historical edge. Five paths clustering in one direction is the meaningful configuration.
Best Match Quality in the panel scores how closely the nearest historical fingerprint resembles the present one. Below roughly 60%, treat the analog layer as noise and rely on the cone alone.
The most probable zone is where the blended distribution peaks. It is a magnet-style reference, not a target — the distribution is wide by construction.
Volatility Regime compares short-window volatility to the full window. Expanding means the cone is likely to understate near-term movement; contracting means the opposite.
Settings
Setting Effect
Projection Horizon Bars projected forward. Also the endpoint of the profile
Volatility Window Sample size for sigma and drift. Longer = smoother, slower to adapt
Include Drift Tilts the cone with the window's mean return
Inner / Mid / Outer Band Sigma multipliers for the three layers
Fingerprint Length Bars compared for similarity. Shorter = more matches, less specific
Scan Depth How far back to search for analogs
Number of Analogs How many historical paths to replay
Profile Rows / Width Resolution and horizontal size of the terminal distribution
Model Weight Gaussian versus empirical blend in the distribution
Redraw on Bar Close Only Recommended on. The scan is heavy; this runs it once per bar
Limitations — read this
This is not a prediction and must not be traded as one. The cone describes a statistical range under an assumption of stable volatility. Real volatility is not stable, and returns have fatter tails than the Gaussian model implies, so moves outside the outer band occur more often than the model suggests.
Analog matching is weak evidence. A few dozen bars of shape similarity is a small sample; markets are non-stationary and a pattern that resolved one way in the past carries no obligation to repeat. The paths are historical context, not a probability statement about the future.
Nothing repaints, but the whole projection is recomputed each bar. Yesterday's cone is not preserved — the drawing always reflects current data only. It is anchored to the last bar by design.
On low-volume, illiquid, or heavily gapped instruments the return distribution is distorted and both layers degrade.
No entries, no stops, no targets, no signals. This is a context tool for sizing expectations and holding time. Indicator

IQ Session Bayesian Particle Filter [TradingIQ]🔹 OVERVIEW
This indicator runs a genuine Sequential Monte Carlo particle filter; the Bayesian architecture used in robotics and signal tracking... on your chart! Session by session, it learns where trading volume concentrates and paints a forecast of the coming session's entire volume-by-price distribution before that session unfolds: every expected high-volume level at once, not a single line.
It is not a moving average wearing a costume. Each finished session is treated as evidence: hundreds of particles are weighed against what actually traded, resampled, and mutated. Predict → observe → update, honestly Bayesian, every session.
🔹 HOW IT WORKS
Two particle swarms run side by side:
• A shape swarm learns the form of the distribution; one lump or several, wide or tight, and where each volume node sits.
• A drift swarm learns how far from the open the session's center of gravity tends to land.
An empirical-Bayes trust term scales the drift forecast by how much it has actually earned: when its track record is poor, the forecast automatically hugs the open. The prediction you see is the shape swarm's density, re-anchored by the trusted fraction of the drift forecast, rendered through a kernel density estimate whose bandwidth follows Silverman's rule.
🔸 HOW TO READ IT
• Session heatmap — the predicted density painted from the session open to the profile. A two-tone gradient split at the open; the tones swap roles across it, so each side mirrors the other. Bold color = expected business, fade = expected quiet.
• Mirrored profile — the forecast on the left, split bullish/bearish at the session open; the realized session volume on the right in a single neutral color.
• Confidence honesty — the prediction's glow scales with the filter's live confidence. When it has been wrong lately, its side visibly goes quiet. The realized side never fades, because reality doesn't.
• Bias info box — seated between the halves: the share of predicted volume above vs below the open (🢁 / 🢃).
• Expected levels — dashed lines at the probability-weighted average predicted price of each half: the session's expected bull and bear magnets.
• HVN lines + POC — the predicted high-volume levels. The point of control always shows; the HVN Threshold input is your dial between a few safe targets and every level worth watching.
🔹 SELF-TUNING
Every statistical free parameter tunes itself from data: the KDE bandwidth (Silverman's rule for visual convenience), the observation noise, the swarms' search domain (tracks the observed session spread), the mutation rate (genetic adaptation), the scout rate (scales with recent error), and the center trust (regression shrinkage). The inputs you are given are visual preferences plus a compute preset. There is nothing statistical to fiddle with, on purpose.
🔸 INPUTS
• Session Engine — Session Timeframe (the session boundary; must exceed the chart timeframe), Prediction Quality (particles per swarm, Fast 100 → Max 4000), Sessions to Keep.
• Volume Profile — toggles for the profile, bias box and expected levels; width, offset, info-box width, transparency.
• Session Heatmap — toggle, faint/bold density transparencies, Tone A / Tone B.
• High Volume Nodes — toggle, HVN Threshold %, reach, color.
• Colors — Bullish, Bearish, Realized.
🔹 VALIDATION
The filter was tested on real intraday data; 10 large-cap symbols, three session horizons, every prediction one-step-ahead and out-of-sample, against uniform, yesterday's-profile, Gaussian-fit, rolling-average and EWMA baselines, with the test harness itself audited too.
• Against naive prediction (uniform prior, yesterday's profile) it wins every metric tested at every horizon.
• Against the strongest profile-averaging methods it trades wins: they edge the single-lump fit metrics; the filter captures materially more of the session's actual traded volume with its predicted levels, and is the only method that reliably names multiple simultaneous targets .
• On sessions with two or more real volume peaks; roughly 4 in 10 sessions, its targets covered 19–42% more realized volume than the best alternative.
🔸 LIMITATIONS AND HONEST NOTES
• The forecast for a session is set when that session opens and is not repainted ; the realized half updates live as the session trades.
• It estimates a distribution of volume , not a promise of direction. The bias %, expected levels and HVN set are probability-weighted readings of that distribution.
• The filter is stochastic by nature: two chart reloads can differ in fine detail, the way two runs of any Monte Carlo method do. The structure it finds is stable; the pixel-level noise is not.
• Requires volume data from your data feed. Not supported on non-standard chart types.
• The chart timeframe must be lower than the session timeframe.
Indicator

Strategy Forecast EngineThe Strategy Forecast Engine is a regime-based Monte Carlo forecasting tool that estimates the future return distribution of trend-following strategies across different market environments. The model identifies the current market regime, conditions forecasts on historical returns observed during comparable regimes, and generates thousands of potential future price paths using Monte Carlo simulation. The resulting return distribution is presented through percentile projections and a structured, color-coded table that provides a comprehensive assessment of the forecast.
First, the model identifies the current market regime using the selected trend-following strategy. Users can choose between a moving-average crossover strategy, a volatility-based trailing stop strategy, or a combined strategy that incorporates both approaches. Supported moving-average types include the Exponential Moving Average (EMA), Simple Moving Average (SMA), Wilder’s Moving Average (RMA), and Weighted Moving Average (WMA). Supported volatility types include the Average True Range (ATR), Standard Deviation (SD), and Mean Absolute Deviation (MAD). By default, the model applies an asymmetric design in which conflicting signals default to bullish unless neutral regimes are enabled in the menu. Market regimes are determined as follows:
Bullish Trend Regime = (Fast MA – Slow MA) > (ATR × Trend Margin)
Bearish Trend Regime = (Fast MA – Slow MA) < –(ATR × Trend Margin)
Bullish Volatility Regime = Price > (Highest Price – (Volatility × Stop Factor))
Bearish Volatility Regime = Price < (Lowest Price + (Volatility × Stop Factor))
Bullish Combined Regime = Bullish Trend Regime and Bullish Volatility Regime
Bearish Combined Regime = Bearish Trend Regime and Bearish Volatility Regime
Once the current regime has been identified, the model collects all historical logarithmic returns that occurred during the same regime beginning from the selected start date. Only returns from the matching regime are used to generate the forecast, allowing projections to be conditioned on historically comparable market environments rather than treating all historical observations as equally relevant. If duration-adjusted forecast is enabled in the menu, the model further restricts the sample pool to returns from regimes that were at least as mature as the current regime.
The Monte Carlo simulation engine then generates thousands of possible future price paths over the selected forecast horizon. Each simulation randomly samples historical returns from the sample pool associated with the current regime and compounds them forward to generate a potential future price path. This process is repeated for the specified number of simulations to produce a broad range of possible future outcomes. The random seed controls reproducibility, ensuring that identical settings produce identical forecasts. Once all individual simulations have been completed, the resulting return distribution is summarized using percentile projections:
95% = 5% of simulations ended above this level and 95% ended below it.
75% = 25% of simulations ended above this level and 75% ended below it.
Median = 50% of simulations ended above this level and 50% ended below it.
25% = 25% of simulations ended below this level and 75% ended above it.
5% = 5% of simulations ended below this level and 95% ended above it.
The upper quartile (75%) and lower quartile (25%) define the Interquartile Range (IQR), which contains the middle 50% of all simulated outcomes and represents the central range of the projected outcome distribution. The upper and lower tail percentiles can be set to 10% (90% / 10%), 5% (95% / 5%), or 1% (99% / 1%). The default setting is 5%, which captures the middle 90% of simulated outcomes. At 10%, the range captures 80% of simulated outcomes, while at 1%, the range captures 98% of simulated outcomes. To further evaluate the risk/reward characteristics of the forecast, the model includes a built-in table with the following metrics:
Regime = Current market regime based on the selected strategy configuration.
Duration = Percentile rank of current regime duration relative to past regimes.
Forecast = Percentile rank of current duration including the forecast horizon.
Win Rate = Percentage of profitable simulations relative to total simulations.
Profit Factor = Ratio of total simulated profits to total simulated losses.
Expectancy = Average expected percentage return across all simulations.
Reward/Risk = Ratio of upper quartile return to lower quartile return.
Asymmetry = Ratio of selected upper tail return to selected lower tail return.
Skewness = Ratio of upside potential to downside risk relative to the median.
Sample Size = Number of historical returns available for the current regime.
Frequency = Percentage of historical returns belonging to the current regime.
In summary, the Strategy Forecast Engine is a comprehensive forecasting tool designed to help investors evaluate the return distribution of trend-following strategies based on the current market regime. By combining regime detection with Monte Carlo simulation, the model conditions forecasts on historical returns observed during comparable market regimes to estimate the distribution of potential outcomes and their associated risk/reward characteristics. While the model provides valuable insight into historical return patterns, investors should remain mindful that historical market behavior may not necessarily persist under future market conditions. Indicator

Monte Carlo Risk Geometry Simulator [Aslan]Thanks to @KioseffTrading for the polyline retracing system and the plotting system as a whole🙏
♦️ What This Script Does
This is a Monte Carlo simulator for visualising and calculating the probability of a return based on risk geometry of the model (Risk %, RR, WR). It assesses the probability of returns by generating hundreds or thousands of possible outcomes using your win rate, risk-reward, and position sizing. Each line you see is a different plausible “future,” showing how your account could realistically evolve.
🔶 How To Use It
Input your strategy stats, run a large number of simulations, and focus on three things: how wide the equity curves spread, how deep drawdowns get, and the percentage of profitable outcomes. Then adjust your model and repeat.
🔷 Application in Prop Firm evaluations
Using the threshold system, you can see what risk geometry is most likely to pass a prop firm evaluation. Suprisingly, the most probable geometry for passing an eval can sometimes have a negative expected value!
♦️ Bottom Line
This script helps you move from “how much can I make?” to “how likely am I to profit?”
🔎 Monte Carlo Simulations Explained
Monte Carlo simulations are a method of modeling uncertainty by running many random versions of the same system to see all possible outcomes. In trading, instead of assuming one fixed result, it repeatedly simulates sequences of wins and losses based on your strategy’s statistics (like win rate and risk-reward). This creates a distribution of potential equity curves, showing not just what did happen, but could happen. It’s essentially a way to test probability and survival under randomness rather than relying on a single backtest. Monte Carlo simulations are widely used on quant trading desks around the world to model uncertainty, test strategy robustness, and estimate the probability distribution of trading outcomes under real-world randomness. Indicator

Predictive Monte Carlo Engine [LuxAlgo]The Predictive Monte Carlo Engine tool is a high-performance forecasting suite that uses probabilistic simulations to project future price paths based on historical volatility and market regimes.
🔶 USAGE
The indicator generates hundreds of potential price paths starting from the current bar (or an anchored point) to visualize the most likely price distribution over a user-defined projection length. It serves as a powerful volatility and support/resistance mapping tool, providing traders with an "expected value" range rather than a single fixed forecast.
Users can choose between three distinct mathematical methods to generate these paths, apply regime filters to isolate specific market conditions, and utilize a real-time dashboard that renders a visual "forecasted candle" for the next period.
🔹 Anchor Mode
By default, the simulation recalculates and updates on every new bar. By enabling Anchor Mode , users can lock the projection starting point. The engine will then only update every X bars (e.g., every 100 bars). This allows traders to observe how price actually reacted against historical Monte Carlo projections and Support/Resistance levels as the chart progresses.
🔶 DETAILS
The engine utilizes three primary simulation methodologies:
Geometric Brownian Motion (GBM): A stochastic process that assumes returns follow a log-normal distribution. This is the industry standard for modeling asset prices, ensuring prices remain positive and incorporating both drift and volatility.
Simple Random Walk (SRW): A basic additive model where price changes are sampled from a normal distribution based on historical mean and standard deviation.
Historical Shuffle (Bootstrapping): Instead of using random numbers, this method randomly samples actual historical price returns from the lookback period. This preserves the "fat tails" and unique characteristics of the specific asset being traded.
🔹 Regime Filtering
To improve accuracy, the engine can filter the historical data used for simulations. If "Trend" or "Momentum" regimes are selected, the indicator only calculates volatility and drift from past bars that match the current market environment (e.g., only using data from previous uptrends to forecast a current uptrend).
🔹 Fading S/R Zones
The tool identifies four key levels based on the simulation distribution: Max, R1 (90th percentile), S1 (10th percentile), and Min. These are rendered as horizontal zones that feature a unique horizontal gradient, fading as they extend into the future to represent the increasing uncertainty of the projection over time.
🔶 SETTINGS
🔹 Monte Carlo Settings
Simulation Method: Choose between GBM, SRW, or Historical Shuffle.
Regime Filter: Filter historical data by Trend (SMA) or Momentum (RSI).
Historical Lookback: The number of past bars used to calculate volatility.
Projection Length: How many bars into the future the paths extend.
Simulation Count: Number of individual paths to calculate (max 200).
Volatility Multiplier: Scales the historical volatility to simulate "stress-test" scenarios.
Anchor Mode: When enabled, locks the projection to update only at specific intervals.
🔹 Style
Path Percentiles: Adjust the thresholds for coloring the "Top" and "Bottom" path groups.
Colors: Customize the colors for bullish, bearish, and neutral paths, as well as the average projection line.
Show S/R Levels: Toggles the visibility of the horizontally fading Support and Resistance zones.
🔹 Dashboard
Show Dashboard: Toggles the statistical metrics table.
Next Candle Prediction: Enables the "Forecasted Candle" visual, which uses the 1-bar-ahead expected mean and distribution to render a text-based candlestick on the dashboard.
Indicator

Risk Simulation Matrix [Monte Carlo]OVERVIEW
This indicator is a multi-dimensional stress-testing tool designed to map the mathematical "fragility" or "robustness" of a trading strategy.
This is NOT a Backtester
While standard backtests provide a static, historical result, the Risk Simulation Matrix constructs a grid of potential outcomes by simultaneously varying Win Rate and Reward-to-Risk (R) parameters. It addresses the fundamental need for sensitivity analysis: understanding how a system performs when its core execution metrics deviate from the ideal. This is not a predictor, but a tool for determining the safety margins of a trading edge within the realm of probability theory.
HOW IT WORKS
To explain the logic through an analogy, imagine telling the Pine Script compiler:
"I have a series of coins where the win probability starts at 10% and increases step-by-step to 60%. For every single one of these coins, I want to test a range of payout scenarios—starting from winning $1.0 per $1 risk and increasing up to $4.0. Now, for every possible intersection (such as the 10% win rate coin paying $1.5, then $2.0, then $2.5, and so on, repeating this for the 15%, 20%, and all other win rates) flip that specific coin 100 times. Repeat each of these unique 100-flip sequences 1000 times. Finally, gather all those results and report the statistical distribution for every single coordinate on this grid."
MECHANICS
The engine combines deterministic randomness with iterative matrix calculations to ensure statistical reliability:
• LCG Implementation (f_random): The script utilizes a Linear Congruential Generator based on Knuth and Park-Miller parameters. This ensures that for a given "Scenario ID" (Seed), the generated trade sequences are identical and repeatable across sessions.
• Sensitivity Grid: The matrix iterates through user-defined ranges for Win Rate and R-multiples. Each cell acts as an independent Monte Carlo engine, processing thousands of simulated trade paths.
• Percentile Interpolation: Rather than relying on simple arithmetic means, the tool uses array.percentile_linear_interpolation. This allows users to view the "Median" (P50) outcome or focus on "Worst-Case" (P0) tails to plan for the most adverse sequences.
• Dynamic Friction: Every trade simulation accounts for compounding equity, randomized stop-loss distances between a defined Min/Max range, and two-way commission fees.
HOW TO USE
• Matrix Dimensions: Define your Min, Max, and Step for both Win Rate and Reward/Risk. To optimize performance, the matrix is limited to 81 cells.
• Setup & Commission: Input your initial capital and the percentage of equity risked per trade (Compounding). Ensure the commission rate reflects your broker’s actual fee structure.
• Stops: Set the range for your Stop-Loss distance (%). This parameter is used to calculate precise position sizing and commission impacts.
• Interpolation (P%): Adjust this value to set the "strictness" of the matrix. 50% represents the median expectation, while 10% reveals how the strategy holds up during significant losing streaks.
OUTPUTS
• Heat Map Table: Cells are four-color-coded based on the Total PnL (%) achieved at the selected percentile.
• Statistical Tooltips: Hovering over any cell reveals a comprehensive performance profile, including Profit Factor, Payoff Ratio, Max Drawdown, Max Loss Streak, and Expectancy in R-multiples.
• Expectancy (Calculated in R): A critical metric provided is the Expectancy per trade, expressed in R-multiples. This reflects the average unit of risk (1R) you can expect to gain or lose per trade, providing a pure measure of the system's mathematical edge regardless of account size.)
For single scenarios and more comprehensive backtest metrics, you can also check out the following indicator: Risk Simulation (single version)
DISCLAIMER
This tool is a mathematical modeling environment and does not account for market liquidity, slippage, or the psychological pressures of live execution. It is designed to test the mathematical viability of a system's parameters; it is not a guarantee of future performance. Users should apply these simulations as a supplementary risk management layer, not as a replacement for comprehensive strategy testing. Indicator

Monte Carlo Expected Move Distribution [LuxAlgo]The Monte Carlo Expected Move Distribution indicator is a statistical forecasting tool that uses Geometric Brownian Motion (GBM) to simulate hundreds of potential price paths, generating a vertical probability distribution to visualize where the market is mathematically expected to trade within a specific future timeframe.
🔶 USAGE
The indicator provides a forward-looking "Expected Move" profile, a concept widely used in options trading to determine the implied range of an asset. It helps traders move away from single-line price predictions and toward a probabilistic understanding of market outcomes.
🔹 Setting Realistic Price Targets
By looking at the vertical distribution at the end of the projection, traders can identify the "Median Outcome" (50th percentile). This represents the most likely price level based on current trend (drift) and volatility.
Conservative Targets: Aim for levels within the highlighted "Expected Move" (1-SD) area.
Aggressive Targets: Levels sitting in the "tails" (gray areas) are statistically less likely to be reached within the chosen timeframe.
🔹 Identifying Overextensions
The dashed projection lines represent the upper (+1 SD) and lower (-1 SD) boundaries.
Upper Expected Move: If price reaches this level ahead of the projection time, it is considered "overbought" relative to current volatility.
Lower Expected Move: If price drops to this level rapidly, it is considered "oversold" from a statistical standpoint.
🔹 Understanding the Distribution Profile
The vertical histogram (bins) at the right of the chart represents the density of the simulations. The widest part of the histogram shows the price zone where the highest number of simulated paths ended, indicating the highest mathematical probability for that price area.
🔶 HOW TO USE
To use the indicator effectively, follow these steps to align the statistical model with your trading timeframe:
Define Your Horizon: Adjust the "Projection Length" to match your trade duration (e.g., 20 bars for a swing trade or 5 bars for a scalp). The distribution will shift further into the future accordingly.
Evaluate the Drift: Enable "Include Trend (Drift)" if you believe the current price momentum will persist. If you expect a sideways market or a "random walk," disable this setting to center the distribution on the current price.
Analyze Probability Zones: Look at the colored region of the histogram. If your target price lies within this zone, there is a ~68% statistical probability (based on current volatility) of price reaching that area within the specified time.
Risk Management: Use the Lower Expected Move (-1 SD) as a guide for stop-loss placement in long positions, as prices falling below this level represent an outlier move beyond normal volatility expectations.
🔶 DETAILS
The script utilizes Monte Carlo Simulation via Geometric Brownian Motion. This model accounts for two primary factors:
Log-Volatility: Derived from the standard deviation of historical log-returns, determining how "wide" the potential price swings are.
Drift (Optional): An approximation of the current trend based on a moving average, providing a directional bias to the simulations.
The "Expected Move" is defined as the 1-Standard Deviation range (the 16th to 84th percentiles). In a normal distribution, approximately 68% of all outcomes fall within this range. The indicator highlights this specific zone in color, while the outliers (the remaining 32%) are shown in a neutral gray.
🔶 SETTINGS
🔹 Monte Carlo Simulation
Simulations: The number of paths to generate (50-500). Higher values result in a smoother, more accurate distribution profile.
Projection Length: How many bars into the future the "Expected Move" is calculated for.
Volatility Lookback: The period used to measure historical price fluctuations.
Include Trend (Drift): When enabled, the distribution will lean toward the current trend direction. When disabled, it assumes a mean-neutral random walk.
🔹 Distribution Visuals
Price Bins: The vertical resolution of the histogram. More bins allow for a more detailed view of the probability peaks.
Distribution Color: Sets the color for the "Expected Move" (68% probability) zone.
Max Distribution Width: Controls how many bars wide the histogram is drawn on the chart.
Indicator

Risk Simulation [Monte Carlo]RISK SIMULATION
This indicator is an analytical tool designed to measure the mathematical viability of a specific trade setup and model the potential scenarios that could occur if one remains loyal to that setup.
This is NOT a Backtester
Classic backtest indicators report the performance of a trading system based on past price action. Risk Simulation, however, does not need price action; it calculates the performance distribution of a system based on its fundamental inputs (Win Rate, Reward/Risk). In this sense, risk simulations are mathematical probability models that allow us to foresee potential scenarios before entering the market. The main idea is to model the probable outcomes of a system designed with the available setup information/decisions.
HOW IT WORKS
To understand how this indicator works without getting lost in complex code, imagine this scenario:
You tell the Pine Script compiler: "I have a coin that lands on heads 35% of the time. If it's heads, I win $2.5; if it's tails, I lose $1. Now, flip this coin 5,000 times and report the statistical distribution."
MECHANICS
The technical structure of this tool is built for repeatability, utilizing a deterministic approach instead of standard pseudo-random generators:
• LCG Implementation (f_random): The script uses a Linear Congruential Generator based on Knuth and Park-Miller parameters to produce a consistent distribution.
• Seed-Based Randomness: Through the "Scenario ID" (Seed input), the engine ensures that the trade sequence remains identical across script recalculations.
• Variable Risk Model (f_simulate_trade): For each trade, a random stop-loss is assigned between the "Min" and "Max" range to calculate commission and position sizing dynamically.
• Data Management (f_run_simulation): Simulation cycles and metrics (Sharpe, Sortino, Kelly, etc.) are processed using matrix and array structures for computational efficiency.
• Percentile Interpolation (f_get_column_stats): Instead of rank-based selection, array.percentile_linear_interpolation is used to calculate the Median and Custom P% results.
HOW TO USE
The indicator requires a few core inputs to model your trading "profile":
• Setup: Define your starting capital, the percentage of risk you take per trade (compounding), your average Win Rate, and your Reward-to-Risk (R) ratio.
• Commission: Enter the percentage fee your broker charges. This is applied to both entry and exit prices for every simulated trade.
• Stops: Set a range for your stop-loss distance. This helps the model simulate how varying market volatility affects your position sizing and net profit.
• Simulation Count: Define how many "alternative futures" you want to generate. You can increase this up to 5000 for a broader statistical sample.
• Circuit Breaker: Set the percentage of capital loss that you consider "bankruptcy." If a simulation hits this level, it stops and is recorded as a "ruin" event.
OUTPUTS
The simulation results are presented in a comparative table that breaks down the performance distribution across various scenarios. Instead of a single backtest result, the table displays the Worst, Median, Best, and Mean outcomes, along with a user-defined percentile (P%) for statistical interpolation. The reporting focuses on three core areas:
• Account Dynamics: Tracks total PnL and equity evolution to show the final balance distribution.
• Risk & Survival: Highlights the Max Drawdown experienced and the Risk of Ruin (RoR), which calculates the probability of hitting your defined bankruptcy threshold.
• Performance Quality: Evaluates the trade model through risk-adjusted return ratios (Sharpe, Sortino) and system quality metrics like the SQN score and Kelly Ratio for position sizing.
DISCLAIMER
This indicator is a mathematical modeling tool based on probability theory. It does not account for market liquidity, slippage, execution errors, or the psychological challenges of live trading. The results are simulations of a specific mathematical model and should be used as a supplementary tool for risk management and strategy evaluation, not as a guarantee of future performance. Indicator

Monte Carlo Mean Reversion Heatmap [LuxAlgo]The Monte Carlo Mean Reversion Heatmap indicator is a statistical forecasting tool that uses Geometric Brownian Motion (GBM) to simulate 100+ potential future price paths and visualize the mathematical probability of price returning to a specific mean.
🔶 USAGE
The indicator provides a visual "probability cloud" projecting from the current price into the future. It helps traders identify statistical overextensions and the likelihood of a trend reversal toward a long-term average.
🔹 1. Assessing Mean Reversion Probability
The dashboard shows a Mean Reversion % . This tells you how many of the 100 simulated paths "touched" or "crossed" the EMA ribbon within the projection window (e.g., the next 30 bars).
High Probability (>70%): If the current price is far from the EMA but the probability of reversion is high, it suggests the market is "overextended." You might look for a counter-trend trade back toward the EMA.
Low Probability (<30%): This suggests that volatility is so high or the trend is so strong that price is statistically unlikely to return to the mean anytime soon. This often happens during "parabolic" runs.
🔹 2. Trading the "Probability Fan"
The dotted lines (5%, 50%, 95%) represent the statistical boundaries of where price is expected to stay.
Overbought/Oversold: If price moves outside the 5% or 95% lines, it is making a move that only happens in 1 out of 20 scenarios. This is a "statistical extreme." Traders often look for reversals or profit-taking when price enters these outer edges of the cone.
The Median Path (50%): This dashed line represents the "most likely" path based on current momentum (drift). It serves as a realistic target for trend-following trades.
🔹 Heatmap Density
The heatmap represents the density of the simulated paths. Darker areas indicate a higher concentration of paths, marking the price zones with the highest mathematical probability of being reached according to the model.
🔶 DETAILS
The engine behind this script is the Geometric Brownian Motion (GBM) model. GBM is a continuous-time stochastic process used in mathematical finance to model stock prices.
The model assumes that price changes follow a random walk with two components:
Drift: The deterministic trend of the mean (directional bias).
Volatility: The random "noise" or shocks based on historical log-returns.
By running 100 individual simulations simultaneously, the script generates a distribution of outcomes rather than a single linear prediction. This allows the user to see the "width" of uncertainty in the current market environment.
🔶 SETTINGS
🔹 Mean Calculation
Mean Length: The period of the EMA used as the target for mean reversion analysis.
Mean Color: The color of the target EMA line on the chart.
🔹 Monte Carlo Simulation
Simulations: The number of random paths to calculate (higher values increase accuracy but may impact performance).
Projection Length: How many bars into the future the simulation projects.
Volatility Lookback: The window used to calculate historical log-volatility for the simulation.
Include Drift: When enabled, the simulation accounts for the slope (trend) of the Mean EMA.
🔹 Visuals
Price Bins: Determines the vertical resolution of the heatmap.
Heatmap Color: The base color used for the probability density cloud.
Show Percentile Lines: Toggles the visibility of the 5%, 50%, and 95% projection lines.
🔹 Dashboard
Show Dashboard: Toggles the statistical information table.
Position/Size: Controls the location and scale of the dashboard on the chart.
Indicator

Stochastic Ensembling of OutputsStochastic Ensembling of Outputs
🙏🏻 This is a simple tool/method that would solve naturally many well known problems:
“Price reversed 1 tick before the actual level, not executing my limit order”
“I consider intraday trend change by checking whether price is above/below VWAP, but is 1 tick enough? What to do, price is now whipsawing around vwap...”.
“I want to gradually accumulate a position around a chosen anchor. But where exactly should I put my orders? And I want to automate it ofc.“
“All these DSP adepts are telling you about some kind of noise in the markets… But how can I actually see it?”
The easy fix is to make things more analog less digital, by synthesizing numerous noise instances & adding it to any price-applied metric of yours. The ones who fw techno & psytrance, and other music, probably don’t need any more explanations. Then by checking not just 2 lines or 1 process against another one, you will be checking cloud vs cloud of lines, even allowing you to introduce proxies of probabilities. More crosses -> more confirmation to act.
How-to use:
The tool has 2 inputs: source and target:
Sources should always be the underlying process. If you apply the tool to price based metric, leave it hlcc4 unless you have a better one point estimate for each bar;
Target is your target, e.g if you want to apply it to VWAP, pick VWAP as target. You can thee on the chart above how trading activity recently never exactly touched VWAP, however noised instances of VWAP 'were' touched
The code is clean and written in modular form, you can simply copy paste it to any script of yours if you don't want to have multiple study-on-study script pairs.
^^ applied to prev days highs and lows
^^ applied to MBAD extensions and basis
^^ applied to input series itself
Here’s how it works, no ML, no “AI”, no 1k lines of code, just stats:
The problem with metrics, even if they are time aware like WMA, is that they still do not directly gain information about “changes” between datapoints. If we pick noise characteristics to match these changes, we’d effectively introduce this info into our ops.
^^ this screenshot represents 2 very different processes: a sine wave and white noise, see how the noise instances learned from each process differ significantly.
Changes can be represented as AR1 process . It’s dead simple, no PHD needed, it’s just how the current datapoint is related (or not) to the previous datapoint, no more than 1, and how this relationship holds/evolves over time. Unlike the mainstream approach like MLE, I estimate this relationship (phi parameter) via MoM but giving more weights to more recent datapoints via exponential smoothing over all the data available on your charts (so I encode temporal information), algocomplexity is O(1), lighting fast, just one pass. <- that gives phi , we’d use it as color for our noise generator
Then we just need to estimate noise amplitude ( gamma ) via checking what AR1 model actually thought vs the reality, variance of these innovations. Same via exponential smoothing, time aware, O(1), one pass, it’s all it does.
Then we generate white gaussian noise, and apply 2 estimated parameters (phi and gamma), and that’s all.
Omg, I think I just made my first real DSP script xd
Just like Monte Carlo for risk management, this is so simple and natural I can’t believe so many “pros” hide it and never talk about it in open access. Sharing it here on PulseWire would’ve not done anything critical for em, but many would’ve benefited.
∞ Indicator

Multi Brownian Forecast📊 Multi Brownian Forecast (Time-Adaptive, Probabilistic)
This indicator uses a sophisticated Geometric Brownian Motion (GBM) Monte Carlo simulation to project future price paths. It adapts to any chart timeframe and provides quantitative, multi-period probability signals.
---
🧠 Core Mathematical Methodology
The model relies on GBM, which is a continuous-time stochastic process that models asset prices.
1. Historical Analysis (Drift & Volatility):
* The script first calculates Logarithmic Returns over a user-defined Historical Lookback (Hours) .
* Drift ($\mu$): Computed as the average of the log returns.
* Volatility ($\sigma$): Computed as the standard deviation of the log returns.
* These values are then time-adapted to an hourly step, compensating for the chart's current timeframe (e.g., 5-minute, 1-hour).
2. Monte Carlo Simulation:
* It runs a specified Number of Simulations (e.g., 1000).
* For each simulation, the price is stepped forward hourly using the GBM formula, which incorporates the calculated drift and a random shock drawn from a normal distribution (generated via the Box-Muller transform ).
---
✨ Key Features
Probabilistic Quartile Forecast: Plots a dynamic "cone" of probability on the chart. It shows key price percentiles (Q1, Q2/Median, Q3, and Q4/Outer Bound) at the forecast's expiration, visualizing the expected range of price outcomes based on the simulations.
Multi-Period Probability Signals: This is the core signal feature. Users can define multiple, independent forecast periods (e.g., 4h, 16h, 48h) in a comma-separated list.
* For each period, a Probability Up and Probability Down is calculated based on hitting a custom Target Price Change (%) (e.g., 2%) at a certain confidence level given a simulation over the historical backlook.
* The probabilities are displayed in a chart table. The cell text turns white if the calculated probability exceeds the user-defined Signal Confidence (%) .
Conditional Fibonacci Retracement: Optionally displays a Fibonacci Retracement on the chart. This feature is only activated when one of the multi-period signals reaches its minimum confidence threshold, providing a contextual technical level when a probabilistic edge is found.
Indicator

Brownian Motion Probabilistic Forecasting (Time Adaptive)Probabilistic Price Forecast Indicator
Overview
The Probabilistic Price Forecast is an advanced technical analysis tool designed for the PulseWire platform. Instead of predicting a single future price, this indicator uses a Monte Carlo simulation to model thousands of potential future price paths, generating a cone of possibilities and calculating the probability of specific outcomes.
This allows traders to move beyond simple price targets and ask more sophisticated questions, such as: "What is the probability that this stock will increase by 5% over the next 24 hours?"
Core Concept: Geometric Brownian Motion
The indicator's forecasting model is built on the principles of Geometric Brownian Motion (GBM) , a widely accepted mathematical model for describing the random movements of financial asset prices. The core idea is that the next price step is a function of the asset's historical trend (drift), its volatility, and a random "shock."
The formula used to project each price step in the simulation is:
next_price = current_price * exp( (μ - (σ²/2))Δt + σZ√(Δt) )
Where:
μ (mu) represents the drift , which is the average historical return.
σ (sigma) represents the volatility , measured by the standard deviation of historical returns.
Z is a random variable from a standard normal distribution, representing the random "shock" or new information affecting the price.
Δt (delta t) is the time step for each projection.
How It Works
The indicator performs a comprehensive analysis on the most recent bar of the chart:
**Historical Analysis**: It first analyzes a user-defined historical period (e.g., the last 240 hours of price data) to calculate the asset's historical drift (μ) and volatility (σ) from its logarithmic returns.
**Monte Carlo Simulation**: It then runs thousands of simulations (e.g., 2000) of future price paths over a specified forecast period (e.g., the next 24 hours). Each path is unique due to the random shock (Z) applied at every step.
**Probability Distribution**: After all simulations are complete, it collects the final price of each path and sorts them to build a probability distribution of potential outcomes.
**Visualization and Signaling**: Finally, it visualizes this distribution on the chart and generates signals based on the user's criteria.
Key Features & Configuration
The indicator is highly configurable, allowing you to tailor its analysis to your specific needs.
Time-Adaptive Periods
The lookback and forecast periods are defined in hours , not bars. The script automatically converts these hour-based inputs into the correct number of bars based on the chart's current timeframe, ensuring the analysis remains consistent across different chart resolutions.
Forecast Quartiles
You can visualize the forecast as a "cone of probability" on the chart. The indicator draws lines and a shaded area representing the price levels for different quartiles (percentiles) of the simulation results. By default, this shows the range between the 25th and 95th percentiles.
Independent Bullish and Bearish Signals
The indicator allows you to set independent criteria for bullish and bearish signals, providing greater flexibility. You can configure:
A bullish signal for an X% confidence of a Y% price increase.
A bearish signal for a W% confidence of a Z% price decrease.
For example, you can set it to alert you for a 90% chance of a 2% drop, while simultaneously looking for a 60% chance of a 10% rally.
How to Interpret the Indicator
The Forecast Cone : The blue shaded area on the chart represents the probable range of future prices. The width of the cone indicates the expected volatility; a wider cone means higher uncertainty. The price labels on the right side of the cone show the calculated percentile levels at the end of the forecast period.
Green Signal Label : A green "UP signal" label appears when the probability of the price increasing by your target percentage exceeds your defined confidence level.
Red Signal Label : A red "DOWN signal" label appears when the probability of the price decreasing by your target percentage exceeds your confidence level.
This tool provides a statistical edge for understanding future possibilities but should be used in conjunction with other analysis techniques.
Indicator

Expected Value Monte CarloI created this indicator after noticing that there was no Expected Value indicator here on PulseWire.
The EVMC provides statistical Expected Value to what might happen in the future regarding the asset you are analyzing.
It uses 2 quantitative methods:
Historical Backtest to ground your analysis in long-term, factual data.
Monte Carlo Simulation to project a cone of probable future outcomes based on recent market behavior.
This gives you a data-driven edge to quantify risk, and make more informed trading decisions.
The indicator includes:
Dual analysis: Combines historical probability with forward-looking simulation.
Quantified projections: Provides the Expected Value ($ and %), Win Rate, and Sharpe Ratio for both methods.
Asset-aware: Automatically adjusts its calculations for Stocks (252 trading days) and Crypto (365 days) for mathematical accuracy.
The projection cone shows the mean expected path and the +/- 1 standard deviation range of outcomes.
No repainting
Calculation:
1. Historical Expected Value:
This is a systematic backtest over thousands of bars. It calculates the return Rᵢ for N past trades (buy-and-hold). The Historical EV is the simple average of these returns, giving a baseline performance measure.
Historical EV % = (Σ Rᵢ) / N
2. Monte Carlo Projection:
This projection uses the Geometric Brownian Motion (GBM) model to simulate thousands of future price paths based on the market's recent behavior.
It first measures the drift (μ), or recent trend, and volatility (σ), or recent risk, from the Projection Lookback period. It then projects a final return for each simulation using the core GBM formula:
Projected Return = exp( (μ - σ²/2)T + σ√T * Z ) - 1
(Where T is the time horizon and Z is a random variable for the simulation.)
The purple line on the chart is the average of all simulated outcomes (the Monte Carlo EV). The cone represents one standard deviation of those outcomes.
The dashed lines represent one standard deviation (+/- 1σ) from the average, forming a cone of probable outcomes. Roughly 68% of the simulated paths ended within this cone.
This projection answers the question: "If the recent trend and volatility continue, where is the price most likely to go?"
Here's how to read the indicator
Expected Value ($/%): Is my average trade profitable?
Win Rate: How often can I expect to be right?
Sharpe Ratio: Am I being adequately compensated for the risk I'm taking?
User Guide
Max trade duration (bars): This is your analysis timeframe. Are you interested in the probable outcome over the next month (21 bars), quarter (63 bars), or year (252 bars)?
Position size ($): Set this to your typical trade size to see the Expected Value in real dollar terms.
Projection lookback (bars): This is the most important input for the Monte Carlo model. A short lookback (e.g., 50) makes the projection highly sensitive to recent momentum. Use this to identify potential recency bias. A long lookback (e.g., 252) provides a more stable, long-term projection of trend and volatility.
Historical Lookback (bars): For the historical backtest, more data is always better. Use the maximum that your PulseWire plan allows for the most statistically significant results.
Use TP/SL for Historical EV: Check this box to see how the historical performance would have changed if you had used a simple Take Profit and Stop Loss, rather than just holding for the full duration.
I hope you find this indicator useful and please let me know if you have any suggestions. 😊 Indicator

Martingale Strategy Simulator [BackQuant]Martingale Strategy Simulator
Purpose
This indicator lets you study how a martingale-style position sizing rule interacts with a simple long or short trading signal. It computes an equity curve from bar-to-bar returns, adapts position size after losing streaks, caps exposure at a user limit, and summarizes risk with portfolio metrics. An optional Monte Carlo module projects possible future equity paths from your realized daily returns.
What a martingale is
A martingale sizing rule increases stake after losses and resets after a win. In its classical form from gambling, you double the bet after each loss so that a single win recovers all prior losses plus one unit of profit. In markets there is no fixed “even-money” payout and returns are multiplicative, so an exact recovery guarantee does not exist. The core idea is unchanged:
Lose one leg → increase next position size
Lose again → increase again
Win → reset to the base size
The expectation of your strategy still depends on the signal’s edge. Sizing does not create positive expectancy on its own. A martingale raises variance and tail risk by concentrating more capital as a losing streak develops.
What it plots
Equity – simulated portfolio equity including compounding
Buy & Hold – equity from holding the chart symbol for context
Optional helpers – last trade outcome, current streak length, current allocation fraction
Optional diagnostics – daily portfolio return, rolling drawdown, metrics table
Optional Monte Carlo probability cone – p5, p16, p50, p84, p95 aggregate bands
Model assumptions
Bar-close execution with no slippage or commissions
Shorting allowed and frictionless
No margin interest, borrow fees, or position limits
No intrabar moves or gaps within a bar (returns are close-to-close)
Sizing applies to equity fraction only and is capped by your setting
All results are hypothetical and for education only.
How the simulator applies it
1) Directional signal
You pick a simple directional rule that produces +1 for long or −1 for short each bar. Options include 100 HMA slope, RSI above or below 50, EMA or SMA crosses, CCI and other oscillators, ATR move, BB basis, and more. The stance is evaluated bar by bar. When the stance flips, the current trade ends and the next one starts.
2) Sizing after losses and wins
Position size is a fraction of equity:
Initial allocation – the starting fraction, for example 0.15 means 15 percent of equity
Increase after loss – multiply the next allocation by your factor after a losing leg, for example 2.00 to double
Reset after win – return to the initial allocation
Max allocation cap – hard ceiling to prevent runaway growth
At a high level the size after k consecutive losses is
alloc(k) = min( cap , base × factor^k ) .
In practice the simulator changes size only when a leg ends and its PnL is known.
3) Equity update
Let r_t = close_t / close_{t-1} − 1 be the symbol’s bar return, d_{t−1} ∈ {+1, −1} the prior bar stance, and a_{t−1} the prior bar allocation fraction. The simulator compounds:
eq_t = eq_{t−1} × (1 + a_{t−1} × d_{t−1} × r_t) .
This is bar-based and avoids intrabar lookahead. Costs, slippage, and borrowing costs are not modeled.
Why traders experiment with martingale sizing
Mean-reversion contexts – if the signal often snaps back after a string of losses, adding size near the tail of a move can pull the average entry closer to the turn
Behavioral or microstructure edges – some rules have modest edge but frequent small whipsaws; size escalation may shorten time-to-recovery when the edge manifests
Exploration and stress testing – studying the relationship between streaks, caps, and drawdowns is instructive even if you do not deploy martingale sizing live
Why martingale is dangerous
Martingale concentrates capital when the strategy is performing worst. The main risks are structural, not cosmetic:
Loss streaks are inevitable – even with a 55 percent win rate you should expect multi-loss runs. The probability of at least one k-loss streak in N trades rises quickly with N.
Size explodes geometrically – with factor 2.0 and base 10 percent, the sequence is 10, 20, 40, 80, 100 (capped) after five losses. Without a strict cap, required size becomes infeasible.
No fixed payout – in gambling, one win at even odds resets PnL. In markets, there is no guaranteed bounce nor fixed profit multiple. Trends can extend and gaps can skip levels.
Correlation of losses – losses cluster in trends and in volatility bursts. A martingale tends to be largest just when volatility is highest.
Margin and liquidity constraints – leverage limits, margin calls, position limits, and widening spreads can force liquidation before a mean reversion occurs.
Fat tails and regime shifts – assumptions of independent, Gaussian returns can understate tail risk. Structural breaks can keep the signal wrong for much longer than expected.
The simulator exposes these dynamics in the equity curve, Max Drawdown, VaR and CVaR, and via Monte Carlo sketches of forward uncertainty.
Interpreting losing streaks with numbers
A rough intuition: if your per-trade win probability is p and loss probability is q=1−p , the chance of a specific run of k consecutive losses is q^k . Over many trades, the chance that at least one k-loss run occurs grows with the number of opportunities. As a sanity check:
If p=0.55 , then q=0.45 . A 6-loss run has probability q^6 ≈ 0.008 on any six-trade window. Across hundreds of trades, a 6 to 8-loss run is not rare.
If your size factor is 1.5 and your base is 10 percent, after 8 losses the requested size is 10% × 1.5^8 ≈ 25.6% . With factor 2.0 it would try to be 10% × 2^8 = 256% but your cap will stop it. The equity curve will still wear the compounded drawdown from the sequence that led to the cap.
This is why the cap setting is central. It does not remove tail risk, but it prevents the sizing rule from demanding impossible positions
Note: The p and q math is illustrative. In live data the win rate and distribution can drift over time, so real streaks can be longer or shorter than the simple q^k intuition suggests..
Using the simulator productively
Parameter studies
Start with conservative settings. Increase one element at a time and watch how the equity, Max Drawdown, and CVaR respond.
Initial allocation – lower base reduces volatility and drawdowns across the board
Increase factor – set modestly above 1.0 if you want the effect at all; doubling is aggressive
Max cap – the most important brake; many users keep it between 20 and 50 percent
Signal selection
Keep sizing fixed and rotate signals to see how streak patterns differ. Trend-following signals tend to produce long wrong-way streaks in choppy ranges. Mean-reversion signals do the opposite. Martingale sizing interacts very differently with each.
Diagnostics to watch
Use the built-in metrics to quantify risk:
Max Drawdown – worst peak-to-trough equity loss
Sharpe and Sortino – volatility and downside-adjusted return
VaR 95 percent and CVaR – tail risk measures from the realized distribution
Alpha and Beta – relationship to your chosen benchmark
If you would like to check out the original performance metrics script with multiple assets with a better explanation on all metrics please see
Monte Carlo exploration
When enabled, the forecast draws many synthetic paths from your realized daily returns:
Choose a horizon and a number of runs
Review the bands: p5 to p95 for a wide risk envelope; p16 to p84 for a narrower range; p50 as the median path
Use the table to read the expected return over the horizon and the tail outcomes
Remember it is a sketch based on your recent distribution, not a predictor
Concrete examples
Example A: Modest martingale
Base 10 percent, factor 1.25, cap 40 percent, RSI>50 signal. You will see small escalations on 2 to 4 loss runs and frequent resets. The equity curve usually remains smooth unless the signal enters a prolonged wrong-way regime. Max DD may rise moderately versus fixed sizing.
Example B: Aggressive martingale
Base 15 percent, factor 2.0, cap 60 percent, EMA cross signal. The curve can look stellar during favorable regimes, then a single extended streak pushes allocation to the cap, and a few more losses drive deep drawdown. CVaR and Max DD jump sharply. This is a textbook case of high tail risk.
Strengths
Bar-by-bar, transparent computation of equity from stance and size
Explicit handling of wins, losses, streaks, and caps
Portable signal inputs so you can A–B test ideas quickly
Risk diagnostics and forward uncertainty visualization in one place
Example, Rolling Max Drawdown
Limitations and important notes
Martingale sizing can escalate drawdowns rapidly. The cap limits position size but not the possibility of extended adverse runs.
No commissions, slippage, margin interest, borrow costs, or liquidity limits are modeled.
Signals are evaluated on closes. Real execution and fills will differ.
Monte Carlo assumes independent draws from your recent return distribution. Markets often have serial correlation, fat tails, and regime changes.
All results are hypothetical. Use this as an educational tool, not a production risk engine.
Practical tips
Prefer gentle factors such as 1.1 to 1.3. Doubling is usually excessive outside of toy examples.
Keep a strict cap. Many users cap between 20 and 40 percent of equity per leg.
Stress test with different start dates and subperiods. Long flat or trending regimes are where martingale weaknesses appear.
Compare to an anti-martingale (increase after wins, cut after losses) to understand the other side of the trade-off.
If you deploy sizing live, add external guardrails such as a daily loss cut, volatility filters, and a global max drawdown stop.
Settings recap
Backtest start date and initial capital
Initial allocation, increase-after-loss factor, max allocation cap
Signal source selector
Trading days per year and risk-free rate
Benchmark symbol for Alpha and Beta
UI toggles for equity, buy and hold, labels, metrics, PnL, and drawdown
Monte Carlo controls for enable, runs, horizon, and result table
Final thoughts
A martingale is not a free lunch. It is a way to tilt capital allocation toward losing streaks. If the signal has a real edge and mean reversion is common, careful and capped escalation can reduce time-to-recovery. If the signal lacks edge or regimes shift, the same rule can magnify losses at the worst possible moment. This simulator makes those trade-offs visible so you can calibrate parameters, understand tail risk, and decide whether the approach belongs anywhere in your research workflow.
Indicator

Seasonality Monte Carlo Forecaster [BackQuant]Seasonality Monte Carlo Forecaster
Plain-English overview
This tool projects a cone of plausible future prices by combining two ideas that traders already use intuitively: seasonality and uncertainty. It watches how your market typically behaves around this calendar date, turns that seasonal tendency into a small daily “drift,” then runs many randomized price paths forward to estimate where price could land tomorrow, next week, or a month from now. The result is a probability cone with a clear expected path, plus optional overlays that show how past years tended to move from this point on the calendar. It is a planning tool, not a crystal ball: the goal is to quantify ranges and odds so you can size, place stops, set targets, and time entries with more realism.
What Monte Carlo is and why quants rely on it
• Definition . Monte Carlo simulation is a way to answer “what might happen next?” when there is randomness in the system. Instead of producing a single forecast, it generates thousands of alternate futures by repeatedly sampling random shocks and adding them to a model of how prices evolve.
• Why it is used . Markets are noisy. A single point forecast hides risk. Monte Carlo gives a distribution of outcomes so you can reason in probabilities: the median path, the 68% band, the 95% band, tail risks, and the chance of hitting a specific level within a horizon.
• Core strengths in quant finance .
– Path-dependent questions : “What is the probability we touch a stop before a target?” “What is the expected drawdown on the way to my objective?”
– Pricing and risk : Useful for path-dependent options, Value-at-Risk (VaR), expected shortfall (CVaR), stress paths, and scenario analysis when closed-form formulas are unrealistic.
– Planning under uncertainty : Portfolio construction and rebalancing rules can be tested against a cloud of plausible futures rather than a single guess.
• Why it fits trading workflows . It turns gut feel like “seasonality is supportive here” into quantitative ranges: “median path suggests +X% with a 68% band of ±Y%; stop at Z has only ~16% odds of being tagged in N days.”
How this indicator builds its probability cone
1) Seasonal pattern discovery
The script builds two day-of-year maps as new data arrives:
• A return map where each calendar day stores an exponentially smoothed average of that day’s log return (yesterday→today). The smoothing (90% old, 10% new) behaves like an EWMA, letting older seasons matter while adapting to new information.
• A volatility map that tracks the typical absolute return for the same calendar day.
It calculates the day-of-year carefully (with leap-year adjustment) and indexes into a 365-slot seasonal array so “March 18” is compared with past March 18ths. This becomes the seasonal bias that gently nudges simulations up or down on each forecast day.
2) Choice of randomness engine
You can pick how the future shocks are generated:
• Daily mode uses a Gaussian draw with the seasonal bias as the mean and a volatility that comes from realized returns, scaled down to avoid over-fitting. It relies on the Box–Muller transform internally to turn two uniform random numbers into one normal shock.
• Weekly mode uses bootstrap sampling from the seasonal return history (resampling actual historical daily drifts and then blending in a fraction of the seasonal bias). Bootstrapping is robust when the empirical distribution has asymmetry or fatter tails than a normal distribution.
Both modes seed their random draws deterministically per path and day, which makes plots reproducible bar-to-bar and avoids flickering bands.
3) Volatility scaling to current conditions
Markets do not always live in average volatility. The engine computes a simple volatility factor from ATR(20)/price and scales the simulated shocks up or down within sensible bounds (clamped between 0.5× and 2.0×). When the current regime is quiet, the cone narrows; when ranges expand, the cone widens. This prevents the classic mistake of projecting calm markets into a storm or vice versa.
4) Many futures, summarized by percentiles
The model generates a matrix of price paths (capped at 100 runs for performance inside PulseWire), each path stepping forward for your selected horizon. For each forecast day it sorts the simulated prices and pulls key percentiles:
• 5th and 95th → approximate 95% band (outer cone).
• 16th and 84th → approximate 68% band (inner cone).
• 50th → the median or “expected path.”
These are drawn as polylines so you can immediately see central tendency and dispersion.
5) A historical overlay (optional)
Turn on the overlay to sketch a dotted path of what a purely seasonal projection would look like for the next ~30 days using only the return map, no randomness. This is not a forecast; it is a visual reminder of the seasonal drift you are biasing toward.
Inputs you control and how to think about them
Monte Carlo Simulation
• Price Series for Calculation . The source series, typically close.
• Enable Probability Forecasts . Master switch for simulation and drawing.
• Simulation Iterations . Requested number of paths to run. Internally capped at 100 to protect performance, which is generally enough to estimate the percentiles for a trading chart. If you need ultra-smooth bands, shorten the horizon.
• Forecast Days Ahead . The length of the cone. Longer horizons dilute seasonal signal and widen uncertainty.
• Probability Bands . Draw all bands, just 95%, just 68%, or a custom level (display logic remains 68/95 internally; the custom number is for labeling and color choice).
• Pattern Resolution . Daily leans on day-of-year effects like “turn-of-month” or holiday patterns. Weekly biases toward day-of-week tendencies and bootstraps from history.
• Volatility Scaling . On by default so the cone respects today’s range context.
Plotting & UI
• Probability Cone . Plots the outer and inner percentile envelopes.
• Expected Path . Plots the median line through the cone.
• Historical Overlay . Dotted seasonal-only projection for context.
• Band Transparency/Colors . Customize primary (outer) and secondary (inner) band colors and the mean path color. Use higher transparency for cleaner charts.
What appears on your chart
• A cone starting at the most recent bar, fanning outward. The outer lines are the ~95% band; the inner lines are the ~68% band.
• A median path (default blue) running through the center of the cone.
• An info panel on the final historical bar that summarizes simulation count, forecast days, number of seasonal patterns learned, the current day-of-year, expected percentage return to the median, and the approximate 95% half-range in percent.
• Optional historical seasonal path drawn as dotted segments for the next 30 bars.
How to use it in trading
1) Position sizing and stop logic
The cone translates “volatility plus seasonality” into distances.
• Put stops outside the inner band if you want only ~16% odds of a stop-out due to noise before your thesis can play.
• Size positions so that a test of the inner band is survivable and a test of the outer band is rare but acceptable.
• If your target sits inside the 68% band at your horizon, the payoff is likely modest; outside the 68% but inside the 95% can justify “one-good-push” trades; beyond the 95% band is a low-probability flyer—consider scaling plans or optionality.
2) Entry timing with seasonal bias
When the median path slopes up from this calendar date and the cone is relatively narrow, a pullback toward the lower inner band can be a high-quality entry with a tight invalidation. If the median slopes down, fade rallies toward the upper band or step aside if it clashes with your system.
3) Target selection
Project your time horizon to N bars ahead, then pick targets around the median or the opposite inner band depending on your style. You can also anchor dynamic take-profits to the moving median as new bars arrive.
4) Scenario planning & “what-ifs”
Before events, glance at the cone: if the 95% band already spans a huge range, trade smaller, expect whips, and avoid placing stops at obvious band edges. If the cone is unusually tight, consider breakout tactics and be ready to add if volatility expands beyond the inner band with follow-through.
5) Options and vol tactics
• When the cone is tight : Prefer long gamma structures (debit spreads) only if you expect a regime shift; otherwise premium selling may dominate.
• When the cone is wide : Debit structures benefit from range; credit spreads need wider wings or smaller size. Align with your separate IV metrics.
Reading the probability cone like a pro
• Cone slope = seasonal drift. Upward slope means the calendar has historically favored positive drift from this date, downward slope the opposite.
• Cone width = regime volatility. A widening fan tells you that uncertainty grows fast; a narrow cone says the market typically stays contained.
• Mean vs. price gap . If spot trades well above the median path and the upper band, mean-reversion risk is high. If spot presses the lower inner band in an up-sloping cone, you are in the “buy fear” zone.
• Touches and pierces . Touching the inner band is common noise; piercing it with momentum signals potential regime change; the outer band should be rare and often brings snap-backs unless there is a structural catalyst.
Methodological notes (what the code actually does)
• Log returns are used for additivity and better statistical behavior: sim_ret is applied via exp(sim_ret) to evolve price.
• Seasonal arrays are updated online with EWMA (90/10) so the model keeps learning as each bar arrives.
• Leap years are handled; indexing still normalizes into a 365-slot map so the seasonal pattern remains stable.
• Gaussian engine (Daily mode) centers shocks on the seasonal bias with a conservative standard deviation.
• Bootstrap engine (Weekly mode) resamples from observed seasonal returns and adds a fraction of the bias, which captures skew and fat tails better.
• Volatility adjustment multiplies each daily shock by a factor derived from ATR(20)/price, clamped between 0.5 and 2.0 to avoid extreme cones.
• Performance guardrails : simulations are capped at 100 paths; the probability cone uses polylines (no heavy fills) and only draws on the last confirmed bar to keep charts responsive.
• Prerequisite data : at least ~30 seasonal entries are required before the model will draw a cone; otherwise it waits for more history.
Strengths and limitations
• Strengths :
– Probabilistic thinking replaces single-point guessing.
– Seasonality adds a small but meaningful directional bias that many markets exhibit.
– Volatility scaling adapts to the current regime so the cone stays realistic.
• Limitations :
– Seasonality can break around structural changes, policy shifts, or one-off events.
– The number of paths is performance-limited; percentile estimates are good for trading, not for academic precision.
– The model assumes tomorrow’s randomness resembles recent randomness; if regime shifts violently, the cone will lag until the EWMA adapts.
– Holidays and missing sessions can thin the seasonal sample for some assets; be cautious with very short histories.
Tuning guide
• Horizon : 10–20 bars for tactical trades; 30+ for swing planning when you care more about broad ranges than precise targets.
• Iterations : The default 100 is enough for stable 5/16/50/84/95 percentiles. If you crave smoother lines, shorten the horizon or run on higher timeframes.
• Daily vs. Weekly : Daily for equities and crypto where month-end and turn-of-month effects matter; Weekly for futures and FX where day-of-week behavior is strong.
• Volatility scaling : Keep it on. Turn off only when you intentionally want a “pure seasonality” cone unaffected by current turbulence.
Workflow examples
• Swing continuation : Cone slopes up, price pulls into the lower inner band, your system fires. Enter near the band, stop just outside the outer line for the next 3–5 bars, target near the median or the opposite inner band.
• Fade extremes : Cone is flat or down, price gaps to the upper outer band on news, then stalls. Favor mean-reversion toward the median, size small if volatility scaling is elevated.
• Event play : Before CPI or earnings on a proxy index, check cone width. If the inner band is already wide, cut size or prefer options structures that benefit from range.
Good habits
• Pair the cone with your entry engine (breakout, pullback, order flow). Let Monte Carlo do range math; let your system do signal quality.
• Do not anchor blindly to the median; recalc after each bar. When the cone’s slope flips or width jumps, the plan should adapt.
• Validate seasonality for your symbol and timeframe; not every market has strong calendar effects.
Summary
The Seasonality Monte Carlo Forecaster wraps institutional risk planning into a single overlay: a data-driven seasonal drift, realistic volatility scaling, and a probabilistic cone that answers “where could we be, with what odds?” within your trading horizon. Use it to place stops where randomness is less likely to take you out, to set targets aligned with realistic travel, and to size positions with confidence born from distributions rather than hunches. It will not predict the future, but it will keep your decisions anchored to probabilities—the language markets actually speak. Indicator

Monte Carlo (Polyline Traceback) [Kioseff Trading]Hello!
This script "Monte Carlo (Polyline Traceback) " performs a Monte Carlo simulation using polylines!
By using polylines, and tracing back the initial simulation to its origin point, we can better replicate the ideal output of a Monte Carlo simulation!
Such as:
The image above shows the output of a simulation (image sourced outside TV).
With this script, and polyline capabilities, we can come quite close on PulseWire.
The image above shows the indicator in action! Not bad considering the ideal output.
Of course, the script is quite heavy and tries its best to circumvent limitations :D
You might run into load time errors, in which case you might try applying the built-in setting "Force Script Load". This setting will cut-off the visuals for some simulations, but has a higher chance of passing load-time limitations!
As shown in the image above, you can select to only show worst-case and best-case simulations. Using this option will reduce chart lag and improve load times.
Features
Monte Carlo Simulation: Performs Monte Carlo simulation to generate multiple future paths.
Asset Price: Can simulate future asset prices based on historical log returns.
Statistical Methods: Offers two simulation methods—Gaussian (Normal) distribution and Bootstrapping.
Adjustable Parameters: Offers numerous user-adjustable settings like number of simulations, forecast length, and more.
Historical Data Points: Option to specify the amount of historical data to be used in the simulation (price).
Best/Worst Case: Allows you to show only the best case / worst case outcome (range) for all simulations!
Thank you! Indicator

Anchored Monte Carlo Shuffled Projection [LuxAlgo]The Anchored Monte Carlo Shuffled Projection tool randomly simulates future price points based on historical bar movements made before a user-anchored point in time.
By anchoring our data and projections to a single point in time, users can better understand and reflect on how the price played out while taking into consideration our random simulations.
🔶 USAGE
After selecting the indicator to apply to the chart, you will be prompted to "Set the Anchor Point". Do so by clicking on the desired location on your chart, only time is used as the anchor point.
Note: To select a new anchor point when applied to the chart, click on the 'More' dropdown next to the indicator status bar (○○○), then select "Reset points...".
Alternate Method: You are also able to click and drag the vertical line that displays on the anchor point bar when the indicator is highlighted.
By randomly simulating bar movements, a range is developed of potential price action which could be utilized to locate future price development as well as potential support/resistance levels.
Performing numerous simulations and taking the average at each step will converge toward the result highlighted by the "Average Line", and can point out where the price might develop, assuming the trend and amount of volatility persist.
Current closing price + Sum of changes in the calculation window
This constraint will cause the simulations always to display an endpoint consistent with the current lookback's slope.
While this may be helpful to some traders, this indicator includes an option to produce a less biased range, as seen below:
🔶 DETAILS
The Anchored Monte Carlo Shuffled Projection tool creates simulations based on prices within a user-set lookback window originating at the specified anchor point. Simulations are done as follows:
Collect each bar's price changes in the user-set window.
Randomize the order of each change in the window.
Project the cumulative sum of the shuffled changes from the current closing price.
Collect data on each point along the way.
This is the process for the Default calculation; for the 'Randomize Direction' calculation, when added onto the front for every other change, the value is inverted, creating the randomized endpoints for each simulation.
The script contains each simulation's data for that bar, with a maximum of 1000 simulations.
To get a glimpse behind the scenes, each simulation (up to 99) can be viewed using the 'Visualize Simulations' Options, as seen below.
Because the script holds the full simulation data, the script can also calculate this data, such as standard deviations.
In this script the Standard deviation lines are the average of all standard deviations across the vertical data groups, this provides a singular value that can be displayed a distance away from the simulation center line.
🔶 SETTINGS
Lookback: Sets the number of Bars to include in calculations.
Simulation Count: Sets the number of randomized simulations to calculate. (Max 1000)
Randomize Direction: See Details Above. Creates a more 'Normalized' Distribution
Visualize Simulations: See Details Above. Turns on Visualizations, and colors are randomly generated. Visualized max does not cap the calculated max. If 1000 simulations are used, the data will be from 1000 simulations, however, only the last 99 simulations will be visualized.
🔹 Standard Deviations
Standard Deviation Multiplier: Sets the multiplier to use for the Standard Deviation distance away from the center line.
🔹 Style
Extend Lines: Extends the Simulated Value Lines into the future for further reference and analysis.
Indicator

Monte Carlo Shuffled Projection [LuxAlgo]The Monte Carlo Shuffled Projection tool randomly simulates future price points based on historical bar movements made within a user-selected window.
The tool shows potential paths price might take in the future, as well as highlighting potential support/resistance levels.
Note that simulations and their resulting elements are subject to slight changes over time.
🔶 USAGE
By randomly simulating bar movements, a range is developed of potential price action which could be utilized to locate future price development as well as potential support/resistance levels.
Performing a large number of simulations and taking the average at each step will converge toward the result highlighted by the "Average Line", and can point out where the price might develop assuming the trend and amount of volatility persist.
Current closing price + Sum of changes in the calculation window)
This constraint will cause the simulations to always display an endpoint consistent with the current lookback's slope.
While this may be helpful to some traders, this indicator includes an option to produce a less biased range as seen below:
🔶 DETAILS
The Monte Carlo Shuffled Projection tool creates simulations based on the most recent prices within a user-set window. Simulations are done as follows:
Collect each bar's price changes in the user-set window.
Randomize the order of each change in the window.
Project the cumulative sum of the shuffled changes from the current closing price.
Collect data on each point along the way.
This is the process for the Default calculation, for the 'Randomize Direction' calculation, when added onto the front for every other change, the value is inverted, creating the randomized endpoints for each simulation.
The script contains each simulation's data for that bar with a maximum of 1000 simulations.
To get a glimpse behind the scenes each simulation (up to 99) can be viewed using the 'Visualize Simulations' Options as seen below.
Because the script holds the full simulation data, the script can also do calculations on this data, such as calculating standard deviations.
In this script the Standard deviation lines are the average of all standard deviations across the vertical data groups, this provides a singular value that can be displayed a distance away from the simulation center line.
🔶 SETTINGS
Color and Toggle Options are Provided throughout.
Lookback: Sets the number of Bars to include in calculations.
Simulation Count: Sets the number of randomized simulations to calculate. (Max 1000)
Randomize Direction: See Details Above. Creates a more 'Normalized' Distribution
Visualize Simulations: See Details Above. Turns on Visualizations, and colors are randomly generated. Visualized max does not cap the calculated max. If 1000 simulations are used, the data will be from 1000 simulations, however only the last 99 simulations will be visualized.
Standard Deviation Multiplier: Sets the multiplier to use for the Standard Deviation distance away from the center line.
Indicator

Monte Carlo Simulation - Your Strategy [Kioseff Trading]Hello!
This script “Monte Carlo Simulation - Your Strategy” uses Monte Carlo simulations for your inputted strategy returns or the asset on your chart!
Features
Monte Carlo Simulation: Performs Monte Carlo simulation to generate multiple future paths.
Asset Price or Strategy: Can simulate either future asset prices based on historical log returns or a specific trading strategy's future performance.
User-Defined Input: Allows you to input your own historical returns for simulation.
Statistical Methods: Offers two simulation methods—Gaussian (Normal) distribution and Bootstrapping.
Graphical Display: Provides options for graphical representation, including line plots and histograms.
Cumulative Probability Target: Enables setting a user-defined cumulative probability target to quantify simulation results.
Adjustable Parameters: Offers numerous user-adjustable settings like number of simulations, forecast length, and more.
Historical Data Points: Option to specify the amount of historical data to be used in the simulation (price).
Custom Binning: Allows you to select the binning method for histograms, with options like Sturges, Rice, and Square Root.
Best/Worst Case: Allows you to show only the best case / worst case outcome (range) for all simulations!
Scatterplot: allows you to show up to 1000 potential outcomes for a specified trade number (or bars forward price endpoint) using a scatter plot.
The image above shows the primary components of the indicator!
The image above shows the best/worst case outcome feature in action!
The image above shows a "fun feature" where 1000 simulated end points for a 15-bar price trajectory are shown as a scatter plot!
How To Perform a Monte Carlo Simulation On Your Strategy
Really, you can input any data into the indicator it will perform a Monte Carlo Simulation on it :D
The following instructions show how to export your strategy results from PulseWire to an Excel File, copy the data, and input it into the indicator.
However , you are not limited to following this method!
Wherever your strategy results are stored, simply copy and paste them into the indicator text area in the settings and simulations will begin.
Returns Should Follow This Format
1
3
-3
2
-5
The numbers are presented as a single column. No commas or separators used.
The numbers above are in sequential order. A return of "1" for the first trade and a return of "-5" for the last trade. Your strategy returns will likely be in sequential order already so don't worry too much about this (:
How To Perform a Monte Carlo Simulation On Your PulseWire Strategy With Excel Data
Export your strategy returns to an excel file using PulseWire
Navigate to your downloads folder to column G "Profit"
Click the column and press CTRL + SPACE to highlight the entire column
Press CTRL + C to copy the entire column
Open this indicator's settings and paste the returns into the text area
The image above illustrates the process!
Notes on Inputting Returns
*Must input your returns without a separate as a vertical list
*The initial text area can only hold so many return values. If your list of trades is large you can input additional returns into two additional text areas at the bottom of the indicator settings.
That should be it; thank you for checking this out!
Indicator

FunctionBlackScholesLibrary "FunctionBlackScholes"
Some methods for the Black Scholes Options Model, which demonstrates several approaches to the valuation of a European call.
// reference:
// people.math.sc.edu
// people.math.sc.edu
asset_path(s0, mu, sigma, t1, n) Simulates the behavior of an asset price over time.
Parameters:
s0 : float, asset price at time 0.
mu : float, growth rate.
sigma : float, volatility.
t1 : float, time to expiry date.
n : int, time steps to expiry date.
Returns: option values at each equal timed step (0 -> t1)
binomial(s0, e, r, sigma, t1, m) Uses the binomial method for a European call.
Parameters:
s0 : float, asset price at time 0.
e : float, exercise price.
r : float, interest rate.
sigma : float, volatility.
t1 : float, time to expiry date.
m : int, time steps to expiry date.
Returns: option value at time 0.
bsf(s0, t0, e, r, sigma, t1) Evaluates the Black-Scholes formula for a European call.
Parameters:
s0 : float, asset price at time 0.
t0 : float, time at which the price is known.
e : float, exercise price.
r : float, interest rate.
sigma : float, volatility.
t1 : float, time to expiry date.
Returns: option value at time 0.
forward(e, r, sigma, t1, nx, nt, smax) Forward difference method to value a European call option.
Parameters:
e : float, exercise price.
r : float, interest rate.
sigma : float, volatility.
t1 : float, time to expiry date.
nx : int, number of space steps in interval (0, L).
nt : int, number of time steps.
smax : float, maximum value of S to consider.
Returns: option values for the european call, float array of size ((nx-1) * (nt+1)).
mc(s0, e, r, sigma, t1, m) Uses Monte Carlo valuation on a European call.
Parameters:
s0 : float, asset price at time 0.
e : float, exercise price.
r : float, interest rate.
sigma : float, volatility.
t1 : float, time to expiry date.
m : int, time steps to expiry date.
Returns: confidence interval for the estimated range of valuation. Library

FunctionSMCMCLibrary "FunctionSMCMC"
Methods to implement Markov Chain Monte Carlo Simulation (MCMC)
markov_chain(weights, actions, target_path, position, last_value) a basic implementation of the markov chain algorithm
Parameters:
weights : float array, weights of the Markov Chain.
actions : float array, actions of the Markov Chain.
target_path : float array, target path array.
position : int, index of the path.
last_value : float, base value to increment.
Returns: void, updates target array
mcmc(weights, actions, start_value, n_iterations) uses a monte carlo algorithm to simulate a markov chain at each step.
Parameters:
weights : float array, weights of the Markov Chain.
actions : float array, actions of the Markov Chain.
start_value : float, base value to start simulation.
n_iterations : integer, number of iterations to run.
Returns: float array with path. Library

Indicator

Indicator
