Oil ETF VolumeDirexxion Daily has both 'bear' and 'bull' oil ETFs.  This tracks the volume in both combined.  It also tracks them individually: the bear ETF is the red line, and bull the green.  
NOTE: the color of the volume bars is determined by whatever ticker you're currently looking at, and whether current close is gt/lt previous close.  It is intended to be used while looking at the USOIL chart.  The colors will be inverted if you're looking at the 'bear' ETF! as the higher closes will actually mean price is going down :D 
"etf当天可以买卖吗"に関するスクリプトを検索
Leveraged ETF Volume Ratio3x/2x Long/short etf pairs for popular tickers, including TSLA, QQQ, META, PLTR... Extreme values indicate bullish/bearish sentiment.
Standardized Leveraged ETF Fund of FlowsThis indicator tracks and standardizes the 3-month fund flows of major leveraged ETFs across different asset classes, including equities, gold, and bonds.
The fund flows are summed over a 3-month period (63 trading days) and then standardized using a 500-day rolling mean and standard deviation.
The resulting normalized fund flow values are plotted in three distinct colors:
Blue for Equities Fund Flows
Yellow for Gold Fund Flows
Green for Bond Fund Flows
CE - 42MACRO Fixed Income and Macro This is Part 2 of 2 from the 42MACRO Recreation Series 
However, there will be a bonus Indicator coming soon!
The CE - 42MACRO Fixed Income and Macro Table is a next level Macroeconomic and market analysis indicator.
It aims to provide a probabilistic insight into the market realized GRID Macro regimes, 
track a multiplex of important Assets, Indices, Bonds and ETF's to derive extra market insights by showing the most important aggregates and their performance over multiple timeframes... and what that might mean for the whole market direction. 
For traders and especially investors, the unique functionalities will be of high value.
 
Quick guide on how to use it:
 docs.google.com 
  
 WARNING   
By the nature of the macro regimes, the outcomes are more accurate over longer Chart Timeframes (Week to Months).   
However, it is also a valuable tool to form an advanced,   
market realized, short to medium term bias.  
 NOTE   
This Indicator is intended to be used alongside the 1nd part "CE - 42MACRO Equity Factor"   
for a more wholistic approach and higher accuracy.  
  
 Methodology:   
The Equity Factor Table tracks specifically chosen Assets to identify their performance and add the combined performances together to visualize 42MACRO's GRID Equity Model.  
For this it uses the below Assets:  
   
 Convertibles (  AMEX:CWB  )
 Leveraged Loans (  AMEX:BKLN  )
 High Yield Credit (  AMEX:HYG  )
 Preferreds (  NASDAQ:PFF  )
 Emerging Market US$ Bonds (  NASDAQ:EMB  )
 Long Bond (  NASDAQ:TLT  )
 5-10yr Treasurys (  NASDAQ:IEF  )
 5-10yr TIPS (  AMEX:TIP  )
 0-5yr TIPS (  AMEX:STIP  )
 EM Local Currency Bonds (  AMEX:EMLC  )
 BDCs (  AMEX:BIZD  )
 Barclays Agg (  AMEX:AGG  )
 Investment Grade Credit (  AMEX:LQD  )
 MBS (  NASDAQ:MBB  )
 1-3yr Treasurys (  NASDAQ:SHY  )
 Bitcoin (  AMEX:BITO  )
 Industrial Metals (  AMEX:DBB  )
 Commodities (  AMEX:DBC  )
 Gold (  AMEX:GLD  )
 Equity Volatility (  AMEX:VIXM  )
 Interest Rate Volatility (  AMEX:PFIX  )
 Energy (  AMEX:USO  )
 Precious Metals (  AMEX:DBP  )
 Agriculture (  AMEX:DBA  )
 US Dollar (  AMEX:UUP  )
 Inverse US Dollar (  AMEX:UDN  )
   
 Functionalities:    
  Fixed Income and Macro Table
  Shows relative market Asset performance  
  Comes with different Calculation options like RoC, 
Sharpe ratio, Sortino ratio, Omega ratio and Normalization
  Allows for advanced market (health) performance
  Provides the calculated, realized GRID market regimes
  Informs about "Risk ON" and "Risk OFF" market states  
   
  
 Visuals - for your best experience only use one (+ BarColoring) at a time:   
You can visualize all important metrics:
- GRID regimes of the currently chosen calculation type
- Risk On/Risk Off with background colouring and additional +1/-1 values
- a smoother GRID model 
- a smoother Risk On/ Risk Off metric
- Barcoloring for enabled metric of the above
 If you have more suggestions, please write me 
 Fixed Income and Macro:   
The visualisation of the relative performance of the different assets provides valuable information about the current market environment and the actual market performance.  
It furthermore makes it possible to obtain a deeper understanding of how the interconnected market works and makes it simple to identify the actual market direction,
thus also providing all the information to derive overall market health, market strength or weakness.  
  
 Utility:   
The Fixed Income and Macro Table is divided in 4 Columns which are the GRID regimes:  
  
 Economic Growth:   
   
 Goldilocks
 Reflation  
   
  
 Economic Contraction:   
   
 Inflation
 Deflation  
   
  
 Top 5 Fixed Income/ Macro Factors:   
Are the values green for a specific Column?  
If so then the market reflects the corresponding GRID behavior.  
  
 Bottom 5 Fixed Income/ Macro Factors:   
Are the values red for a specific Column?  
If so then the market reflects the corresponding GRID behavior.  
  
So if we have Goldilocks as current regime we would see green values in the Top 5 Goldilocks Cells and red values in the Bottom 5 Goldilocks Cells.  
You will find that Reflation will look similar, as it is also a sign of Economic Growth.  
Same is the case for the two Contraction regimes.  
  
******
This Indicator again is based to a majority on 42MACRO's models.  
I only brought them into TV and added things on top of it.  
  
If you have questions or need a more in-depth guide DM me.  
  
GM
RSI - S&P Sector ETFsThe script displays RSI of each S&P SPDR Sector ETF
 
 XLB - Materials
 XLC - Communications
 XLE - Energy
 XLF - Financials
 XLI - Industrials
 XLK - Technology
 XLP - Consumer Staples
 XLRE - Real Estate
 XLU - Utilities
 XLV - Healthcare
 XLY - Consumer Discretionary
 
It is meant to identify changes in sector rotation, compare oversold/overbought signals of each sector, and/or any price momentum trading strategy applicable to a trader.
InfoPanel - SeasonalityThis panel will show which is the best month to buy a stock, index or ETF or even a cryptocurrency in the past 5 years.
Script to use only with MONTHLY timeframe.
Thanks to: RicardoSantos for his hard work.
Please use comment section for any feedback. 
5 Moving Averages (Fully Customizable)I couldn't find any indicators that you could fully customize multiple moving average lines, so I made one. 
You can change the color, line type, thickness, length, and opacity. Also make a custom color if you want.
You can make them SMA, EMA, WMA, HMA, VWMA. 
Hope you enjoy! 
Composite Buy/Sell Score [-100 to +100] by LMComposite Buy/Sell Score   (Stabilized + Sensitivity) by LM
Description:
This indicator calculates a composite trend strength score ranging from -100 to +100 by combining multiple popular technical indicators into a single, smoothed metric. It is designed to give traders a clear view of bullish and bearish trends, while filtering out short-term noise.
The score incorporates signals from:
PPO (Percentage Price Oscillator) – measures momentum via the difference between fast and slow EMAs.
ADX (Average Directional Index) – detects trend strength.
RSI (Relative Strength Index) – identifies short-term momentum swings.
Stochastic RSI – measures RSI momentum and speed of change.
MACD (Moving Average Convergence Divergence) – detects momentum shifts using EMA crossovers.
Williams %R – highlights overbought/oversold conditions.
Each component is weighted, smoothed, and optionally confirmed across a configurable number of bars, producing a stabilized composite score that reacts more reliably to significant trend changes.
Key Features:
Smoothed Composite Score
The final score is smoothed using an EMA to reduce volatility and emphasize meaningful trends.
A Sensitivity Multiplier allows traders to exaggerate the score for stronger trend signals or dampen it for quieter markets.
Customizable Inputs
You can adjust each indicator’s parameters, smoothing lengths, and confirm bars to suit your preferred timeframe and trading style.
The sensitivity multiplier allows fine-tuning the responsiveness of the trend line without changing underlying indicator calculations.
Visual Representation
Score Line: Green for positive (bullish) trends, red for negative (bearish) trends, gray near neutral.
Reference Lines:
0 = neutral
+100 = maximum bullish
-100 = maximum bearish
Adaptive Background: Optionally highlights the background intensity proportional to trend strength. Strong green for bullish trends, strong red for bearish trends.
Multi-Indicator Integration
Combines momentum, trend, and overbought/oversold signals into a single metric.
Helps identify clear entry/exit trends while avoiding whipsaw noise common in individual indicators.
Recommended Use:
Trend Identification: Look for sustained movement above 0 for bullish trends and below 0 for bearish trends.
Exaggerated Trends: Use the Sensitivity Multiplier to emphasize strong trends.
Filtering Noise: The smoothed score and confirmBars settings help reduce false signals from minor price fluctuations.
Inputs Overview:
Input	Purpose
PPO Fast EMA / Slow EMA / Signal	Controls PPO momentum sensitivity
ADX Length / Threshold	Detects trend strength
RSI Length / Overbought / Oversold	Measures short-term momentum
Stoch RSI Length / %K / %D	Measures speed of RSI changes
MACD Fast / Slow / Signal	Measures momentum crossover
Williams %R Length	Detects overbought/oversold conditions
Final Score Smoothing Length	EMA smoothing for final composite score
Confirm Bars for Each Signal	Number of bars used to confirm individual indicator signals
Sensitivity Multiplier	Scales the final composite score for exaggerated trend response
Highlight Background by Trend Strength	Enables adaptive background coloring
This indicator is suitable for traders looking for a single, clear trend metric derived from multiple indicators. It can be applied to any timeframe and can help identify both strong and emerging trends in the market.
Ripster Clouds (EMA + MTF)v6🧠 Purpose
This indicator combines Ripster EMA Clouds and Multi-Timeframe (MTF) EMA Clouds into one script.
It allows you to visualize short vs long exponential (or simple) moving averages as colored “clouds” to identify trend direction and momentum — across both your current timeframe and a higher timeframe (e.g., daily).
⚙️ Main Features
1. EMA Clouds (Local Timeframe)
Up to 5 separate EMA/SMA cloud sets (8/9, 5/12, 34/50, 72/89, 180/200 by default).
Each can be individually enabled/disabled in the settings.
MA type toggle → Choose between EMA and SMA.
Optional line display toggle for showing the short and long MA lines.
Color-coded trend clouds:
Greenish tones = bullish (short > long)
Reddish tones = bearish (short < long)
Configurable leading offset and global offset for alignment.
2. MTF Clouds (Higher Timeframe)
Two sets of higher timeframe EMA clouds (default: 50/55 and 20/21).
Uses request.security() to pull EMA data from a selected higher timeframe (default = Daily).
Optional line visibility toggle (Display Lines).
Blue and teal semi-transparent fills to distinguish from local clouds.
Each MTF cloud can be toggled independently.
3. Unified Controls
Master toggles:
✅ Show EMA Clouds
✅ Show MTF Clouds
Transparent cloud fills with dynamically changing colors based on EMA crossovers and slope.
No local-scope plot() or fill() calls — fully compliant with Pine v6 rules.
🎨 Color Logic
Each EMA cloud uses a unique color pair (5 total).
Cloud color changes dynamically based on whether the short EMA is above or below the long EMA.
Line color changes with slope:
Olive = EMA rising
Maroon = EMA falling
📊 Technical Structure
Written in Pine Script v6.
All plot() and fill() calls are at global scope to prevent compilation errors.
Uses helper functions only for math/color logic.
Performance-optimized for TradingView’s rendering limits.
🧩 Quick Setup in TradingView
Paste the script into the Pine Editor.
Add to chart.
In settings:
Toggle on/off any EMA or MTF clouds.
Adjust timeframe (Resolution), line visibility, or offsets.
Choose EMA or SMA as the base calculation.
✅ Result
You now have one unified, customizable Ripster EMA + MTF Cloud indicator, stable in Pine v6, with complete flexibility to toggle, style, and analyze multiple timeframe trends on a single chart.
Risk Position Sizer (Entry=Close, Stop=Daily Low)This is for trading stocks/shares. Its main goal is to help you gauge how big or how small of a position you should add based on your account size. 
Delta Volume MA (3-Min Tuned v5 - Low-Lag Fast/Slow)This indicator provides a low-lag, fast/slow cumulative delta (CVD) line designed specifically for 3-minute scalping and short-term intraday trading. It measures buy vs. sell volume imbalance and smooths it with a T3 Tilson moving average for precision while minimizing lag.
Rolling Correlation vs Another Symbol (SPY Default)This indicator visualizes the rolling correlation between the current chart symbol and another selected asset, helping traders understand how closely the two move together over time.
It calculates the Pearson correlation coefficient over a user-defined period (default 22 bars) and plots it as a color-coded line:
	•	Green line → positive correlation (move in the same direction)
	•	Red line → negative correlation (move in opposite directions)
	•	A gray dashed line marks the zero level (no correlation).
The background highlights periods of strong relationship:
	•	Light green when correlation > +0.7 (strong positive)
	•	Light red when correlation < –0.7 (strong negative)
Use this tool to quickly spot diversification opportunities, confirm hedges, or understand how assets interact during different market regimes.
Ultimate Oscillator (ULTOSC)The Ultimate Oscillator (ULTOSC) is a technical momentum indicator developed by Larry Williams that combines three different time periods to reduce the volatility and false signals common in single-period oscillators. By using a weighted average of three Stochastic-like calculations across short, medium, and long-term periods, the Ultimate Oscillator provides a more comprehensive view of market momentum while maintaining sensitivity to price changes.
The indicator addresses the common problem of oscillators being either too sensitive (generating many false signals) or too slow (missing opportunities). By incorporating multiple timeframes with decreasing weights for longer periods, ULTOSC attempts to capture both short-term momentum shifts and longer-term trend strength, making it particularly valuable for identifying divergences and potential reversal points.
## Core Concepts
* **Multi-timeframe analysis:** Combines three different periods (typically 7, 14, 28) to capture various momentum cycles
* **Weighted averaging:** Assigns higher weights to shorter periods for responsiveness while including longer periods for stability
* **Buying pressure focus:** Measures the relationship between closing price and the true range rather than just high-low range
* **Divergence detection:** Particularly effective at identifying momentum divergences that precede price reversals
* **Normalized scale:** Oscillates between 0 and 100, with clear overbought/oversold levels
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|---------------|
| Fast Period | 7 | Short-term momentum calculation | Lower (5-6) for more sensitivity, higher (9-12) for smoother signals |
| Medium Period | 14 | Medium-term momentum calculation | Adjust based on typical swing duration in the market |
| Slow Period | 28 | Long-term momentum calculation | Higher values (35-42) for longer-term position trading |
| Fast Weight | 4.0 | Weight applied to fast period | Higher weight increases short-term sensitivity |
| Medium Weight | 2.0 | Weight applied to medium period | Adjust to balance medium-term influence |
| Slow Weight | 1.0 | Weight applied to slow period | Usually kept at 1.0 as the baseline weight |
**Pro Tip:** The classic 7/14/28 periods with 4/2/1 weights work well for most markets, but consider using 5/10/20 with adjusted weights for faster markets or 14/28/56 for longer-term analysis.
## Calculation and Mathematical Foundation
**Simplified explanation:**
The Ultimate Oscillator calculates three separate "buying pressure" ratios using different time periods, then combines them using weighted averaging. Buying pressure is defined as the close minus the true low, divided by the true range.
**Technical formula:**
```
BP = Close - Min(Low, Previous Close)
TR = Max(High, Previous Close) - Min(Low, Previous Close)
BP_Sum_Fast = Sum(BP, Fast Period)
TR_Sum_Fast = Sum(TR, Fast Period)
Raw_Fast = 100 × (BP_Sum_Fast / TR_Sum_Fast)
BP_Sum_Medium = Sum(BP, Medium Period)
TR_Sum_Medium = Sum(TR, Medium Period)
Raw_Medium = 100 × (BP_Sum_Medium / TR_Sum_Medium)
BP_Sum_Slow = Sum(BP, Slow Period)
TR_Sum_Slow = Sum(TR, Slow Period)
Raw_Slow = 100 × (BP_Sum_Slow / TR_Sum_Slow)
ULTOSC = 100 ×   / (Fast_Weight + Medium_Weight + Slow_Weight)
```
Where:
- BP = Buying Pressure
- TR = True Range
- Fast Period = 7, Medium Period = 14, Slow Period = 28 (defaults)
- Fast Weight = 4, Medium Weight = 2, Slow Weight = 1 (defaults)
> 🔍 **Technical Note:** The implementation uses efficient circular buffers for all three period calculations, maintaining O(1) time complexity per bar. The algorithm properly handles true range calculations including gaps and ensures accurate buying pressure measurements across all timeframes.
## Interpretation Details
ULTOSC provides several analytical perspectives:
* **Overbought/Oversold conditions:** Values above 70 suggest overbought conditions, below 30 suggest oversold conditions
* **Momentum direction:** Rising ULTOSC indicates increasing buying pressure, falling indicates increasing selling pressure
* **Divergence analysis:** Divergences between ULTOSC and price often precede significant reversals
* **Trend confirmation:** ULTOSC direction can confirm or question the prevailing price trend
* **Signal quality:** Extreme readings (>80 or <20) indicate strong momentum that may be unsustainable
* **Multiple timeframe consensus:** When all three underlying periods agree, signals are typically more reliable
## Trading Applications
**Primary Uses:**
- **Divergence trading:** Identify when momentum diverges from price for reversal signals
- **Overbought/oversold identification:** Find potential entry/exit points at extreme levels
- **Trend confirmation:** Validate breakouts and trend continuations
- **Momentum analysis:** Assess the strength of current price movements
**Advanced Strategies:**
- **Multi-divergence confirmation:** Look for divergences across multiple timeframes
- **Momentum breakouts:** Trade when ULTOSC breaks above/below key levels with volume
- **Swing trading entries:** Use oversold/overbought levels for swing position entries
- **Trend strength assessment:** Evaluate trend quality using momentum consistency
## Signal Combinations
**Strong Bullish Signals:**
- ULTOSC rises from oversold territory (<30) with positive price divergence
- ULTOSC breaks above 50 after forming a base near 30
- All three underlying periods show increasing buying pressure
**Strong Bearish Signals:**
- ULTOSC falls from overbought territory (>70) with negative price divergence
- ULTOSC breaks below 50 after forming a top near 70
- All three underlying periods show decreasing buying pressure
**Divergence Signals:**
- **Bullish divergence:** Price makes lower lows while ULTOSC makes higher lows
- **Bearish divergence:** Price makes higher highs while ULTOSC makes lower highs
- **Hidden bullish divergence:** Price makes higher lows while ULTOSC makes lower lows (trend continuation)
- **Hidden bearish divergence:** Price makes lower highs while ULTOSC makes higher highs (trend continuation)
## Comparison with Related Oscillators
| Indicator | Periods | Focus | Best Use Case |
|-----------|---------|-------|---------------|
| **Ultimate Oscillator** | 3 periods | Buying pressure | Divergence detection |
| **Stochastic** | 1-2 periods | Price position | Overbought/oversold |
| **RSI** | 1 period | Price momentum | Momentum analysis |
| **Williams %R** | 1 period | Price position | Short-term signals |
## Advanced Configurations
**Fast Trading Setup:**
- Fast: 5, Medium: 10, Slow: 20
- Weights: 4/2/1, Thresholds: 75/25
**Standard Setup:**
- Fast: 7, Medium: 14, Slow: 28
- Weights: 4/2/1, Thresholds: 70/30
**Conservative Setup:**
- Fast: 14, Medium: 28, Slow: 56
- Weights: 3/2/1, Thresholds: 65/35
**Divergence Focused:**
- Fast: 7, Medium: 14, Slow: 28
- Weights: 2/2/2, Thresholds: 70/30
## Market-Specific Adjustments
**Volatile Markets:**
- Use longer periods (10/20/40) to reduce noise
- Consider higher threshold levels (75/25)
- Focus on extreme readings for signal quality
**Trending Markets:**
- Emphasize divergence analysis over absolute levels
- Look for momentum confirmation rather than reversal signals
- Use hidden divergences for trend continuation
**Range-Bound Markets:**
- Standard overbought/oversold levels work well
- Trade reversals from extreme levels
- Combine with support/resistance analysis
## Limitations and Considerations
* **Lagging component:** Contains inherent lag due to multiple moving average calculations
* **Complex calculation:** More computationally intensive than single-period oscillators
* **Parameter sensitivity:** Performance varies significantly with different period/weight combinations
* **Market dependency:** Most effective in trending markets with clear momentum patterns
* **False divergences:** Not all divergences lead to significant price reversals
* **Whipsaw potential:** Can generate conflicting signals in choppy markets
## Best Practices
**Effective Usage:**
- Focus on divergences rather than absolute overbought/oversold levels
- Combine with trend analysis for context
- Use multiple timeframe analysis for confirmation
- Pay attention to the speed of momentum changes
**Common Mistakes:**
- Over-relying on overbought/oversold levels in strong trends
- Ignoring the underlying trend direction
- Using inappropriate period settings for the market being analyzed
- Trading every divergence without additional confirmation
**Signal Enhancement:**
- Combine with volume analysis for confirmation
- Use price action context (support/resistance levels)
- Consider market volatility when setting thresholds
- Look for convergence across multiple momentum indicators
## Historical Context and Development
The Ultimate Oscillator was developed by Larry Williams and introduced in his 1985 article "The Ultimate Oscillator" in Technical Analysis of Stocks and Commodities magazine. Williams designed it to address the limitations of single-period oscillators by:
- Reducing false signals through multi-timeframe analysis
- Maintaining sensitivity to short-term momentum changes
- Providing more reliable divergence signals
- Creating a more robust momentum measurement tool
The indicator has become a standard tool in technical analysis, particularly valued for its divergence detection capabilities and its balanced approach to momentum measurement.
## References
* Williams, L. R. (1985). The Ultimate Oscillator. Technical Analysis of Stocks and Commodities, 3(4).
* Williams, L. R. (1999). Long-Term Secrets to Short-Term Trading. Wiley Trading.
Standardization (Z-score)Standardization, often referred to as Z-score normalization, is a data preprocessing technique that rescales data to have a mean of 0 and a standard deviation of 1. The resulting values, known as Z-scores, indicate how many standard deviations an individual data point is from the mean of the dataset (or a rolling sample of it).
This indicator calculates and plots the Z-score for a given input series over a specified lookback period. It is a fundamental tool for statistical analysis, outlier detection, and preparing data for certain machine learning algorithms.
## Core Concepts
*   **Standardization:** The process of transforming data to fit a standard normal distribution (or more generally, to have a mean of 0 and standard deviation of 1).
*   **Z-score (Standard Score):** A dimensionless quantity that represents the number of standard deviations by which a data point deviates from the mean of its sample.
    The formula for a Z-score is:
    `Z = (x - μ) / σ`
    Where:
    *   `x` is the individual data point (e.g., current value of the source series).
    *   `μ` (mu) is the mean of the sample (calculated over the lookback period).
    *   `σ` (sigma) is the standard deviation of the sample (calculated over the lookback period).
*   **Mean (μ):** The average value of the data points in the sample.
*   **Standard Deviation (σ):** A measure of the amount of variation or dispersion of a set of values. A low standard deviation indicates that the values tend to be close to the mean, while a high standard deviation indicates that the values are spread out over a wider range.
## Common Settings and Parameters
| Parameter       | Type         | Default | Function                                                                                                | When to Adjust                                                                                                                                                              |
| :-------------- | :----------- | :------ | :------------------------------------------------------------------------------------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Source          | series float | close   | The input data series (e.g., price, volume, indicator values).                                          | Choose the series you want to standardize.                                                                                                                                  |
| Lookback Period | int          | 20      | The number of bars (sample size) used for calculating the mean (μ) and standard deviation (σ). Min 2.   | A larger period provides more stable estimates of μ and σ but will be less responsive to recent changes. A shorter period is more reactive. `minval` is 2 because `ta.stdev` requires it. |
**Pro Tip:** Z-scores are excellent for identifying anomalies or extreme values. For instance, applying Standardization to trading volume can help quickly spot days with unusually high or low activity relative to the recent norm (e.g., Z-score > 2 or < -2).
## Calculation and Mathematical Foundation
The Z-score is calculated for each bar as follows, using a rolling window defined by the `Lookback Period`:
1.  **Calculate Mean (μ):** The simple moving average (`ta.sma`) of the `Source` data over the specified `Lookback Period` is calculated. This serves as the sample mean `μ`.
    `μ = ta.sma(Source, Lookback Period)`
2.  **Calculate Standard Deviation (σ):** The standard deviation (`ta.stdev`) of the `Source` data over the same `Lookback Period` is calculated. This serves as the sample standard deviation `σ`.
    `σ = ta.stdev(Source, Lookback Period)`
3.  **Calculate Z-score:**
    *   If `σ > 0`: The Z-score is calculated using the formula:
        `Z = (Current Source Value - μ) / σ`
    *   If `σ = 0`: This implies all values in the lookback window are identical (and equal to the mean). In this case, the Z-score is defined as 0, as the current source value is also equal to the mean.
    *   If `σ` is `na` (e.g., insufficient data in the lookback period), the Z-score is `na`.
> 🔍 **Technical Note:**
> *   The `Lookback Period` must be at least 2 for `ta.stdev` to compute a valid standard deviation.
> *   The Z-score calculation uses the sample mean and sample standard deviation from the rolling lookback window.
## Interpreting the Z-score
*   **Magnitude and Sign:**
    *   A Z-score of **0** means the data point is identical to the sample mean.
    *   A **positive Z-score** indicates the data point is above the sample mean. For example, Z = 1 means the point is 1 standard deviation above the mean.
    *   A **negative Z-score** indicates the data point is below the sample mean. For example, Z = -1 means the point is 1 standard deviation below the mean.
*   **Typical Range:** For data that is approximately normally distributed (bell-shaped curve):
    *   About 68% of Z-scores fall between -1 and +1.
    *   About 95% of Z-scores fall between -2 and +2.
    *   About 99.7% of Z-scores fall between -3 and +3.
*   **Outlier Detection:** Z-scores significantly outside the -2 to +2 range, and especially outside -3 to +3, are often considered outliers or extreme values relative to the recent historical data in the lookback window.
*   **Volatility Indication:** When applied to price, large absolute Z-scores can indicate moments of high volatility or significant deviation from the recent price trend.
The indicator plots horizontal lines at ±1, ±2, and ±3 standard deviations to help visualize these common thresholds.
## Common Applications
1.  **Outlier Detection:** Identifying data points that are unusual or extreme compared to the rest of the sample. This is a primary use in financial markets for spotting abnormal price moves, volume spikes, etc.
2.  **Comparative Analysis:** Allows for comparison of scores from different distributions that might have different means and standard deviations. For example, comparing the Z-score of returns for two different assets.
3.  **Feature Scaling in Machine Learning:** Standardizing features to have a mean of 0 and standard deviation of 1 is a common preprocessing step for many machine learning algorithms (e.g., SVMs, logistic regression, neural networks) to improve performance and convergence.
4.  **Creating Normalized Oscillators:** The Z-score itself can be used as a bounded (though not strictly between -1 and +1) oscillator, indicating how far the current price has deviated from its moving average in terms of standard deviations.
5.  **Statistical Process Control:** Used in quality control charts to monitor if a process is within expected statistical limits.
## Limitations and Considerations
*   **Assumption of Normality for Probabilistic Interpretation:** While Z-scores can always be calculated, the probabilistic interpretations (e.g., "68% of data within ±1σ") strictly apply to normally distributed data. Financial data is often not perfectly normal (e.g., it can have fat tails).
*   **Sensitivity of Mean and Standard Deviation to Outliers:** The sample mean (μ) and standard deviation (σ) used in the Z-score calculation can themselves be influenced by extreme outliers within the lookback period. This can sometimes mask or exaggerate the Z-score of other points.
*   **Choice of Lookback Period:** The Z-score is highly dependent on the `Lookback Period`. A short period makes it very sensitive to recent fluctuations, while a long period makes it smoother and less responsive. The appropriate period depends on the analytical goal.
*   **Stationarity:** For time series data, Z-scores are calculated based on a rolling window. This implicitly assumes some level of local stationarity (i.e., the mean and standard deviation are relatively stable within the window).
Triangular Moving Average (TRIMA)The Triangular Moving Average (TRIMA) is a technical indicator that applies a triangular weighting scheme to price data, providing enhanced smoothing compared to simpler moving averages. Originating in the early 1970s as technical analysts sought more effective noise filtering methods, the TRIMA was first popularized through the work of market technician Arthur Merrill. Its formal mathematical properties were established in the 1980s, and the indicator gained widespread adoption in the 1990s as computerized charting became standard. TRIMA effectively filters out market noise while maintaining important trends through its unique center-weighted calculation method.
## Core Concepts
* **Double-smoothing process:** TRIMA can be viewed as applying a simple moving average twice, creating more effective noise filtering
* **Triangular weighting:** Uses a symmetrical weight distribution that emphasizes central data points and reduces emphasis toward both ends
* **Constant-time implementation:** Two $O(1)$ SMA passes with circular buffers preserve exact triangular weights while keeping update cost constant per bar
* **Market application:** Particularly effective for identifying the underlying trend in noisy market conditions where standard moving averages generate too many false signals
* **Timeframe flexibility:** Works across multiple timeframes, with longer periods providing cleaner trend signals in higher timeframes
The core innovation of TRIMA is its unique triangular weighting scheme, which can be viewed either as a specialized weight distribution or as a twice-applied simple moving average with adjusted period. This creates more effective noise filtering without the excessive lag penalty typically associated with longer-period averages. The symmetrical nature of the weight distribution ensures zero phase distortion, preserving the timing of important market turning points.
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|---------------|
| Length | 14 | Controls the lookback period | Increase for smoother signals in volatile markets, decrease for responsiveness |
| Source | close | Price data used for calculation | Consider using hlc3 for a more balanced price representation |
**Pro Tip:** For a good balance between smoothing and responsiveness, try using a TRIMA with period N instead of an SMA with period 2N - you'll get similar smoothing characteristics but with less lag.
## Calculation and Mathematical Foundation
**Simplified explanation:**
TRIMA calculates a weighted average of prices where the weights form a triangle shape. The middle prices get the most weight, and weights gradually decrease toward both the recent and older ends. This creates a smooth filter that effectively removes random price fluctuations while preserving the underlying trend.
**Technical formula:**
TRIMA = Σ(Price  × Weight ) / Σ(Weight )
Where the triangular weights form a symmetric pattern:
- Weight  = min(i, n-1-i) + 1
- Example for n=5: weights =  
- Example for n=4: weights =  
Alternatively, TRIMA can be calculated as:
TRIMA(source, p) = SMA(SMA(source, (p+1)/2), (p+1)/2)
> 🔍 **Technical Note:** The double application of SMA explains why TRIMA provides better smoothing than a single SMA or WMA. This approach effectively applies smoothing twice with optimal period adjustment, creating a -18dB/octave roll-off in the frequency domain compared to -6dB/octave for a simple moving average, and the current implementation achieves $O(1)$ complexity through circular buffers and NA-safe warmup compensation.
## Interpretation Details
TRIMA can be used in various trading strategies:
* **Trend identification:** The direction of TRIMA indicates the prevailing trend
* **Signal generation:** Crossovers between price and TRIMA generate trade signals with fewer false alarms than SMA
* **Support/resistance levels:** TRIMA can act as dynamic support during uptrends and resistance during downtrends
* **Trend strength assessment:** Distance between price and TRIMA can indicate trend strength
* **Multiple timeframe analysis:** Using TRIMAs with different periods can confirm trends across different timeframes
## Limitations and Considerations
* **Market conditions:** Like all moving averages, less effective in choppy, sideways markets
* **Lag factor:** More lag than WMA or EMA due to center-weighted emphasis
* **Limited adaptability:** Fixed weighting scheme cannot adapt to changing market volatility
* **Response time:** Takes longer to reflect sudden price changes than directionally-weighted averages
* **Complementary tools:** Best used with momentum oscillators or volume indicators for confirmation
## References
* Ehlers, John F. "Cycle Analytics for Traders." Wiley, 2013
* Kaufman, Perry J. "Trading Systems and Methods." Wiley, 2013
* Colby, Robert W. "The Encyclopedia of Technical Market Indicators." McGraw-Hill, 2002
Savitzky-Golay Filter (SGF)The Savitzky-Golay Filter (SGF) is a digital filter that performs local polynomial regression on a series of values to determine the smoothed value for each point. Developed by Abraham Savitzky and Marcel Golay in 1964, it is particularly effective at preserving higher moments of the data while reducing noise. This implementation provides a practical adaptation for financial time series, offering superior preservation of peaks, valleys, and other important market structures that might be distorted by simpler moving averages.
## Core Concepts
* **Local polynomial fitting:** Fits a polynomial of specified order to a sliding window of data points
* **Moment preservation:** Maintains higher statistical moments (peaks, valleys, inflection points)
* **Optimized coefficients:** Uses pre-computed coefficients for common polynomial orders
* **Adaptive weighting:** Weight distribution varies based on polynomial order and window size
* **Market application:** Particularly effective for preserving significant price movements while filtering noise
The core innovation of the Savitzky-Golay filter is its ability to smooth data while preserving important features that are often flattened by other filtering methods. This makes it especially valuable for technical analysis where maintaining the shape of price patterns is crucial.
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|---------------|
| Window Size | 11 | Number of points used in local fitting (must be odd) | Increase for smoother output, decrease for better feature preservation |
| Polynomial Order | 2 | Order of fitting polynomial (2 or 4) | Use 2 for general smoothing, 4 for better peak preservation |
| Source | close | Price data used for calculation | Consider using hlc3 for more stable fitting |
**Pro Tip:** A window size of 11 with polynomial order 2 provides a good balance between smoothing and feature preservation. For sharper peaks and valleys, use order 4 with a smaller window size.
## Calculation and Mathematical Foundation
**Simplified explanation:**
The filter fits a polynomial of specified order to a moving window of price data. The smoothed value at each point is computed from this local fit, effectively removing noise while preserving the underlying shape of the data.
**Technical formula:**
For a window of size N and polynomial order M, the filtered value is:
y  = Σ(c_i × x )
Where:
- c_i are the pre-computed filter coefficients
- x  are the input values in the window
- Coefficients depend on window size N and polynomial order M
> 🔍 **Technical Note:** The implementation uses optimized coefficient calculations for orders 2 and 4, which cover most practical applications while maintaining computational efficiency.
## Interpretation Details
The Savitzky-Golay filter can be used in various trading strategies:
* **Pattern recognition:** Preserves chart patterns while removing noise
* **Peak detection:** Maintains amplitude and width of significant peaks
* **Trend analysis:** Smooths price movement without distorting important transitions
* **Divergence trading:** Better preservation of local maxima and minima
* **Volatility analysis:** Accurate representation of price movement dynamics
## Limitations and Considerations
* **Computational complexity:** More intensive than simple moving averages
* **Edge effects:** First and last few points may show end effects
* **Parameter sensitivity:** Performance depends on appropriate window size and order selection
* **Data requirements:** Needs sufficient points for polynomial fitting
* **Complementary tools:** Best used with volume analysis and momentum indicators
## References
* Savitzky, A., Golay, M.J.E. "Smoothing and Differentiation of Data by Simplified Least Squares Procedures," Analytical Chemistry, 1964
* Press, W.H. et al. "Numerical Recipes: The Art of Scientific Computing," Chapter 14
* Schafer, R.W. "What Is a Savitzky-Golay Filter?" IEEE Signal Processing Magazine, 2011
Bilateral Filter (BILATERAL)The Bilateral Filter is an edge-preserving smoothing technique that combines spatial filtering with intensity filtering to achieve noise reduction while maintaining significant price structure. Originally developed in computer vision for image processing, this adaptive filter has been adapted for financial time series analysis to provide superior smoothing that preserves important market transitions. The filter intelligently reduces noise in stable price regions while preserving sharp transitions like breakouts, reversals, and other significant market structures that would be blurred by conventional filters.
## Core Concepts
* **Dual-domain filtering:** Combines traditional time-based (spatial) filtering with value-based (range) filtering for adaptive smoothing
* **Edge preservation:** Maintains important price transitions while aggressively smoothing areas of minor fluctuation
* **Adaptive processing:** Automatically adjusts filtering strength based on local price characteristics
The core innovation of the Bilateral Filter is its ability to distinguish between random noise and significant price movements. Unlike conventional filters that smooth everything equally, Bilateral filtering preserves major price transitions by reducing the influence of price points that differ significantly from the current price, effectively preserving market structure while still eliminating noise.
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|---------------|
| Length | 14 | Controls the lookback window size | Increase for more context in filtering decisions, decrease for quicker response |
| Sigma_S_Ratio | 0.3 | Controls spatial (time) weighting | Lower values emphasize recent bars, higher values distribute influence more evenly |
| Sigma_R_Mult | 2.0 | Controls range (price) sensitivity | Lower values increase edge preservation, higher values increase smoothing |
| Source | close | Price data used for calculation | Consider using hlc3 for a more balanced price representation |
**Pro Tip:** For breakout trading strategies, try reducing Sigma_R_Mult to 1.0-1.5 to make the filter more sensitive to significant price moves, allowing it to preserve breakout signals while still filtering noise.
## Calculation and Mathematical Foundation
**Simplified explanation:**
The Bilateral Filter calculates a weighted average of nearby prices, where the weights depend on two factors: how far away in time the price point is (spatial weight) and how different the price value is (range weight). Points that are close in time AND similar in value get the highest weight. This means stable price regions get smoothed while significant changes are preserved.
**Technical formula:**
BF  = (1 / Wp) × Σ_{q ∈ S} G_s(||p - q||) × G_r(|I  - I |) × I 
Where:
- G_s is the spatial Gaussian kernel: exp(-||p - q||² / (2 × σ_s²))
- G_r is the range Gaussian kernel: exp(-|I  - I |² / (2 × σ_r²))
- Wp is the normalization factor (sum of all weights)
> 🔍 **Technical Note:** The sigma_r parameter is typically calculated dynamically based on local price volatility (standard deviation) to provide adaptive filtering - this automatically adjusts filtering strength based on market conditions.
## Interpretation Details
The Bilateral Filter can be applied in various trading contexts:
* **Trend identification:** Reveals cleaner underlying price direction by removing noise while preserving trend changes
* **Support/resistance identification:** Provides clearer price levels by preserving significant turning points
* **Pattern recognition:** Maintains critical chart patterns while eliminating distracting minor fluctuations
* **Breakout trading:** Preserves sharp price transitions for more reliable breakout signals
* **Pre-processing:** Can be used as an initial filter before applying other technical indicators to reduce false signals
## Limitations and Considerations
* **Computational complexity:** More intensive calculations than traditional linear filters
* **Parameter sensitivity:** Performance highly dependent on proper parameter selection
* **Non-linearity:** Non-linear behavior may produce unexpected results in certain market conditions
* **Interpretation adjustment:** Requires different interpretation than conventional moving averages
* **Complementary tools:** Best used alongside volume analysis and traditional indicators for confirmation
## References
* Tomasi, C. and Manduchi, R. "Bilateral Filtering for Gray and Color Images," Proceedings of IEEE ICCV, 1998
* Paris, S. et al. "A Gentle Introduction to Bilateral Filtering and its Applications," ACM SIGGRAPH, 2008
Double Weighted Moving Average (DWMA)# DWMA: Double Weighted Moving Average
## Overview and Purpose
The Double Weighted Moving Average (DWMA) is a technical indicator that applies weighted averaging twice in sequence to create a smoother signal with enhanced noise reduction. Developed in the late 1990s as an evolution of traditional weighted moving averages, the DWMA was created by quantitative analysts seeking enhanced smoothing without the excessive lag typically associated with longer period averages. By applying a weighted moving average calculation to the results of an initial weighted moving average, DWMA achieves more effective filtering while preserving important trend characteristics.
## Core Concepts
* **Cascaded filtering:** DWMA applies weighted averaging twice in sequence for enhanced smoothing and superior noise reduction
* **Linear weighting:** Uses progressively increasing weights for more recent data in both calculation passes
* **Market application:** Particularly effective for trend following strategies where noise reduction is prioritized over rapid signal response
* **Timeframe flexibility:** Works across multiple timeframes but particularly valuable on daily and weekly charts for identifying significant trends
The core innovation of DWMA is its two-stage approach that creates more effective noise filtering while minimizing the additional lag typically associated with longer-period or higher-order filters. This sequential processing creates a more refined output that balances noise reduction and signal preservation better than simply increasing the length of a standard weighted moving average.
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|---------------|
| Length | 14 | Controls the lookback period for both WMA calculations | Increase for smoother signals in volatile markets, decrease for more responsiveness |
| Source | close | Price data used for calculation | Consider using hlc3 for a more balanced price representation |
**Pro Tip:** For trend following, use a length of 10-14 with DWMA instead of a single WMA with double the period - this provides better smoothing with less lag than simply increasing the period of a standard WMA.
## Calculation and Mathematical Foundation
**Simplified explanation:**
DWMA first calculates a weighted moving average where recent prices have more importance than older prices. Then, it applies the same weighted calculation again to the results of the first calculation, creating a smoother line that reduces market noise more effectively.
**Technical formula:**
```
DWMA is calculated by applying WMA twice:
1. First WMA calculation:
   WMA₁ = (P₁ × w₁ + P₂ × w₂ + ... + Pₙ × wₙ) / (w₁ + w₂ + ... + wₙ)
2. Second WMA calculation applied to WMA₁:
   DWMA = (WMA₁₁ × w₁ + WMA₁₂ × w₂ + ... + WMA₁ₙ × wₙ) / (w₁ + w₂ + ... + wₙ)
```
Where:
- Linear weights: most recent value has weight = n, second most recent has weight = n-1, etc.
- n is the period length
- Sum of weights = n(n+1)/2
**O(1) Optimization - Inline Dual WMA Architecture:**
This implementation uses an advanced O(1) algorithm with two complete inline WMA calculations. Each WMA uses the dual running sums technique:
1. **First WMA (source → wma1)**:
   - Maintains buffer1, sum1, weighted_sum1
   - Recurrence: `W₁_new = W₁_old - S₁_old + (n × P_new)`
   - Cached denominator norm1 after warmup
2. **Second WMA (wma1 → dwma)**:
   - Maintains buffer2, sum2, weighted_sum2
   - Recurrence: `W₂_new = W₂_old - S₂_old + (n × WMA₁_new)`
   - Cached denominator norm2 after warmup
**Implementation details:**
- Both WMAs fully integrated inline (no helper functions)
- Each maintains independent state: buffers, sums, counters, norms
- Both warm up independently from bar 1
- Performance: ~16 operations per bar regardless of period (vs ~10,000 for naive O(n²) implementation)
**Why inline architecture:**
Unlike helper functions, the inline approach makes all state variables and calculations visible in a single scope, eliminating function call overhead and making the dual-pass nature explicit. This is ideal for educational purposes and when debugging complex cascaded filters.
> 🔍 **Technical Note:** The dual-pass O(1) approach creates a filter that effectively increases smoothing without the quadratic increase in computational cost. Original O(n²) implementations required ~10,000 operations for period=100; this optimized version requires only ~16 operations, achieving a 625x speedup while maintaining exact mathematical equivalence.
## Interpretation Details
DWMA can be used in various trading strategies:
* **Trend identification:** The direction of DWMA indicates the prevailing trend
* **Signal generation:** Crossovers between price and DWMA generate trade signals, though they occur later than with single WMA
* **Support/resistance levels:** DWMA can act as dynamic support during uptrends and resistance during downtrends
* **Trend strength assessment:** Distance between price and DWMA can indicate trend strength
* **Noise filtering:** Using DWMA to filter noisy price data before applying other indicators
## Limitations and Considerations
* **Market conditions:** Less effective in choppy, sideways markets where its lag becomes a disadvantage
* **Lag factor:** More lag than single WMA due to double calculation process
* **Initialization requirement:** Requires more data points for full calculation, showing more NA values at chart start
* **Short-term trading:** May miss short-term trading opportunities due to increased smoothing
* **Complementary tools:** Best used with momentum oscillators or volume indicators for confirmation
## References
* Jurik, M. "Double Weighted Moving Averages: Theory and Applications in Algorithmic Trading Systems", Jurik Research Papers, 2004
* Ehlers, J.F. "Cycle Analytics for Traders," Wiley, 2013
Weighted Moving Average (WMA)This implementation uses O(1) algorithm that eliminates the need to loop through all period values on each bar. It also generates valid WMA values from the first bar and is not returning NA when number of bars is less than period.
## Overview and Purpose
The Weighted Moving Average (WMA) is a technical indicator that applies progressively increasing weights to more recent price data. Emerging in the early 1950s during the formative years of technical analysis, WMA gained significant adoption among professional traders through the 1970s as computational methods became more accessible. The approach was formalized in Robert Colby's 1988 "Encyclopedia of Technical Market Indicators," establishing it as a staple in technical analysis software. Unlike the Simple Moving Average (SMA) which gives equal weight to all prices, WMA assigns greater importance to recent prices, creating a more responsive indicator that reacts faster to price changes while still providing effective noise filtering.
## Core Concepts
* **Linear weighting:** WMA applies progressively increasing weights to more recent price data, creating a recency bias that improves responsiveness
* **Market application:** Particularly effective for identifying trend changes earlier than SMA while maintaining better noise filtering than faster-responding averages like EMA
* **Timeframe flexibility:** Works effectively across all timeframes, with appropriate period adjustments for different trading horizons
The core innovation of WMA is its linear weighting scheme, which strikes a balance between the equal-weight approach of SMA and the exponential decay of EMA. This creates an intuitive and effective compromise that prioritizes recent data while maintaining a finite lookback period, making it particularly valuable for traders seeking to reduce lag without excessive sensitivity to price fluctuations.
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|---------------|
| Length | 14 | Controls the lookback period | Increase for smoother signals in volatile markets, decrease for responsiveness |
| Source | close | Price data used for calculation | Consider using hlc3 for a more balanced price representation |
**Pro Tip:** For most trading applications, using a WMA with period N provides better responsiveness than an SMA with the same period, while generating fewer whipsaws than an EMA with comparable responsiveness.
## Calculation and Mathematical Foundation
**Simplified explanation:**
WMA calculates a weighted average of prices where the most recent price receives the highest weight, and each progressively older price receives one unit less weight. For example, in a 5-period WMA, the most recent price gets a weight of 5, the next most recent a weight of 4, and so on, with the oldest price getting a weight of 1.
**Technical formula:**
```
WMA = (P₁ × w₁ + P₂ × w₂ + ... + Pₙ × wₙ) / (w₁ + w₂ + ... + wₙ)
```
Where:
- Linear weights: most recent value has weight = n, second most recent has weight = n-1, etc.
- The sum of weights for a period n is calculated as: n(n+1)/2
- For example, for a 5-period WMA, the sum of weights is 5(5+1)/2 = 15
**O(1) Optimization - Dual Running Sums:**
The key insight is maintaining two running sums:
1. **Unweighted sum (S)**: Simple sum of all values in the window
2. **Weighted sum (W)**: Sum of all weighted values
The recurrence relation for a full window is:
```
W_new = W_old - S_old + (n × P_new)
```
This works because when all weights decrement by 1 (as the window slides), it's mathematically equivalent to subtracting the entire unweighted sum. The implementation:
- **During warmup**: Accumulates both sums as the window fills, computing denominator each bar
- **After warmup**: Uses cached denominator (constant at n(n+1)/2), updates both sums in constant time
- **Performance**: ~8 operations per bar regardless of period, vs ~100+ for naive O(n) implementation
> 🔍 **Technical Note:** Unlike EMA which theoretically considers all historical data (with diminishing influence), WMA has a finite memory, completely dropping prices that fall outside its lookback window. This creates a cleaner break from outdated market conditions. The O(1) optimization achieves 12-25x speedup over naive implementations while maintaining exact mathematical equivalence.
## Interpretation Details
WMA can be used in various trading strategies:
* **Trend identification:** The direction of WMA indicates the prevailing trend with greater responsiveness than SMA
* **Signal generation:** Crossovers between price and WMA generate trade signals earlier than with SMA
* **Support/resistance levels:** WMA can act as dynamic support during uptrends and resistance during downtrends
* **Moving average crossovers:** When a shorter-period WMA crosses above a longer-period WMA, it signals a potential uptrend (and vice versa)
* **Trend strength assessment:** Distance between price and WMA can indicate trend strength
## Limitations and Considerations
* **Market conditions:** Still suboptimal in highly volatile or sideways markets where enhanced responsiveness may generate false signals
* **Lag factor:** While less than SMA, still introduces some lag in signal generation
* **Abrupt window exit:** The oldest price suddenly drops out of calculation when leaving the window, potentially causing small jumps
* **Step changes:** Linear weighting creates discrete steps in influence rather than a smooth decay
* **Complementary tools:** Best used with volume indicators and momentum oscillators for confirmation
## References
* Colby, Robert W. "The Encyclopedia of Technical Market Indicators." McGraw-Hill, 2002
* Murphy, John J. "Technical Analysis of the Financial Markets." New York Institute of Finance, 1999
* Kaufman, Perry J. "Trading Systems and Methods." Wiley, 2013
Simple Moving Average (SMA)## Overview and Purpose
The Simple Moving Average (SMA) is one of the most fundamental and widely used technical indicators in financial analysis. It calculates the arithmetic mean of a selected range of prices over a specified number of periods. Developed in the early days of technical analysis, the SMA provides traders with a straightforward method to identify trends by smoothing price data and filtering out short-term fluctuations. Due to its simplicity and effectiveness, it remains a cornerstone indicator that forms the basis for numerous other technical analysis tools.
## What’s Different in this Implementation
- **Constant streaming update:**  
  On each bar we:
  1) subtract the value leaving the window,  
  2) add the new value,  
  3) divide by the number of valid samples (early) or by `period` (once full).
- **Deterministic lag, same as textbook SMA:**  
  Once full, lag is `(period - 1)/2` bars—identical to the classic SMA. You just **don’t lose the first `period-1` bars** to `na`.
- **Large windows without penalty:**  
  Complexity is constant per tick; memory is bounded by `period`. Very long SMAs stay cheap.
## Behavior on Early Bars
- **Bars < period:** returns the arithmetic mean of **available** samples.  
  Example (period = 10): bar #3 is the average of the first 3 inputs—not `na`.
- **Bars ≥ period:** behaves exactly like standard SMA over a fixed-length window.
> Implication: Crosses and signals can appear earlier than with `ta.sma()` because you’re not suppressing the first `period-1` bars.
## When to Prefer This
- Backtests needing early bars: You want signals and state from the very first bars.
- High-frequency or very long SMAs: O(1) updates avoid per-bar CPU spikes.
- Memory-tight scripts: Single circular buffer; no large temp arrays per tick.
## Caveats & Tips
Backtest comparability: If you previously relied on na gating from ta.sma(), add your own warm-up guard (e.g., only trade after bar_index >= period-1) for apples-to-apples.
Missing data: The function treats the current bar via nz(source); adjust if you need strict NA propagation.
Window semantics: After warm-up, results match the textbook SMA window; early bars are a partial-window mean by design.
## Math Notes
Running-sum update:
sum_t = sum_{t-1} - oldest + newest
SMA_t = sum_t / k where k = min(#valid_samples, period)
Lag (full window): (period - 1) / 2 bars.
## References
- Edwards & Magee, Technical Analysis of Stock Trends
- Murphy, Technical Analysis of the Financial Markets
Adaptive Trend SelectorThe Adaptive Trend Selector is a comprehensive trend-following tool designed to automatically identify the optimal moving average crossover strategy. It features adjustable parameters and an integrated backtester that delivers institutional-grade insights into the recommended strategy. The model continuously adapts to new data in real time by evaluating multiple moving average combinations, determining the best performing lengths, and presenting the backtest results in a clear, color-coded table that benchmarks performance against the buy-and-hold strategy.
At its core, the model systematically backtests a wide range of moving average combinations to identify the configuration that maximizes the selected optimization metric. Users can choose to optimize for absolute returns or risk-adjusted returns using the Sharpe, Sortino, or Calmar ratios. Alternatively, users can enable manual optimization to test custom fast and slow moving average lengths and view the corresponding backtest results. The label displays the Compounded Annual Growth Rate (CAGR) of the strategy, with the buy-and-hold CAGR in parentheses for comparison. The table presents the backtest results based on the fast and slow lengths displayed at the top:
 
 Sharpe = CAGR per unit of standard deviation.
 Sortino = CAGR per unit of downside deviation.
 Calmar = CAGR relative to maximum drawdown.
 Max DD = Largest peak-to-trough decline in value.
 Beta (β) = Return sensitivity relative to buy-and-hold.
 Alpha (α) = Excess annualized risk-adjusted returns.
 Win Rate = Ratio of profitable trades to total trades.
 Profit Factor = Total gross profit per unit of losses.
 Expectancy = Average expected return per trade.
 Trades/Year = Average number of trades per year.
 
This indicator is designed with flexibility in mind, enabling users to specify the start date of the backtesting period and the preferred moving average strategy. Supported strategies include the Exponential Moving Average (EMA), Simple Moving Average (SMA), Wilder’s Moving Average (RMA), Weighted Moving Average (WMA), and Volume-Weighted Moving Average (VWMA). To minimize overfitting, users can define constraints such as a minimum and maximum number of trades per year, as well as an optional optimization margin that prioritizes longer, more robust combinations by requiring shorter-length strategies to exceed this threshold. The table follows an intuitive color logic that enables quick performance comparison against buy-and-hold (B&H):
 
 Sharpe = Green indicates better than B&H, while red indicates worse.
 Sortino = Green indicates better than B&H, while red indicates worse.
 Calmar = Green indicates better than B&H, while red indicates worse.
 Max DD = Green indicates better than B&H, while red indicates worse.
 Beta (β) = Green indicates better than B&H, while red indicates worse.
 Alpha (α) = Green indicates above 0%, while red indicates below 0%.
 Win Rate = Green indicates above 50%, while red indicates below 50%.
 Profit Factor = Green indicates above 2, while red indicates below 1.
 Expectancy = Green indicates above 0%, while red indicates below 0%.
 
In summary, the Adaptive Trend Selector is a powerful tool designed to help investors make data-driven decisions when selecting moving average crossover strategies. By optimizing for risk-adjusted returns, investors can confidently identify the best lengths using institutional-grade metrics. While results are based on the selected historical period, users should be mindful of potential overfitting, as past results may not persist under future market conditions. Since the model recalibrates to incorporate new data, the recommended lengths may evolve over time.






















