What is the stochastic oscillator? %K, %D, formula and example

On this page

Key takeaways

  • The stochastic oscillator asks one question: did today close near the top or near the bottom of the recent trading range? Near the top it reads close to a hundred, near the bottom close to zero.
  • %K is the raw reading; %D is a short average of it that moves more slowly. %K crossing above %D is the classic short-term buy signal.
  • Unlike the RSI, it uses each day's high and low, so it reflects where prices traded during the day, not only the change from one close to the next.
  • In a strong uptrend the close keeps finishing near the top of its range, so overbought readings can last for weeks; in a decline, oversold readings can last just as long.
  • In MarketHeist the indicator's main line is the raw %K, and comparing %K with its own three-day average reproduces the rule of %K above %D exactly.

Definition

The stochastic oscillator, developed by George Lane in the 1950s, measures where a closing price sits within the range between the highest high and the lowest low of a lookback window, on a scale from 0 (the close at the range's low) to 100 (at its high). The raw line is %K, a short moving average of it is %D, and readings above 80 and below 20 are conventionally called overbought and oversold.

Also known as: stochastic, stochastics, %K, %D, fast stochastic, slow stochastic, Lane's stochastics, stochastic 14 3.

How it works

Take the last fourteen days, the default window. Find the highest high and the lowest low in that window, today included: that is the recent range. %K says where today's close sits in it, as a percentage: zero at the bottom of the range, a hundred at the top, fifty in the middle. %D is a three-day simple average of %K, a slower line that filters some of %K's jumps.

Lane's idea was that closing prices tend to finish near the top of the range while a rise has strength behind it and drift toward the bottom as it fades, so the position of the close can turn before the price does. Readings above 80 are called overbought and below 20 oversold, and the cross of %K over %D, especially from below 20, is the standard buy signal.

The stochastic oscillator is like ranking today's temperature between the coldest and the warmest day of the past fortnight: a mild day in a cold fortnight still ranks near the top.

Platforms show two versions. The fast stochastic is %K and its three-day average. The slow stochastic smooths once more: its %K is the fast %D, and its %D is an average of that. MarketHeist's indicator is the fast version, with the raw %K as its main line and %D as a second output.

Because the range comes from highs and lows, the oscillator reacts to intraday moves that the RSI, built from closes alone, does not see, and it jumps around more. A rule that acts on every cross of %K and %D trades very often, which makes costs a large part of its result.

Formula

Stochastic %K and %D (fast)
%Kt=100×Ct−LLtHHt−LLt,HHt=max0≤j<nHt−j,LLt=min0≤j<nLt−j,%Dt=1m∑k=0m−1%Kt−k
Cₜ, Hₜ, Lₜ
adjusted close, high and low on day t
HHₜ, LLₜ
highest high and lowest low of the last n days, day t included
n
the %K window: 14 by default
m
the %D window: 3 by default

When the high and the low of the window are equal, MarketHeist sets %K to 50. Williams %R is the same quantity on a scale from −100 to 0: %R = %K − 100.

The %K-above-%D rule as a crossover rule
pt=1⇔%Kt>13∑k=02%Kt−k=%Dt
pₜ
the position decided at day t's close: 1 = invested, 0 = cash

A crossover position rule with a 3-bar window on %K is exactly %K above %D when the %D window is 3.

Worked example

SPY's daily bars from Oct 2006 to Sep 2026, about 20 years, with the 14-day stochastic %K and three rules, each acted on with the standard one-bar delay, no trading costs and no interest on cash.

SPY's %K had a median of 73.46 over the window, and on four days in five it sat between 15.93 and 97.25: in a market that rose over most of the window, the close finished in the upper half of its two-week range more often than in the lower half.

The backtester's default rule, long while %K is above 20, stays invested except in oversold stretches. It held SPY on 87.6% of days, with 293 round trips, 14.7 a year, and grew 3.5% a year against 11.1% for holding SPY, with a worst decline of -63.5% against -55.2%.

Turned around, long only while %K was below 20, the rule held SPY on 12.4% of days and grew 7.4% a year. 76.1% of its 293 trades ended with a gain.

The rule of %K above %D traded the most: 1031 round trips, 51.7 a year, invested on 51.7% of days, growing 3.4% a year before any costs. At that pace a few basis points per trade add up; see transaction costs.

Data through Sep 2026. Reproduce id f8cdc588599d7ef3 (this guide, its lab setup and the data month).

Interactive lab

SPY's price with the days invested shaded, %K with the rule's line in the indicator panel, and the results table for the default rule, the oversold reading and %K above %D against buy-and-hold. Change the windows, the level, the rule, the cost or the fund.

SPY price with the days the base rule held itS&P 500, adjusted daily close, Oct 2006 to Sep 2026, log scale. Shaded: the 294 stretches the base rule held the fund (88% of 5030 days).$50$100$200$50020062011201620212026SPY adjusted closeHeld by the base rule
SPY on a log scale. Shaded: the days the base rule held the fund. Oct 2006 to Sep 2026.
Stochastic %K with the base rule's lineStochastic %K on SPY, Oct 2006 to Sep 2026. The rule compares it with the fixed line 20.0204060801002006201120162021202620Stochastic %K
Stochastic %K and the line the base rule compares it with. Oct 2006 to Sep 2026.
Growth of $10,000: the setups against buy and holdS&P 500, Oct 2006 to Sep 2026, log scale. $10,000 grows to $19,740 (base), $41,688 (Oversold only: %K below 20), $19,422 (%K above %D (3-day average of %K)), $82,292 (buy and hold).$5k$10k$20k$50k20062011201620212026Base ruleOversold only: %K below 20%K above %D (3-day average of %K)Buy and hold
Growth of $10,000 on a log scale, same days for every line. Oct 2006 to Sep 2026.
MeasureBaseOversold only: %K below 20%K above %D (3-day average of %K)Buy and hold
CAGR3.5%7.4%3.4%11.1%
Volatility (annualized)16.1%10.9%13.9%19.4%
Maximum drawdown-63.5%-20.9%-50.9%-55.2%
Sharpe ratio0.290.710.310.64
Sortino ratio0.391.190.42n/a
Growth of $10,000$19,740$41,688$19,422$82,292
Time in the market87.6%12.4%51.7%100.0%
Round trips2932931031n/a
Round trips per year14.714.751.7n/a
Win rate31.1%76.1%46.7%n/a
Average win5.3%1.3%1.3%n/a
Average loss-1.9%-1.9%-1.0%n/a
Payoff ratio2.760.661.31n/a
Average days held15.02.12.5n/a
Expectancy per trade0.3%0.5%0.1%n/a
Profit factor, per day1.061.491.091.13
Profit factor, per trade1.242.101.15n/a
Indicator, last day54.33854.33854.338n/a
Indicator, 10th / 50th / 90th percentile15.933 / 73.462 / 97.24815.933 / 73.462 / 97.24815.933 / 73.462 / 97.248n/a
Days the rule alone is long87.6%12.4%51.7%n/a

S&P 500, Oct 2006 to Sep 2026, 5030 trading days. Every setup is measured over the same days, with the indicator warmed up on earlier ones; cash earns 0. Base: Stochastic Oscillator (%K/%D) (k period 14, d period 3); long while the Stochastic %K is above 20; execution delay 1; cost 0 bps one way. Oversold only: %K below 20: Stochastic Oscillator (%K/%D) (k period 14, d period 3); long while the Stochastic %K is below 20; execution delay 1; cost 0 bps one way. %K above %D (3-day average of %K): Stochastic Oscillator (%K/%D) (k period 14, d period 3); long while the Stochastic %K is above its own 3-day average; execution delay 1; cost 0 bps one way.

Buy and hold, same daysValue
Largest one-day gain14.5% on 13 Oct 2008
Largest one-day loss-10.9% on 16 Mar 2020
CAGR without the 10 largest gains6.6%
CAGR without the 30 largest gains1.8%
CAGR without the 10 largest losses16.0%
CAGR without the 30 largest losses22.1%

The days replaced by 0 are the largest daily gains (or losses) of the window.

How MarketHeist computes it

Every choice an implementation has to make, as the code makes it today. The page is checked against the code each time it is built.

ChoiceHow it is computedIn the code
DataDaily bars (open, high, low, close, volume) of the fund as the MarketHeist data service serves them to the backtester: prices adjusted for splits and dividends, so a dividend counts as reinvested. They come from a snapshot taken each month and cut at the data month of this page, and are not rounded. The fund's own history, not an extension: a fund younger than the window is measured over the years it has.
WindowThe worked example and the lab measure the last 20 years of trading days, Oct 2006 to Sep 2026 (5030 days), ending at the data month of this page. Every setup, and buy and hold, is measured over exactly these days; an indicator is warmed up on the days before them, so changing a setting never moves the window, and a setting that needs more history than exists before the window is refused rather than measured over fewer days.
BacktestThe backtester's own engine, in the order it runs it: the indicator, the position rule (or entry and exit triggers) and the optional regime filter produce a position for every day of the fund's whole history; the position is then shifted forward by the execution delay and applied to each day's return over the window. Cash earns 0, there is no leverage, and a one-way cost in basis points is charged on the size of every change of position. Round trips are the closed entries of the trade log (a trade still open on the last day is not counted); the win rate is the share of them with a gain; the payoff ratio is the average win over the size of the average loss; expectancy is the average return per trade; the per-trade profit factor is the sum of the winning trades' returns over the size of the sum of the losing ones, while the per-day profit factor sums days.
Years and volatilityA year is 252 trading days, the engine's convention: trades per year is round trips over days divided by 252, the CAGR is the growth multiple to the power 252 over the days, and volatility is the sample standard deviation of the daily returns times the square root of 252.
Indicator statisticsThe indicator's main output over the window: its last value, its 10th, 50th and 90th percentile (linear interpolation between ranks), and the share of days the rule alone says long, before the delay and any regime filter. Every output of the indicator is also summarized by its median and the share of days below 0.
Buy and holdThe fund held every day of the window with dividends reinvested. The largest one-day gain and loss are the highest and lowest daily returns; the CAGR without the 10 or 30 largest gains (or losses) replaces those days' returns with 0 and recompounds.
%K100 × (close − lowest low) ÷ (highest high − lowest low) over the last k_period bars, the current bar included, on adjusted high, low and close. 50 when the range is zero. k_period is floored at 2.computepackages/shared/engine/indicators/stochastic.ts
%DSimple moving average of %K over d_period bars (floored at 1). It is a second output for charts; the position rules read %K, the primary output.smapackages/shared/engine/utils.ts
Fast, not slowThe raw (fast) %K, with no smoothing before %D. A slow stochastic, whose %K is the fast %D, is not built in.computepackages/shared/engine/indicators/stochastic.ts
%K above %DA crossover position rule compares %K with its own simple moving average; with a window of 3 that average is %D for the default d_period of 3. Changing d_period does not change the rule's window, so set both together.generatePositionpackages/shared/engine/positions.ts
Defaultsk_period 14 (range 2 to 200), d_period 3 (1 to 50); default rule long while %K is above 20.SPECpackages/shared/engine/indicators/stochastic.ts
Engine functionsThe functions the portfolio app and the MarketHeist MCP tools run, called here on the same monthly returns.computePositionpackages/shared/engine/run_basic.tsgeneratePositionpackages/shared/engine/positions.tsapplyRegimeFilterpackages/shared/engine/regime_filter.tsgenerateTriggeredPositionpackages/shared/engine/triggered_position.tsrunBacktestpackages/shared/engine/backtest.tsgetIndicatorpackages/shared/engine/indicators/registry.ts

Stochastic oscillator (%K and %D) compared with its neighbours

The stochastic oscillator and its neighbours
IndicatorQuestion it answersInputsScale
Stochastic %KWhere did the close finish in the recent high-low range?High, low, close0 to 100
Williams %RThe same, measured from the top of the rangeHigh, low, close−100 to 0
RSIWere recent up closes larger than down closes?Close0 to 100
Bollinger %BWhere is the close between volatility bands around its average?Close0 to 1 inside the bands, unbounded
CCIHow far is the typical price from its average, in mean deviations?High, low, closeUnbounded

Limitations

  • Overbought and oversold readings describe the recent range, not what comes next; in strong trends they persist.
  • The fast %K jumps with every unusual high or low, and rules built on its crosses trade very often; the example charges no costs.
  • Adjusted highs and lows are scaled with the same dividend factor as the close, so the range is consistent, but values can differ slightly from a platform that uses unadjusted prices.
  • Only the fast stochastic is built in. Results for a slow stochastic, common on charting platforms, can differ.
  • One fund over one window that rose for most of its length; on a falling or range-bound asset the same rules behave differently.

Frequently asked questions

What is the difference between %K and %D?
%K is the raw reading of where the close sits in the recent range. %D is a short moving average of %K, three days by default, so it moves more slowly. Crosses of %K over %D are the oscillator's usual signals.
What is the difference between the fast and the slow stochastic?
The fast stochastic uses the raw %K and its three-day average. The slow stochastic averages once more: its %K is the fast %D, and its %D is an average of that, which removes much of the fast version's jumpiness. MarketHeist computes the fast version.
Stochastic oscillator or RSI: what is the difference?
The RSI compares the sizes of recent up and down closes. The stochastic oscillator compares the close with the recent high and low. On the same asset they often agree on direction, but the stochastic reacts to intraday ranges and moves more abruptly.
What do the 80 and 20 levels mean?
They are the conventional overbought and oversold lines: above 80 the close is near the top of its recent range, below 20 near the bottom. They are descriptions of the recent range, not signals that a reversal is due.
Does MarketHeist use adjusted highs and lows?
Yes. The daily high, low and close are all adjusted for dividends and splits with the same factor, so the close and its range stay consistent across distributions.

References

  1. Lane, G. C. (1984) Lane's Stochastics. Technical Analysis of Stocks and Commodities magazine. The author's own description of %K and %D.
  2. Murphy, J. J. (1999) Technical Analysis of the Financial Markets. New York Institute of Finance. Stochastics, fast and slow, and their usual readings.

Try it on your own holdings

Open the stochastic oscillator in the backtester →

Or ask an assistant connected to the MarketHeist MCP server (https://marketheist.io/mcp), which computes the same figures:

Using MarketHeist.io, backtest the 14-day stochastic %K on SPY daily bars with execution delay 1 three ways: long while %K is above 20, long only while %K is below 20, and long while %K is above its 3-day average (%D, crossover rule). Compare trades per year, CAGR and max drawdown with buy-and-hold.

Ask an AI assistant

The prompt opens in a new tab, already filled in. An assistant without the MarketHeist connector answers from its own knowledge, not from the figures on this page.

Historical simulation, not advice. Computed by the MarketHeist portfolio engine from monthly total returns, data through Sep 2026. Markdown version of this page: stochastic-oscillator.md.