Inside Bar + Harami ComboThis indicator visually highlights Inside Bars, Outside Bars, and Harami candlestick patterns directly on your chart using clean color-coded candles — no labels, no shapes, just visual clarity.
It helps traders quickly identify potential reversal and continuation setups by coloring candles according to the detected pattern type.
🔍 Patterns Detected
🟨 Inside Bar — Current candle’s range is completely inside the previous candle’s range.
Often signals price contraction before a breakout.
💗 Outside Bar — Current candle’s high and low exceed the previous candle’s range.
Indicates volatility expansion and possible trend continuation.
🟩 Bullish Harami — A small bullish candle within the body of a prior bearish candle.
Suggests potential reversal to the upside.
🟥 Bearish Harami — A small bearish candle within the body of a prior bullish candle.
Suggests potential reversal to the downside.
⚙️ Features
Customizable colors for each pattern type.
Simple overlay visualization — no shapes, no labels, just colored candles.
Harami colors automatically override Inside/Outside colors when both occur on the same bar.
Lightweight logic for smooth performance on any timeframe or symbol.
💡 How to Use
Apply the indicator to your chart.
Configure colors in the settings panel if desired.
Watch for highlighted candles:
Inside Bars often precede breakouts.
Harami patterns can mark reversal zones.
Combine with trend tools (like moving averages) to confirm setups.
⚠️ Note
This indicator is for visual pattern detection and educational use only.
Always combine candlestick signals with broader technical or market context before trading decisions.
المؤشرات والاستراتيجيات
Volume + MA5 & MA10This Volume + MA5 & MA10 (Technical Volume Trend Analysis)
The Volume + MA5 & MA10 indicator provides a precise view of market participation and volume momentum by combining raw volume data with two moving averages (MA5 and MA10). It’s designed for traders who rely on volume-based confirmation to validate price movements, breakouts, and trend reversals.
🔍 Overview
This indicator displays volume bars alongside two smooth volume averages — MA5 (short-term) and MA10 (medium-term) — making it easier to detect shifts in market activity.
When the short-term average crosses above or below the long-term average, it signals a potential change in trading intensity or market sentiment.
⚙️ Key Features
Dual Volume Moving Averages (MA5 & MA10) for short- and medium-term analysis.
Dynamic Bar Coloring based on whether current volume exceeds MA5 or MA10.
Crossover Detection with visual markers for MA5/MA10 intersections.
Alert Conditions to notify you of significant volume trend shifts.
Fully customizable appearance and smoothing options.
📊 How to Interpret
MA5 > MA10 → Increasing short-term volume activity (strengthening momentum).
MA5 < MA10 → Decreasing short-term volume (weakening participation).
Rising volume with price → Confirms trend strength.
Falling volume with rising/falling price → Suggests potential reversal or reduced conviction.
💡 Applications
Confirm breakouts and trend continuations.
Identify momentum divergences between price and volume.
Filter out low-volume or weak-trend setups.
Combine with RSI, MACD, or moving averages for enhanced signal validation.
✅ Advantages
Simple yet powerful structure for clean visual analysis.
Works across all timeframes and markets (crypto, stocks, forex, indices).
No repainting — reliable for both live and historical backtesting.
Use Volume + MA5 & MA10 to strengthen your technical analysis and gain a deeper understanding of how market participation drives price trends.
OBV (Delta or regular)This is a quite simple script to apply some choices to OBV.
You can choose to use regular OBV values or you can choose to use delta OBV values.
Delta OBV values calculates the delta between selling volume and buying volume per bar to find discrepancies.
You can make the OBV a smoothed line or just keep the normal rigid line. Rigid line is default.
A secondary smoothed OBV line is added automatically with color change if the OBV is above or below the smoothed line.
You can set your desired MA from SMA, EMA, VWMA and WMA, The same will be applied to both lines if chosen to smooth them both.
Both lines are editable from the styles tab (visibility, color and line type)
If you for some reason don't want color change on the secondary line, chose the same color for both color 1 and 2.
Simple delta OBV example:
If a red bar has a long lower wick, OBV will calculate the entire bar towards bearish volume, while the delta will check if there's more buying or selling happening in total. Some times you'll be able to catch divergences in the volume which implies a reversal might be in the making.
For instance more selling on a green candle making the OBV drop instead of increasing or vise versa.
Hopefully someone finds is useful.
EMA 9 + VWAP Bands Crossover With Buy Sell SignalsEMA 9 + VWAP Bands Crossover With Buy Sell Signal. Includes alerts
Holt Damped Forecast [CHE]A Friendly Note on These Pine Script Scripts
Hey there! Just wanted to share a quick, heartfelt heads-up: All these Pine Script examples come straight from my own self-study adventures as a total autodidact—think late nights tinkering and learning on my own. They're purely for educational vibes, helping me (and hopefully you!) get the hang of Pine Script basics, cool indicators, and building simple strategies.
That said, please know this isn't any kind of financial advice, investment nudge, or pro-level trading blueprint. I'd love for you to dive in with your own research, run those backtests like a champ, and maybe bounce ideas off a qualified expert before trying anything in a real trading setup. No guarantees here on performance or spot-on accuracy—trading's got its risks, and those are totally on each of us.
Let's keep it fun and educational—happy coding! 😊
Holt Damped Forecast — Damped trend forecasts with fan bands for uncertainty visualization and momentum integration
Summary
This indicator applies damped exponential smoothing to generate forward price forecasts, displaying them as probabilistic fan bands to highlight potential ranges rather than point estimates. It incorporates residual-based uncertainty to make projections more reliable in varying market conditions, reducing overconfidence in strong trends. Momentum from the trend component is shown in an optional label alongside signals, aiding quick assessment of direction and strength without relying on lagging oscillators.
Motivation: Why this design?
Standard exponential smoothing often extrapolates trends indefinitely, leading to unrealistic forecasts during mean reversion or weakening momentum. This design uses damping to gradually flatten long-term projections, better suiting real markets where trends fade. It addresses the need for visual uncertainty in forecasts, helping traders avoid entries based on overly optimistic point predictions.
What’s different vs. standard approaches?
- Reference baseline: Diverges from basic Holt's linear exponential smoothing, which assumes persistent trends without decay.
- Architecture differences:
- Adds damping to the trend extrapolation for finite-horizon realism.
- Builds fan bands from historical residuals for probabilistic ranges at multiple confidence levels.
- Integrates a dynamic label combining forecast details, scaled momentum, and directional signals.
- Applies tail background coloring to recent bars based on forecast direction for immediate visual cues.
- Practical effect: Charts show converging forecast bands over time, emphasizing shorter horizons where accuracy is higher. This visibly tempers aggressive projections in trends, making it easier to spot when uncertainty widens, which signals potential reversals or consolidation.
How it works (technical)
The indicator maintains two persistent components: a level tracking the current price baseline and a trend capturing directional slope. On each bar, the level updates by blending the current source price with a one-step-ahead expectation from the prior level and damped trend. The trend then adjusts by weighting the change in level against the prior damped trend. Forecasts extend this forward over a user-defined number of steps, with damping ensuring the trend influence diminishes over distance.
Uncertainty derives from the standard deviation of historical residuals—the differences between actual prices and one-step expectations—scaled by the damping structure for the forecast horizon. Bands form around the median forecast at specified confidence intervals using these scaled errors. Initialization seeds the level to the first bar's price and trend to zero, with persistence handling subsequent updates. A security call fetches the last bar index for tail logic, using lookahead to align with realtime but introducing minor repaint on unconfirmed bars.
Parameter Guide
The Source parameter selects the price input for level and residual calculations, defaulting to close; consider using high or low for assets sensitive to volatility, as close works well for most trend-following setups. Forecast Steps (h) defines the number of bars ahead for projections, defaulting to 4—shorter values like 1 to 5 suit intraday trading, while longer ones may widen bands excessively in choppy conditions. The Color Scheme (2025 Trends) option sets the base, up, and down colors for bands, labels, and backgrounds, starting with Ruby Dawn; opt for serene schemes on clean charts or vibrant ones to stand out in dark themes.
Level Smoothing α controls the responsiveness of the price baseline, defaulting to 0.3—values above 0.5 enhance tracking in fast markets but may amplify noise, whereas lower settings filter disturbances better. Trend Smoothing β adjusts sensitivity to slope changes, at 0.1 by default; increasing to 0.2 helps detect emerging shifts quicker, but keeping it low prevents whipsaws in sideways action. Damping φ (0..1) governs trend persistence, defaulting to 0.8—near 0.9 preserves carryover in sustained moves, while closer to 0.5 curbs overextensions more aggressively.
Show Fan Bands (50/75/95) toggles the probabilistic range display, enabled by default; disable it in oscillator panes to reduce clutter, but it's key for overlay forecasts. Residual Window (Bars) sets the length for deviation estimates, at 400 bars initially—100 to 200 works for short timeframes, and 500 or more adds stability over extended histories. Line Width determines the thickness of band and median lines, defaulting to 2; go thicker at 3 to 5 for emphasis on higher timeframes or thinner for layered indicators.
Show Median/Forecast Line reveals the central projection, on by default—hide if bands provide enough detail, or keep for pinpoint entry references. Show Integrated Label activates the combined view of forecast, momentum, and signal, defaulting to true; it's right-aligned for convenience, so turn it off on smaller screens to save space. Show Tail Background colors the last few bars by forecast direction, enabled initially; pair low transparency for subtle hints or higher for bolder emphasis.
Tail Length (Bars) specifies bars to color backward from the current one, at 3 by default—1 to 2 fits scalping, while 5 or more underscores building momentum. Tail Transparency (%) fades the background intensity, starting at 80; 50 to 70 delivers strong signals, and 90 or above allows seamless blending. Include Momentum in Label adds the scaled trend value, defaulting to true—ATR% scaling here offers relative strength context across assets.
Include Long/Short/Neutral Signal in Label displays direction from the trend sign, on by default; neutral helps in ranging markets, though it can be overlooked during strong trends. Scaling normalizes momentum output (raw, ATR-relative, or level-relative), set to ATR% initially—ATR% ensures cross-asset comparability, while %Level provides percentage perspectives. ATR Length defines the period for true range averaging in scaling, at 14; align it with your chart timeframe or shorten for quicker volatility responses.
Decimals sets precision in the momentum label, defaulting to 2—0 to 1 yields clean integers, and 3 or more suits detailed forex views. Show Zero-Cross Markers places arrows at direction changes, enabled by default; keep size small to minimize clutter, with text labels for fast scanning.
Reading & Interpretation
Fan bands expand outward from the current bar, with the median line as the central forecast—narrower bands indicate lower uncertainty, wider suggest caution. Colors tint up (positive forecast vs. prior level) in the scheme's up hue and down otherwise. The optional label lists the horizon, median, and range brackets at 50%, 75%, and 95% levels, followed by momentum (scaled per mode) and signal (Long if positive trend, Short if negative, Neutral if zero). Zero-cross arrows mark trend flips: upward triangle below bar for bullish cross, downward above for bearish. Tail background reinforces the forecast direction on recent bars.
Practical Workflows & Combinations
- Trend following: Enter long on upward zero-cross if median forecast rises above price and bands contain it; confirm with higher highs/lows. Short on downward cross with falling median.
- Exits/Stops: Trail stops below 50% lower band in longs; exit if momentum drifts negative or signal turns neutral. Use wider bands (75/95%) for conservative holds in volatile regimes.
- Multi-asset/Multi-TF: Defaults work across stocks, forex, crypto on 5m-1D; scale steps by TF (e.g., 10+ on daily). Layer with volume or structure tools—avoid over-reliance on isolated crosses.
Behavior, Constraints & Performance
Closed-bar logic ensures stable historical plots, but realtime updates via security lookahead may shift forecasts until bar confirmation, introducing minor repaint on the last bar. No explicit HTF calls beyond bar index fetch, minimizing gaps but watch for low-liquidity assets. Resources include a 2000-bar lookback for residuals and up to 500 labels, with no loops—efficient for most charts. Known limits: Early bars show wide bands due to sparse residuals; assumes stationary errors, so gaps or regime shifts widen inaccuracies.
Sensible Defaults & Quick Tuning
Start with defaults for balanced smoothing on 15m-4H charts. For choppy conditions (too many crosses), lower β to 0.05 and raise residual window to 600 for stability. In trending markets (sluggish signals), increase α/β to 0.4/0.2 and shorten steps to 2. If bands overexpand, boost φ toward 0.95 to preserve trend carry. Tune colors for theme fit without altering logic.
What this indicator is—and isn’t
This is a visualization and signal layer for damped forecasts and momentum, complementing price action analysis. It isn’t a standalone system—pair with risk rules and broader context. Not predictive beyond the horizon; use for confirmation, not blind entries.
Disclaimer
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
Best regards and happy trading
Chervolino
Turtle Donchian Screener — with signalsTurtle strategy for Pine screener — with signals for buy and sell (long positions).
Kalman Exponential SuperTrendThe Kalman Exponential SuperTrend is a new, smoother & superior version of the famous "SuperTrend". Using Kalman smoothing, a concept from the EMA (Exponential Moving Average), this script leverages the best out of each and combines it into a single indicator.
How does it work?
First, we need to calculate the Kalman smoothed source. This is a kind of complex calculation, so you need to study it if you want to know how it works precisely. It smooths the source of the SuperTrend, which helps us smooth the SuperTrend.
Then, we calculate "a" where:
n = user defined ATR length
a = 2/(n+1)
Now we calculate the ATR over "n" period. Classical calculation, nothing changed here.
Now we calculate the SuperTrend using the Kalman smoothed source & ATR where:
kalman = kalman smoothed source
ATR = Average True Range
m = Factor chosen by user.
Upper Band = kalman + ATR * m
Lower Band = kalman - ATR * m
Now we just smooth it a bit further using the "a" and a concept from the EMA.
u1 = Upper Band a bar ago
l1 = Lower Band a bar ago
u = Upper Band
l = Lower Band
Upper = u1 * (1-a) + u * a
Lower = l1 * (1-a) + u * a
When the classical (not Kalman) source crosses above the Upper, it indicates an uptrend. When it crosses below the Lower, it indicates a downtrend.
Methodology & Concepts
When I took a look at the classical SuperTrend => It was just far too slow, and if I made it faster it was noisy as hell. So I decided I would try to make up for it.
I tried the gaussian, bilateral filter, but then I tried kalman and that worked the best, so I added it. Now it was still too noisy and unconsistent, so I revisited my knowledge of concepts and picked the one from the EMA, and it kinda solved it.
In the core of the indicator, all it does is combine them in a really simple way, but if you go more deeply you see how it fits the puzzlé really well.
It is not about trying out random things´=> but about seeking what it is missing and trying to lessen its bad side.
That is the entire point of this indicator => Offer a unique approach to the SuperTrend type, that lessen the bad sides of it.
I also added different plotting types, this is so everyone can find their favorite
Enjoy Gs!
Simple VWAP + BandsSimple VWAP + Bands
A clean and customizable VWAP (Volume Weighted Average Price) indicator with standard deviation bands and RTH (Regular Trading Hours) session support.
Features:
- VWAP Line: Volume-weighted average price calculation
- Three Standard Deviation Bands: Configurable bands at 1σ, 2σ, and 3σ levels (above and below VWAP)
- RTH Session Support: Option to calculate VWAP only during regular trading hours
- Customizable Session Times: Configure your own trading session hours and timezone
- Clean Visualization: Line breaks between sessions prevent messy connections across non-trading periods
- Toggle Bands: Show/hide individual standard deviation bands as needed
Use Cases:
- Identify overbought/oversold conditions relative to volume-weighted price
- Track price deviation from VWAP during trading sessions
- Support and resistance levels based on standard deviations
- Mean reversion trading strategies
RBLR - GSK Vizag AP IndiaThis indicator identifies the Opening Range High (ORH) and Low (ORL) based on the first 15 minutes of the Indian equity market session (9:15 AM to 9:30 AM IST). It draws horizontal lines extending these levels until market close (3:30 PM IST) and generates visual signals for price breakouts above ORH or below ORL, as well as reversals back into the range.
Key features:
- **Range Calculation**: Captures the high and low during the opening period using real-time bar data.
- **Line Extension**: Lines are dynamically extended bar-by-bar within the session for clear visualization.
- **Signals**:
- Green triangle up: Crossover above ORH (potential bullish breakout).
- Red triangle down: Crossunder below ORL (potential bearish breakout).
- Yellow labels: Reversals from breakout levels back into the range.
- **Labels**: "RAM BAAN" marks the ORH (inspired by a precise arrow from the Ramayana), and "LAKSHMAN REKHA" marks the ORL (inspired by a protective boundary line from the same epic).
- **Customization**: Toggle signals on/off and select line styles (Dotted, Dashed, Solid, or Smoothed, with transparency for Smoothed).
The state-tracking logic prevents redundant signals by monitoring if price remains outside the range after a breakout. This helps users observe range-bound behavior or directional moves without built-in alerts. This indicator is particularly useful for day trading on longer intraday timeframes (e.g., 15-minute charts) to identify session-wide trends and avoid noise in shorter frames. For best results, apply on intraday timeframes on NSE/BSE symbols. Note that lines and labels are limited to the script's max counts to avoid performance issues on long histories.
**Disclaimer**: This indicator is for educational and informational purposes only and does not constitute financial, investment, or trading advice. Trading in financial markets involves significant risk of loss and is not suitable for all investors. Past performance is not indicative of future results. Users should conduct their own research, consider their financial situation, and consult with qualified professionals before making any investment decisions. The author and TradingView assume no liability for any losses incurred from its use.
EMA 9 + VWAP Bands Crossover With Buy Sell SignalsEMA 9 + VWAP Bands Crossover With Buy Sell Signals
Liquidity Stress Index (SOFR - IORB)How to use:
> +10 bps — TIGHT
−5 +10 bps — NEUTRAL
< −5 bps — LOOSE
PG ATM Strike Line with Call & Put PremiumsPine Script: ATM Strike Line with Call & Put Premiums (Simplified)This Pine Script for TradingView displays the At-The-Money (ATM) strike price, futures price, call/put premiums (time value), and two ratios—Premium Ratio (PR) and Volume Ratio (VR)—for a user-selected underlying asset (e.g., NIFTY, BANKNIFTY, or stocks). It helps traders gauge near-term market direction using options data.How the Script WorksInputs:Expiry: Select year (e.g., '25), month (01–12), day (01–31) for option expiry (e.g., '251028').
Timeframe: Choose data timeframe (e.g., Daily, 15-min).
Symbol: Auto-detects chart symbol or select from Indian indices/stocks.
Strike: Auto-ATM (based on futures) or manual strike input.
Interval: Auto (e.g., 100 for NIFTY) or custom strike interval.
Colors: Customizable for ATM line, labels (Futures Price, CPR, PPR, VR, PR).
Calculations:Futures Price (FP): Fetches front-month futures price (e.g., NSE:NIFTY1!).
ATM Strike: Rounds futures price to nearest strike interval.
Option Data: Retrieves Last Traded Price (LTP) and volume for ATM call/put options (e.g., NSE:NIFTY251028C24200).
Call Premium (CPR): Call LTP minus intrinsic value (max(0, FP - Strike)).
Put Premium (PPR): Put LTP minus intrinsic value (max(0, Strike - FP)).
Premium Ratio (PR): PPR / CPR.
Volume Ratio (VR): Put Volume / Call Volume.
Visuals:Draws ATM strike line on chart.
Displays labels: FP (futures price), CPR (call premium), PPR (put premium), VR, PR.
VR/PR labels: Red (≥ 1.25, bearish), Green (≤ 0.75, bullish), Gray (0.75–1.25, neutral).
Updates on last confirmed bar to avoid redraws.
Using PR and VR for Market DirectionPremium Ratio (PR):PR ≥ 1.25 (Red): High put premiums suggest bearish sentiment (expect price drop).
PR ≤ 0.75 (Green): High call premiums suggest bullish sentiment (expect price rise).
0.75 < PR < 1.25 (Gray): Neutral, no clear direction.
Use: High PR favors bearish trades (e.g., buy puts); low PR favors bullish trades (e.g., buy calls).
Volume Ratio (VR):VR ≥ 1.25 (Red): High put volume indicates bearish activity.
VR ≤ 0.75 (Green): High call volume indicates bullish activity.
0.75 < VR < 1.25 (Gray): Neutral trading activity.
Use: High VR suggests bearish moves; low VR suggests bullish moves.
Combined Signals:High PR & VR: Strong bearish signal; consider put buying or call selling.
Low PR & VR: Strong bullish signal; consider call buying or put selling.
Mixed/Neutral: Use price action or support/resistance for confirmation.
Tips:Combine with technical analysis (e.g., trends, levels).
Match timeframe to trading horizon (e.g., 15-min for intraday).
Monitor FP for context; check volatility or news for accuracy.
ExampleNIFTY: FP = 24,237.50, ATM = 24,200, CPR = 120.25, PPR = 180.50, PR = 1.50 (Red), VR = 1.30 (Red).
Insight: High PR/VR suggests bearish bias; consider bearish trades if price nears resistance.
Action: Buy puts or exit longs, confirm with price action.
Conclusion: This script provides a concise tool for options traders, showing ATM strike, premiums, and PR/VR ratios. High PR/VR (≥ 1.25) signals bearish sentiment, low PR/VR (≤ 0.75) signals bullish sentiment, and neutral (0.75–1.25) suggests indecision. Combine with technical analysis for robust trading decisions in the Indian options market.
Turtle/Donchian Screener — Recency & CloseAtBuyTurtle strategy with buy and sellsignals. Donchian channels. For Pine screener.
Current Weekly Open LineThis indicator is an indicator to make your weekly review.
It shows exactly where the last weekly open candle has been, so you don't have to search it manually.
Current Weekly Open LineVertical line on current weekly open.
To know exactly on every chart where the current weekly opening is, without having to do it manually.
Yield Curve RegimesCurrently we are seeing equities and all other risk assets rallying to new all time high. But when will this stop?
There are multiple risks/signals i am monitoring to stay at the right side of the macro trade. Macro is everything: “When you get the Big-Picture wrong you wont live long.”
So lets go through a major risk that could be the catalyst for the next deeper correction
Capital needs to begin to move BACK across the risk curve as the yield curve steepens. We don't know if the source of the the crash will be from bear steepening or bull steepening because its unclear if long end rates blowing out will be the source of the crash.
If the Fed continues to make the policy error of being overly accommodative at this high level of nominal GDP + Inflation risk, the long end of the curve will price this.
Simple: If the Fed is to lose the long end can move up to price the inflation risk, which could ultimately pull risk assets down.
We have not seen this yet because the last inflation prints came in flat, but I expect these to come in higher over the next 6 months.
This means watching long end rates and their potential drag on equities will be critical. We are not seeing this yet as the Russell is sitting at all time highs and capital continues to move into low quality factors.
Look where the long end is moving + the attribution analysis for the move.
→ Down growth risk
→ Up Inflation risk
+ look what the 2s10s & the 10s30 are pricing and how these changes in the curve connect to the current yield curve regimes.
You can get the Trading view Skript 100% free here
HoneG_BJVH 改良版v2ザオプションのワンタッチ取引向けのサブチャート用ツールver2です
旧版は無効です
This is version 2 of the subchart tool for one-touch trading on The Option.
The previous version is no longer valid.
Micro cycle0-Minute Quarter Cycle Indicator (Q90-Final)
This indicator plots vertical lines marking the four quarters (Q1,Q2,Q3,Q4) of a continuous 90-minute cycle.
It is designed for traders who utilize time-based cycles for market analysis and entry/exit timing.
So you can easy identify the cycles off the micro cycles Q1,Q2,Q3 and Q4
ATR Trailing Stop with Entry Date & First-Day MultiplierATR based trailing stop based on a X post of Aksel Kibar.
Corpus Bollinger BandsThis is a copy of the build-in indicator, but as addition, it shows the distance between upper and lower band in percentage.
LogNormalLibrary "LogNormal"
A collection of functions used to model skewed distributions as log-normal.
Prices are commonly modeled using log-normal distributions (ie. Black-Scholes) because they exhibit multiplicative changes with long tails; skewed exponential growth and high variance. This approach is particularly useful for understanding price behavior and estimating risk, assuming continuously compounding returns are normally distributed.
Because log space analysis is not as direct as using math.log(price) , this library extends the Error Functions library to make working with log-normally distributed data as simple as possible.
- - -
QUICK START
Import library into your project
Initialize model with a mean and standard deviation
Pass model params between methods to compute various properties
var LogNorm model = LN.init(arr.avg(), arr.stdev()) // Assumes the library is imported as LN
var mode = model.mode()
Outputs from the model can be adjusted to better fit the data.
var Quantile data = arr.quantiles()
var more_accurate_mode = mode.fit(model, data) // Fits value from model to data
Inputs to the model can also be adjusted to better fit the data.
datum = 123.45
model_equivalent_datum = datum.fit(data, model) // Fits value from data to the model
area_from_zero_to_datum = model.cdf(model_equivalent_datum)
- - -
TYPES
There are two requisite UDTs: LogNorm and Quantile . They are used to pass parameters between functions and are set automatically (see Type Management ).
LogNorm
Object for log space parameters and linear space quantiles .
Fields:
mu (float) : Log space mu ( µ ).
sigma (float) : Log space sigma ( σ ).
variance (float) : Log space variance ( σ² ).
quantiles (Quantile) : Linear space quantiles.
Quantile
Object for linear quantiles, most similar to a seven-number summary .
Fields:
Q0 (float) : Smallest Value
LW (float) : Lower Whisker Endpoint
LC (float) : Lower Whisker Crosshatch
Q1 (float) : First Quartile
Q2 (float) : Second Quartile
Q3 (float) : Third Quartile
UC (float) : Upper Whisker Crosshatch
UW (float) : Upper Whisker Endpoint
Q4 (float) : Largest Value
IQR (float) : Interquartile Range
MH (float) : Midhinge
TM (float) : Trimean
MR (float) : Mid-Range
- - -
TYPE MANAGEMENT
These functions reliably initialize and update the UDTs. Because parameterization is interdependent, avoid setting the LogNorm and Quantile fields directly .
init(mean, stdev, variance)
Initializes a LogNorm object.
Parameters:
mean (float) : Linearly measured mean.
stdev (float) : Linearly measured standard deviation.
variance (float) : Linearly measured variance.
Returns: LogNorm Object
set(ln, mean, stdev, variance)
Transforms linear measurements into log space parameters for a LogNorm object.
Parameters:
ln (LogNorm) : Object containing log space parameters.
mean (float) : Linearly measured mean.
stdev (float) : Linearly measured standard deviation.
variance (float) : Linearly measured variance.
Returns: LogNorm Object
quantiles(arr)
Gets empirical quantiles from an array of floats.
Parameters:
arr (array) : Float array object.
Returns: Quantile Object
- - -
DESCRIPTIVE STATISTICS
Using only the initialized LogNorm parameters, these functions compute a model's central tendency and standardized moments.
mean(ln)
Computes the linear mean from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
Returns: Between 0 and ∞
median(ln)
Computes the linear median from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
Returns: Between 0 and ∞
mode(ln)
Computes the linear mode from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
Returns: Between 0 and ∞
variance(ln)
Computes the linear variance from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
Returns: Between 0 and ∞
skewness(ln)
Computes the linear skewness from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
Returns: Between 0 and ∞
kurtosis(ln, excess)
Computes the linear kurtosis from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
excess (bool) : Excess Kurtosis (true) or regular Kurtosis (false).
Returns: Between 0 and ∞
hyper_skewness(ln)
Computes the linear hyper skewness from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
Returns: Between 0 and ∞
hyper_kurtosis(ln, excess)
Computes the linear hyper kurtosis from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
excess (bool) : Excess Hyper Kurtosis (true) or regular Hyper Kurtosis (false).
Returns: Between 0 and ∞
- - -
DISTRIBUTION FUNCTIONS
These wrap Gaussian functions to make working with model space more direct. Because they are contained within a log-normal library, they describe estimations relative to a log-normal curve, even though they fundamentally measure a Gaussian curve.
pdf(ln, x, empirical_quantiles)
A Probability Density Function estimates the probability density . For clarity, density is not a probability .
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate for which a density will be estimated.
empirical_quantiles (Quantile) : Quantiles as observed in the data (optional).
Returns: Between 0 and ∞
cdf(ln, x, precise)
A Cumulative Distribution Function estimates the area under a Log-Normal curve between Zero and a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and 1
ccdf(ln, x, precise)
A Complementary Cumulative Distribution Function estimates the area under a Log-Normal curve between a linear X coordinate and Infinity.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and 1
cdfinv(ln, a, precise)
An Inverse Cumulative Distribution Function reverses the Log-Normal cdf() by estimating the linear X coordinate from an area.
Parameters:
ln (LogNorm) : Object of log space parameters.
a (float) : Normalized area .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and ∞
ccdfinv(ln, a, precise)
An Inverse Complementary Cumulative Distribution Function reverses the Log-Normal ccdf() by estimating the linear X coordinate from an area.
Parameters:
ln (LogNorm) : Object of log space parameters.
a (float) : Normalized area .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and ∞
cdfab(ln, x1, x2, precise)
A Cumulative Distribution Function from A to B estimates the area under a Log-Normal curve between two linear X coordinates (A and B).
Parameters:
ln (LogNorm) : Object of log space parameters.
x1 (float) : First linear X coordinate .
x2 (float) : Second linear X coordinate .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and 1
ott(ln, x, precise)
A One-Tailed Test transforms a linear X coordinate into an absolute Z Score before estimating the area under a Log-Normal curve between Z and Infinity.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and 0.5
ttt(ln, x, precise)
A Two-Tailed Test transforms a linear X coordinate into symmetrical ± Z Scores before estimating the area under a Log-Normal curve from Zero to -Z, and +Z to Infinity.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and 1
ottinv(ln, a, precise)
An Inverse One-Tailed Test reverses the Log-Normal ott() by estimating a linear X coordinate for the right tail from an area.
Parameters:
ln (LogNorm) : Object of log space parameters.
a (float) : Half a normalized area .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and ∞
tttinv(ln, a, precise)
An Inverse Two-Tailed Test reverses the Log-Normal ttt() by estimating two linear X coordinates from an area.
Parameters:
ln (LogNorm) : Object of log space parameters.
a (float) : Normalized area .
precise (bool) : Double precision (true) or single precision (false).
Returns: Linear space tuple :
- - -
UNCERTAINTY
Model-based measures of uncertainty, information, and risk.
sterr(sample_size, fisher_info)
The standard error of a sample statistic.
Parameters:
sample_size (float) : Number of observations.
fisher_info (float) : Fisher information.
Returns: Between 0 and ∞
surprisal(p, base)
Quantifies the information content of a single event.
Parameters:
p (float) : Probability of the event .
base (float) : Logarithmic base (optional).
Returns: Between 0 and ∞
entropy(ln, base)
Computes the differential entropy (average surprisal).
Parameters:
ln (LogNorm) : Object of log space parameters.
base (float) : Logarithmic base (optional).
Returns: Between 0 and ∞
perplexity(ln, base)
Computes the average number of distinguishable outcomes from the entropy.
Parameters:
ln (LogNorm)
base (float) : Logarithmic base used for Entropy (optional).
Returns: Between 0 and ∞
value_at_risk(ln, p, precise)
Estimates a risk threshold under normal market conditions for a given confidence level.
Parameters:
ln (LogNorm) : Object of log space parameters.
p (float) : Probability threshold, aka. the confidence level .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and ∞
value_at_risk_inv(ln, value_at_risk, precise)
Reverses the value_at_risk() by estimating the confidence level from the risk threshold.
Parameters:
ln (LogNorm) : Object of log space parameters.
value_at_risk (float) : Value at Risk.
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and 1
conditional_value_at_risk(ln, p, precise)
Estimates the average loss beyond a confidence level, aka. expected shortfall.
Parameters:
ln (LogNorm) : Object of log space parameters.
p (float) : Probability threshold, aka. the confidence level .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and ∞
conditional_value_at_risk_inv(ln, conditional_value_at_risk, precise)
Reverses the conditional_value_at_risk() by estimating the confidence level of an average loss.
Parameters:
ln (LogNorm) : Object of log space parameters.
conditional_value_at_risk (float) : Conditional Value at Risk.
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and 1
partial_expectation(ln, x, precise)
Estimates the partial expectation of a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and µ
partial_expectation_inv(ln, partial_expectation, precise)
Reverses the partial_expectation() by estimating a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
partial_expectation (float) : Partial Expectation .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and ∞
conditional_expectation(ln, x, precise)
Estimates the conditional expectation of a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between X and ∞
conditional_expectation_inv(ln, conditional_expectation, precise)
Reverses the conditional_expectation by estimating a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
conditional_expectation (float) : Conditional Expectation .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and ∞
fisher(ln, log)
Computes the Fisher Information Matrix for the distribution, not a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
log (bool) : Sets if the matrix should be in log (true) or linear (false) space.
Returns: FIM for the distribution
fisher(ln, x, log)
Computes the Fisher Information Matrix for a linear X coordinate, not the distribution itself.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
log (bool) : Sets if the matrix should be in log (true) or linear (false) space.
Returns: FIM for the linear X coordinate
confidence_interval(ln, x, sample_size, confidence, precise)
Estimates a confidence interval for a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
sample_size (float) : Number of observations.
confidence (float) : Confidence level .
precise (bool) : Double precision (true) or single precision (false).
Returns: CI for the linear X coordinate
- - -
CURVE FITTING
An overloaded function that helps transform values between spaces. The primary function uses quantiles, and the overloads wrap the primary function to make working with LogNorm more direct.
fit(x, a, b)
Transforms X coordinate between spaces A and B.
Parameters:
x (float) : Linear X coordinate from space A .
a (LogNorm | Quantile | array) : LogNorm, Quantile, or float array.
b (LogNorm | Quantile | array) : LogNorm, Quantile, or float array.
Returns: Adjusted X coordinate
- - -
EXPORTED HELPERS
Small utilities to simplify extensibility.
z_score(ln, x)
Converts a linear X coordinate into a Z Score.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate.
Returns: Between -∞ and +∞
x_coord(ln, z)
Converts a Z Score into a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
z (float) : Standard normal Z Score.
Returns: Between 0 and ∞
iget(arr, index)
Gets an interpolated value of a pseudo -element (fictional element between real array elements). Useful for quantile mapping.
Parameters:
arr (array) : Float array object.
index (float) : Index of the pseudo element.
Returns: Interpolated value of the arrays pseudo element.






















