PINE LIBRARY

PineStats

199
█ OVERVIEW

PineStats is a comprehensive statistical analysis library for Pine Script v6, providing 104 functions across 6 modules. Built for quantitative traders, researchers, and indicator developers who need professional-grade statistics without reinventing the wheel.

For building mean-reversion strategies, analyzing return distributions, measuring correlations, or testing for market regimes.

█ MODULES
CORE STATISTICS (20 functions)
• Central tendency: mean, median, WMA, EMA
• Dispersion: variance, stdev, MAD, range
• Standardization: z-score, robust z-score, normalize, percentile
• Distribution shape: skewness, kurtosis

PROBABILITY DISTRIBUTIONS (17 functions)
• Normal: PDF, CDF, inverse CDF (quantile function)
• Power-law: Hill estimator, MLE alpha, survival function
• Exponential: PDF, CDF, rate estimation
• Normality testing: Jarque-Bera test

ENTROPY (9 functions)
• Shannon entropy (information theory)
• Tsallis entropy (non-extensive, fat-tail sensitive)
• Permutation entropy (ordinal patterns)
• Approximate entropy (regularity measure)
• Entropy-based regime detection

PROBABILITY (21 functions)
• Win rates and expected value
• First passage time estimation
• TP/SL probability analysis
• Conditional probability and Bayes updates
• Streak and drawdown probabilities

REGRESSION (19 functions)
• Linear regression: slope, intercept, forecast
• Goodness of fit: R², adjusted R², standard error
• Statistical tests: t-statistic, p-value, significance
• Trend analysis: strength, angle, acceleration
• Quadratic regression

CORRELATION (18 functions)
• Pearson, Spearman, Kendall correlation
• Covariance, beta, alpha (Jensen's)
• Rolling correlation analysis
• Autocorrelation and cross-correlation
• Information ratio, tracking error


█ QUICK START

Pine Script®
import HenriqueCentieiro/PineStats/1 as stats


Pine Script®
// Z-score for mean reversion z = stats.zscore(close, 20) // Test if returns are normally distributed returns = (close - close[1]) / close[1] isGaussian = stats.is_normal(returns, 100, 0.05) // Regression channel [center, upper, lower] = stats.linreg_channel(close, 50, 2.0) // Correlation with benchmark spyReturns = request.security("SPY", timeframe.period, close/close[1] - 1) beta = stats.beta(returns, spyReturns, 60)


█ USE CASES
✓ Mean Reversion — z-scores, percentiles, Bollinger-style analysis
✓ Regime Detection — entropy measures, correlation regimes
✓ Risk Analysis — drawdown probability, VaR via quantiles
✓ Strategy Evaluation — expected value, win rates, R:R analysis
✓ Distribution Analysis — normality tests, fat-tail detection
✓ Multi-Asset — beta, alpha, correlation, relative strength

█ NOTES
• All functions return `na` on invalid inputs
• Designed for Pine Script v6
• Fully documented in the library header
• Part of the Pine ecosystem: PineStats, PineQuant, PineCriticality, PineWavelet

█ REFERENCES
• Abramowitz & Stegun — Normal CDF approximation
• Acklam's algorithm — Inverse normal CDF
• Hill estimator — Power-law tail estimation
• Tsallis statistics — Non-extensive entropy

Full documentation in the library header.

mean(src, length)
  Calculates the arithmetic mean (simple moving average) over a lookback period
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 1)
  Returns: Arithmetic mean of the last `length` values, or `na` if inputs invalid

wma_custom(src, length)
  Calculates weighted moving average with linearly decreasing weights
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 1)
  Returns: Weighted moving average, or `na` if inputs invalid

ema_custom(src, length)
  Calculates exponential moving average
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 1)
  Returns: Exponential moving average, or `na` if inputs invalid

median(src, length)
  Calculates the median value over a lookback period
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 1)
  Returns: Median value, or `na` if inputs invalid

variance(src, length)
  Calculates population variance over a lookback period
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 1)
  Returns: Population variance, or `na` if inputs invalid

stdev(src, length)
  Calculates population standard deviation over a lookback period
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 1)
  Returns: Population standard deviation, or `na` if inputs invalid

mad(src, length)
  Calculates Median Absolute Deviation (MAD) - robust dispersion measure
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 1)
  Returns: MAD value, or `na` if inputs invalid

data_range(src, length)
  Calculates the range (highest - lowest) over a lookback period
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 1)
  Returns: Range value, or `na` if inputs invalid

zscore(src, length)
  Calculates z-score (number of standard deviations from mean)
  Parameters:
    src (float): Source series
    length (simple int): Lookback period for mean and stdev calculation (must be >= 2)
  Returns: Z-score, or `na` if inputs invalid or stdev is zero

zscore_robust(src, length)
  Calculates robust z-score using median and MAD (resistant to outliers)
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 2)
  Returns: Robust z-score, or `na` if inputs invalid or MAD is zero

normalize(src, length)
  Normalizes value to [0, 1] range using min-max scaling
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 1)
  Returns: Normalized value in [0, 1], or `na` if inputs invalid or range is zero

percentile(src, length)
  Calculates percentile rank of current value within lookback window
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 1)
  Returns: Percentile rank (0 to 100), or `na` if inputs invalid

winsorize(src, length, lower_pct, upper_pct)
  Winsorizes values by clamping to percentile bounds (reduces outlier impact)
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 1)
    lower_pct (simple float): Lower percentile bound (0-100, e.g., 5 for 5th percentile)
    upper_pct (simple float): Upper percentile bound (0-100, e.g., 95 for 95th percentile)
  Returns: Winsorized value clamped to [lower_pct, upper_pct] bounds

skewness(src, length)
  Calculates sample skewness (measure of distribution asymmetry)
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 3)
  Returns: Skewness value (negative = left tail, positive = right tail), or `na` if invalid

kurtosis(src, length)
  Calculates excess kurtosis (measure of distribution tail heaviness)
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 4)
  Returns: Excess kurtosis (>0 = heavy tails, <0 = light tails), or `na` if invalid

count_valid(src, length)
  Counts non-na values in lookback window (useful for data quality checks)
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 1)
  Returns: Count of valid (non-na) values

sum(src, length)
  Calculates sum over lookback period
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 1)
  Returns: Sum of values, or `na` if inputs invalid

cumsum(src)
  Calculates cumulative sum (running total from first bar)
  Parameters:
    src (float): Source series
  Returns: Cumulative sum

change(src, length)
  Returns the change (difference) from n bars ago
  Parameters:
    src (float): Source series
    length (simple int): Number of bars to look back (must be >= 1)
  Returns: Current value minus value from `length` bars ago

roc(src, length)
  Calculates Rate of Change (percentage change from n bars ago)
  Parameters:
    src (float): Source series
    length (simple int): Number of bars to look back (must be >= 1)
  Returns: Percentage change as decimal (0.05 = 5%), or `na` if invalid

normal_pdf_standard(x)
  Calculates the standard normal probability density function (PDF)
  Parameters:
    x (float): The value to evaluate
  Returns: PDF value at x for standard normal N(0,1)

normal_pdf(x, mu, sigma)
  Calculates the normal probability density function (PDF)
  Parameters:
    x (float): The value to evaluate
    mu (float): Mean of the distribution (default: 0)
    sigma (float): Standard deviation (default: 1, must be > 0)
  Returns: PDF value at x for normal N(mu, sigma²)

normal_cdf_standard(x)
  Calculates the standard normal cumulative distribution function (CDF)
  Parameters:
    x (float): The value to evaluate
  Returns: Probability P(X <= x) for standard normal N(0,1)
description Uses Abramowitz & Stegun approximation (formula 7.1.26), accurate to ~1.5e-7

normal_cdf(x, mu, sigma)
  Calculates the normal cumulative distribution function (CDF)
  Parameters:
    x (float): The value to evaluate
    mu (float): Mean of the distribution (default: 0)
    sigma (float): Standard deviation (default: 1, must be > 0)
  Returns: Probability P(X <= x) for normal N(mu, sigma²)

normal_inv_standard(p)
  Calculates the inverse standard normal CDF (quantile function)
  Parameters:
    p (float): Probability value (must be in (0, 1))
  Returns: x such that P(X <= x) = p for standard normal N(0,1)
description Uses Acklam's algorithm, accurate to ~1.15e-9

normal_inv(p, mu, sigma)
  Calculates the inverse normal CDF (quantile function)
  Parameters:
    p (float): Probability value (must be in (0, 1))
    mu (float): Mean of the distribution
    sigma (float): Standard deviation (must be > 0)
  Returns: x such that P(X <= x) = p for normal N(mu, sigma²)

power_law_alpha(src, length, tail_pct)
  Estimates power-law exponent (alpha) using Hill estimator
  Parameters:
    src (float): Source series (typically absolute returns or drawdowns)
    length (simple int): Lookback period (must be >= 10 for reliable estimates)
    tail_pct (simple float): Percentage of data to use for tail estimation (default: 0.1 = top 10%)
  Returns: Estimated alpha (tail index), typically 2-4 for financial data
description Alpha < 2 indicates infinite variance (very heavy tails)
description Alpha < 3 indicates infinite kurtosis
description Alpha > 4 suggests near-Gaussian behavior

power_law_alpha_mle(src, length, x_min)
  Estimates power-law alpha using maximum likelihood (Clauset method)
  Parameters:
    src (float): Source series (positive values expected)
    length (simple int): Lookback period (must be >= 20)
    x_min (float): Minimum threshold for power-law behavior
  Returns: Estimated alpha using MLE

power_law_pdf(x, alpha, x_min)
  Calculates power-law probability density (Pareto Type I)
  Parameters:
    x (float): Value to evaluate (must be >= x_min)
    alpha (float): Power-law exponent (must be > 1)
    x_min (float): Minimum value / scale parameter (must be > 0)
  Returns: PDF value

power_law_survival(x, alpha, x_min)
  Calculates power-law survival function P(X > x)
  Parameters:
    x (float): Value to evaluate (must be >= x_min)
    alpha (float): Power-law exponent (must be > 1)
    x_min (float): Minimum value / scale parameter (must be > 0)
  Returns: Probability of exceeding x

power_law_ks(src, length, alpha, x_min)
  Tests if data follows power-law using simplified Kolmogorov-Smirnov
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
    alpha (float): Estimated alpha from power_law_alpha()
    x_min (float): Threshold value
  Returns: KS statistic (lower = better fit, typically < 0.1 for good fit)

is_power_law(src, length, tail_pct, ks_threshold)
  Simple test if distribution appears to follow power-law
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
    tail_pct (simple float): Tail percentage for alpha estimation
    ks_threshold (simple float): Maximum KS statistic for acceptance (default: 0.1)
  Returns: true if KS test suggests power-law fit

exp_pdf(x, lambda)
  Calculates exponential probability density function
  Parameters:
    x (float): Value to evaluate (must be >= 0)
    lambda (float): Rate parameter (must be > 0)
  Returns: PDF value

exp_cdf(x, lambda)
  Calculates exponential cumulative distribution function
  Parameters:
    x (float): Value to evaluate (must be >= 0)
    lambda (float): Rate parameter (must be > 0)
  Returns: Probability P(X <= x)

exp_lambda(src, length)
  Estimates exponential rate parameter (lambda) using MLE
  Parameters:
    src (float): Source series (positive values)
    length (simple int): Lookback period
  Returns: Estimated lambda (1/mean)

jarque_bera(src, length)
  Calculates Jarque-Bera test statistic for normality
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 10)
  Returns: JB statistic (higher = more deviation from normality)
description Under normality, JB ~ chi-squared(2). JB > 6 suggests non-normality at 5% level

is_normal(src, length, significance)
  Tests if distribution is approximately normal
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
    significance (simple float): Significance level (default: 0.05)
  Returns: true if Jarque-Bera test does not reject normality

shannon_entropy(src, length, n_bins)
  Calculates Shannon entropy from a probability distribution
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 10)
    n_bins (simple int): Number of histogram bins for discretization (default: 10)
  Returns: Shannon entropy in bits (log base 2)
description Higher entropy = more randomness/uncertainty, lower = more predictability

shannon_entropy_norm(src, length, n_bins)
  Calculates normalized Shannon entropy [0, 1]
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
    n_bins (simple int): Number of histogram bins
  Returns: Normalized entropy where 0 = perfectly predictable, 1 = maximum randomness

tsallis_entropy(src, length, q, n_bins)
  Calculates Tsallis entropy with q-parameter
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 10)
    q (float): Entropic index (q=1 recovers Shannon entropy)
    n_bins (simple int): Number of histogram bins
  Returns: Tsallis entropy value
description q < 1: emphasizes rare events (fat tails)
description q = 1: equivalent to Shannon entropy
description q > 1: emphasizes common events

optimal_q(src, length)
  Estimates optimal q parameter from kurtosis
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
  Returns: Estimated q value that best captures the distribution's tail behavior
description Uses relationship: q ≈ (5 + kurtosis) / (3 + kurtosis) for kurtosis > 0

tsallis_q_gaussian(x, q, beta)
  Calculates Tsallis q-Gaussian probability density
  Parameters:
    x (float): Value to evaluate
    q (float): Tsallis q parameter (must be < 3)
    beta (float): Width parameter (inverse temperature, must be > 0)
  Returns: q-Gaussian PDF value
description q=1 recovers standard Gaussian

permutation_entropy(src, length, order)
  Calculates permutation entropy (ordinal pattern complexity)
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 20)
    order (simple int): Embedding dimension / pattern length (2-5, default: 3)
  Returns: Normalized permutation entropy [0, 1]
description Measures complexity of temporal ordering patterns
description 0 = perfectly predictable sequence, 1 = random

approx_entropy(src, length, m, r)
  Calculates Approximate Entropy (ApEn) - regularity measure
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 50)
    m (simple int): Embedding dimension (default: 2)
    r (simple float): Tolerance as fraction of stdev (default: 0.2)
  Returns: Approximate entropy value (higher = more irregular/complex)
description Lower ApEn indicates more self-similarity and predictability

entropy_regime(src, length, q, n_bins)
  Detects market regime based on entropy level
  Parameters:
    src (float): Source series (typically returns)
    length (simple int): Lookback period
    q (float): Tsallis q parameter (use optimal_q() or default 1.5)
    n_bins (simple int): Number of histogram bins
  Returns: Regime indicator: -1 = trending (low entropy), 0 = transition, 1 = ranging (high entropy)

entropy_risk(src, length)
  Calculates entropy-based risk indicator
  Parameters:
    src (float): Source series (typically returns)
    length (simple int): Lookback period
  Returns: Risk score [0, 1] where 1 = maximum divergence from Gaussian 1

hit_rate(src, length)
  Calculates hit rate (probability of positive outcome) over lookback
  Parameters:
    src (float): Source series (positive values count as hits)
    length (simple int): Lookback period
  Returns: Hit rate as decimal [0, 1]

hit_rate_cond(condition, length)
  Calculates hit rate for custom condition over lookback
  Parameters:
    condition (bool): Boolean series (true = hit)
    length (simple int): Lookback period
  Returns: Hit rate as decimal [0, 1]

expected_value(src, length)
  Calculates expected value of a series
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
  Returns: Expected value (mean)

expected_value_trade(win_prob, take_profit, stop_loss)
  Calculates expected value for a trade with TP and SL levels
  Parameters:
    win_prob (float): Probability of hitting TP (0-1)
    take_profit (float): Take profit in price units or %
    stop_loss (float): Stop loss in price units or % (positive value)
  Returns: Expected value per trade
description EV = (win_prob * TP) - ((1 - win_prob) * SL)

breakeven_winrate(take_profit, stop_loss)
  Calculates breakeven win rate for given TP/SL ratio
  Parameters:
    take_profit (float): Take profit distance
    stop_loss (float): Stop loss distance
  Returns: Required win rate for breakeven (EV = 0)

reward_risk_ratio(take_profit, stop_loss)
  Calculates the reward-to-risk ratio
  Parameters:
    take_profit (float): Take profit distance
    stop_loss (float): Stop loss distance
  Returns: R:R ratio

fpt_probability(src, length, target, max_bars)
  Estimates probability of price reaching target within N bars
  Parameters:
    src (float): Source series (typically returns)
    length (simple int): Lookback for volatility estimation
    target (float): Target move (in same units as src, e.g., % return)
    max_bars (simple int): Maximum bars to consider
  Returns: Probability of reaching target within max_bars
description Based on random walk with drift approximation

fpt_mean(src, length, target)
  Estimates mean first passage time to target level
  Parameters:
    src (float): Source series (typically returns)
    length (simple int): Lookback for volatility estimation
    target (float): Target move
  Returns: Expected number of bars to reach target (can be infinite)

fpt_historical(src, length, target)
  Counts historical bars to reach target from each point
  Parameters:
    src (float): Source series (typically price or returns)
    length (simple int): Lookback period
    target (float): Target move from each starting point
  Returns: Array of first passage times (na if target not reached within lookback)

tp_probability(src, length, tp_distance, sl_distance)
  Estimates probability of hitting TP before SL
  Parameters:
    src (float): Source series (typically returns)
    length (simple int): Lookback for estimation
    tp_distance (float): Take profit distance (positive)
    sl_distance (float): Stop loss distance (positive)
  Returns: Probability of TP being hit first

trade_probability(src, length, tp_pct, sl_pct)
  Calculates complete trade probability and EV analysis
  Parameters:
    src (float): Source series (typically returns)
    length (simple int): Lookback period
    tp_pct (float): Take profit percentage
    sl_pct (float): Stop loss percentage
  Returns: Tuple: [tp_probability, expected_value, breakeven_wr, actual_rr]

cond_prob(condition_a, condition_b, length)
  Calculates conditional probability P(B|A) from historical data
  Parameters:
    condition_a (bool): Condition A (the given condition)
    condition_b (bool): Condition B (the outcome)
    length (simple int): Lookback period
  Returns: P(B|A) = P(A and B) / P(A)

bayes_update(prior, likelihood, false_positive)
  Updates probability using Bayes' theorem
  Parameters:
    prior (float): Prior probability P(H)
    likelihood (float): P(E|H) - probability of evidence given hypothesis
    false_positive (float): P(E|~H) - probability of evidence given hypothesis is false
  Returns: Posterior probability P(H|E)

streak_prob(win_rate, streak_length)
  Calculates probability of N consecutive wins given win rate
  Parameters:
    win_rate (float): Single-trade win probability
    streak_length (simple int): Number of consecutive wins
  Returns: Probability of streak

losing_streak_prob(win_rate, streak_length)
  Calculates probability of experiencing N consecutive losses
  Parameters:
    win_rate (float): Single-trade win probability
    streak_length (simple int): Number of consecutive losses
  Returns: Probability of losing streak

drawdown_prob(src, length, dd_threshold)
  Estimates probability of drawdown exceeding threshold
  Parameters:
    src (float): Source series (returns)
    length (simple int): Lookback period
    dd_threshold (float): Drawdown threshold (as positive decimal, e.g., 0.10 = 10%)
  Returns: Historical probability of exceeding drawdown threshold

prob_to_odds(prob)
  Calculates odds from probability
  Parameters:
    prob (float): Probability (0-1)
  Returns: Odds (prob / (1 - prob))

odds_to_prob(odds)
  Calculates probability from odds
  Parameters:
    odds (float): Odds ratio
  Returns: Probability (0-1)

implied_prob(decimal_odds)
  Calculates implied probability from decimal odds (betting)
  Parameters:
    decimal_odds (float): Decimal odds (e.g., 2.5 means $2.50 return per $1 bet)
  Returns: Implied probability

logit(prob)
  Calculates log-odds (logit) from probability
  Parameters:
    prob (float): Probability (must be in (0, 1))
  Returns: Log-odds

inv_logit(log_odds)
  Calculates probability from log-odds (inverse logit / sigmoid)
  Parameters:
    log_odds (float): Log-odds value
  Returns: Probability (0-1)

linreg_slope(src, length)
  Calculates linear regression slope
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 2)
  Returns: Slope coefficient (change per bar)

linreg_intercept(src, length)
  Calculates linear regression intercept
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 2)
  Returns: Intercept (predicted value at oldest bar in window)

linreg_value(src, length)
  Calculates predicted value at current bar using linear regression
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
  Returns: Predicted value at current bar (end of regression line)

linreg_forecast(src, length, offset)
  Forecasts value N bars ahead using linear regression
  Parameters:
    src (float): Source series
    length (simple int): Lookback period for regression
    offset (simple int): Bars ahead to forecast (positive = future)
  Returns: Forecasted value

linreg_channel(src, length, mult)
  Calculates linear regression channel with bands
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
    mult (simple float): Standard deviation multiplier for bands
  Returns: Tuple: [center, upper, lower]

r_squared(src, length)
  Calculates R-squared (coefficient of determination)
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
  Returns: R² value [0, 1] where 1 = perfect linear fit

adj_r_squared(src, length)
  Calculates adjusted R-squared (accounts for sample size)
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
  Returns: Adjusted R² value

std_error(src, length)
  Calculates standard error of estimate (residual standard deviation)
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
  Returns: Standard error

residual(src, length)
  Calculates residual at current bar
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
  Returns: Residual (actual - predicted)

residuals(src, length)
  Returns array of all residuals in lookback window
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
  Returns: Array of residuals

t_statistic(src, length)
  Calculates t-statistic for slope coefficient
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
  Returns: T-statistic (slope / standard error of slope)

slope_pvalue(src, length)
  Approximates p-value for slope t-test (two-tailed)
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
  Returns: Approximate p-value

is_significant(src, length, alpha)
  Tests if regression slope is statistically significant
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
    alpha (simple float): Significance level (default: 0.05)
  Returns: true if slope is significant at alpha level

trend_strength(src, length)
  Calculates normalized trend strength based on R² and slope
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
  Returns: Trend strength [-1, 1] where sign indicates direction

trend_angle(src, length)
  Calculates trend angle in degrees
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
  Returns: Angle in degrees (positive = uptrend, negative = downtrend)

linreg_acceleration(src, length)
  Calculates trend acceleration (second derivative)
  Parameters:
    src (float): Source series
    length (simple int): Lookback period for each regression
  Returns: Acceleration (change in slope)

linreg_deviation(src, length)
  Calculates deviation from regression line in standard error units
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
  Returns: Deviation in standard error units (like z-score)

quadreg_coefficients(src, length)
  Fits quadratic regression and returns coefficients
  Parameters:
    src (float): Source series
    length (simple int): Lookback period (must be >= 4)
  Returns: Tuple: [a, b, c] for y = a*x² + b*x + c

quadreg_value(src, length)
  Calculates quadratic regression value at current bar
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
  Returns: Predicted value from quadratic fit

correlation(x, y, length)
  Calculates Pearson correlation coefficient between two series
  Parameters:
    x (float): First series
    y (float): Second series
    length (simple int): Lookback period (must be >= 3)
  Returns: Correlation coefficient [-1, 1]

covariance(x, y, length)
  Calculates sample covariance between two series
  Parameters:
    x (float): First series
    y (float): Second series
    length (simple int): Lookback period (must be >= 2)
  Returns: Covariance value

beta(asset, benchmark, length)
  Calculates beta coefficient (slope of regression of y on x)
  Parameters:
    asset (float): Asset returns series
    benchmark (float): Benchmark returns series
    length (simple int): Lookback period
  Returns: Beta coefficient
description Beta = Cov(asset, benchmark) / Var(benchmark)

alpha(asset, benchmark, length, risk_free)
  Calculates alpha (Jensen's alpha / intercept)
  Parameters:
    asset (float): Asset returns series
    benchmark (float): Benchmark returns series
    length (simple int): Lookback period
    risk_free (float): Risk-free rate (default: 0)
  Returns: Alpha value (excess return not explained by beta)

spearman(x, y, length)
  Calculates Spearman rank correlation coefficient
  Parameters:
    x (float): First series
    y (float): Second series
    length (simple int): Lookback period (must be >= 3)
  Returns: Spearman correlation [-1, 1]
description More robust to outliers than Pearson correlation

kendall_tau(x, y, length)
  Calculates Kendall's tau rank correlation (simplified)
  Parameters:
    x (float): First series
    y (float): Second series
    length (simple int): Lookback period (must be >= 3)
  Returns: Kendall's tau [-1, 1]

correlation_change(x, y, length, change_period)
  Calculates change in correlation over time
  Parameters:
    x (float): First series
    y (float): Second series
    length (simple int): Lookback period for correlation
    change_period (simple int): Period over which to measure change
  Returns: Change in correlation

correlation_regime(x, y, length, ma_length)
  Detects correlation regime based on level and stability
  Parameters:
    x (float): First series
    y (float): Second series
    length (simple int): Lookback period for correlation
    ma_length (simple int): Moving average length for smoothing
  Returns: Regime: -1 = negative, 0 = uncorrelated, 1 = positive

correlation_stability(x, y, length, stability_length)
  Calculates correlation stability (inverse of volatility)
  Parameters:
    x (float): First series
    y (float): Second series
    length (simple int): Lookback for correlation
    stability_length (simple int): Lookback for stability calculation
  Returns: Stability score [0, 1] where 1 = perfectly stable

relative_strength(asset, benchmark, length)
  Calculates relative strength of asset vs benchmark
  Parameters:
    asset (float): Asset price series
    benchmark (float): Benchmark price series
    length (simple int): Smoothing period
  Returns: Relative strength ratio (normalized)

tracking_error(asset, benchmark, length)
  Calculates tracking error (standard deviation of excess returns)
  Parameters:
    asset (float): Asset returns
    benchmark (float): Benchmark returns
    length (simple int): Lookback period
  Returns: Tracking error (annualize by multiplying by sqrt(252) for daily data)

information_ratio(asset, benchmark, length)
  Calculates information ratio (risk-adjusted excess return)
  Parameters:
    asset (float): Asset returns
    benchmark (float): Benchmark returns
    length (simple int): Lookback period
  Returns: Information ratio

capture_ratio(asset, benchmark, length, up_capture)
  Calculates up/down capture ratio
  Parameters:
    asset (float): Asset returns
    benchmark (float): Benchmark returns
    length (simple int): Lookback period
    up_capture (simple bool): If true, calculate up capture; if false, down capture
  Returns: Capture ratio

autocorrelation(src, length, lag)
  Calculates autocorrelation at specified lag
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
    lag (simple int): Lag for autocorrelation (default: 1)
  Returns: Autocorrelation at specified lag

partial_autocorr(src, length)
  Calculates partial autocorrelation at lag 1
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
  Returns: PACF at lag 1 (equals ACF at lag 1)

autocorr_test(src, length, max_lag)
  Tests for significant autocorrelation (Ljung-Box inspired)
  Parameters:
    src (float): Source series
    length (simple int): Lookback period
    max_lag (simple int): Maximum lag to test
  Returns: Sum of squared autocorrelations (higher = more autocorrelation)

cross_correlation(x, y, length, lag)
  Calculates cross-correlation at specified lag
  Parameters:
    x (float): First series
    y (float): Second series (lagged)
    length (simple int): Lookback period
    lag (simple int): Lag to apply to y (positive = y leads x)
  Returns: Cross-correlation at specified lag

cross_correlation_peak(x, y, length, max_lag)
  Finds lag with maximum cross-correlation
  Parameters:
    x (float): First series
    y (float): Second series
    length (simple int): Lookback period
    max_lag (simple int): Maximum lag to search (both directions)
  Returns: Tuple: [best_lag, max_correlation]

כתב ויתור

המידע והפרסומים אינם מיועדים להיות, ואינם מהווים, ייעוץ או המלצה פיננסית, השקעתית, מסחרית או מכל סוג אחר המסופקת או מאושרת על ידי TradingView. קרא עוד ב־תנאי השימוש.