Systemicalpha

Stochastic Oscillator

systemic:core-soIndicatorsfunction1 cr

Inputs

NameTypeDescription
WindowintegerThe lookback period for finding the highest high and lowest low.
Smooth FactorintegerThe number of periods for the Simple Moving Average applied to %K to produce %D.
Price HighfloatarrayThe highest price reached during each period (candle).
Price LowfloatarrayThe lowest price reached during each period (candle).
Price ClosefloatarrayThe closing price for each period.

Outputs

NameTypeDescription
SOKfloatarrayThe raw Stochastic Oscillator value, measuring where the current close sits within the recent range.
SODfloatarrayThe signal line — a smoothed moving average of %K.

The Insight: Momentum Changes Before Price

In the late 1950s, George C. Lane made an observation that would become one of the most influential ideas in technical analysis:

"It doesn't follow price, it doesn't follow volume or anything like that. It follows the speed or the momentum of price. As a rule, the momentum changes direction before price."

Think of a ball thrown straight up into the air. Before it reverses direction and falls back down, it slows down. The ball's momentum shifts before its trajectory does. Lane noticed that markets behave the same way — momentum weakens before price reverses.

The Stochastic Oscillator captures this by asking a simple question: Where is the current close within the recent price range?


The Formula

%K=Close−Lowest LownHighest Highn−Lowest Lown×100\%K = \frac{\text{Close} - \text{Lowest Low}_n}{\text{Highest High}_n - \text{Lowest Low}_n} \times 100 %D=SMA(%K,m)\%D = \text{SMA}(\%K, m)

Where:

  • nn = the lookback window (default: 14 periods)
  • mm = the smoothing factor for %D (default: 3 periods)

What %K measures: If the stock closed at its 14-day high, %K = 100. If it closed at its 14-day low, %K = 0. A %K of 70 means the close is 70% of the way from the lowest low to the highest high.


Why This Works

During an uptrend, prices tend to close near the high of each period — buyers push prices up throughout the session and hold them there. During a downtrend, prices tend to close near the low — sellers dominate.

When an uptrend is losing steam, you'll notice something subtle: even though prices may still be making new highs, they start closing further from those highs. The Stochastic Oscillator detects this weakening grip before the price chart shows an obvious reversal.

flowchart LR
    subgraph Healthy["Healthy Uptrend"]
        direction TB
        H1["Price makes new high"]
        C1["Close near the high"]
        K1["%K stays elevated"]
    end
    
    subgraph Weakening["Weakening Uptrend"]
        direction TB
        H2["Price makes new high"]
        C2["Close drifts from high"]
        K2["%K starts falling"]
    end
    
    Healthy --> Weakening

This is the core insight: the oscillator often turns before price does.


Interpreting the Zones

%K ValueZoneWhat It Means
80–100OverboughtClose is near the top of the recent range
50–79Upper neutralBuyers have the edge
21–49Lower neutralSellers have the edge
0–20OversoldClose is near the bottom of the recent range

A Critical Caveat

Overbought ≠ Sell. Oversold ≠ Buy.

This is perhaps the most misunderstood aspect of the Stochastic Oscillator. In a strong uptrend, the oscillator can remain overbought for weeks or even months while the price continues climbing. Similarly, in a vicious downtrend, it can stay oversold while prices keep falling.

Lane himself emphasized that overbought/oversold readings are context-dependent. They tell you where the close is relative to the range — not whether a reversal is imminent. You need additional confirmation.


The Two Lines: %K and %D

The oscillator produces two lines:

LineRoleBehavior
%KThe raw measurementFaster, more reactive, noisier
%DThe signal line (SMA of %K)Slower, smoother, used for crossovers

Lane considered %D divergence to be the most important signal — more important than crossovers or zone readings. When %D diverges from price (price makes a new high but %D doesn't), it's a warning that momentum has already turned.


Trading Signals

1. Crossovers

SignalConditionStrongest When
Bullish%K crosses above %DFrom oversold territory (<20)
Bearish%K crosses below %DFrom overbought territory (>80)

Crossovers in the middle of the range (30–70) tend to be less reliable and more prone to whipsaws.

2. Divergence — Lane's "Only Signal"

Lane famously stated that divergence is "the only signal which will cause you to buy or sell."

TypePriceStochasticImplication
Bullish divergenceLower lowHigher lowDownside momentum weakening
Bearish divergenceHigher highLower highUpside momentum weakening

Divergence doesn't tell you when to act — it tells you to pay attention. Confirmation (a support break, a crossover, or a move past 50) is needed.

3. The 50-Line

The centerline at 50 acts like the 50-yard line in football:

  • %K above 50: Price is closing in the upper half of its range (bullish bias)
  • %K below 50: Price is closing in the lower half of its range (bearish bias)

Crossing 50 after a divergence confirms the shift in momentum.


Parameter Tuning

ParameterDefaultLower ValuesHigher Values
Window (n)14More sensitive, more signals, more noiseSmoother, fewer signals, more lag
Smooth Factor (m)3%D follows %K more closely%D lags further behind %K

Common configurations:

  • (5, 3): Fast, for scalping or day trading
  • (14, 3): Standard, balanced sensitivity
  • (21, 5): Slow, for swing trading or position trading

When It Works, When It Struggles

Excels In:

  • Range-bound markets — The classic use case. When price oscillates between support and resistance, the Stochastic excels at timing entries and exits
  • Trend pullbacks — In an established uptrend, oversold readings can identify good pullback entry points
  • Divergence detection — Early warning of momentum exhaustion

Struggles In:

  • Strong trends — Can stay overbought/oversold for extended periods while price continues moving
  • Choppy, directionless markets — Frequent whipsaws as %K and %D cross repeatedly
  • Low-volume or illiquid assets — Erratic price movements produce noisy signals

Creative Applications

Regime Detection

The Stochastic isn't just a buy/sell signal generator. It can help you understand what type of market you're in:

  • %K consistently above 50: Trending up — favor long entries, be patient with overbought readings
  • %K consistently below 50: Trending down — favor short entries, be patient with oversold readings
  • %K oscillating around 50: Range-bound — trade the extremes

Multi-Timeframe Confirmation

Check the Stochastic on a higher timeframe to establish bias, then trade signals on a lower timeframe:

Higher TF StochasticLower TF Action
Rising, not overboughtTake bullish crossovers
Falling, not oversoldTake bearish crossovers
Overbought + divergenceBe cautious with longs

Mean Reversion on Correlated Assets

When two highly correlated assets diverge in their Stochastic readings (one oversold, one overbought), it may signal a mean-reversion opportunity in the spread.


Summary

AspectKey Point
Core insightMomentum changes before price
What it measuresWhere the close sits within the recent range
%KThe raw oscillator (0–100)
%DSmoothed signal line
Overbought/OversoldContext matters — not automatic signals
Best signalDivergence between price and oscillator
Best environmentRange-bound markets, trend pullbacks

Missing Data

"N-bar" means N observed bars, not N calendar slots. A bar missing any one of high, low, or close (a data gap, or a closed-market slot such as a weekend) is a missing bar entirely — its high/low never leak into a neighboring window. A missing bar is skipped when assembling the highest-high/lowest-low window, and a Friday-close-to-Monday-open window is computed over adjacent observed bars — the weekend gap is bridged, never treated as a zero or a repeated value.

  • Gaps are bridged, not broken: the window always contains N genuine observed bars; a gap does not shrink the window and is never averaged over as if it were a real bar.
  • Warm-up is null, not partial: the first window - 1 observed bars have no complete window yet and are null — never the old partial-window %K or the sentinel 50 value ta fabricated on a gap.
  • Interior and trailing gaps stay null in place: a missing slot never receives a substitute value, so %K/%D never fabricate a reading where no data exists.
  • A flat window (highest high equals lowest low) is null: %K is mathematically undefined there — it is never silently reported as 50 (neutral) or any other sentinel.
  • Live execution returns exactly one datapoint — the newest — which is null when the current bar's window is not yet complete or its data is missing.

Indicator Assessment

%%{init: {"quadrantChart": {"titleFontSize": 16}}}%%
quadrantChart
    title Stochastic Oscillator Assessment
    x-axis Low Complexity --> High Complexity
    y-axis Low Reliability --> High Reliability
    quadrant-1 Complex but Reliable
    quadrant-2 Simple and Reliable
    quadrant-3 Simple but Unreliable
    quadrant-4 Complex and Unreliable
    SO - Stocks: [0.30, 0.70]
    SO - Crypto: [0.30, 0.55]
DimensionStocks/MacroCryptoNotes
Popularity9/108/10One of the most widely used oscillators since 1950s; standard in virtually all charting platforms
Reliability7/105.5/10Excellent in ranging markets; prone to false signals in trends; crypto's volatility increases whipsaws
Complexity3/103/10Moderate formula complexity with multiple components (%K, %D, smoothing); intuitive zone interpretation
Versatility8/107/10Works across timeframes and asset classes; adaptable parameters; crypto benefits from parameter tuning
Recent Interest6/107/10Established classic; renewed crypto interest for mean-reversion strategies in ranging altcoin markets

Assessment Rationale

  • Popularity: The Stochastic Oscillator is a cornerstone of technical analysis, developed by George Lane in the 1950s. It appears in every major charting platform and is taught in nearly all technical analysis curricula.

  • Reliability: In ranging markets, the Stochastic delivers reliable overbought/oversold signals. However, during strong trends, it can remain in extreme zones for extended periods, generating numerous false reversal signals. Crypto markets, with their tendency for explosive moves and volatility clustering, amplify this weakness.

  • Complexity: While the formula involves multiple calculations (highest high, lowest low, smoothing), the concept is intuitive: "Where is the current close relative to the recent range?" The 0-100 scale with clear overbought/oversold zones makes interpretation accessible to beginners.

  • Versatility: The Stochastic works across equities, forex, commodities, and crypto. Parameter adjustment (window, smooth factor) allows customization for different volatility regimes. The multiple signal types (crossovers, divergence, zone reversals) provide trading opportunities in various market conditions.

  • Recent Interest: As a well-established indicator, the Stochastic sees steady rather than surging interest. However, the crypto community has shown renewed attention to momentum oscillators for identifying mean-reversion opportunities in range-bound altcoin markets, particularly during consolidation phases between major trend moves.


Further Reading

Rendering diagrams...
© 2026 WanoLabs. All rights reservedAlpha build v0.1.5