Vivek Jha
Vivek Jha

Reputation: 1590

Slow Stochastic Implementation in Python Pandas

I am new to pandas and I need a function for calculating slow stochastic. I think it should be possible without much difficulty but I am not familiar with advanced APIs in pandas.

My data frame contains, 'open', 'high', 'low' and 'close' prices and it is indexed on dates. This much information should be enough to calculate slow stochastic.

Following is the formula for calculating Slow Stochastic:
%K = 100[(C - L14)/(H14 - L14)] 

C = the most recent closing price 
L14 = the low of the 14 previous trading sessions 
H14 = the highest price traded during the same 14-day period.

%D = 3-period moving average of %K 

Upvotes: 4

Views: 12028

Answers (3)

user11186769
user11186769

Reputation:

You can use the following simple function to handle both slow and fast stochastics.

def stochastics(dataframe, low, high, close, k, d ):
    """
    Fast stochastic calculation
    %K = (Current Close - Lowest Low)/
    (Highest High - Lowest Low) * 100
    %D = 3-day SMA of %K

    Slow stochastic calculation
    %K = %D of fast stochastic
    %D = 3-day SMA of %K

    When %K crosses above %D, buy signal 
    When the %K crosses below %D, sell signal
    """

    df = dataframe.copy()

    # Set minimum low and maximum high of the k stoch
    low_min  = df[low].rolling( window = k ).min()
    high_max = df[high].rolling( window = k ).max()

    # Fast Stochastic
    df['k_fast'] = 100 * (df[close] - low_min)/(high_max - low_min)
    df['k_fast'].ffill(inplace=True)
    df['d_fast'] = df['k_fast'].rolling(window = d).mean()

    # Slow Stochastic
    df['k_slow'] = df["d_fast"]
    df['d_slow'] = df['k_slow'].rolling(window = d).mean()

    return df


stochs = stochastics( df, 'Low', 'High', 'Close', 14, 3 )
slow_k = stochs['k_slow'].values
fast_k = stochs['k_fast'].values

Upvotes: 11

Vivek Jha
Vivek Jha

Reputation: 1590

I think what I have done is correct, can someone please verify:

def simple_moving_average(prices, period=26):
    """
    :param df: pandas dataframe object
    :param period: periods for calculating SMA
    :return: a pandas series
    """
    weights = np.repeat(1.0, period)/period
    sma = np.convolve(prices, weights, 'valid')
    return sma


def fast_stochastic(lowp, highp, closep, period=14, smoothing=3):
    """ calculate slow stochastic
    Fast stochastic calculation
    %K = (Current Close - Lowest Low)/(Highest High - Lowest Low) * 100
    %D = 3-day SMA of %K
    """
    low_min = pd.rolling_min(lowp, period)
    high_max = pd.rolling_max(highp, period)
    k_fast = 100 * (closep - low_min)/(high_max - low_min)
    k_fast = k_fast.dropna()
    d_fast = simple_moving_average(k_fast, smoothing)
    return k_fast, d_fast


def slow_stochastic(lowp, highp, closep, period=14, smoothing=3):
    """ calculate slow stochastic
    Slow stochastic calculation
    %K = %D of fast stochastic
    %D = 3-day SMA of %K
    """
    k_fast, d_fast = fast_stochastic(lowp, highp, closep, period=period, smoothing=smoothing)

    # D in fast stochastic is K in slow stochastic
    k_slow = d_fast
    d_slow = simple_moving_average(k_slow, smoothing)
    return k_slow, d_slow

Upvotes: 3

Ami Tavory
Ami Tavory

Reputation: 76316

You can do this with the rolling_* family of functions.

E.g., 100[(C - L14)/(H14 - L14)] can be found by:

import pandas as pd

l, h = pd.rolling_min(c, 4), pd.rolling_max(c, 4)
k = 100 * (c - l) / (h - l) 

and the rolling mean can be found by:

pd.rolling_mean(k, 3)

Moreover, if you're into this stuff, you can check out pandas & econometrics.

Upvotes: 5

Related Questions