PDF Smoothed Moving Average [BackQuant]PDF Smoothed Moving Average
Introducing BackQuant’s PDF Smoothed Moving Average (PDF-MA) — an innovative trading indicator that applies Probability Density Function (PDF) weighting to moving averages, creating a unique, trend-following tool that offers adaptive smoothing to price movements. This advanced indicator gives traders an edge by blending PDF-weighted values with conventional moving averages, helping to capture trend shifts with enhanced clarity.
Core Concept: Probability Density Function (PDF) Smoothing
The Probability Density Function (PDF) provides a mathematical approach to applying adaptive weighting to data points based on a specified variance and mean. In the PDF-MA indicator, the PDF function is used to weight price data, adding a layer of probabilistic smoothing that enhances the detection of trend strength while reducing noise.
The PDF weights are controlled by two key parameters:
Variance: Determines the spread of the weights, where higher values spread out the weighting effect, providing broader smoothing.
Mean : Centers the weights around a particular price value, influencing the trend’s directionality and sensitivity.
These PDF weights are applied to each price point over the chosen period, creating an adaptive and smooth moving average that more closely reflects the underlying price trend.
Blending PDF with Standard Moving Averages
To further improve the PDF-MA, this indicator combines the PDF-weighted average with a traditional moving average, selected by the user as either an Exponential Moving Average (EMA) or Simple Moving Average (SMA). This blended approach leverages the strengths of each method: the responsiveness of PDF smoothing and the robustness of conventional moving averages.
Smoothing Method: Traders can choose between EMA and SMA for the additional moving average layer. The EMA is more responsive to recent prices, while the SMA provides a consistent average across the selected period.
Smoothing Period: Controls the length of the lookback period, affecting how sensitive the average is to price changes.
The result is a PDF-MA that provides a reliable trend line, reflecting both the PDF weighting and traditional moving average values, ideal for use in trend-following and momentum-based strategies.
Trend Detection and Candle Coloring
The PDF-MA includes a built-in trend detection feature that dynamically colors candles based on the direction of the smoothed moving average:
Uptrend: When the PDF-MA value is increasing, the trend is considered bullish, and candles are colored green, indicating potential buying conditions.
Downtrend: When the PDF-MA value is decreasing, the trend is considered bearish, and candles are colored red, signaling potential selling or shorting conditions.
These color-coded candles provide a quick visual reference for the trend direction, helping traders make real-time decisions based on the current market trend.
Customization and Visualization Options
This indicator offers a range of customization options, allowing traders to tailor it to their specific preferences and trading environment:
Price Source : Choose the price data for calculation, with options like close, open, high, low, or HLC3.
Variance and Mean : Fine-tune the PDF weighting parameters to control the indicator’s sensitivity and responsiveness to price data.
Smoothing Method : Select either EMA or SMA to customize the conventional moving average layer used in conjunction with the PDF.
Smoothing Period : Set the lookback period for the moving average, with a longer period providing more stability and a shorter period offering greater sensitivity.
Candle Coloring : Enable or disable candle coloring based on trend direction, providing additional clarity in identifying bullish and bearish phases.
Trading Applications
The PDF Smoothed Moving Average can be applied across various trading strategies and timeframes:
Trend Following : By smoothing price data with PDF weighting, this indicator helps traders identify long-term trends while filtering out short-term noise.
Reversal Trading : The PDF-MA’s trend coloring feature can help pinpoint potential reversal points by showing shifts in the trend direction, allowing traders to enter or exit positions at optimal moments.
Swing Trading : The PDF-MA provides a clear trend line that swing traders can use to capture intermediate price moves, following the trend direction until it shifts.
Final Thoughts
The PDF Smoothed Moving Average is a highly adaptable indicator that combines probabilistic smoothing with traditional moving averages, providing a nuanced view of market trends. By integrating PDF-based weighting with the flexibility of EMA or SMA smoothing, this indicator offers traders an advanced tool for trend analysis that adapts to changing market conditions with reduced lag and increased accuracy.
Whether you’re trading trends, reversals, or swings, the PDF-MA offers valuable insights into the direction and strength of price movements, making it a versatile addition to any trading strategy.

# Probability

HMA Z-Score Probability Indicator by Erika BarkerThis indicator is a modified version of SteverSteves's original work, enhanced by Erika Barker. It visually represents asset price movements in terms of standard deviations from a Hull Moving Average (HMA), commonly known as a Z-Score.
Key Features:
Z-Score Calculation: Measures how many standard deviations the current price is from its HMA.
Hull Moving Average (HMA): This moving average provides a more responsive baseline for Z-Score calculations.
Flexible Display: Offers both area and candlestick visualization options for the Z-Score.
Probability Zones: Color-coded areas showing the statistical likelihood of prices based on their Z-Score.
Dynamic Price Level Labels: Displays actual price levels corresponding to Z-Score values.
Z-Table: An optional table showing the probability of occurrence for different Z-Score ranges.
Standard Deviation Lines: Horizontal lines at each standard deviation level for easy reference.
How It Works:
The indicator calculates the Z-Score by comparing the current price to its HMA and dividing by the standard deviation. This Z-Score is then plotted on a separate pane below the main chart.
Green areas/candles: Indicate prices above the HMA (positive Z-Score)
Red areas/candles: Indicate prices below the HMA (negative Z-Score)
Color-coded zones:
Green: Within 1 standard deviation (high probability)
Yellow: Between 1 and 2 standard deviations (medium probability)
Red: Beyond 2 standard deviations (low probability)
The HMA line (white) shows the trend of the Z-Score itself, offering insight into whether the asset is becoming more or less volatile over time.
Customization Options:
Adjust lookback periods for Z-Score and HMA calculations
Toggle between area and candlestick display
Show/hide probability fills, Z-Table, HMA line, and standard deviation bands
Customize text color and decimal rounding for price levels
Interpretation:
This indicator helps traders identify potential overbought or oversold conditions based on statistical probabilities. Extreme Z-Score values (beyond ±2 or ±3) often suggest a higher likelihood of mean reversion, while consistent Z-Scores in one direction may indicate a strong trend.
By combining the Z-Score with the HMA and probability zones, traders can gain a nuanced understanding of price movements relative to recent trends and their statistical significance.

Price Close ProbabilityThe Price Close Probability Indicator is designed to help traders estimate the likelihood of price closing above or below specified levels within a given bar. By placing two levels on your chart, you can quickly gauge the probability of the current price bar closing above or below these levels in real-time.
Key Features:
Dynamic Probability Calculation: The indicator continuously updates the probability of price closing above or below your set levels as the current bar progresses, providing you with timely insights as the bar approaches its close.
Customizable Standard Deviation : Adjust the length of the Standard Deviation used in the calculations to tailor the probability estimates to your preferred settings.
User-Friendly Probability Table : A clean, easy-to-read table displays the calculated probabilities, helping you make informed trading decisions at a glance.
Assumptions and Considerations:
While the indicator assumes that returns are normally distributed, which may not fully reflect reality, it still offers a valuable approximation of the probabilities for price movement within the current bar.
Future Enhancements (Coming Soon):
Multi-Bar Probability: Calculate probabilities across multiple bars to enhance your forecasting capabilities.
Additional Levels: Set more than two levels for a broader analysis of price movements.
Refined Distribution Modeling: Improve the accuracy of probability calculations by adjusting for more realistic return distributions.
Disclaimer
Please remember that past performance may not be indicative of future results.
Due to various factors, including changing market conditions, the strategy may no longer perform as well as in historical backtesting.
This post and the script don’t provide any financial advice.

Markov Chain Trend IndicatorOverview
The Markov Chain Trend Indicator utilizes the principles of Markov Chain processes to analyze stock price movements and predict future trends. By calculating the probabilities of transitioning between different market states (Uptrend, Downtrend, and Sideways), this indicator provides traders with valuable insights into market dynamics.
Key Features
State Identification: Differentiates between Uptrend, Downtrend, and Sideways states based on price movements.
Transition Probability Calculation: Calculates the probability of transitioning from one state to another using historical data.
Real-time Dashboard: Displays the probabilities of each state on the chart, helping traders make informed decisions.
Background Color Coding: Visually represents the current market state with background colors for easy interpretation.
Concepts Underlying the Calculations
Markov Chains: A stochastic process where the probability of moving to the next state depends only on the current state, not on the sequence of events that preceded it.
Logarithmic Returns: Used to normalize price changes and identify states based on significant movements.
Transition Matrices: Utilized to store and calculate the probabilities of moving from one state to another.
How It Works
The indicator first calculates the logarithmic returns of the stock price to identify significant movements. Based on these returns, it determines the current state (Uptrend, Downtrend, or Sideways). It then updates the transition matrices to keep track of how often the price moves from one state to another. Using these matrices, the indicator calculates the probabilities of transitioning to each state and displays this information on the chart.
How Traders Can Use It
Traders can use the Markov Chain Trend Indicator to:
Identify Market Trends: Quickly determine if the market is in an uptrend, downtrend, or sideways state.
Predict Future Movements: Use the transition probabilities to forecast potential market movements and make informed trading decisions.
Enhance Trading Strategies: Combine with other technical indicators to refine entry and exit points based on predicted trends.
Example Usage Instructions
Add the Markov Chain Trend Indicator to your TradingView chart.
Observe the background color to quickly identify the current market state:
Green for Uptrend, Red for Downtrend, Gray for Sideways
Check the dashboard label to see the probabilities of transitioning to each state.
Use these probabilities to anticipate market movements and adjust your trading strategy accordingly.
Combine the indicator with other technical analysis tools for more robust decision-making.

Bayesian Trend Indicator [ChartPrime]Bayesian Trend Indicator
Overview:
In probability theory and statistics, Bayes' theorem (alternatively Bayes' law or Bayes' rule), named after Thomas Bayes, describes the probability of an event, based on prior knowledge of conditions that might be related to the event.
The "Bayesian Trend Indicator" is a sophisticated technical analysis tool designed to assess the direction of price trends in financial markets. It combines the principles of Bayesian probability theory with moving average analysis to provide traders with a comprehensive understanding of market sentiment and potential trend reversals.
At its core, the indicator utilizes multiple moving averages, including the Exponential Moving Average (EMA), Simple Moving Average (SMA), Double Exponential Moving Average (DEMA), and Volume Weighted Moving Average (VWMA) . These moving averages are calculated based on user-defined parameters such as length and gap length, allowing traders to customize the indicator to suit their trading strategies and preferences.
The indicator begins by calculating the trend for both fast and slow moving averages using a Smoothed Gradient Signal Function. This function assigns a numerical value to each data point based on its relationship with historical data, indicating the strength and direction of the trend.
// Smoothed Gradient Signal Function
sig(float src, gap)=>
ta.ema(source >= src ? 1 :
source >= src ? 0.9 :
source >= src ? 0.8 :
source >= src ? 0.7 :
source >= src ? 0.6 :
source >= src ? 0.5 :
source >= src ? 0.4 :
source >= src ? 0.3 :
source >= src ? 0.2 :
source >= src ? 0.1 :
0, 4)
Next, the indicator calculates prior probabilities using the trend information from the slow moving averages and likelihood probabilities using the trend information from the fast moving averages . These probabilities represent the likelihood of an uptrend or downtrend based on historical data.
// Define prior probabilities using moving averages
prior_up = (ema_trend + sma_trend + dema_trend + vwma_trend) / 4
prior_down = 1 - prior_up
// Define likelihoods using faster moving averages
likelihood_up = (ema_trend_fast + sma_trend_fast + dema_trend_fast + vwma_trend_fast) / 4
likelihood_down = 1 - likelihood_up
Using Bayes' theorem , the indicator then combines the prior and likelihood probabilities to calculate posterior probabilities, which reflect the updated probability of an uptrend or downtrend given the current market conditions. These posterior probabilities serve as a key signal for traders, informing them about the prevailing market sentiment and potential trend reversals.
// Calculate posterior probabilities using Bayes' theorem
posterior_up = prior_up * likelihood_up
/
(prior_up * likelihood_up + prior_down * likelihood_down)
Key Features:
◆ The trend direction:
To visually represent the trend direction , the indicator colors the bars on the chart based on the posterior probabilities. Bars are colored green to indicate an uptrend when the posterior probability is greater than 0.5 (>50%), while bars are colored red to indicate a downtrend when the posterior probability is less than 0.5 (<50%).
◆ Dashboard on the chart
Additionally, the indicator displays a dashboard on the chart , providing traders with detailed information about the probability of an uptrend , as well as the trends for each type of moving average. This dashboard serves as a valuable reference for traders to monitor trend strength and make informed trading decisions.
◆ Probability labels and signals:
Furthermore, the indicator includes probability labels and signals , which are displayed near the corresponding bars on the chart. These labels indicate the posterior probability of a trend, while small diamonds above or below bars indicate crossover or crossunder events when the posterior probability crosses the 0.5 threshold (50%).
The posterior probability of a trend
Crossover or Crossunder events
◆ User Inputs
Source:
Description: Defines the price source for the indicator's calculations. Users can select between different price values like close, open, high, low, etc.
MA's Length:
Description: Sets the length for the moving averages used in the trend calculations. A larger length will smooth out the moving averages, making the indicator less sensitive to short-term fluctuations.
Gap Length Between Fast and Slow MA's:
Description: Determines the difference in lengths between the slow and fast moving averages. A higher gap length will increase the difference, potentially identifying stronger trend signals.
Gap Signals:
Description: Defines the gap used for the smoothed gradient signal function. This parameter affects the sensitivity of the trend signals by setting the number of bars used in the signal calculations.
In summary, the "Bayesian Trend Indicator" is a powerful tool that leverages Bayesian probability theory and moving average analysis to help traders identify trend direction, assess market sentiment, and make informed trading decisions in various financial markets.

Bayesian Bias OscillatorWhat is a Bayes Estimator?
Bayesian estimation, or Bayesian inference, is a statistical method for estimating unknown parameters of a probability distribution based on observed data and prior knowledge about those parameters. At first , you will need a prior probability distribution, which is a prior belief about the distribution of the parameter that you are interested in estimating. This distribution represents your initial beliefs or knowledge about the parameter value before observing any data. Second , you need a likelihood function, which represents the probability of observing the data given different values of the parameter. This function quantifies how well different parameter values explain the observed data. Then , you will need a posterior probability distribution by combining the prior distribution and the likelihood function to obtain the posterior distribution of the parameter. The posterior distribution represents the updated belief about the parameter value after observing the data.
Bayesian Bias Oscillator
This tool calculates the Bayes bias of returns, which are directional probabilities that provide insight on the "trend" of the market or the directional bias of returns. It comes with two outputs: the default one, which is the Z-Score of the Bayes Bias, and the regular raw probability, which can be switched on in the settings of the indicator.
The Z-Score output value doesn't tell you the probability, but it does tell you how much of a standard deviation the value is from the mean. It uses both probabilities, the probability of a positive return and the probability of a negative return, which is just (1 - probability of a positive return).
The probability output value shows you the raw probability of a positive return vs. the probability of a negative return. The probability is the value of each line plotted (blue is the probability of a positive return, and purple is the probability of a negative return).

Likelihood of Winning - Probability Density FunctionIn developing the "Likelihood of Winning - Probability Density Function (PDF)" indicator, my aim was to offer traders a statistical tool to quantify the probability of reaching target prices. This indicator, grounded in risk assessment principles, enables users to analyze potential outcomes based on the normal distribution, providing insights into market dynamics.
The tool's flexibility allows for customization of the data series, lookback periods, and target settings for both long and short scenarios. It features a color-coded visualization to easily distinguish between probabilities of hitting specified targets, enhancing decision-making in trading strategies.
I'm excited to share this indicator with the trading community, hoping it will enhance data-driven decision-making and offer a deeper understanding of market risks and opportunities. My goal is to continuously improve this tool based on user feedback and market evolution, contributing to more informed trading practices.
This indicator leverages the "NormalDistributionFunctions" library, enabling easy integration into other indicators or strategies. Users can readily embed advanced statistical analysis into their trading tools, fostering innovation within the Pine Script community.

Breakout Probability Indicator (FinnoVent)The Breakout Probability Indicator is a cutting-edge tool designed for traders looking to gauge the likelihood of price breakouts above or below current levels. This indicator intelligently combines Average True Range (ATR) and recent price action to provide a probabilistic insight into potential future price movements, enhancing strategy formulation and risk management.
Core Features:
Volatility Assessment: Utilizes the Average True Range (ATR) to measure market volatility, a critical component in identifying potential breakout scenarios.
Dynamic Price Levels: Calculates and plots potential breakout levels based on recent highs and lows, adjusted for current market volatility.
Probability Estimation: Provides an estimation of the probability of reaching these breakout levels, using a responsive logarithmic scale for improved sensitivity.
Real-time Updates: Continuously updates probabilities and levels as new price information becomes available, ensuring traders have the most current data at their fingertips.
Usage:
Add this indicator to any chart in TradingView to see the upper and lower breakout levels, each accompanied by a dynamically calculated probability percentage. These probabilities help traders understand the potential for price movement in either direction, forming a basis for entry or exit decisions, stop-loss placement, and strategy adjustments.
Compliance and Guidelines:
This script is shared for educational purposes, offering a novel approach to understanding market dynamics. It does not constitute financial advice and should be used as part of a comprehensive trading strategy. Traders are encouraged to backtest and paper-trade any new tool before live implementation to ensure it aligns with their trading style and risk tolerance.

ATH Drawdown Indicator by Atilla YurtsevenThe ATH (All-Time High) Drawdown Indicator, developed by Atilla Yurtseven, is an essential tool for traders and investors who seek to understand the current price position in relation to historical peaks. This indicator is especially useful in volatile markets like cryptocurrencies and stocks, offering insights into potential buy or sell opportunities based on historical price action.
This indicator is suitable for long-term investors. It shows the average value loss of a price. However, it's important to remember that this indicator only displays statistics based on past price movements. The price of a stock can remain cheap for many years.
1. Utility of the Indicator:
The ATH Drawdown Indicator provides a clear view of how far the current price is from its all-time high. This is particularly beneficial in assessing the magnitude of a pullback or retracement from peak levels. By understanding these levels, traders can gauge market sentiment and make informed decisions about entry and exit points.
2. Risk Management:
This indicator aids in risk management by highlighting significant drawdowns from the ATH. Traders can use this information to adjust their position sizes or set stop-loss orders more effectively. For instance, entering trades when the price is significantly below the ATH could indicate a higher potential for recovery, while a minimal drawdown from the ATH may suggest caution due to potential overvaluation.
3. Indicator Functionality:
The indicator calculates the percentage drawdown from the ATH for each trading period. It can display this data either as a line graph or overlaid on candles, based on user preference. Horizontal lines at -25%, -50%, -75%, and -100% drawdown levels offer quick visual cues for significant price levels. The color-coding of candles further aids in visualizing bullish or bearish trends in the context of ATH drawdowns.
4. ATH Level Indicator (0 Level):
A unique feature of this indicator is the 0 level, which signifies that the price is currently at its all-time high. This level is a critical reference point for understanding the market's peak performance.
5. Mean Line Indicator:
Additionally, this indicator includes a 'Mean Line', representing the average percentage drawdown from the ATH. This average is calculated over more than a thousand past bars, leveraging the law of large numbers to provide a reliable mean value. This mean line is instrumental in understanding the typical market behavior in relation to the ATH.
Disclaimer:
Please note that this ATH Drawdown Indicator by Atilla Yurtseven is provided as an open-source tool for educational purposes only. It should not be construed as investment advice. Users should conduct their own research and consult a financial advisor before making any investment decisions. The creator of this indicator bears no responsibility for any trading losses incurred using this tool.
Please remember to follow and comment!
Trade smart, stay safe
Atilla Yurtseven

Pro Bollinger Bands CalculatorThe "Pro Bollinger Bands Calculator" indicator joins our suite of custom trading tools, which includes the "Pro Supertrend Calculator", the "Pro RSI Calculator" and the "Pro Momentum Calculator."
Expanding on this series, the "Pro Bollinger Bands Calculator" is tailored to offer traders deeper insights into market dynamics by harnessing the power of the Bollinger Bands indicator.
Its core mission remains unchanged: to scrutinize historical price data and provide informed predictions about future price movements, with a specific focus on detecting potential bullish (green) or bearish (red) candlestick patterns.
1. Bollinger Bands Calculation:
The indicator kicks off by computing the Bollinger Bands, a well-known volatility indicator. It calculates two pivotal Bollinger Bands parameters:
- Bollinger Bands Length: This parameter sets the lookback period for Bollinger Bands calculations.
- Bollinger Bands Deviation: It determines the deviation multiplier for the upper and lower bands, typically set at 2.0.
2. Visualizing Bollinger Bands:
The Bollinger Bands derived from the calculations are skillfully plotted on the price chart:
- Red Line: Represents the upper Bollinger Band during bearish trends, suggesting potential price declines.
- Teal Line: Represents the lower Bollinger Band in bullish market conditions, signaling the possibility of price increases.
3.Analyzing Consecutive Candlesticks:
The indicator's core functionality revolves around tracking consecutive candlestick patterns based on their relationship with the Bollinger Bands lines. To be considered for analysis, a candlestick must consistently close either above (green candles) or below (red candles) the Bollinger Bands lines for multiple consecutive periods.
4. Labeling and Enumeration:
To convey the count of consecutive candles displaying consistent trend behavior, the indicator meticulously assigns labels to the price chart. The position of these labels varies depending on the direction of the trend, appearing either below (for bullish patterns) or above (for bearish patterns) the candlesticks. The label colors match the candle colors: green labels for bullish candles and red labels for bearish ones.
5. Tabular Data Presentation:
The indicator complements its graphical analysis with a customizable table that prominently displays comprehensive statistical insights. Key data points within the table encompass:
- Consecutive Candles: The count of consecutive candles displaying consistent trend characteristics.
- Candles Above Upper BB: The number of candles closing above the upper Bollinger Band during the consecutive period.
- Candles Below Lower BB: The number of candles closing below the lower Bollinger Band during the consecutive period.
- Upcoming Green Candle: An estimated probability of the next candlestick being bullish, derived from historical data.
- Upcoming Red Candle: An estimated probability of the next candlestick being bearish, also based on historical data.
6. Custom Configuration:
To cater to diverse trading strategies and preferences, the indicator offers extensive customization options. Traders can fine-tune parameters such as Bollinger Bands length, upper and lower band deviations, label and table placement, and table size to align with their unique trading approaches.

SimilarityMeasuresLibrary "SimilarityMeasures"
Similarity measures are statistical methods used to quantify the distance between different data sets
or strings. There are various types of similarity measures, including those that compare:
- data points (SSD, Euclidean, Manhattan, Minkowski, Chebyshev, Correlation, Cosine, Camberra, MAE, MSE, Lorentzian, Intersection, Penrose Shape, Meehl),
- strings (Edit(Levenshtein), Lee, Hamming, Jaro),
- probability distributions (Mahalanobis, Fidelity, Bhattacharyya, Hellinger),
- sets (Kumar Hassebrook, Jaccard, Sorensen, Chi Square).
---
These measures are used in various fields such as data analysis, machine learning, and pattern recognition. They
help to compare and analyze similarities and differences between different data sets or strings, which
can be useful for making predictions, classifications, and decisions.
---
References:
en.wikipedia.org
cran.r-project.org
numerics.mathdotnet.com
github.com
github.com
github.com
Encyclopedia of Distances, doi.org
ssd(p, q)
Sum of squared difference for N dimensions.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Measure of distance that calculates the squared euclidean distance.
euclidean(p, q)
Euclidean distance for N dimensions.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Measure of distance that calculates the straight-line (or Euclidean).
manhattan(p, q)
Manhattan distance for N dimensions.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Measure of absolute differences between both points.
minkowski(p, q, p_value)
Minkowsky Distance for N dimensions.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
p_value (float) : `float` P value, default=1.0(1: manhatan, 2: euclidean), does not support chebychev.
Returns: Measure of similarity in the normed vector space.
chebyshev(p, q)
Chebyshev distance for N dimensions.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Measure of maximum absolute difference.
correlation(p, q)
Correlation distance for N dimensions.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Measure of maximum absolute difference.
cosine(p, q)
Cosine distance between provided vectors.
Parameters:
p (float ) : `array` 1D Vector.
q (float ) : `array` 1D Vector.
Returns: The Cosine distance between vectors `p` and `q`.
---
angiogenesis.dkfz.de
camberra(p, q)
Camberra distance for N dimensions.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Weighted measure of absolute differences between both points.
mae(p, q)
Mean absolute error is a normalized version of the sum of absolute difference (manhattan).
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Mean absolute error of vectors `p` and `q`.
mse(p, q)
Mean squared error is a normalized version of the sum of squared difference.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Mean squared error of vectors `p` and `q`.
lorentzian(p, q)
Lorentzian distance between provided vectors.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Lorentzian distance of vectors `p` and `q`.
---
angiogenesis.dkfz.de
intersection(p, q)
Intersection distance between provided vectors.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Intersection distance of vectors `p` and `q`.
---
angiogenesis.dkfz.de
penrose(p, q)
Penrose Shape distance between provided vectors.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Penrose shape distance of vectors `p` and `q`.
---
angiogenesis.dkfz.de
meehl(p, q)
Meehl distance between provided vectors.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Meehl distance of vectors `p` and `q`.
---
angiogenesis.dkfz.de
edit(x, y)
Edit (aka Levenshtein) distance for indexed strings.
Parameters:
x (int ) : `array` Indexed array.
y (int ) : `array` Indexed array.
Returns: Number of deletions, insertions, or substitutions required to transform source string into target string.
---
generated description:
The Edit distance is a measure of similarity used to compare two strings. It is defined as the minimum number of
operations (insertions, deletions, or substitutions) required to transform one string into another. The operations
are performed on the characters of the strings, and the cost of each operation depends on the specific algorithm
used.
The Edit distance is widely used in various applications such as spell checking, text similarity, and machine
translation. It can also be used for other purposes like finding the closest match between two strings or
identifying the common prefixes or suffixes between them.
---
github.com
www.red-gate.com
planetcalc.com
lee(x, y, dsize)
Distance between two indexed strings of equal length.
Parameters:
x (int ) : `array` Indexed array.
y (int ) : `array` Indexed array.
dsize (int) : `int` Dictionary size.
Returns: Distance between two strings by accounting for dictionary size.
---
www.johndcook.com
hamming(x, y)
Distance between two indexed strings of equal length.
Parameters:
x (int ) : `array` Indexed array.
y (int ) : `array` Indexed array.
Returns: Length of different components on both sequences.
---
en.wikipedia.org
jaro(x, y)
Distance between two indexed strings.
Parameters:
x (int ) : `array` Indexed array.
y (int ) : `array` Indexed array.
Returns: Measure of two strings' similarity: the higher the value, the more similar the strings are.
The score is normalized such that `0` equates to no similarities and `1` is an exact match.
---
rosettacode.org
mahalanobis(p, q, VI)
Mahalanobis distance between two vectors with population inverse covariance matrix.
Parameters:
p (float ) : `array` 1D Vector.
q (float ) : `array` 1D Vector.
VI (matrix) : `matrix` Inverse of the covariance matrix.
Returns: The mahalanobis distance between vectors `p` and `q`.
---
people.revoledu.com
stat.ethz.ch
docs.scipy.org
fidelity(p, q)
Fidelity distance between provided vectors.
Parameters:
p (float ) : `array` 1D Vector.
q (float ) : `array` 1D Vector.
Returns: The Bhattacharyya Coefficient between vectors `p` and `q`.
---
en.wikipedia.org
bhattacharyya(p, q)
Bhattacharyya distance between provided vectors.
Parameters:
p (float ) : `array` 1D Vector.
q (float ) : `array` 1D Vector.
Returns: The Bhattacharyya distance between vectors `p` and `q`.
---
en.wikipedia.org
hellinger(p, q)
Hellinger distance between provided vectors.
Parameters:
p (float ) : `array` 1D Vector.
q (float ) : `array` 1D Vector.
Returns: The hellinger distance between vectors `p` and `q`.
---
en.wikipedia.org
jamesmccaffrey.wordpress.com
kumar_hassebrook(p, q)
Kumar Hassebrook distance between provided vectors.
Parameters:
p (float ) : `array` 1D Vector.
q (float ) : `array` 1D Vector.
Returns: The Kumar Hassebrook distance between vectors `p` and `q`.
---
github.com
jaccard(p, q)
Jaccard distance between provided vectors.
Parameters:
p (float ) : `array` 1D Vector.
q (float ) : `array` 1D Vector.
Returns: The Jaccard distance between vectors `p` and `q`.
---
github.com
sorensen(p, q)
Sorensen distance between provided vectors.
Parameters:
p (float ) : `array` 1D Vector.
q (float ) : `array` 1D Vector.
Returns: The Sorensen distance between vectors `p` and `q`.
---
people.revoledu.com
chi_square(p, q, eps)
Chi Square distance between provided vectors.
Parameters:
p (float ) : `array` 1D Vector.
q (float ) : `array` 1D Vector.
eps (float)
Returns: The Chi Square distance between vectors `p` and `q`.
---
uw.pressbooks.pub
stats.stackexchange.com
www.itl.nist.gov
kulczynsky(p, q, eps)
Kulczynsky distance between provided vectors.
Parameters:
p (float ) : `array` 1D Vector.
q (float ) : `array` 1D Vector.
eps (float)
Returns: The Kulczynsky distance between vectors `p` and `q`.
---
github.com

FunctionMatrixCovarianceLibrary "FunctionMatrixCovariance"
In probability theory and statistics, a covariance matrix (also known as auto-covariance matrix, dispersion matrix, variance matrix, or variance–covariance matrix) is a square matrix giving the covariance between each pair of elements of a given random vector.
Intuitively, the covariance matrix generalizes the notion of variance to multiple dimensions. As an example, the variation in a collection of random points in two-dimensional space cannot be characterized fully by a single number, nor would the variances in the `x` and `y` directions contain all of the necessary information; a `2 × 2` matrix would be necessary to fully characterize the two-dimensional variation.
Any covariance matrix is symmetric and positive semi-definite and its main diagonal contains variances (i.e., the covariance of each element with itself).
The covariance matrix of a random vector `X` is typically denoted by `Kxx`, `Σ` or `S`.
~wikipedia.
method cov(M, bias)
Estimate Covariance matrix with provided data.
Namespace types: matrix
Parameters:
M (matrix) : `matrix` Matrix with vectors in column order.
bias (bool)
Returns: Covariance matrix of provided vectors.
---
en.wikipedia.org
numpy.org

Candles In Row (Expo)█ Overview
The Candles In Row (Expo) indicator is a powerful tool designed to track and visualize sequences of consecutive candlesticks in a price chart. Whether you're looking to gauge momentum or determine the prevailing trend, this indicator offers versatile functionality tailored to the needs of active traders. The Candles In Row indicator can be an integral part of a multi-timeframe trading strategy, allowing traders to understand market momentum, and set trading bias. By recognizing the patterns and likelihood of future price movements, traders can make more informed decisions and align their trades with the overall market direction.
█ How to use
The indicator enhances traders' understanding of the consecutive candle patterns, helping them to uncover trends and momentum. Consecutive candles in the same direction may indicate a strong trend. The Candles In Row indicator can be an essential tool for traders employing a multiple timeframes strategy.
Analyzing a Higher Timeframe:
Understanding Momentum: By analyzing consecutive green or red candles in a higher timeframe, traders can identify the prevailing momentum in the market. A series of green candles would suggest an upward trend, while a series of red candles would indicate a downward trend.
Predicting Next Candle: The indicator's predictive feature calculates the likelihood of the next candle being green or red based on historical patterns. This probability helps traders gauge the potential continuation of the trend.
Setting the Trading Bias: If the likelihood of the next candle being green is high, the trader may decide to focus on long (buy) opportunities. Conversely, if the likelihood of the next candle being red is high, the trader may look for short (sell) opportunities.
In this example, we are using the Heikin Ashi candles.
Moving to a Lower Timeframe:
Finding Entry Points: Once the trading bias is set based on the higher timeframe analysis, traders can switch to a lower timeframe to look for entry points in the direction of the bias. For example, if the higher timeframe suggests a high likelihood of a green candle, traders may look for buy opportunities in the lower timeframe.
Combining Timeframes for a Comprehensive Strategy:
Confirmation and Alignment: By analyzing the higher timeframe and confirming the direction in the lower timeframe, traders can ensure that they are trading in alignment with the broader trend.
Avoiding False Signals: By using a higher timeframe to set the trading bias and a lower timeframe to find entries, traders can avoid false signals and whipsaws that might be present in a single timeframe analysis.
█ Settings
Price Input Selection: Choose between regular open and close prices or Heikin Ashi candles as the basis for calculation.
Data Window Control: Decide between displaying the full data window or only the active data. You can also enable a counter that keeps track of the number of candles.
Alert Configuration: Set the desired number and color of consecutive candles that must occur in a row to trigger an alert.
Table Display Customization: Customize the location and size of the display table according to your preferences.
-----------------
Disclaimer
The information contained in my Scripts/Indicators/Ideas/Algos/Systems does not constitute financial advice or a solicitation to buy or sell any securities of any type. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
My Scripts/Indicators/Ideas/Algos/Systems are only for educational purposes!

Normal Distribution CurveThis Normal Distribution Curve is designed to overlay a simple normal distribution curve on top of any TradingView indicator. This curve represents a probability distribution for a given dataset and can be used to gain insights into the likelihood of various data levels occurring within a specified range, providing traders and investors with a clear visualization of the distribution of values within a specific dataset. With the only inputs being the variable source and plot colour, I think this is by far the simplest and most intuitive iteration of any statistical analysis based indicator I've seen here!
Traders can quickly assess how data clusters around the mean in a bell curve and easily see the percentile frequency of the data; or perhaps with both and upper and lower peaks identify likely periods of upcoming volatility or mean reversion. Facilitating the identification of outliers was my main purpose when creating this tool, I believed fixed values for upper/lower bounds within most indicators are too static and do not dynamically fit the vastly different movements of all assets and timeframes - and being able to easily understand the spread of information simplifies the process of identifying key regions to take action.
The curve's tails, representing the extreme percentiles, can help identify outliers and potential areas of price reversal or trend acceleration. For example using the RSI which typically has static levels of 70 and 30, which will be breached considerably more on a less liquid or more volatile asset and therefore reduce the actionable effectiveness of the indicator, likewise for an asset with little to no directional volatility failing to ever reach this overbought/oversold areas. It makes considerably more sense to look for the top/bottom 5% or 10% levels of outlying data which are automatically calculated with this indicator, and may be a noticeable distance from the 70 and 30 values, as regions to be observing for your investing.
This normal distribution curve employs percentile linear interpolation to calculate the distribution. This interpolation technique considers the nearest data points and calculates the price values between them. This process ensures a smooth curve that accurately represents the probability distribution, even for percentiles not directly present in the original dataset; and applicable to any asset regardless of timeframe. The lookback period is set to a value of 5000 which should ensure ample data is taken into calculation and consideration without surpassing any TradingView constraints and limitations, for datasets smaller than this the indicator will adjust the length to just include all data. The labels providing the percentile and average levels can also be removed in the style tab if preferred.
Additionally, as an unplanned benefit is its applicability to the underlying price data as well as any derived indicators. Turning it into something comparable to a volume profile indicator but based on the time an assets price was within a specific range as opposed to the volume. This can therefore be used as a tool for identifying potential support and resistance zones, as well as areas that mark market inefficiencies as price rapidly accelerated through. This may then give a cleaner outlook as it eliminates the potential drawbacks of volume based profiles that maybe don't collate all exchange data or are misrepresented due to large unforeseen increases/decreases underlying capital inflows/outflows.
Thanks to @ALifeToMake, @Bjorgum, vgladkov on stackoverflow (and possibly some chatGPT!) for all the assistance in bringing this indicator to life. I really hope every user can find some use from this and help bring a unique and data driven perspective to their decision making. And make sure to please share any original implementaions of this tool too! If you've managed to apply this to the average price change once you've entered your position to better manage your trade management, or maybe overlaying on an implied volatility indicator to identify potential options arbitrage opportunities; let me know! And of course if anyone has any issues, questions, queries or requests please feel free to reach out! Thanks and enjoy.

Probability Trend IndicatorUnderstanding the Indicator:
The indicator calculates the probabilities of upward and downward trends based on the percentage change in price over a specified lookback period.
It displays these probabilities in a table and plots a histogram to represent the difference between the probabilities.
The colors of the histogram bars indicate the trend direction and whether the trend is increasing or decreasing.
Setting the Lookback Period:
The indicator allows you to specify the lookback period, which determines the number of bars to consider for calculating the probabilities.
By default, the lookback period is set to 50 bars. However, you can adjust it based on your trading preferences and the timeframe you're analyzing.
Analyzing the Probabilities:
The indicator calculates the probabilities of upward and downward trends and displays them in a table on the chart.
The probabilities are presented as percentages, representing the likelihood of each type of trend occurring.
You can use these probabilities to gain insights into the potential market direction and assess the strength of the prevailing trend.
Interpreting the Histogram:
The histogram is plotted based on the difference between the probabilities of upward and downward trends, known as the oscillator value.
The histogram bars are colored to provide visual cues about the trend direction and whether the trend is gaining or losing strength.
Green bars indicate upward trends, and red bars indicate downward trends.
Lighter shades of green or red suggest increasing trends, while darker shades suggest decreasing trends.
Making Trading Decisions:
The indicator serves as a tool for assessing the probabilities of trends and can be used alongside other technical analysis methods.
You can consider the probabilities, the histogram pattern, and the overall market context to make informed trading decisions.
It's important to remember that no indicator or tool can guarantee future market movements, so prudent risk management and additional analysis are essential.

BenfordsLawLibrary "BenfordsLaw"
Methods to deal with Benford's law which states that a distribution of first and higher order digits
of numerical strings has a characteristic pattern.
"Benford's law is an observation about the leading digits of the numbers found in real-world data sets.
Intuitively, one might expect that the leading digits of these numbers would be uniformly distributed so that
each of the digits from 1 to 9 is equally likely to appear. In fact, it is often the case that 1 occurs more
frequently than 2, 2 more frequently than 3, and so on. This observation is a simplified version of Benford's law.
More precisely, the law gives a prediction of the frequency of leading digits using base-10 logarithms that
predicts specific frequencies which decrease as the digits increase from 1 to 9." ~(2)
---
reference:
- 1: en.wikipedia.org
- 2: brilliant.org
- 4: github.com
cumsum_difference(a, b)
Calculate the cumulative sum difference of two arrays of same size.
Parameters:
a (float ) : `array` List of values.
b (float ) : `array` List of values.
Returns: List with CumSum Difference between arrays.
fractional_int(number)
Transform a floating number including its fractional part to integer form ex:. `1.2345 -> 12345`.
Parameters:
number (float) : `float` The number to transform.
Returns: Transformed number.
split_to_digits(number, reverse)
Transforms a integer number into a list of its digits.
Parameters:
number (int) : `int` Number to transform.
reverse (bool) : `bool` `default=true`, Reverse the order of the digits, if true, last will be first.
Returns: Transformed number digits list.
digit_in(number, digit)
Digit at index.
Parameters:
number (int) : `int` Number to parse.
digit (int) : `int` `default=0`, Index of digit.
Returns: Digit found at the index.
digits_from(data, dindex)
Process a list of `int` values and get the list of digits.
Parameters:
data (int ) : `array` List of numbers.
dindex (int) : `int` `default=0`, Index of digit.
Returns: List of digits at the index.
digit_counters(digits)
Score digits.
Parameters:
digits (int ) : `array` List of digits.
Returns: List of counters per digit (1-9).
digit_distribution(counters)
Calculates the frequency distribution based on counters provided.
Parameters:
counters (int ) : `array` List of counters, must have size(9).
Returns: Distribution of the frequency of the digits.
digit_p(digit)
Expected probability for digit according to Benford.
Parameters:
digit (int) : `int` Digit number reference in range `1 -> 9`.
Returns: Probability of digit according to Benford's law.
benfords_distribution()
Calculated Expected distribution per digit according to Benford's Law.
Returns: List with the expected distribution.
benfords_distribution_aprox()
Aproximate Expected distribution per digit according to Benford's Law.
Returns: List with the expected distribution.
test_benfords(digits, calculate_benfords)
Tests Benford's Law on provided list of digits.
Parameters:
digits (int ) : `array` List of digits.
calculate_benfords (bool)
Returns: Tuple with:
- Counters: Score of each digit.
- Sample distribution: Frequency for each digit.
- Expected distribution: Expected frequency according to Benford's.
- Cumulative Sum of difference:
to_table(digits, _text_color, _border_color, _frame_color)
Parameters:
digits (int )
_text_color (color)
_border_color (color)
_frame_color (color)

Trend Reversal Probability CalculatorThe "Trend Reversal Probability Calculator" is a TradingView indicator that calculates the probability of a trend reversal based on the crossover of multiple moving averages and the rate of change (ROC) of their slopes. This indicator is designed to help traders identify potential trend reversals by providing signals when the short-term moving averages start to slope in the opposite direction of the long-term moving average.
To use the indicator, simply add it to your TradingView chart and adjust the input parameters according to your preferences. The input parameters include the length of the moving averages, the ROC length (trend sensitivity), and the reversal sensitivity (signal percentage).
The indicator calculates the ROC of the moving averages and determines if the short-term moving averages are sloping in the opposite direction of the long-term moving average. The number of short-term moving averages that meet this condition is then counted, and the probability of a trend reversal is calculated based on the percentage of short-term moving averages that meet this condition.
When the probability of a trend reversal is high, a bullish or bearish signal is generated, depending on the direction of the reversal. The bullish signal is generated when the short-term moving averages start to slope upward, and the bearish signal is generated when the short-term moving averages start to slope downward.
Traders can use the "Trend Reversal Probability Calculator" to identify potential trend reversals and adjust their trading strategies accordingly. It is important to note that this indicator is not a guarantee of a trend reversal and should be used in conjunction with other technical analysis tools to make informed trading decisions.

MarkovChainLibrary "MarkovChain"
Generic Markov Chain type functions.
---
A Markov chain or Markov process is a stochastic model describing a sequence of possible events in which the
probability of each event depends only on the state attained in the previous event.
---
reference:
Understanding Markov Chains, Examples and Applications. Second Edition. Book by Nicolas Privault.
en.wikipedia.org
www.geeksforgeeks.org
towardsdatascience.com
github.com
stats.stackexchange.com
timeseriesreasoning.com
www.ris-ai.com
github.com
gist.github.com
github.com
gist.github.com
writings.stephenwolfram.com
kevingal.com
towardsdatascience.com
spedygiorgio.github.io
github.com
www.projectrhea.org
method to_string(this)
Translate a Markov Chain object to a string format.
Namespace types: MC
Parameters:
this (MC) : `MC` . Markov Chain object.
Returns: string
method to_table(this, position, text_color, text_size)
Namespace types: MC
Parameters:
this (MC)
position (string)
text_color (color)
text_size (string)
method create_transition_matrix(this)
Namespace types: MC
Parameters:
this (MC)
method generate_transition_matrix(this)
Namespace types: MC
Parameters:
this (MC)
new_chain(states, name)
Parameters:
states (state )
name (string)
from_data(data, name)
Parameters:
data (string )
name (string)
method probability_at_step(this, target_step)
Namespace types: MC
Parameters:
this (MC)
target_step (int)
method state_at_step(this, start_state, target_state, target_step)
Namespace types: MC
Parameters:
this (MC)
start_state (int)
target_state (int)
target_step (int)
method forward(this, obs)
Namespace types: HMC
Parameters:
this (HMC)
obs (int )
method backward(this, obs)
Namespace types: HMC
Parameters:
this (HMC)
obs (int )
method viterbi(this, observations)
Namespace types: HMC
Parameters:
this (HMC)
observations (int )
method baumwelch(this, observations)
Namespace types: HMC
Parameters:
this (HMC)
observations (int )
Node
Target node.
Fields:
index (series int) : . Key index of the node.
probability (series float) : . Probability rate of activation.
state
State reference.
Fields:
name (series string) : . Name of the state.
index (series int) : . Key index of the state.
target_nodes (Node ) : . List of index references and probabilities to target states.
MC
Markov Chain reference object.
Fields:
name (series string) : . Name of the chain.
states (state ) : . List of state nodes and its name, index, targets and transition probabilities.
size (series int) : . Number of unique states
transitions (matrix) : . Transition matrix
HMC
Hidden Markov Chain reference object.
Fields:
name (series string) : . Name of thehidden chain.
states_hidden (state ) : . List of state nodes and its name, index, targets and transition probabilities.
states_obs (state ) : . List of state nodes and its name, index, targets and transition probabilities.
transitions (matrix) : . Transition matrix
emissions (matrix) : . Emission matrix
initial_distribution (float )

FunctionProbabilityViterbiLibrary "FunctionProbabilityViterbi"
The Viterbi Algorithm calculates the most likely sequence of hidden states *(called Viterbi path)*
that results in a sequence of observed events.
viterbi(observations, transitions, emissions, initial_distribution)
Calculate most probable path in a Markov model.
Parameters:
observations (int ) : array . Observation states data.
transitions (matrix) : matrix . Transition probability table, (HxH, H:Hidden states).
emissions (matrix) : matrix . Emission probability table, (OxH, O:Observed states).
initial_distribution (float ) : array . Initial probability distribution for the hidden states.
Returns: array. Most probable path.

FunctionBaumWelchLibrary "FunctionBaumWelch"
Baum-Welch Algorithm, also known as Forward-Backward Algorithm, uses the well known EM algorithm
to find the maximum likelihood estimate of the parameters of a hidden Markov model given a set of observed
feature vectors.
---
### Function List:
> `forward (array pi, matrix a, matrix b, array obs)`
> `forward (array pi, matrix a, matrix b, array obs, bool scaling)`
> `backward (matrix a, matrix b, array obs)`
> `backward (matrix a, matrix b, array obs, array c)`
> `baumwelch (array observations, int nstates)`
> `baumwelch (array observations, array pi, matrix a, matrix b)`
---
### Reference:
> en.wikipedia.org
> github.com
> en.wikipedia.org
> www.rdocumentation.org
> www.rdocumentation.org
forward(pi, a, b, obs)
Computes forward probabilities for state `X` up to observation at time `k`, is defined as the
probability of observing sequence of observations `e_1 ... e_k` and that the state at time `k` is `X`.
Parameters:
pi (float ) : Initial probabilities.
a (matrix) : Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing
states given a state matrix is size (M x M) where M is number of states.
b (matrix) : Emissions, matrix of observation probabilities b or beta = observation probabilities. Given
state matrix is size (M x O) where M is number of states and O is number of different
possible observations.
obs (int ) : List with actual state observation data.
Returns: - `matrix _alpha`: Forward probabilities. The probabilities are given on a logarithmic scale (natural logarithm). The first
dimension refers to the state and the second dimension to time.
forward(pi, a, b, obs, scaling)
Computes forward probabilities for state `X` up to observation at time `k`, is defined as the
probability of observing sequence of observations `e_1 ... e_k` and that the state at time `k` is `X`.
Parameters:
pi (float ) : Initial probabilities.
a (matrix) : Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing
states given a state matrix is size (M x M) where M is number of states.
b (matrix) : Emissions, matrix of observation probabilities b or beta = observation probabilities. Given
state matrix is size (M x O) where M is number of states and O is number of different
possible observations.
obs (int ) : List with actual state observation data.
scaling (bool) : Normalize `alpha` scale.
Returns: - #### Tuple with:
> - `matrix _alpha`: Forward probabilities. The probabilities are given on a logarithmic scale (natural logarithm). The first
dimension refers to the state and the second dimension to time.
> - `array _c`: Array with normalization scale.
backward(a, b, obs)
Computes backward probabilities for state `X` and observation at time `k`, is defined as the probability of observing the sequence of observations `e_k+1, ... , e_n` under the condition that the state at time `k` is `X`.
Parameters:
a (matrix) : Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing states
given a state matrix is size (M x M) where M is number of states
b (matrix) : Emissions, matrix of observation probabilities b or beta = observation probabilities. given state
matrix is size (M x O) where M is number of states and O is number of different possible observations
obs (int ) : Array with actual state observation data.
Returns: - `matrix _beta`: Backward probabilities. The probabilities are given on a logarithmic scale (natural logarithm). The first dimension refers to the state and the second dimension to time.
backward(a, b, obs, c)
Computes backward probabilities for state `X` and observation at time `k`, is defined as the probability of observing the sequence of observations `e_k+1, ... , e_n` under the condition that the state at time `k` is `X`.
Parameters:
a (matrix) : Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing states
given a state matrix is size (M x M) where M is number of states
b (matrix) : Emissions, matrix of observation probabilities b or beta = observation probabilities. given state
matrix is size (M x O) where M is number of states and O is number of different possible observations
obs (int ) : Array with actual state observation data.
c (float ) : Array with Normalization scaling coefficients.
Returns: - `matrix _beta`: Backward probabilities. The probabilities are given on a logarithmic scale (natural logarithm). The first dimension refers to the state and the second dimension to time.
baumwelch(observations, nstates)
**(Random Initialization)** Baum–Welch algorithm is a special case of the expectation–maximization algorithm used to find the
unknown parameters of a hidden Markov model (HMM). It makes use of the forward-backward algorithm
to compute the statistics for the expectation step.
Parameters:
observations (int ) : List of observed states.
nstates (int)
Returns: - #### Tuple with:
> - `array _pi`: Initial probability distribution.
> - `matrix _a`: Transition probability matrix.
> - `matrix _b`: Emission probability matrix.
---
requires: `import RicardoSantos/WIPTensor/2 as Tensor`
baumwelch(observations, pi, a, b)
Baum–Welch algorithm is a special case of the expectation–maximization algorithm used to find the
unknown parameters of a hidden Markov model (HMM). It makes use of the forward-backward algorithm
to compute the statistics for the expectation step.
Parameters:
observations (int ) : List of observed states.
pi (float ) : Initial probaility distribution.
a (matrix) : Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing states
given a state matrix is size (M x M) where M is number of states
b (matrix) : Emissions, matrix of observation probabilities b or beta = observation probabilities. given state
matrix is size (M x O) where M is number of states and O is number of different possible observations
Returns: - #### Tuple with:
> - `array _pi`: Initial probability distribution.
> - `matrix _a`: Transition probability matrix.
> - `matrix _b`: Emission probability matrix.
---
requires: `import RicardoSantos/WIPTensor/2 as Tensor`

VS Score [SpiritualHealer117]An experimental indicator that uses historical prices and readings of technical indicators to give the probability that stock and crypto prices will be in a certain range on the next close. This indicator may be helpful for options traders or for traders who want to see the probability of a move.
It classifies returns into five categories:
Extreme Rise - Over 2 standard deviations above normal returns
Rise - Between 0.5 standard deviations and 2 standard deviations above normal returns
Flat - Falling in the range of +/- 0.5 standard deviations of normal returns
Fall - Between 0.5 standard deviations and 2 standard deviations below normal returns
Extreme Fall - Over 2 standard deviations below normal returns
It is an adaptive probability model, which trains on the previous 1000 data points, and is calculated by creating probability vectors for the current reading of the PPO, MA, volume histogram, and previous return, and combining them into one probability vector.

Quantitative Price Forecasting - The Quant ScienceThis script is a quantitative price forecasting indicator that forecasts price changes for a given asset.
The model aims to forecast future prices by analyzing past data within a selected time period. Mathematical probability is used to calculate whether starting from time X can lead to reaching prices Y1 and Y2. In this context, X represents the current selected time period, Y1 represents the selected percentage decrease, and Y2 represents the selected percentage increase. The probabilities are estimated using the simple average.
The simple average is displayed on the chart, showing in red the periods where the price is below the average and in green the periods where the price is above the average.
This powerful tool not only provides forecasts of future prices but also calculates the distribution of variations around the average. It then takes this information and creates an estimate of the average price variation around the simple average.
Using a mean-reverting logic, buying and selling opportunities are highlighted.
We recommend turning off the display of bars on your chart for a better experience when using this indicator.
Unlock the full potential of your trading strategy with our powerful indicator. By analyzing past price data, it provides accurate forecasts and calculates the probability of reaching specific price targets. Its mean-reverting logic highlights buying and selling opportunities, while the simple moving average displayed on the chart shows periods where the price is above or below the average. Additionally, it estimates the average variation of price around the simple average, giving you valuable insights into price movements. Don't miss out on this valuable tool that can take your trading to the next level

Chebyshevs BandsThis script calculates upper and lower bands using Chebyshev's inequality formula.
The main pros.: the band doesn't depend on particular distribution. It fits to any type of random variables. Also it allows to calculate bands for instruments with extremely high volatility.
Cons.: formula provides a rough estimation in some special cases like lognormal distribution.