Attachments forums

Re: Python to MT5

Banzai, Mon Nov 16, 2026 9:06 am

Links: | TradingView | TradeStation | NinjaTrader | MT4 | MT5 | Python |

Jack & Jill

Python: December 2026

The Python code shown here is an implementation of John Ehlers’ indicators described in his article in this issue, “The Jack & Jill Indicator.”

Code: Select all

"""
Python implementation of the Jack and Jill indicator using adaptive
and contra-adaptive SuperSmoother filters, with an illustrative
long or cash trading rule and a chart of the resulting signals.

Copy the code sections into Jupyter notebook cells and run in order.
The example uses SPY and a 120-bar base period. Change the ticker,
dates and period to explore other instruments and settings.

Written by:
Rajeev Jain, October 2026
jainraje@yahoo.com

Complete source code:
https://github.com/jainraje/TraderTipArticles/
"""

# import required python modules
import pandas as pd
import numpy as np
import yfinance as yf

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.collections import LineCollection
from matplotlib.lines import Line2D

print(yf.__version__)

# get SPY price data from Yahoo Finance

# Choose the ticker and history range; Yahoo excludes end_date itself.
ticker = 'SPY'
start_date = "1995-01-01"
end_date = "2026-10-17"

ohlcv = yf.download(
    ticker, 
    start=start_date, 
    end=end_date, 
    #group_by="Ticker",
    auto_adjust=False,
)
ohlcv = ohlcv.stack('Ticker', future_stack=True ).reset_index().set_index('Date')
ohlcv
# indicator functions

import numpy as np
import pandas as pd
from math import exp, cos, sqrt


# Calculate one SuperSmoother value from the current price and prior values.
# Shared by the fixed-period filter and the adaptive Jack and Jill filters.
def _smoother_step(close, previous_close, y1, y2, period):
    """One SuperSmoother calculation, shared by both routines."""
    q = exp(-1.414 * 3.14159 / period)
    c1 = 2 * q * cos(1.414 * np.pi / period)
    c2 = q * q
    a0 = (1 - c1 + c2) / 2

    return a0 * (close + previous_close) + c1 * y1 - c2 * y2


# Smooth a complete price Series; period can be fixed or one value per bar.
def super_smoother(close, period):
    """Period can be fixed or an array containing one period per bar."""
    close = pd.Series(close, dtype=float)
    x = close.to_numpy()
    periods = np.broadcast_to(np.asarray(period, dtype=float), x.shape)
    output = x.copy()

    for i in range(3, len(x)):
        output[i] = _smoother_step(
            x[i], x[i - 1],
            output[i - 1], output[i - 2],
            periods[i],
        )

    return pd.Series(output, index=close.index, name="SuperSmoother")


# Measure recent change magnitude over length bars for normalization.
# Missing initial history is treated as zero; a zero sum retains the last RMS.
def rms(price, length):
    """Rolling RMS with zero-padded initial history."""
    price = pd.Series(price, dtype=float)

    result = np.sqrt(
        price.pow(2).rolling(length, min_periods=1).sum() / length
    )

    # Preserve the article's behavior when SumSq is zero.
    return result.replace(0, np.nan).ffill().fillna(0)


# Build the adaptive Jack and contra-adaptive Jill lines in one forward pass.
# period0 controls their base responsiveness; return Jack, Jill and Jack-Jill.
def jack_jill(close, period0=20):
    close = pd.Series(close, dtype=float)
    x = close.to_numpy()
    n = len(x)

    if not n or not np.isfinite(x).all():
        raise ValueError("close must contain finite prices.")
    if not np.isfinite(period0) or period0 < 2:
        raise ValueError("period0 must be finite and at least 2.")

    jack = np.empty(n)
    jill = np.empty(n)

    jack_changes = np.zeros(n)
    jill_changes = np.zeros(n)

    jack_period = jill_period = 20.0
    jack_rms = jill_rms = 0.0
    jack_roc = jill_roc = 0.0

    for i in range(n):
        if i < 3:
            jack[i] = jill[i] = x[i]
        else:
            jack[i] = _smoother_step(
                x[i], x[i - 1],
                jack[i - 1], jack[i - 2],
                jack_period,
            )
            jill[i] = _smoother_step(
                x[i], x[i - 1],
                jill[i - 1], jill[i - 2],
                jill_period,
            )

        # Zero prehistory, matching the preceding implementation.
        jack_changes[i] = jack[i] - (jack[i - 1] if i else 0.0)
        jill_changes[i] = jill[i] - (jill[i - 1] if i else 0.0)

        # Evaluate only the current 81-bar window.
        start = max(0, i - 80)
        jc = jack_changes[start:i + 1]
        lc = jill_changes[start:i + 1]

        jack_sum_sq = float(np.dot(jc, jc))
        jill_sum_sq = float(np.dot(lc, lc))

        if jack_sum_sq != 0:
            jack_rms = sqrt(jack_sum_sq / 81)

        if jill_sum_sq != 0:
            jill_rms = sqrt(jill_sum_sq / 81)

        if jack_rms != 0:
            jack_roc = min(abs(jack_changes[i] / jack_rms), 2)

        if jill_rms != 0:
            jill_roc = min(abs(jill_changes[i] / jill_rms), 2)

        # These periods apply to the NEXT bar.
        jack_period = max(
            2, period0 * (1 - 0.5 * jack_roc) ** 2
        )
        jill_period = period0 * (1 + 0.5 * jill_roc) ** 2

    return pd.DataFrame(
        {
            "Jack": jack,
            "Jill": jill,
            "Oscillator": jack - jill,
        },
        index=close.index,
    )


# Remove a session gap when the bar time equals session_open + time_bars.
# Times use HHMM arithmetic; this helper is not used in the daily example.
def degap(price, session_open, time_bars):
    """Price must have a DatetimeIndex in the session timezone."""
    price = pd.Series(price, dtype=float)
    x = price.to_numpy()
    output = np.empty(len(x))
    times = price.index.hour * 100 + price.index.minute
    gap = 0.0

    for i in range(len(x)):
        if times[i] == session_open + time_bars:
            previous = output[i - 1] if i else 0.0
            gap = x[i] - previous

        output[i] = x[i] - gap

    return pd.Series(output, index=price.index, name="Degapped")


df = ohlcv.copy()
# Change period0 to tune responsiveness; calculate before slicing history.
df = df.join(jack_jill(df["Close"], period0=120))
df




# Illustrative long/cash rule using (Jack - Jill) / Close.
# Enter when the spread is above 0; exit when it is below -0.04 (-4%).
# Between thresholds, including equality, keep the previous signal.
# Start in cash. Return a copy with Signal: 1 = long, 0 = cash.
# Change the entry/exit thresholds below to suit the intended trading rule.
# Signals use closing data; model execution separately when backtesting.
def trading_logic(df):
    df = df.copy()

    if df.empty:
        return df

    # Divide by Close so thresholds are comparable across price levels.
    oscillator = (df["Jack"] - df["Jill"]) / df["Close"]

    # Adjust 0 and -0.04 for entry and exit; -0.04 means a -4% spread.
    df["Signal"] = np.select(
        [oscillator > 0, oscillator < -0.04],
        [1, 0],
        default=np.nan,
    )

    # Signal: 1 = long, 0 = cash. Start in cash; hold state between thresholds.
    df.iloc[0, df.columns.get_loc("Signal")] = 0
    df["Signal"] = df["Signal"].ffill().astype(int)

    return df
    
df = trading_logic(df)
df

import matplotlib.pyplot as plt

# Plot price, Jack, Jill and the percentage spread for the supplied DataFrame.
# Pass a date slice to limit the chart; markers and shading follow Signal.
# Title is centered and the figure is 9 by 6; edit styling here as needed.
def plot_signals(df, title="Jack & Jill"):
    """Plot indicators, signal-date markers and matching long-state shading."""
    d = df.copy()
    if d.empty:
        raise ValueError("DataFrame is empty.")
    # Mark signal changes at that day’s close, not at an execution price.
    change = d["Signal"].diff().fillna(0)
    invested = d["Signal"].eq(1)
    previous = invested.shift(fill_value=False)
    starts = list(d.index[invested & ~previous])
    ends = list(d.index[~invested & previous])
    if invested.iloc[-1]:
        ends.append(d.index[-1])

    fig, ax = plt.subplots(
        2, 1, figsize=(9, 6), sharex=True, layout="constrained",
        gridspec_kw={"height_ratios": [3, 1]}
    )
    for col, color in [("Close", "#586575"), ("Jack", "#1265c8"), ("Jill", "#e38a19")]:
        ax[0].plot(d.index, d[col], color=color, lw=1.3, label=col)
    for mask, marker, color, label in [
        (change.gt(0), "^", "#129252", "Buy signal"),
        (change.lt(0), "v", "#cd3349", "Sell signal")
    ]:
        ax[0].scatter(
            d.index[mask], d.loc[mask, "Close"], marker=marker, color=color,
            s=65, edgecolors="white", zorder=5, label=label
        )

    # If trading thresholds change, update the chart guide lines below too.
    spread = 100 * (d["Jack"] - d["Jill"]) / d["Close"]
    ax[1].plot(d.index, spread, color="#7954ac", label="Spread (%)")
    ax[1].axhline(0, color="gray", ls="--", lw=.9, label="Entry: 0%")
    ax[1].axhline(-1, color="#cd3349", ls="--", lw=.9, label="Exit: −1%")
    for a, label in zip(ax, ["Price", "Spread (%)"]):
        for start, end in zip(starts, ends):
            a.axvspan(start, end, color="#129252", alpha=.06, lw=0)
        a.set_ylabel(label)
        a.legend(loc="upper left", ncol=3, frameon=False, fontsize=8)
        a.tick_params(labelsize=8)
        a.grid(alpha=.15)
        a.spines[["top", "right"]].set_visible(False)
    ax[0].set_title(title, loc="center")
    return fig, ax

# Select the chart date range here; keep full history for indicator calculation.
fig, ax = plot_signals(signals["2026":], title="SPY - Jack & Jill Indicator & Trading Signals, period=120")
plt.show()
An example of the Jack & Jill indicator and oscillator are plotted on a daily chart of SPY, shown in Figure 8.

Sample Chart FIGURE 8: PYTHON. The Jack & Jill indicator is plotted on a daily chart of SPY.
All files in topic