Skip to content

inject ¤

cci ¤

cci(series, window=14)

compute commodity channel index

Source code in lettrade/indicator/vendor/qtpylib/qtpylib.py
469
470
471
472
473
474
475
476
def cci(series, window=14):
    """
    compute commodity channel index
    """
    price = typical_price(series)
    typical_mean = rolling_mean(price, window)
    res = (price - typical_mean) / (0.015 * np.std(typical_mean))
    return pd.Series(index=series.index, data=res)

ibs ¤

ibs(bars)

Internal bar strength

Source code in lettrade/indicator/vendor/qtpylib/qtpylib.py
173
174
175
176
def ibs(bars):
    """Internal bar strength"""
    res = np.round((bars["close"] - bars["low"]) / (bars["high"] - bars["low"]), 2)
    return pd.Series(index=bars.index, data=res)

macd ¤

macd(series, fast=3, slow=10, smooth=16)

compute the MACD (Moving Average Convergence/Divergence) using a fast and slow exponential moving avg' return value is emaslow, emafast, macd which are len(x) arrays

Source code in lettrade/indicator/vendor/qtpylib/qtpylib.py
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
def macd(series, fast=3, slow=10, smooth=16):
    """
    compute the MACD (Moving Average Convergence/Divergence)
    using a fast and slow exponential moving avg'
    return value is emaslow, emafast, macd which are len(x) arrays
    """
    macd_line = rolling_weighted_mean(series, window=fast) - rolling_weighted_mean(
        series, window=slow
    )
    signal = rolling_weighted_mean(macd_line, window=smooth)
    histogram = macd_line - signal
    # return macd_line, signal, histogram
    return pd.DataFrame(
        index=series.index,
        data={
            "macd": macd_line.values,
            "signal": signal.values,
            "histogram": histogram.values,
        },
    )

pvt ¤

pvt(bars)

Price Volume Trend

Source code in lettrade/indicator/vendor/qtpylib/qtpylib.py
541
542
543
544
545
546
def pvt(bars):
    """Price Volume Trend"""
    trend = ((bars["close"] - bars["close"].shift(1)) / bars["close"].shift(1)) * bars[
        "volume"
    ]
    return trend.cumsum()

roc ¤

roc(series, window=14)

compute rate of change

Source code in lettrade/indicator/vendor/qtpylib/qtpylib.py
461
462
463
464
465
466
def roc(series, window=14):
    """
    compute rate of change
    """
    res = (series - series.shift(window)) / series.shift(window)
    return pd.Series(index=series.index, data=res)

rolling_vwap ¤

rolling_vwap(bars, window=200, min_periods=None)

calculate vwap using moving window (input can be pandas series or numpy array) bars are usually mid [ (h+l)/2 ] or typical [ (h+l+c)/3 ]

Source code in lettrade/indicator/vendor/qtpylib/qtpylib.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
def rolling_vwap(bars, window=200, min_periods=None):
    """
    calculate vwap using moving window
    (input can be pandas series or numpy array)
    bars are usually mid [ (h+l)/2 ] or typical [ (h+l+c)/3 ]
    """
    min_periods = window if min_periods is None else min_periods

    typical = (bars["high"] + bars["low"] + bars["close"]) / 3
    volume = bars["volume"]

    left = (volume * typical).rolling(window=window, min_periods=min_periods).sum()
    right = volume.rolling(window=window, min_periods=min_periods).sum()

    return (
        pd.Series(index=bars.index, data=(left / right))
        .replace([np.inf, -np.inf], float("NaN"))
        .ffill()
    )

rsi ¤

rsi(series, window=14)

compute the n period relative strength indicator

Source code in lettrade/indicator/vendor/qtpylib/qtpylib.py
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
def rsi(series, window=14):
    """
    compute the n period relative strength indicator
    """

    # 100-(100/relative_strength)
    deltas = np.diff(series)
    seed = deltas[: window + 1]

    # default values
    ups = seed[seed > 0].sum() / window
    downs = -seed[seed < 0].sum() / window
    rsival = np.zeros_like(series)
    rsival[:window] = 100.0 - 100.0 / (1.0 + ups / downs)

    # period values
    for i in range(window, len(series)):
        delta = deltas[i - 1]
        if delta > 0:
            upval = delta
            downval = 0
        else:
            upval = 0
            downval = -delta

        ups = (ups * (window - 1) + upval) / window
        downs = (downs * (window - 1.0) + downval) / window
        rsival[i] = 100.0 - 100.0 / (1.0 + ups / downs)

    # return rsival
    return pd.Series(index=series.index, data=rsival)

session ¤

session(df, start='17:00', end='16:00')

remove previous globex day from df

Source code in lettrade/indicator/vendor/qtpylib/qtpylib.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
def session(df, start="17:00", end="16:00"):
    """remove previous globex day from df"""
    if df.empty:
        return df

    # get start/end/now as decimals
    int_start = list(map(int, start.split(":")))
    int_start = (int_start[0] + int_start[1] - 1 / 100) - 0.0001
    int_end = list(map(int, end.split(":")))
    int_end = int_end[0] + int_end[1] / 100
    int_now = df[-1:].index.hour[0] + (df[:1].index.minute[0]) / 100

    # same-dat session?
    is_same_day = int_end > int_start

    # set pointers
    curr = prev = df[-1:].index[0].strftime("%Y-%m-%d")

    # globex/forex session
    if not is_same_day:
        prev = (datetime.strptime(curr, "%Y-%m-%d") - timedelta(1)).strftime("%Y-%m-%d")

    # slice
    if int_now >= int_start:
        df = df[df.index >= curr + " " + start]
    else:
        df = df[df.index >= prev + " " + start]

    return df.copy()

stoch ¤

stoch(df, window=14, d=3, k=3, fast=False)

compute the n period relative strength indicator http://excelta.blogspot.co.il/2013/09/stochastic-oscillator-technical.html

Source code in lettrade/indicator/vendor/qtpylib/qtpylib.py
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
def stoch(df, window=14, d=3, k=3, fast=False):
    """
    compute the n period relative strength indicator
    http://excelta.blogspot.co.il/2013/09/stochastic-oscillator-technical.html
    """

    my_df = pd.DataFrame(index=df.index)

    my_df["rolling_max"] = df["high"].rolling(window).max()
    my_df["rolling_min"] = df["low"].rolling(window).min()

    my_df["fast_k"] = (
        100
        * (df["close"] - my_df["rolling_min"])
        / (my_df["rolling_max"] - my_df["rolling_min"])
    )
    my_df["fast_d"] = my_df["fast_k"].rolling(d).mean()

    if fast:
        return my_df.loc[:, ["fast_k", "fast_d"]]

    my_df["slow_k"] = my_df["fast_k"].rolling(k).mean()
    my_df["slow_d"] = my_df["slow_k"].rolling(d).mean()

    return my_df.loc[:, ["slow_k", "slow_d"]]

vwap ¤

vwap(bars)

calculate vwap of entire time series (input can be pandas series or numpy array) bars are usually mid [ (h+l)/2 ] or typical [ (h+l+c)/3 ]

Source code in lettrade/indicator/vendor/qtpylib/qtpylib.py
302
303
304
305
306
307
308
309
310
311
def vwap(bars):
    """
    calculate vwap of entire time series
    (input can be pandas series or numpy array)
    bars are usually mid [ (h+l)/2 ] or typical [ (h+l+c)/3 ]
    """
    raise ValueError(
        "using `qtpylib.vwap` facilitates lookahead bias. Please use "
        "`qtpylib.rolling_vwap` instead, which calculates vwap in a rolling manner."
    )

zlma ¤

zlma(series, window=20, min_periods=None, kind='ema')

John Ehlers' Zero lag (exponential) moving average https://en.wikipedia.org/wiki/Zero_lag_exponential_moving_average

Source code in lettrade/indicator/vendor/qtpylib/qtpylib.py
506
507
508
509
510
511
512
513
514
515
516
517
518
519
def zlma(series, window=20, min_periods=None, kind="ema"):
    """
    John Ehlers' Zero lag (exponential) moving average
    https://en.wikipedia.org/wiki/Zero_lag_exponential_moving_average
    """
    min_periods = window if min_periods is None else min_periods

    lag = (window - 1) // 2
    series = 2 * series - series.shift(lag)
    if kind in ["ewm", "ema"]:
        return wma(series, lag, min_periods)
    elif kind == "hma":
        return hma(series, lag, min_periods)
    return sma(series, lag, min_periods)

zscore ¤

zscore(bars, window=20, stds=1, col='close')

get zscore of price

Source code in lettrade/indicator/vendor/qtpylib/qtpylib.py
534
535
536
537
538
def zscore(bars, window=20, stds=1, col="close"):
    """get zscore of price"""
    std = numpy_rolling_std(bars[col], window)
    mean = numpy_rolling_mean(bars[col], window)
    return (bars[col] - mean) / (std * stds)