Two-panel chart of Apple (AAPL) from October 2025 to October 2026: daily closing price on top, 14-day Wilder RSI below with dashed lines at 70 and 30 and the readings above 70 and below 30 shaded
|

How to calculate RSI in Python: Wilder’s method on Apple stock

Disclosure: I have no position in AAPL. I also hold diversified funds (IWDA, QQQ, SPY, VWRL) that may include AAPL. Positions checked on 28 October 2026.

Updated 28 October 2026.

Affiliate disclosure: some links in this post are affiliate links. If you buy through one, I may earn a commission at no extra cost to you. It does not change what I write about the product.

Two-panel chart of Apple (AAPL) from October 2025 to October 2026: daily closing price on top, 14-day Wilder RSI below with dashed lines at 70 and 30 and the readings above 70 and below 30 shaded

The RSI Python code below pulls a year of Apple’s daily closes from Market Data and computes J. Welles Wilder’s 14-day Relative Strength Index. On 26 October 2026 Apple’s RSI stood at 57.7. Over the year it spent 21 trading days above 70 and 12 below 30, the two levels Wilder used to mark tops and bottoms.

What changed since March 2025

The main change is the formula. The old function averaged gains and losses with a 14-day rolling mean and noted that the result “might differ slightly” from Wilder’s. That rolling-mean version has a name of its own, Cutler’s RSI, and on this year of Apple data “slightly” undersold it: up to 24.4 points on a single day, and the two versions put Apple in a different zone (above 70, below 30 or in between) on 45 of 237 days. The function below now uses Wilder’s original smoothing, and Step 3 checks it against his recursion written out by hand.

Three smaller fixes. The chart is saved to a file with savefig, so the script runs unattended. When the average loss is zero, meaning no down day since the series began, the function now returns 100 explicitly; the old code relied on a division by zero. And the price request states which corporate actions it adjusts for.

Two charts are new: Step 3 plots the two RSI versions together, and “What can go wrong” shows how the start date moves the early values. The worked example now uses a year of Apple’s daily prices.

Step 1: get Apple’s daily closes from Market Data

Market Data’s daily candles endpoint takes a ticker and a date range and returns parallel arrays of timestamps, opens, highs, lows, closes and volumes. The function below keeps the closes. It sends a token only if you have set one, so the Apple example runs as written. For other tickers, create a free Market Data account and set MARKETDATA_TOKEN to its token.

import os
import numpy as np
import pandas as pd
import requests
import matplotlib.pyplot as plt

# Market Data serves AAPL without a token. For other tickers, set your own token first:
#   export MARKETDATA_TOKEN=YOUR_TOKEN
TOKEN = os.environ.get("MARKETDATA_TOKEN")
HEADERS = {"Authorization": f"Bearer {TOKEN}"} if TOKEN else {}


def daily_closes(ticker, start, end, adjust_dividends=False):
    """Daily closing prices from Market Data, adjusted for splits (and optionally dividends)."""
    url = f"https://api.marketdata.app/v1/stocks/candles/D/{ticker}/"
    params = {"from": start, "to": end, "adjustdividends": str(adjust_dividends).lower()}
    data = requests.get(url, params=params, headers=HEADERS, timeout=30).json()
    if data.get("s") != "ok":
        raise RuntimeError(data.get("errmsg", data))
    dates = pd.to_datetime(data["t"], unit="s", utc=True).tz_convert("America/New_York").tz_localize(None).normalize()
    return pd.Series(data["c"], index=dates, name=ticker)


close = daily_closes("AAPL", "2025-10-27", "2026-10-26")
print(f"{len(close)} trading days, {close.index[0]:%Y-%m-%d} to {close.index[-1]:%Y-%m-%d}")
print(close.tail(3).round(2).to_string())
251 trading days, 2025-10-27 to 2026-10-26
2026-10-22    348.22
2026-10-23    347.72
2026-10-26    343.91

Two details in that function matter for the RSI. The API stamps each daily candle at midnight US Eastern time on the session date, so the code reads the Unix timestamps in New York time and keeps only the date. And by default the API adjusts daily candles for both splits and dividends. The code passes adjustdividends=false, so the closes are adjusted for splits only, which leaves them at the prices that actually traded unless the stock has split since. “What can go wrong” below measures how much the choice moves the RSI.

The request returned 251 trading days from 27 October 2025 to 26 October 2026, which is enough history for a 14-day indicator to settle once the warm-up described under “What can go wrong” has passed.

Step 2: the RSI Python function, Wilder’s way

The RSI compares the size of recent up days with the size of recent down days. Take each day’s change in the close, split it into a gain and a loss, and average each over 14 days. On an up day the gain is the change and the loss is zero; on a down day the loss is the size of the drop and the gain is zero. The ratio of average gain to average loss is the relative strength, RS, and the index is 100 - 100 / (1 + RS), which squeezes RS into a scale from 0 to 100.

Wilder’s averaging is what the old version skipped. The first average is a plain mean of the first 14 gains, and the same for losses. After that, each day’s average is the previous average times 13, plus today’s value, divided by 14. That is an exponential average with a smoothing factor of 1/14, which pandas computes with ewm(alpha=1/14, adjust=False) once the first value of the series is the 14-day mean. The smooth helper builds exactly that series.

def rsi_wilder(close, period=14):
    """Wilder's RSI: a simple average to start, then his smoothing (alpha = 1/period)."""
    delta = close.diff().dropna()
    gain, loss = delta.clip(lower=0), -delta.clip(upper=0)

    def smooth(x):
        seed = pd.Series([x.iloc[:period].mean()], index=[x.index[period - 1]])
        return pd.concat([seed, x.iloc[period:]]).ewm(alpha=1 / period, adjust=False).mean()

    avg_gain, avg_loss = smooth(gain), smooth(loss)
    rs = avg_gain / avg_loss
    rsi = 100 - 100 / (1 + rs)
    return rsi.where(avg_loss > 0, 100.0).reindex(close.index)


def rsi_sma(close, period=14):
    """The first version of this post: simple rolling averages of gains and losses."""
    delta = close.diff()
    gain, loss = delta.clip(lower=0), -delta.clip(upper=0)
    rs = gain.rolling(period).mean() / loss.rolling(period).mean()
    return 100 - 100 / (1 + rs)


rsi = rsi_wilder(close)
print(rsi.dropna().tail(3).round(1).to_string())
print(f"first RSI value: {rsi.first_valid_index():%Y-%m-%d}")
2026-10-22    64.8
2026-10-23    63.9
2026-10-26    57.7
first RSI value: 2025-11-14

The first RSI value lands on 14 November 2025, the 15th close in the data, because 14 daily changes need 15 prices. Earlier dates stay empty in the series so it lines up with the prices for charting. The last three readings show the index falling from the mid-60s as Apple’s close slipped over two sessions.

Step 3: check the result against Wilder’s recursion

A one-line pandas call is easy to get wrong without noticing. Leave adjust at its default, or seed the average with the first day’s change, and the numbers drift. So the check below writes Wilder’s update rule out as a plain Python loop and compares every value. The same block then lines the new RSI up against the rolling-mean version from the first edition of this post and plots the two.

# Wilder's recursion written out as a plain loop, to check the pandas version
delta = close.diff().dropna().to_numpy()
g, l = np.clip(delta, 0, None), np.clip(-delta, 0, None)
ag, al = g[:14].mean(), l[:14].mean()
loop = [100 - 100 / (1 + ag / al)]
for gi, li in zip(g[14:], l[14:]):
    ag, al = (ag * 13 + gi) / 14, (al * 13 + li) / 14
    loop.append(100 - 100 / (1 + ag / al))
check_gap = np.abs(np.array(loop) - rsi.dropna().to_numpy()).max()
print(f"largest gap, loop vs pandas: {check_gap:.1e}")

old = rsi_sma(close)
both = pd.DataFrame({"wilder": rsi, "sma": old}).dropna()
gap = (both["wilder"] - both["sma"]).abs()
zone = lambda s: np.select([s > 70, s < 30], ["above 70", "below 30"], "between")
disagree = (zone(both["wilder"]) != zone(both["sma"])).sum()
print(f"Wilder vs simple average: largest gap {gap.max():.1f} points on {gap.idxmax():%Y-%m-%d}, mean gap {gap.mean():.1f}")
print(f"days the two put AAPL in a different zone: {disagree} of {len(both)}")

# Chart: both versions, with the days they put Apple in different zones shaded
fig, ax = plt.subplots(figsize=(11, 4.5))
ax.plot(both.index, both["wilder"], color="#6a3d9a", lw=1.3, label="Wilder (this post)")
ax.plot(both.index, both["sma"], color="#e08214", lw=1.1, label="14-day rolling mean (first version)")
for day in both.index[zone(both["wilder"]) != zone(both["sma"])]:
    ax.axvspan(day - pd.Timedelta(hours=12), day + pd.Timedelta(hours=12), color="#999999", alpha=0.25, lw=0)
ax.axhline(70, color="#b2182b", ls="--", lw=0.9)
ax.axhline(30, color="#2166ac", ls="--", lw=0.9)
ax.set_ylim(0, 100)
ax.set_ylabel("RSI (14)")
ax.set_title("Apple (AAPL) 14-day RSI, Wilder vs rolling mean; grey = the two disagree on the zone")
ax.legend(loc="lower right", fontsize=9)
ax.grid(alpha=0.3)
fig.text(0.01, -0.02, "Data: Market Data (marketdata.app). Code: pythonandfinancehub.com", fontsize=8, color="gray")
plt.savefig("aapl-wilder-vs-sma.png", dpi=150, bbox_inches="tight")
largest gap, loop vs pandas: 2.8e-14
Wilder vs simple average: largest gap 24.4 points on 2025-12-22, mean gap 6.9
days the two put AAPL in a different zone: 45 of 237

The loop and the pandas version differ by at most 2.8e-14 points, which is floating-point rounding, so the vectorised function computes Wilder’s RSI. The largest gap from the old function, 24.4 points on 22 December 2025, falls inside the warm-up described under “What can go wrong”, so its exact size depends on where the series starts; the 6.9-point mean over the full year is the steadier comparison. A rolling mean drops each day’s change completely after 14 sessions, so a single large move jolts the reading twice, once when it enters the window and again when it drops out. Wilder’s average lets old changes fade a little each day. Two averages that weight the past this differently give different numbers, so a platform that uses Wilder’s method will disagree with the rolling-mean code, on some days by a whole zone.

Apple (AAPL) 14-day RSI from November 2025 to October 2026 computed two ways, Wilder's smoothing in purple and a 14-day rolling mean in orange, with grey bands on the days the two place Apple in different zones relative to 70 and 30

The chart above plots both versions over the year. The grey bands mark the 45 days on which one version was above 70 or below 30 and the other was not. On those days the two readings were 11.3 points apart on average, against 6.9 over the whole year. On 42 of them it was the rolling-mean version that sat beyond 70 or 30 while Wilder’s stayed between 30 and 70. An average of only the last 14 changes reacts harder to a short run of up or down days, so it is usually the one that crosses.

Step 4: count the days above 70 and below 30

With the series in hand, counting readings above 70 and below 30 is a pair of comparisons. The crossings line keeps only the days when the RSI moved into one of the zones from outside it.

r = rsi.dropna()
above, below = (r > 70).sum(), (r < 30).sum()
crossings = r[((r > 70) & (r.shift() <= 70)) | ((r < 30) & (r.shift() >= 30))]
print(f"days above 70: {above}, days below 30: {below}")
print("crossings into a zone:")
print(crossings.round(1).to_string())
runs = ((r > 70) != (r > 70).shift()).cumsum()[r > 70]
longest = runs.value_counts().idxmax()
streak = r[r > 70][runs == longest]
print(f"longest run above 70: {len(streak)} days, {streak.index[0]:%Y-%m-%d} to {streak.index[-1]:%Y-%m-%d}")
print(f"latest: RSI {r.iloc[-1]:.1f} on {r.index[-1]:%Y-%m-%d}")
days above 70: 21, days below 30: 12
crossings into a zone:
2025-12-01    72.6
2026-01-06    28.5
2026-01-14    29.8
2026-05-08    72.9
2026-06-02    73.6
2026-07-16    71.4
longest run above 70: 15 days, 2026-05-08 to 2026-05-29
latest: RSI 57.7 on 2026-10-26

Apple’s year produced 6 crossings, 4 into the zone above 70 and 2 into the zone below 30. Both of the low ones came in January. The RSI dipped under 30 on 6 January, edged back above it and went under again on 14 January. The longest run above 70 lasted 15 trading days, from 8 May to 29 May 2026. That describes one stock over one year. The counts say nothing about what came after each crossing, and testing that would be a backtest with its own rules, costs and sample-size problems; the portfolio backtesting post on this site builds that kind of framework. Backtest results are hypothetical, based on past data only, and are not an indication of future results.

Step 5: chart the price and the RSI

The chart at the top of this post comes from the block below: the close on a tall panel, the RSI on a shorter one with dashed lines at 70 and 30, and the readings beyond those lines shaded. sharex=True keeps the two panels on the same dates, so a spike in the RSI sits directly under the move in the price that caused it.

fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(11, 7), sharex=True, gridspec_kw={"height_ratios": [3, 1.4]})
ax1.plot(close.index, close, color="#1f4e79", lw=1.4)
ax1.set_title("Apple (AAPL) daily close and 14-day RSI (Wilder), Oct 2025 to Oct 2026")
ax1.set_ylabel("Close (US$, split-adjusted)")
ax1.grid(alpha=0.3)
ax2.plot(rsi.index, rsi, color="#6a3d9a", lw=1.2)
ax2.axhline(70, color="#b2182b", ls="--", lw=0.9)
ax2.axhline(30, color="#2166ac", ls="--", lw=0.9)
ax2.fill_between(rsi.index, 70, rsi, where=rsi > 70, color="#b2182b", alpha=0.25)
ax2.fill_between(rsi.index, 30, rsi, where=rsi < 30, color="#2166ac", alpha=0.25)
ax2.set_ylim(0, 100)
ax2.set_ylabel("RSI (14)")
ax2.grid(alpha=0.3)
fig.text(0.01, 0.005, "Data: Market Data (marketdata.app). Code: pythonandfinancehub.com", fontsize=8, color="gray")
plt.tight_layout()
plt.savefig("aapl-chart.png", dpi=150, bbox_inches="tight")

The script saves aapl-chart.png in the current working directory. Swap savefig for plt.show() to open the chart in a window instead.

What can go wrong

The block below runs two of the checks behind this section on the same Apple data.

# Same RSI, started three months later: the early values carry the starting point
late = rsi_wilder(close.loc["2026-01-26":])
gaps = (late - rsi).abs().dropna()
print(f"first 20 days of the later series: gap up to {gaps.iloc[:20].max():.1f} points")
print(f"on {close.index[-1]:%Y-%m-%d}: {rsi.iloc[-1]:.4f} vs {late.iloc[-1]:.4f}")

# Same RSI on closes adjusted for dividends too (Market Data's default for daily candles)
adj = daily_closes("AAPL", "2025-10-27", "2026-10-26", adjust_dividends=True)
adj_gap = (rsi_wilder(adj) - rsi).abs().max()
print(f"largest RSI gap, dividend-adjusted vs split-adjusted closes: {adj_gap:.2f} points")

# Chart: the full-year RSI and the one started on 26 January, over the later series' first months
window = slice("2026-01-26", "2026-05-29")
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(11, 6), sharex=True, gridspec_kw={"height_ratios": [2.2, 1]})
ax1.plot(rsi.loc[window].index, rsi.loc[window], color="#6a3d9a", lw=1.3, label="started 27 Oct 2025")
ax1.plot(late.loc[window].index, late.loc[window], color="#1b7837", lw=1.1, ls="--", label="started 26 Jan 2026")
ax1.set_ylim(0, 100)
ax1.set_ylabel("RSI (14)")
ax1.set_title("Apple (AAPL) 14-day Wilder RSI from two start dates")
ax1.legend(loc="lower right", fontsize=9)
ax1.grid(alpha=0.3)
ax2.plot(gaps.loc[window].index, gaps.loc[window], color="#4d4d4d", lw=1.2)
ax2.set_ylabel("Gap (points)")
ax2.grid(alpha=0.3)
fig.text(0.01, -0.01, "Data: Market Data (marketdata.app). Code: pythonandfinancehub.com", fontsize=8, color="gray")
plt.tight_layout()
plt.savefig("aapl-rsi-start-date.png", dpi=150, bbox_inches="tight")

figures = {
    "n_days": len(close),
    "rsi_latest": float(r.iloc[-1]),
    "max_gap": float(gap.max()),
    "mean_gap": float(gap.mean()),
    "disagree": int(disagree),
    "n_both": len(both),
    "disagree_gap": float(gap[zone(both["wilder"]) != zone(both["sma"])].mean()),
    "sma_only": int(((zone(both["wilder"]) == "between") & (zone(both["sma"]) != "between")).sum()),
    "days_above": int(above),
    "days_below": int(below),
    "n_cross": len(crossings),
    "streak_len": len(streak),
    "late_gap_20": float(gaps.iloc[:20].max()),
    "adj_gap": float(adj_gap),
    "close_min": float(close.min()),
    "close_max": float(close.max()),
}
first 20 days of the later series: gap up to 11.0 points
on 2026-10-26: 57.6911 vs 57.6912
largest RSI gap, dividend-adjusted vs split-adjusted closes: 0.61 points

The start date moves the early values. Wilder’s average never fully forgets its first 14 days, so an RSI started on a different date gives different numbers until the starting point fades. Starting the same calculation in late January 2026 put it up to 11.0 points away from the full-year series during its first 20 days; by 26 October 2026 they matched to three decimal places, 57.6911 against 57.6912. This is the problem Cutler’s variant was meant to remove. The practical fix is to request a few months more history than you plan to show and to throw away the warm-up period. This post’s own series starts on 14 November 2025, so the December crossing and the January readings in Step 4 sit inside its warm-up and could move with a longer request, possibly enough to change the crossing count. Your numbers will also differ slightly from a charting platform that started its calculation years earlier.

Apple (AAPL) 14-day Wilder RSI from late January to late May 2026 computed from two start dates, October 2025 and January 2026, with the gap between them in a lower panel shrinking towards zero

The chart overlays the two series to the end of May. The later one has its first value on 13 February, its 15th close, and the gap in the lower panel is widest on that day. It stays above a point until 7 April and is close to zero by May.

Adjusted prices. Market Data adjusts daily candles for dividends by default. On Apple, switching between dividend-adjusted and split-only closes moved the RSI by at most 0.61 points over the year, which fits a small dividend against closes between $247 and $348. Apple’s quarterly cash dividend was $0.26 a share as of 27 September 2025, according to its 10-K for fiscal 2025, and the board declared $0.27 a share payable on 13 August 2026, according to the June-quarter results filed on Form 8-K. In split-only prices the mechanical drop on each ex-dividend date shrinks that day’s gain or adds to its loss. For a stock whose dividend is large next to its daily moves, the two series can drift further apart, so pick one and set adjustdividends explicitly.

Tokens. Without a token, a request for another ticker such as MSFT comes back with status error and the message “Invalid token header. No credentials provided.”, which daily_closes raises as a RuntimeError. Set MARKETDATA_TOKEN in your shell so the token stays out of the script. Check the plan limits on Market Data’s site before requesting long histories for many tickers.

Thresholds and periods are conventions. Wilder’s defaults are the 70 and 30 levels and a 14-day period. A stock in a steady uptrend can stay above 70 for weeks, as Apple did in May. Change period in rsi_wilder and rerun Step 4 to see how the counts move with a shorter or longer window.

What to watch

The figures end on 26 October 2026. To update them, change the end date in the daily_closes calls and rerun the whole script. Apple posts its quarterly results and dividend declarations on its investor relations site; each new ex-dividend date adds one more small gap between the two price series.

Two outside changes could shift the numbers without an error message. Market Data might change a default of the candles endpoint; its documentation lists the current ones, and the code sets adjustdividends explicitly for that reason. In pandas, the behaviour of ewm(adjust=False) is the part to retest after an upgrade; the loop in Step 3 catches any change.

The RSI is the second of the technical indicators in this series, after moving averages in Python, and the MACD in Python post builds its indicator from exponential moving averages of the price. For company fundamentals from filings, the SEC EDGAR API tutorial pulls a company’s financial statements with no API key.

My longer company research is published on the newsletter Sector Playbook, which is available by email subscription.

Sources

Market Data, stock candles endpoint (timestamps, split and dividend adjustment defaults) and authentication (AAPL without a token). Apple Inc., Form 10-K for fiscal 2025 (quarterly cash dividend) and Form 8-K, Exhibit 99.1, June quarter 2026 (dividend declared July 2026). pandas, Series.ewm. Relative strength index (Wilder’s 1978 definition, the 70 and 30 levels, Wilder’s smoothing and Cutler’s variant).

*Time: 15 minutes. Python 3.12.14, matplotlib 3.11.2, numpy 2.5.4, pandas 3.1.0, requests 2.34.2. API key: none for AAPL, which Market Data serves without a token; most other tickers need your own token. Market Data provides this site’s data access. Tested 27 October 2026.*

Disclaimer

This article is general information about a listed company, written for educational purposes. It is not investment advice and not a personal recommendation to buy, sell or hold any security, and it does not take into account anyone’s financial situation or objectives. I am not a registered investment adviser or a licensed financial services provider. Figures come from company filings and the other sources linked in the text, as of the dates given, and may have changed since. I may hold positions in the securities discussed; see the disclosure above. Investment decisions call for independent research or the advice of a licensed professional.

This is my own research, done with the help of AI tools.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.