DOC MAINT STY #476

This commit is contained in:
Kevin Johnson
2022-02-08 12:09:00 -08:00
parent fc0d2cc439
commit 4843614925
134 changed files with 1017 additions and 888 deletions
+2 -1
View File
@@ -27,7 +27,8 @@ def cdl_doji(
length (int): The period. Default: 10
factor (float): Doji value. Default: 100
scalar (float): How much to magnify. Default: 100
asint (bool): Keep results numerical instead of boolean. Default: True
asint (bool): Keep results numerical instead of boolean.
Default: True
Kwargs:
naive (bool, optional): If True, prefills potential Doji less than
+7 -6
View File
@@ -10,13 +10,14 @@ def cdl_inside(
) -> Series:
"""Candle Type: Inside Bar
An Inside Bar is a bar that is engulfed by the prior highs and lows of it's
previous bar. In other words, the current bar is smaller than it's previous
bar.
An Inside Bar is a bar that is engulfed by the prior highs and lows of
it's previous bar. In other words, the current bar is smaller than it's
previous bar.
Set asbool=True if you want to know if it is an Inside Bar. Note by default
asbool=False so this returns a 0 if it is not an Inside Bar, 1 if it is an
Inside Bar and close > open, and -1 if it is an Inside Bar but close < open.
Set asbool=True if you want to know if it is an Inside Bar. Note by
default asbool=False so this returns a 0 if it is not an Inside Bar, 1 if
it is an Inside Bar and close > open, and -1 if it is an Inside Bar
but close < open.
Sources:
https://www.tradingview.com/script/IyIGN1WO-Inside-Bar/
+2 -2
View File
@@ -38,11 +38,11 @@ def cdl_pattern(
df = df.ta.cdl_pattern(name="all")
Get only one pattern::
df = df.ta.cdl_pattern(name="doji")
Get some patterns::
df = df.ta.cdl_pattern(name=["doji", "inside"])
Args:
+2 -1
View File
@@ -52,7 +52,8 @@ def ha(
})
for i in range(1, m):
df["HA_open"].iloc[i] = 0.5 * (df["HA_open"].iloc[i - 1] + df["HA_close"].iloc[i - 1])
df["HA_open"].iloc[i] = 0.5 * (df["HA_open"].iloc[i - 1] \
+ df["HA_close"].iloc[i - 1])
df["HA_high"] = df[["HA_open", "HA_high", "HA_close"]].max(axis=1)
df["HA_low"] = df[["HA_open", "HA_low", "HA_close"]].min(axis=1)
+20 -17
View File
@@ -11,20 +11,23 @@ def ebsw(
) -> Series:
"""Even Better SineWave (EBSW)
This indicator measures market cycles and uses a low pass filter to remove noise.
Its output is bound signal between -1 and 1 and the maximum length of a detected
trend is limited by its length input.
This indicator measures market cycles and uses a low pass filter to
remove noise. Its output is bound signal between -1 and 1 and the
maximum length of a detected trend is limited by its length input.
Written by rengel8 for Pandas TA based on a publication at 'prorealcode.com' and
a book by J.F.Ehlers. According to the suggestion by Squigglez2* and major differences between
the initial version's output close to the implementation from Ehler's, the default version is now
more closely related to the code from pro-realcode.
Written by rengel8 for Pandas TA based on a publication at
'prorealcode.com' and a book by J.F.Ehlers. According to the suggestion
by Squigglez2* and major differences between the initial version's
output close to the implementation from Ehler's, the default version is
now more closely related to the code from pro-realcode.
Remark:
The default version is now more cycle oriented and tends to be less whipsaw-prune. Thus the older version
might offer earlier signals at medium and stronger reversals.
A test against the version at TradingView showed very close results with the advantage to be one bar/candle
faster, than the corresponding reference value. This might be pre-roll related and was not further investigated.
The default version is now more cycle oriented and tends to be less
whipsaw-prune. Thus the older version might offer earlier signals at
medium and stronger reversals. A test against the version at TradingView
showed very close results with the advantage to be one bar/candle faster,
than the corresponding reference value. This might be pre-roll related
and was not further investigated.
* https://github.com/twopirllc/pandas-ta/issues/350
Sources:
@@ -33,8 +36,8 @@ def ebsw(
Args:
close (pd.Series): Series of 'close's
length (int): It's max cycle/trend period. Values between 40-48 work like
expected with minimum value: 39. Default: 40.
length (int): It's max cycle/trend period. Values between 40-48
work like expected with minimum value: 39. Default: 40.
bars (int): Period of low pass filtering. Default: 10
drift (int): The difference period. Default: 1
offset (int): How many periods to offset the result. Default: 0
@@ -89,11 +92,11 @@ def ebsw(
# 3 Bar average of wave amplitude and power
wave = (filter_ + filtHist[1] + filtHist[0]) / 3
power_ = (
filter_ * filter_ + filtHist[1] * filtHist[1] + filtHist[0] * filtHist[0]) / 3
power_ = filter_ * filter_ + filtHist[1] * filtHist[1] \
+ filtHist[0] * filtHist[0]
power_ /= 3
# Normalize the Average Wave to Square Root of the Average Power
wave = wave / np.sqrt(power_)
wave = wave / sqrt(power_)
# update storage, result
filtHist.append(filter_) # append new filter_ value
+8 -6
View File
@@ -49,13 +49,15 @@ def reflex(
"""Reflex (reflex)
John F. Ehlers introduced two indicators within the article
"Reflex: A New Zero-Lag Indicator” in February 2020, TASC magazine. One of which
is the Reflex, a lag reduced cycle indicator. Both indicators (Reflex/Trendflex)
are oscillators and complement each other with the focus for cycle and trend.
"Reflex: A New Zero-Lag Indicator” in February 2020, TASC magazine. One
of which is the Reflex, a lag reduced cycle indicator. Both indicators
(Reflex/Trendflex) are oscillators and complement each other with the
focus for cycle and trend.
Written for Pandas TA by rengel8 (2021-08-11) based on the implementation on
ProRealCode (see Sources). Beyond the mentioned source, this implementation has
a separate control parameter for the internal applied SuperSmoother.
Written for Pandas TA by rengel8 (2021-08-11) based on the implementation
on ProRealCode (see Sources). Beyond the mentioned source, this
implementation has a separate control parameter for the internal
applied SuperSmoother.
Sources:
http://traders.com/Documentation/FEEDbk_docs/2020/02/TradersTips.html
+3 -2
View File
@@ -10,8 +10,9 @@ def ao(
) -> Series:
"""Awesome Oscillator (AO)
The Awesome Oscillator is an indicator used to measure a security's momentum.
AO is generally used to affirm trends or to anticipate possible reversals.
The Awesome Oscillator is an indicator used to measure a security's
momentum. AO is generally used to affirm trends or to anticipate
possible reversals.
Sources:
https://www.tradingview.com/wiki/Awesome_Oscillator_(AO)
+6 -5
View File
@@ -12,9 +12,10 @@ def apo(
) -> Series:
"""Absolute Price Oscillator (APO)
The Absolute Price Oscillator is an indicator used to measure a security's
momentum. It is simply the difference of two Exponential Moving Averages
(EMA) of two different periods. Note: APO and MACD lines are equivalent.
The Absolute Price Oscillator is an indicator used to measure a
security's momentum. It is simply the difference of two Exponential
Moving Averages (EMA) of two different periods. Note: APO and MACD lines
are equivalent.
Sources:
https://www.tradingtechnologies.com/xtrader-help/x-study/technical-indicator-definitions/absolute-price-oscillator-apo/
@@ -24,8 +25,8 @@ def apo(
fast (int): The short period. Default: 12
slow (int): The long period. Default: 26
mamode (str): See ``help(ta.ma)``. Default: 'sma'
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
+2 -2
View File
@@ -22,8 +22,8 @@ def bop(
low (pd.Series): Series of 'low's
close (pd.Series): Series of 'close's
scalar (float): How much to magnify. Default: 1
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
+4 -4
View File
@@ -13,8 +13,8 @@ def cci(
) -> Series:
"""Commodity Channel Index (CCI)
Commodity Channel Index is a momentum oscillator used to primarily identify
overbought and oversold levels relative to a mean.
Commodity Channel Index is a momentum oscillator used to primarily
identify overbought and oversold levels relative to a mean.
Sources:
https://www.tradingview.com/wiki/Commodity_Channel_Index_(CCI)
@@ -25,8 +25,8 @@ def cci(
close (pd.Series): Series of 'close's
length (int): It's period. Default: 14
c (float): Scaling Constant. Default: 0.015
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
+3 -2
View File
@@ -11,8 +11,9 @@ def cfo(
) -> Series:
"""Chande Forcast Oscillator (CFO)
The Forecast Oscillator calculates the percentage difference between the actual
price and the Time Series Forecast (the endpoint of a linear regression line).
The Forecast Oscillator calculates the percentage difference between
the actual price and the Time Series Forecast (the endpoint of a
linear regression line).
Sources:
https://www.fmlabs.com/reference/default.htm?url=ForecastOscillator.htm
+2 -2
View File
@@ -9,8 +9,8 @@ def cg(
) -> Series:
"""Center of Gravity (CG)
The Center of Gravity Indicator by John Ehlers attempts to identify turning
points while exhibiting zero lag and smoothing.
The Center of Gravity Indicator by John Ehlers attempts to identify
turning points while exhibiting zero lag and smoothing.
Sources:
http://www.mesasoftware.com/papers/TheCGOscillator.pdf
+5 -4
View File
@@ -22,14 +22,15 @@ def cmo(
Args:
close (pd.Series): Series of 'close's
scalar (float): How much to magnify. Default: 100
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. If TA Lib is not installed but talib is True, it runs the Python
version TA Lib. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. If TA Lib is not installed but talib is True,
it runs the Python version TA Lib. Default: True
drift (int): The short period. Default: 1
offset (int): How many periods to offset the result. Default: 0
Kwargs:
talib (bool): If True, uses TA-Libs implementation. Otherwise uses EMA version. Default: True
talib (bool): If True, uses TA-Libs implementation. Otherwise uses
EMA version. Default: True
fillna (value, optional): pd.DataFrame.fillna(value)
fill_method (value, optional): Type of fill method
+5 -5
View File
@@ -11,11 +11,11 @@ def coppock(
) -> Series:
"""Coppock Curve (COPC)
Coppock Curve (originally called the "Trendex Model") is a momentum indicator
is designed for use on a monthly time scale. Although designed for monthly
use, a daily calculation over the same period can be made, converting the
periods to 294-day and 231-day rate of changes, and a 210-day weighted
moving average.
Coppock Curve (originally called the "Trendex Model") is a momentum
indicator is designed for use on a monthly time scale. Although designed
for monthly use, a daily calculation over the same period can be made,
converting the periods to 294-day and 231-day rate of changes,
and a 210-day WMA.
Sources:
https://en.wikipedia.org/wiki/Coppock_curve
+5 -4
View File
@@ -10,10 +10,11 @@ def cti(
) -> Series:
"""Correlation Trend Indicator (CTI)
The Correlation Trend Indicator is an oscillator created by John Ehler in 2020.
It assigns a value depending on how close prices in that range are to following
a positively- or negatively-sloping straight line. Values range from -1 to 1.
This is a wrapper for ta.linreg(close, r=True).
The Correlation Trend Indicator is an oscillator created
by John Ehler in 2020. It assigns a value depending on how close prices
in that range are to following a positively- or negatively-sloping
straight line. Values range from -1 to 1. This is a wrapper
for ta.linreg(close, r=True).
Args:
close (pd.Series): Series of 'close's
+5 -5
View File
@@ -12,9 +12,9 @@ def dm(
) -> DataFrame:
"""Directional Movement (DM)
The Directional Movement was developed by J. Welles Wilder in 1978 attempts to
determine which direction the price of an asset is moving. It compares prior
highs and lows to yield to two series +DM and -DM.
The Directional Movement was developed by J. Welles Wilder in 1978
attempts to determine which direction the price of an asset is moving.
It compares prior highs and lows to yield to two series +DM and -DM.
Sources:
https://www.tradingview.com/pine-script-reference/#fun_dmi
@@ -24,8 +24,8 @@ def dm(
high (pd.Series): Series of 'high's
low (pd.Series): Series of 'low's
mamode (str): See ``help(ta.ma)``. Default: 'rma'
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
drift (int): The difference period. Default: 1
offset (int): How many periods to offset the result. Default: 0
+5 -2
View File
@@ -9,9 +9,12 @@ def er(
) -> Series:
"""Efficiency Ratio (ER)
The Efficiency Ratio was invented by Perry J. Kaufman and presented in his book "New Trading Systems and Methods". It is designed to account for market noise or volatility.
The Efficiency Ratio was invented by Perry J. Kaufman and presented in
his book "New Trading Systems and Methods". It is designed to account
for market noise or volatility.
It is calculated by dividing the net change in price movement over N periods by the sum of the absolute net changes over the same N periods.
It is calculated by dividing the net change in price movement over
N periods by the sum of the absolute net changes over the same N periods.
Sources:
https://help.tc2000.com/m/69404/l/749623-kaufman-efficiency-ratio
+7 -8
View File
@@ -10,15 +10,14 @@ def eri(
) -> DataFrame:
"""Elder Ray Index (ERI)
Elder's Bulls Ray Index contains his Bull and Bear Powers. Which are useful ways
to look at the price and see the strength behind the market. Bull Power
measures the capability of buyers in the market, to lift prices above an average
consensus of value.
Elder's Bulls Ray Index contains his Bull and Bear Powers. Which are
useful ways to look at the price and see the strength behind the market.
Bull Power measures the capability of buyers in the market, to lift
prices above an average consensus of value.
Bears Power measures the capability of sellers, to drag prices below an average
consensus of value. Using them in tandem with a measure of trend allows you to
identify favourable entry points. We hope you've found this to be a useful
discussion of the Bulls and Bears Power indicators.
Bears Power measures the capability of sellers, to drag prices below
an average consensus of value. Using them in tandem with a measure of
trend allows you to identify favourable entry points.
Sources:
https://admiralmarkets.com/education/articles/forex-indicators/bears-and-bulls-power-indicator
+3 -3
View File
@@ -11,9 +11,9 @@ def fisher(
) -> Series:
"""Fisher Transform (FISHT)
Attempts to identify significant price reversals by normalizing prices over a
user-specified number of periods. A reversal signal is suggested when the the
two lines cross.
Attempts to identify significant price reversals by normalizing prices
over a user-specified number of periods. A reversal signal is suggested
when the the two lines cross.
Sources:
TradingView (Correlation >99%)
+10 -10
View File
@@ -11,10 +11,10 @@ def macd(
) -> DataFrame:
"""Moving Average Convergence Divergence (MACD)
The MACD is a popular indicator to that is used to identify a security's trend.
While APO and MACD are the same calculation, MACD also returns two more series
called Signal and Histogram. The Signal is an EMA of MACD and the Histogram is
the difference of MACD and Signal.
The MACD is a popular indicator to that is used to identify a security's
trend. While APO and MACD are the same calculation, MACD also returns
two more series called Signal and Histogram. The Signal is an EMA of
MACD and the Histogram is the difference of MACD and Signal.
Sources:
https://www.tradingview.com/wiki/MACD_(Moving_Average_Convergence/Divergence)
@@ -25,8 +25,8 @@ def macd(
fast (int): The short period. Default: 12
slow (int): The long period. Default: 26
signal (int): The signal period. Default: 9
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
@@ -62,14 +62,14 @@ def macd(
slowma = ema(close, length=slow, talib=mode_tal)
macd = fastma - slowma
signalma = ema(
close=macd.loc[macd.first_valid_index():, ], length=signal, talib=mode_tal)
macd_fvi = macd.loc[macd.first_valid_index():, ]
signalma = ema(close=macd_fvi, length=signal, talib=mode_tal)
histogram = macd - signalma
if as_mode:
macd = macd - signalma
signalma = ema(
close=macd.loc[macd.first_valid_index():, ], length=signal, talib=mode_tal)
macd_fvi = macd.loc[macd.first_valid_index():, ]
signalma = ema(close=macd_fvi, length=signal, talib=mode_tal)
histogram = macd - signalma
# Offset
+4 -4
View File
@@ -10,8 +10,8 @@ def mom(
) -> Series:
"""Momentum (MOM)
Momentum is an indicator used to measure a security's speed (or strength) of
movement. Or simply the change in price.
Momentum is an indicator used to measure a security's speed
(or strength) of movement or simply the change in price.
Sources:
http://www.onlinetradingconcepts.com/TechnicalAnalysis/Momentum.html
@@ -19,8 +19,8 @@ def mom(
Args:
close (pd.Series): Series of 'close's
length (int): It's period. Default: 1
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
+5 -3
View File
@@ -11,9 +11,11 @@ def pgo(
) -> Series:
"""Pretty Good Oscillator (PGO)
The Pretty Good Oscillator indicator was created by Mark Johnson to measure the distance of the current close from its N-day Simple Moving Average, expressed in terms of an average true range over a similar period. Johnson's approach was to
use it as a breakout system for longer term trades. Long if greater than 3.0 and
short if less than -3.0.
The Pretty Good Oscillator indicator was created by Mark Johnson to
measure the distance of the current close from its N-day SMA, expressed
in terms of an average true range over a similar period. Johnson's
approach was to use it as a breakout system for longer term trades.
Long if greater than 3.0 and short if less than -3.0.
Sources:
https://library.tradingtechnologies.com/trade/chrt-ti-pretty-good-oscillator.html
+2 -2
View File
@@ -24,8 +24,8 @@ def ppo(
signal(int): The signal period. Default: 9
scalar (float): How much to magnify. Default: 100
mamode (str): See ``help(ta.ma)``. Default: 'sma'
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset(int): How many periods to offset the result. Default: 0
Kwargs:
+15 -6
View File
@@ -14,9 +14,17 @@ def qqe(
) -> DataFrame:
"""Quantitative Qualitative Estimation (QQE)
The Quantitative Qualitative Estimation (QQE) is similar to SuperTrend but uses a Smoothed RSI with an upper and lower bands. The band width is a combination of a one period True Range of the Smoothed RSI which is double smoothed using Wilder's smoothing length (2 * rsiLength - 1) and multiplied by the default factor of 4.236. A Long trend is determined when the Smoothed RSI crosses the previous upperband and a Short trend when the Smoothed RSI crosses the previous lowerband.
The Quantitative Qualitative Estimation (QQE) is similar to SuperTrend
but uses a Smoothed RSI with an upper and lower bands. The band width
is a combination of a one period True Range of the Smoothed RSI which
is double smoothed using Wilder's smoothing length (2 * rsiLength - 1)
and multiplied by the default factor of 4.236. A Long trend is
determined when the Smoothed RSI crosses the previous upperband and
a Short trend when the Smoothed RSI crosses the previous lowerband.
Based on QQE.mq5 by EarnForex Copyright © 2010, based on version by Tim Hyder (2008), based on version by Roman Ignatov (2006)
Based on QQE.mq5 by EarnForex Copyright © 2010
based on version by Tim Hyder (2008),
based on version by Roman Ignatov (2006)
Sources:
https://www.tradingview.com/script/IYfA9R2k-QQE-MT4/
@@ -37,7 +45,7 @@ def qqe(
fill_method (value, optional): Type of fill method
Returns:
pd.DataFrame: QQE, RSI_MA (basis), QQEl (long), and QQEs (short) columns.
pd.DataFrame: QQE, RSI_MA (basis), QQEl (long), QQEs (short) columns.
"""
# Validate
length = int(length) if isinstance(length, int) and length > 0 else 14
@@ -103,11 +111,12 @@ def qqe(
# Trend & QQE Calculation
# Long: Current RSI_MA value Crosses the Prior Short Line Value
# Short: Current RSI_MA Crosses the Prior Long Line Value
if (c_rsi > c_short and p_rsi < p_short) or (
c_rsi <= c_short and p_rsi >= p_short):
if (c_rsi > c_short and p_rsi < p_short) or \
(c_rsi <= c_short and p_rsi >= p_short):
trend.iloc[i] = 1
qqe.iloc[i] = qqe_long.iloc[i] = long.iloc[i]
elif (c_rsi > c_long and p_rsi < p_long) or (c_rsi <= c_long and p_rsi >= p_long):
elif (c_rsi > c_long and p_rsi < p_long) or \
(c_rsi <= c_long and p_rsi >= p_long):
trend.iloc[i] = -1
qqe.iloc[i] = qqe_short.iloc[i] = short.iloc[i]
else:
+8 -7
View File
@@ -12,9 +12,10 @@ def roc(
) -> Series:
"""Rate of Change (ROC)
Rate of Change is an indicator is also referred to as Momentum (yeah, confusingly).
It is a pure momentum oscillator that measures the percent change in price with the
previous price 'n' (or length) periods ago.
Rate of Change is an indicator is also referred to as Momentum
(yeah, confusingly). It is a pure momentum oscillator that measures the
percent change in price with the previous price 'n' (or length)
periods ago.
Sources:
https://www.tradingview.com/wiki/Rate_of_Change_(ROC)
@@ -23,8 +24,8 @@ def roc(
close (pd.Series): Series of 'close's
length (int): It's period. Default: 1
scalar (float): How much to magnify. Default: 100
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
@@ -49,8 +50,8 @@ def roc(
from talib import ROC
roc = ROC(close, length)
else:
roc = scalar * mom(close=close, length=length,
talib=mode_tal) / close.shift(length)
roc = scalar * mom(close=close, length=length, talib=mode_tal)
roc /= close.shift(length)
# Offset
if offset != 0:
+5 -4
View File
@@ -12,8 +12,9 @@ def rsi(
) -> Series:
"""Relative Strength Index (RSI)
The Relative Strength Index is popular momentum oscillator used to measure the
velocity as well as the magnitude of directional price movements.
The Relative Strength Index is popular momentum oscillator used to
measure the velocity as well as the magnitude of directional price
movements.
Sources:
https://www.tradingview.com/wiki/Relative_Strength_Index_(RSI)
@@ -22,8 +23,8 @@ def rsi(
close (pd.Series): Series of 'close's
length (int): It's period. Default: 14
scalar (float): How much to magnify. Default: 100
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
drift (int): The difference period. Default: 1
offset (int): How many periods to offset the result. Default: 0
+5 -5
View File
@@ -10,11 +10,11 @@ def rsx(
) -> Series:
"""Relative Strength Xtra (rsx)
The Relative Strength Xtra is based on the popular RSI indicator and inspired
by the work Jurik Research. The code implemented is based on published code
found at 'prorealcode.com'. This enhanced version of the rsi reduces noise and
provides a clearer, only slightly delayed insight on momentum and velocity of
price movements.
The Relative Strength Xtra is based on the popular RSI indicator and
inspired by the work Jurik Research. The code implemented is based on
published code found at 'prorealcode.com'. This enhanced version of the
rsi reduces noise and provides a clearer, only slightly delayed insight
on momentum and velocity of price movements.
Sources:
http://www.jurikres.com/catalog1/ms_rsx.htm
+8 -8
View File
@@ -11,10 +11,10 @@ def rvgi(
) -> Series:
"""Relative Vigor Index (RVGI)
The Relative Vigor Index attempts to measure the strength of a trend relative to
its closing price to its trading range. It is based on the belief that it tends
to close higher than they open in uptrends or close lower than they open in
downtrends.
The Relative Vigor Index attempts to measure the strength of a trend
relative to its closing price to its trading range. It is based on the
belief that it tends to close higher than they open in uptrends or close
lower than they open in downtrends.
Sources:
https://www.investopedia.com/terms/r/relative_vigor_index.asp
@@ -52,11 +52,11 @@ def rvgi(
# Calculate
numerator = swma(
close_open_range,
length=swma_length).rolling(length).sum()
close_open_range, length=swma_length
).rolling(length).sum()
denominator = swma(
high_low_range,
length=swma_length).rolling(length).sum()
high_low_range, length=swma_length
).rolling(length).sum()
rvgi = numerator / denominator
signal = swma(rvgi, length=swma_length)
+2 -1
View File
@@ -30,7 +30,8 @@ def slope(
close (pd.Series): Series of 'close's
length (int): It's period. Default: 1
as_angle (value, optional): Converts slope to an angle. Default: False
to_degrees (value, optional): Converts slope angle to degrees. Default: False
to_degrees (value, optional): Converts slope angle to degrees.
Default: False
offset (int): How many periods to offset the result. Default: 0
Kwargs:
+8 -7
View File
@@ -11,13 +11,14 @@ def smi(
) -> DataFrame:
"""SMI Ergodic Indicator (SMI)
The SMI Ergodic Indicator is the same as the True Strength Index (TSI) developed
by William Blau, except the SMI includes a signal line. The SMI uses double
moving averages of price minus previous price over 2 time frames. The signal
line, which is an EMA of the SMI, is plotted to help trigger trading signals.
The trend is bullish when crossing above zero and bearish when crossing below
zero. This implementation includes both the SMI Ergodic Indicator and SMI
Ergodic Oscillator.
The SMI Ergodic Indicator is the same as the True Strength Index (TSI)
developed by William Blau, except the SMI includes a signal line.
The SMI uses double moving averages of price minus previous price
over 2 time frames. The signal line, which is an EMA of the SMI, is
plotted to help trigger trading signals. The trend is bullish when
crossing above zero and bearish when crossing below zero. This
implementation includes both the SMI Ergodic Indicator and
SMI Ergodic Oscillator.
Sources:
https://www.motivewave.com/studies/smi_ergodic_indicator.htm
+13 -19
View File
@@ -3,7 +3,7 @@ from numpy import nan
from pandas import DataFrame, Series
from pandas_ta.overlap import ema, linreg, sma
from pandas_ta.trend import decreasing, increasing
from pandas_ta.utils import get_offset, unsigned_differences, verify_series
from pandas_ta.utils import get_offset, simplify_columns, unsigned_differences, verify_series
from pandas_ta.volatility import bbands, kc
from .mom import mom
@@ -18,12 +18,13 @@ def squeeze(
) -> DataFrame:
"""Squeeze (SQZ)
The default is based on John Carter's "TTM Squeeze" indicator, as discussed
in his book "Mastering the Trade" (chapter 11). The Squeeze indicator attempts
to capture the relationship between two studies: Bollinger Bands® and Keltner's
Channels. When the volatility increases, so does the distance between the bands,
conversely, when the volatility declines, the distance also decreases. It finds
sections of the Bollinger Bands® study which fall inside the Keltner's Channels.
The default is based on John Carter's "TTM Squeeze" indicator, as
discussed in his book "Mastering the Trade" (chapter 11). The Squeeze
indicator attempts to capture the relationship between two studies:
Bollinger Bands® and Keltner's Channels. When the volatility increases,
so does the distance between the bands, conversely, when the volatility
declines, the distance also decreases. It finds sections of the
Bollinger Bands® study which fall inside the Keltner's Channels.
Sources:
https://tradestation.tradingappstore.com/products/TTMSqueeze
@@ -44,7 +45,8 @@ def squeeze(
offset (int): How many periods to offset the result. Default: 0
Kwargs:
tr (value, optional): Use True Range for Keltner Channels. Default: True
tr (value, optional): Use True Range for Keltner Channels.
Default: True
asint (value, optional): Use integers instead of bool. Default: True
mamode (value, optional): Which MA to use. Default: "sma"
lazybear (value, optional): Use LazyBear's TradingView implementation.
@@ -80,20 +82,12 @@ def squeeze(
lazybear = kwargs.pop("lazybear", False)
mamode = mamode if isinstance(mamode, str) else "sma"
def simplify_columns(df, n=3):
df.columns = df.columns.str.lower()
return [c.split("_")[0][n - 1:n] for c in df.columns]
# Calculate
bbd = bbands(close, length=bb_length, std=bb_std, mamode=mamode)
kch = kc(
high,
low,
close,
length=kc_length,
scalar=kc_scalar,
mamode=mamode,
tr=use_tr)
high, low, close, length=kc_length, scalar=kc_scalar,
mamode=mamode, tr=use_tr
)
# Simplify KC and BBAND column names for dynamic access
bbd.columns = simplify_columns(bbd)
+44 -44
View File
@@ -5,7 +5,7 @@ from pandas_ta.momentum import mom
from pandas_ta.overlap import ema, sma
from pandas_ta.trend import decreasing, increasing
from pandas_ta.volatility import bbands, kc
from pandas_ta.utils import get_offset, unsigned_differences, verify_series
from pandas_ta.utils import get_offset, simplify_columns, unsigned_differences, verify_series
def squeeze_pro(
@@ -20,12 +20,13 @@ def squeeze_pro(
"""Squeeze PRO(SQZPRO)
This indicator is an extended version of "TTM Squeeze" from John Carter.
The default is based on John Carter's "TTM Squeeze" indicator, as discussed
in his book "Mastering the Trade" (chapter 11). The Squeeze indicator attempts
to capture the relationship between two studies: Bollinger Bands® and Keltner's
Channels. When the volatility increases, so does the distance between the bands,
conversely, when the volatility declines, the distance also decreases. It finds
sections of the Bollinger Bands® study which fall inside the Keltner's Channels.
The default is based on John Carter's "TTM Squeeze" indicator, as
discussed in his book "Mastering the Trade" (chapter 11). The Squeeze
indicator attempts to capture the relationship between two studies:
Bollinger Bands® and Keltner's Channels. When the volatility increases,
so does the distance between the bands, conversely, when the volatility
declines, the distance also decreases. It finds sections of the
Bollinger Bands® study which fall inside the Keltner's Channels.
Sources:
https://usethinkscript.com/threads/john-carters-squeeze-pro-indicator-for-thinkorswim-free.4021/
@@ -38,16 +39,20 @@ def squeeze_pro(
bb_length (int): Bollinger Bands period. Default: 20
bb_std (float): Bollinger Bands Std. Dev. Default: 2
kc_length (int): Keltner Channel period. Default: 20
kc_scalar_wide (float): Keltner Channel scalar for wider channel. Default: 2
kc_scalar_normal (float): Keltner Channel scalar for normal channel. Default: 1.5
kc_scalar_narrow (float): Keltner Channel scalar for narrow channel. Default: 1
kc_scalar_wide (float): Keltner Channel scalar for wider channel.
Default: 2
kc_scalar_normal (float): Keltner Channel scalar for normal channel.
Default: 1.5
kc_scalar_narrow (float): Keltner Channel scalar for narrow channel.
Default: 1
mom_length (int): Momentum Period. Default: 12
mom_smooth (int): Smoothing Period of Momentum. Default: 6
mamode (str): Only "ema" or "sma". Default: "sma"
offset (int): How many periods to offset the result. Default: 0
Kwargs:
tr (value, optional): Use True Range for Keltner Channels. Default: True
tr (value, optional): Use True Range for Keltner Channels.
Default: True
asint (value, optional): Use integers instead of bool. Default: True
mamode (value, optional): Which MA to use. Default: "sma"
detailed (value, optional): Return additional variations of SQZ for
@@ -56,19 +61,30 @@ def squeeze_pro(
fill_method (value, optional): Type of fill method
Returns:
pd.DataFrame: SQZPRO, SQZPRO_ON_WIDE, SQZPRO_ON_NORMAL, SQZPRO_ON_NARROW, SQZPRO_OFF_WIDE, SQZPRO_NO columns by default. More
detailed columns if 'detailed' kwarg is True.
pd.DataFrame: SQZPRO, SQZPRO_ON_WIDE, SQZPRO_ON_NORMAL,
SQZPRO_ON_NARROW, SQZPRO_OFF_WIDE, SQZPRO_NO columns by default.
More detailed columns if 'detailed' kwarg is True.
"""
# Validate
bb_length = int(bb_length) if bb_length and bb_length > 0 else 20
bb_std = float(bb_std) if bb_std and bb_std > 0 else 2.0
kc_length = int(kc_length) if kc_length and kc_length > 0 else 20
kc_scalar_wide = float(
kc_scalar_wide) if kc_scalar_wide and kc_scalar_wide > 0 else 2
kc_scalar_normal = float(
kc_scalar_normal) if kc_scalar_normal and kc_scalar_normal > 0 else 1.5
kc_scalar_narrow = float(
kc_scalar_narrow) if kc_scalar_narrow and kc_scalar_narrow > 0 else 1
if kc_scalar_wide and kc_scalar_wide > 0:
kc_scalar_wide = float(kc_scalar_wide)
else:
kc_scalar_wide = 2
if kc_scalar_normal and kc_scalar_normal > 0:
kc_scalar_normal = float(kc_scalar_normal)
else:
kc_scalar_normal = 1.5
if kc_scalar_narrow and kc_scalar_narrow > 0:
kc_scalar_narrow = float(kc_scalar_narrow)
else:
kc_scalar_narrow = 1
mom_length = int(mom_length) if mom_length and mom_length > 0 else 12
mom_smooth = int(mom_smooth) if mom_smooth and mom_smooth > 0 else 6
@@ -90,36 +106,20 @@ def squeeze_pro(
detailed = kwargs.pop("detailed", False)
mamode = mamode if isinstance(mamode, str) else "sma"
def simplify_columns(df, n=3):
df.columns = df.columns.str.lower()
return [c.split("_")[0][n - 1:n] for c in df.columns]
# Calculate
bbd = bbands(close, length=bb_length, std=bb_std, mamode=mamode)
kch_wide = kc(
high,
low,
close,
length=kc_length,
scalar=kc_scalar_wide,
mamode=mamode,
tr=use_tr)
high, low, close, length=kc_length, scalar=kc_scalar_wide,
mamode=mamode, tr=use_tr
)
kch_normal = kc(
high,
low,
close,
length=kc_length,
scalar=kc_scalar_normal,
mamode=mamode,
tr=use_tr)
high, low, close, length=kc_length, scalar=kc_scalar_normal,
mamode=mamode, tr=use_tr
)
kch_narrow = kc(
high,
low,
close,
length=kc_length,
scalar=kc_scalar_narrow,
mamode=mamode,
tr=use_tr)
high, low, close, length=kc_length, scalar=kc_scalar_narrow,
mamode=mamode, tr=use_tr
)
# Simplify KC and BBAND column names for dynamic access
bbd.columns = simplify_columns(bbd)
+19 -16
View File
@@ -11,14 +11,15 @@ def stc(
) -> DataFrame:
"""Schaff Trend Cycle (STC)
The Schaff Trend Cycle is an evolution of the popular MACD incorportating two
cascaded stochastic calculations with additional smoothing.
The Schaff Trend Cycle is an evolution of the popular MACD
incorportating two cascaded stochastic calculations with additional
smoothing.
The STC returns also the beginning MACD result as well as the result after the
first stochastic including its smoothing. This implementation has been extended
for Pandas TA to also allow for separatly feeding any other two moving Averages
(as ma1 and ma2) or to skip this to feed an oscillator (osc), based on which the
Schaff Trend Cycle should be calculated.
The STC returns also the beginning MACD result as well as the result
after the first stochastic including its smoothing. This implementation
has been extended for Pandas TA to also allow for separatly feeding any
other two moving Averages (as ma1 and ma2) or to skip this to feed an
oscillator, based on which the Schaff Trend Cycle should be calculated.
Feed external moving averages:
Internally calculation..
@@ -35,17 +36,19 @@ def stc(
https://www.prorealcode.com/prorealtime-indicators/schaff-trend-cycle2/
Args:
close (pd.Series): Series of 'close's, used for indexing Series, mandatory
tclen (int): SchaffTC Signal-Line length. Default: 10 (adjust to the half of cycle)
fast (int): The short period. Default: 12
slow (int): The long period. Default: 26
factor (float): smoothing factor for last stoch. calculation. Default: 0.5
offset (int): How many periods to offset the result. Default: 0
close (pd.Series): Series of 'close's
tclen (int): SchaffTC Signal-Line length.
Default: 10 (adjust to the half of cycle)
fast (int): The short period. Default: 12
slow (int): The long period. Default: 26
factor (float): smoothing factor for last stoch. calculation.
Default: 0.5
offset (int): How many periods to offset the result. Default: 0
Kwargs:
ma1: 1st moving average provided externally (mandatory in conjuction with ma2)
ma2: 2nd moving average provided externally (mandatory in conjuction with ma1)
osc: an externally feeded osillator
ma1: External MA (mandatory in conjuction with ma2)
ma2: External MA (mandatory in conjuction with ma1)
osc: External osillator
fillna (value, optional): pd.DataFrame.fillna(value)
fill_method (value, optional): Type of fill method
+16 -20
View File
@@ -13,14 +13,15 @@ def stoch(
) -> DataFrame:
"""Stochastic (STOCH)
The Stochastic Oscillator (STOCH) was developed by George Lane in the 1950's.
He believed this indicator was a good way to measure momentum because changes in
momentum precede changes in price.
The Stochastic Oscillator (STOCH) was developed by George Lane in the
1950's. He believed this indicator was a good way to measure momentum
because changes in momentum precede changes in price.
It is a range-bound oscillator with two lines moving between 0 and 100.
The first line (%K) displays the current close in relation to the period's
high/low range. The second line (%D) is a Simple Moving Average of the %K line.
The most common choices are a 14 period %K and a 3 period SMA for %D.
The first line (%K) displays the current close in relation to the
period's high/low range. The second line (%D) is a Simple Moving Average
of the %K line. The most common choices are a 14 period %K and a 3 period
SMA for %D.
Sources:
https://www.tradingview.com/wiki/Stochastic_(STOCH)
@@ -34,8 +35,8 @@ def stoch(
d (int): The Slow %D period. Default: 3
smooth_k (int): The Slow %K period. Default: 3
mamode (str): See ``help(ta.ma)``. Default: 'sma'
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
@@ -64,14 +65,8 @@ def stoch(
if Imports["talib"] and mode_tal:
from talib import STOCH
stoch_ = STOCH(
high,
low,
close,
k,
d,
tal_ma(mamode),
d,
tal_ma(mamode))
high, low, close, k, d, tal_ma(mamode), d, tal_ma(mamode)
)
stoch_k, stoch_d = stoch_[0], stoch_[1]
else:
lowest_low = low.rolling(k).min()
@@ -80,10 +75,11 @@ def stoch(
stoch = 100 * (close - lowest_low)
stoch /= non_zero_range(highest_high, lowest_low)
stoch_k = ma(
mamode, stoch.loc[stoch.first_valid_index():, ], length=smooth_k)
stoch_d = ma(
mamode, stoch_k.loc[stoch_k.first_valid_index():, ], length=d)
stoch_fvi = stoch.loc[stoch.first_valid_index():, ]
stoch_k = ma(mamode, stoch_fvi, length=smooth_k)
stochk_fvi = stoch_k.loc[stoch_k.first_valid_index():, ]
stoch_d = ma(mamode, stochk_fvi, length=d)
# Offset
if offset != 0:
+7 -10
View File
@@ -12,9 +12,9 @@ def stochf(
) -> DataFrame:
"""Fast Stochastic (STOCHF)
The Fast Stochastic Oscillator (STOCHF) was developed by George Lane in the
1950's. This STOCHF is more volatile than STOCH (help(ta.stoch)) and it's
calculation is similar to STOCH.
The Fast Stochastic Oscillator (STOCHF) was developed by George Lane
in the 1950's. This STOCHF is more volatile than STOCH (help(ta.stoch))
and it's calculation is similar to STOCH.
Sources:
https://www.sierrachart.com/index.php?page=doc/StudiesReference.php&ID=333&Name=KD_-_Fast
@@ -27,8 +27,8 @@ def stochf(
k (int): The Fast %K period. Default: 14
d (int): The Slow %D period. Default: 3
mamode (str): See ``help(ta.ma)``. Default: 'sma'
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
@@ -63,11 +63,8 @@ def stochf(
stochf_k = 100 * (close - lowest_low)
stochf_k /= non_zero_range(highest_high, lowest_low)
stochf_d = ma(mamode,
stochf_k.loc[stochf_k.first_valid_index():,
],
length=d,
talib=mode_tal)
stochfk_fvi = stochf_k.loc[stochf_k.first_valid_index():, ]
stochf_d = ma(mamode, stochfk_fvi, length=d, talib=mode_tal)
# Offset
if offset != 0:
+5 -3
View File
@@ -12,12 +12,14 @@ def stochrsi(
) -> DataFrame:
"""Stochastic (STOCHRSI)
"Stochastic RSI and Dynamic Momentum Index" was created by Tushar Chande and Stanley Kroll and published in Stock & Commodities V.11:5 (189-199)
"Stochastic RSI and Dynamic Momentum Index" was created by Tushar Chande
and Stanley Kroll and published in Stock & Commodities V.11:5 (189-199)
It is a range-bound oscillator with two lines moving between 0 and 100.
The first line (%K) displays the current RSI in relation to the period's
high/low range. The second line (%D) is a Simple Moving Average of the %K line.
The most common choices are a 14 period %K and a 3 period SMA for %D.
high/low range. The second line (%D) is a Simple Moving Average of the
%K line. The most common choices are a 14 period %K and a 3 period
SMA for %D.
Sources:
https://www.tradingview.com/wiki/Stochastic_(STOCH)
+3 -3
View File
@@ -12,9 +12,9 @@ def tsi(
) -> DataFrame:
"""True Strength Index (TSI)
The True Strength Index is a momentum indicator used to identify short-term
swings while in the direction of the trend as well as determining overbought
and oversold conditions.
The True Strength Index is a momentum indicator used to identify
short-term swings while in the direction of the trend as well as
determining overbought and oversold conditions.
Sources:
https://www.investopedia.com/terms/t/tsi.asp
+6 -7
View File
@@ -29,8 +29,8 @@ def uo(
fast_w (float): The Fast %K period. Default: 4.0
medium_w (float): The Slow %K period. Default: 2.0
slow_w (float): The Slow %D period. Default: 1.0
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
drift (int): The difference period. Default: 1
offset (int): How many periods to offset the result. Default: 0
@@ -64,10 +64,9 @@ def uo(
from talib import ULTOSC
uo = ULTOSC(high, low, close, fast, medium, slow)
else:
close_drift = close.shift(drift)
tdf = DataFrame({
"high": high,
"low": low,
f"close_{drift}": close.shift(drift)
"high": high, "low": low, f"close_{drift}": close_drift
})
max_h_or_pc = tdf.loc[:, ["high", f"close_{drift}"]].max(axis=1)
min_l_or_pc = tdf.loc[:, ["low", f"close_{drift}"]].min(axis=1)
@@ -81,8 +80,8 @@ def uo(
slow_avg = bp.rolling(slow).sum() / tr.rolling(slow).sum()
total_weight = fast_w + medium_w + slow_w
weights = (fast_w * fast_avg) + (medium_w *
medium_avg) + (slow_w * slow_avg)
weights = (fast_w * fast_avg) + (medium_w * medium_avg) \
+ (slow_w * slow_avg)
uo = 100 * weights / total_weight
# Offset
+6 -4
View File
@@ -22,8 +22,8 @@ def willr(
low (pd.Series): Series of 'low's
close (pd.Series): Series of 'close's
length (int): It's period. Default: 14
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
@@ -35,8 +35,10 @@ def willr(
"""
# Validate
length = int(length) if length and length > 0 else 14
min_periods = int(
kwargs["min_periods"]) if "min_periods" in kwargs and kwargs["min_periods"] is not None else length
if "min_periods" in kwargs and kwargs["min_periods"] is not None:
min_periods = int(kwargs["min_periods"])
else:
min_periods = length
_length = max(length, min_periods)
high = verify_series(high, _length)
low = verify_series(low, _length)
+10 -9
View File
@@ -11,13 +11,14 @@ def alligator(
) -> DataFrame:
"""Bill Williams Alligator (ALLIGATOR)
The Alligator Indicator was developed by Bill Williams and combines moving
averages with fractal geometry and the lines are meant to resemeble an alligator
opening and closing his mouth.. It attempts to identify if an asset is trending.
It consists of 3 lines: the Alligator's Jaw, Teeth, and Lips. Each have
different lookback periods and but require the user to offset the results; this
is avoid data leaks by Pandas TA. See help(ta.ichimoku) or help(ta.dpo) to
offset the resultant lines.
The Alligator Indicator was developed by Bill Williams and combines
moving averages with fractal geometry and the lines are meant to
resemeble an alligator opening and closing his mouth.. It attempts to
identify if an asset is trending. It consists of 3 lines: the
Alligator's Jaw, Teeth, and Lips. Each have different lookback periods
and but require the user to offset the results; this is avoid data leaks
by Pandas TA. See help(ta.ichimoku) or help(ta.dpo) to offset the
resultant lines.
Sources:
https://www.tradingview.com/scripts/alligator/
@@ -28,8 +29,8 @@ def alligator(
jaw (int): The Jaw period. Default: 13
teeth (int): The Teeth period. Default: 8
lips (int): The Lips period. Default: 5
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
+8 -9
View File
@@ -12,11 +12,11 @@ def alma(
) -> Series:
"""Arnaud Legoux Moving Average (ALMA)
The ALMA moving average uses the curve of the Normal (Gauss) distribution, which
can be shifted from 0 to 1. This allows regulating the smoothness and high
sensitivity of the indicator. Sigma is another parameter that is responsible for
the shape of the curve coefficients. This moving average reduces lag of the data
in conjunction with smoothing to reduce noise.
The ALMA moving average uses the curve of the Normal (Gauss) distribution,
which can be shifted from 0 to 1. This allows regulating the smoothness
and high sensitivity of the indicator. Sigma is another parameter that is
responsible for the shape of the curve coefficients. This moving average
reduces lag of the data in conjunction with smoothing to reduce noise.
Sources:
https://www.sierrachart.com/index.php?page=doc/StudiesReference.php&ID=475&Name=Moving_Average_-_Arnaud_Legoux
@@ -26,8 +26,8 @@ def alma(
close (pd.Series): Series of 'close's
length (int): It's period, window size. Default: 9
sigma (float): Smoothing value. Default 6.0
dist_offset (float): Value to offset the distribution where min 0 (smoother),
max 1 (more responsive). Default 0.85
dist_offset (float): Value to offset the distribution where
min 0 (smoother), max 1 (more responsive). Default 0.85
offset (int): How many periods to offset the result. Default: 0
Kwargs:
@@ -40,8 +40,7 @@ def alma(
# Validate
length = int(length) if isinstance(length, int) and length > 0 else 9
sigma = float(sigma) if isinstance(sigma, float) and sigma > 0 else 6.0
if isinstance(dist_offset,
float) and dist_offset >= 0 and dist_offset <= 1:
if isinstance(dist_offset, float) and 0 <= dist_offset <= 1:
offset_ = float(dist_offset)
else:
offset_ = 0.85
+4 -4
View File
@@ -11,8 +11,8 @@ def dema(
) -> Series:
"""Double Exponential Moving Average (DEMA)
The Double Exponential Moving Average attempts to a smoother average with less
lag than the normal Exponential Moving Average (EMA).
The Double Exponential Moving Average attempts to a smoother average
with less lag than the normal Exponential Moving Average (EMA).
Sources:
https://www.tradingtechnologies.com/help/x-study/technical-indicator-definitions/double-exponential-moving-average-dema/
@@ -20,8 +20,8 @@ def dema(
Args:
close (pd.Series): Series of 'close's
length (int): It's period. Default: 10
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
+10 -10
View File
@@ -29,12 +29,12 @@ def ema(
) -> Series:
"""Exponential Moving Average (EMA)
The Exponential Moving Average is a more responsive moving average compared
to the Simple Moving Average (SMA). The weights are determined by alpha
which is proportional to it's length. There are several different methods
of calculating EMA. One method uses just the standard definition of EMA and
another uses the SMA to generate the initial value for the rest of the
calculation.
The Exponential Moving Average is a more responsive moving average
compared to the Simple Moving Average (SMA). The weights are determined
by alpha which is proportional to it's length. There are several
different methods of calculating EMA. One method uses just the standard
definition of EMA and another uses the SMA to generate the initial value
for the rest of the calculation.
Sources:
https://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:moving_averages
@@ -43,10 +43,10 @@ def ema(
Args:
close (pd.Series): Series of 'close's
length (int): It's period. Default: 10
talib (bool): If TA Lib is installed and talib=True, it returns the
TA Lib values. Default: True
presma (bool, optional): If True, uses SMA for initial value like TA Lib.
Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
presma (bool, optional): If True, uses SMA for initial value like
TA Lib. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
+4 -7
View File
@@ -9,8 +9,8 @@ def fwma(
) -> Series:
"""Fibonacci's Weighted Moving Average (FWMA)
Fibonacci's Weighted Moving Average is similar to a Weighted Moving Average
(WMA) where the weights are based on the Fibonacci Sequence.
Fibonacci's Weighted Moving Average is similar to a Weighted Moving
Average (WMA) where the weights are based on the Fibonacci Sequence.
Source: Kevin Johnson
@@ -38,11 +38,8 @@ def fwma(
# Calculate
fibs = fibonacci(n=length, weighted=True)
fwma = close.rolling(
length,
min_periods=length).apply(
weights(fibs),
raw=True)
fwma = close.rolling(length, min_periods=length) \
.apply(weights(fibs), raw=True)
# Offset
if offset != 0:
+5 -5
View File
@@ -12,12 +12,12 @@ def hilo(
) -> DataFrame:
"""Gann HiLo Activator(HiLo)
The Gann High Low Activator Indicator was created by Robert Krausz in a 1998
issue of Stocks & Commodities Magazine. It is a moving average based trend
indicator consisting of two different simple moving averages.
The Gann High Low Activator Indicator was created by Robert Krausz in
a 1998 issue of Stocks & Commodities Magazine. It is a moving average
based trend indicator consisting of two different simple moving averages.
The indicator tracks both curves (of the highs and the lows). The close of the
bar defines which of the two gets plotted.
The indicator tracks both curves (of the highs and the lows). The close
of the bar defines which of the two gets plotted.
Increasing high_length and decreasing low_length better for short trades,
vice versa for long positions.
+2 -1
View File
@@ -25,7 +25,8 @@ def hl2(
offset = get_offset(offset)
# Calculate
hl2 = Series(0.5 * (high.values + low.values), index=high.index)
avg = 0.5 * (high.values + low.values)
hl2 = Series(avg, index=high.index)
# Offset
if offset != 0:
+2 -3
View File
@@ -33,9 +33,8 @@ def hlc3(
from talib import TYPPRICE
hlc3 = TYPPRICE(high, low, close)
else:
hlc3 = Series(
(high.values + low.values + close.values) / 3.0,
index=close.index)
avg = (high.values + low.values + close.values) / 3.0
hlc3 = Series(avg, index=close.index)
# Offset
if offset != 0:
+2 -2
View File
@@ -11,8 +11,8 @@ def hma(
) -> Series:
"""Hull Moving Average (HMA)
The Hull Exponential Moving Average attempts to reduce or remove lag in moving
averages.
The Hull Exponential Moving Average attempts to reduce or remove lag
in moving averages.
Sources:
https://alanhull.com/hull-moving-average
+4 -5
View File
@@ -9,9 +9,9 @@ def hwma(
) -> Series:
"""HWMA (Holt-Winter Moving Average)
Indicator HWMA (Holt-Winter Moving Average) is a three-parameter moving average
by the Holt-Winter method; the three parameters should be selected to obtain a
forecast.
Indicator HWMA (Holt-Winter Moving Average) is a three-parameter
moving average by the Holt-Winter method; the three parameters should
be selected to obtain a forecast.
This version has been implemented for Pandas TA by rengel8 based
on a publication for MetaTrader 5.
@@ -66,8 +66,7 @@ def hwma(
hwma.fillna(method=kwargs["fill_method"], inplace=True)
# Name and Category
suffix = f"{na}_{nb}_{nc}"
hwma.name = f"HWMA_{suffix}"
hwma.name = f"HWMA_{na}_{nb}_{nc}"
hwma.category = "overlap"
return hwma
+2 -1
View File
@@ -24,7 +24,8 @@ def ichimoku(
tenkan (int): Tenkan period. Default: 9
kijun (int): Kijun period. Default: 26
senkou (int): Senkou period. Default: 52
include_chikou (bool): Whether to include chikou component. Default: True
include_chikou (bool): Whether to include chikou component.
Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
+4 -4
View File
@@ -12,9 +12,9 @@ def jma(
) -> Series:
"""Jurik Moving Average Average (JMA)
Mark Jurik's Moving Average (JMA) attempts to eliminate noise to see the "true"
underlying activity. It has extremely low lag, is very smooth and is responsive
to market gaps.
Mark Jurik's Moving Average (JMA) attempts to eliminate noise to see
the "true" underlying activity. It has extremely low lag, is very
smooth and is responsive to market gaps.
Sources:
https://c.mql5.com/forextsd/forum/164/jurik_1.pdf
@@ -94,7 +94,7 @@ def jma(
ma2 = ma1 + pr * det0
# 3rd stage - final smoothing by unique Jurik adaptive filter
det1 = ((ma2 - jma[i - 1]) * (1 - alpha) *
det1 = ((ma2 - jma[i - 1]) * (1 - alpha) * \
(1 - alpha)) + (alpha * alpha * det1)
jma[i] = jma[i - 1] + det1
+11 -9
View File
@@ -12,11 +12,13 @@ def kama(
) -> Series:
"""Kaufman's Adaptive Moving Average (KAMA)
Developed by Perry Kaufman, Kaufman's Adaptive Moving Average (KAMA) is a moving average
designed to account for market noise or volatility. KAMA will closely follow prices when
the price swings are relatively small and the noise is low. KAMA will adjust when the
price swings widen and follow prices from a greater distance. This trend-following indicator
can be used to identify the overall trend, time turning points and filter price movements.
Developed by Perry Kaufman, Kaufman's Adaptive Moving Average (KAMA) is
a moving average designed to account for market noise or volatility.
KAMA will closely follow prices when the price swings are relatively
small and the noise is low. KAMA will adjust when the price swings widen
and follow prices from a greater distance. This trend-following
indicator can be used to identify the overall trend, time turning points
and filter price movements.
Sources:
https://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:kaufman_s_adaptive_moving_average
@@ -28,8 +30,8 @@ def kama(
fast (int): Fast MA period. Default: 2
slow (int): Slow MA period. Default: 30
mamode (str): See ``help(ta.ma)``. Valid MAs that support initialize
the first value: 'ema', 'fwma', 'linreg', 'midpoint', 'pwma', 'rma',
'sinwma', 'sma', 'swma', 'trima', 'wma'. Default: 'sma'
the first value: 'ema', 'fwma', 'linreg', 'midpoint', 'pwma',
'rma', 'sinwma', 'sma', 'swma', 'trima', 'wma'. Default: 'sma'
drift (int): The difference period. Default: 1
offset (int): How many periods to offset the result. Default: 0
@@ -77,8 +79,8 @@ def kama(
ma0 = ma(mamode, close.iloc[:length], length=length, **kwargs).iloc[-1]
result = [nan for _ in range(0, length - 1)] + [ma0]
for i in range(length, m):
result.append(sc.iloc[i] * close.iloc[i] +
(1 - sc.iloc[i]) * result[i - 1])
result.append(sc.iloc[i] * close.iloc[i] \
+ (1 - sc.iloc[i]) * result[i - 1])
kama = Series(result, index=close.index)
+16 -12
View File
@@ -12,27 +12,28 @@ def linreg(
) -> Series:
"""Linear Regression Moving Average (linreg)
Linear Regression Moving Average (LINREG). This is a simplified version of a
Standard Linear Regression. LINREG is a rolling regression of one variable. A
Standard Linear Regression is between two or more variables.
Linear Regression Moving Average (LINREG). This is a simplified version
of a Standard Linear Regression. LINREG is a rolling regression of one
variable. A Standard Linear Regression is between two or more variables.
Source: TA Lib
Args:
close (pd.Series): Series of 'close's
length (int): It's period. Default: 10
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
angle (bool, optional): If True, returns the angle of the slope in radians.
angle (bool, optional): If True, returns the slope angle in radians.
Default: False.
degrees (bool, optional): If True, returns the angle of the slope in
degrees (bool, optional): If True, returns the slope angle in
degrees. Default: False.
intercept (bool, optional): If True, returns the angle of the slope in
radians. Default: False.
r (bool, optional): If True, returns it's correlation 'r'. Default: False.
intercept (bool, optional): If True, returns the intercept.
Default: False.
r (bool, optional): If True, returns it's correlation 'r'.
Default: False.
slope (bool, optional): If True, returns the slope. Default: False.
tsf (bool, optional): If True, returns the Time Series Forecast value.
Default: False.
@@ -80,6 +81,7 @@ def linreg(
x2_sum = x_sum * (2 * length + 1) / 3
divisor = length * x2_sum - x_sum * x_sum
# Needs to be reworked outside the method
def linear_regression(series):
y_sum = series.sum()
xy_sum = (x * series).sum()
@@ -109,12 +111,14 @@ def linreg(
from numpy.lib.stride_tricks import sliding_window_view
linreg_ = [
linear_regression(_) for _ in sliding_window_view(
np_close, length)]
np_close, length)
]
else:
linreg_ = [
linear_regression(_) for _ in strided_window(
np_close, length)]
np_close, length)
]
linreg = Series([nan] * (length - 1) + linreg_, index=close.index)
+10 -8
View File
@@ -9,13 +9,14 @@ def mcgd(
) -> Series:
"""McGinley Dynamic Indicator
The McGinley Dynamic looks like a moving average line, yet it is actually a
smoothing mechanism for prices that minimizes price separation, price whipsaws,
and hugs prices much more closely. Because of the calculation, the Dynamic Line
speeds up in down markets as it follows prices yet moves more slowly in up
markets. The indicator was designed by John R. McGinley, a Certified Market
Technician and former editor of the Market Technicians Association's Journal
of Technical Analysis.
The McGinley Dynamic looks like a moving average line, yet it is
actually a smoothing mechanism for prices that minimizes price
separation, price whipsaws, and hugs prices much more closely. Because
of the calculation, the Dynamic Line speeds up in down markets as it
follows prices yet moves more slowly in up markets. The indicator was
designed by John R. McGinley, a Certified Market Technician and former
editor of the Market Technicians Association's Journal of Technical
Analysis.
Sources:
https://www.investopedia.com/articles/forex/09/mcginley-dynamic-indicator.asp
@@ -23,7 +24,8 @@ def mcgd(
Args:
close (pd.Series): Series of 'close's
length (int): Indicator's period. Default: 10
c (float): Multiplier for the denominator, sometimes set to 0.6. Default: 1
c (float): Multiplier for the denominator, sometimes set to 0.6.
Default: 1
offset (int): Number of periods to offset the result. Default: 0
Kwargs:
+6 -4
View File
@@ -15,8 +15,8 @@ def midpoint(
Args:
close (pd.Series): Series of 'close's
length (int): It's period. Default: 2
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
@@ -28,8 +28,10 @@ def midpoint(
"""
# Validate
length = int(length) if length and length > 0 else 2
min_periods = int(
kwargs["min_periods"]) if "min_periods" in kwargs and kwargs["min_periods"] is not None else length
if "min_periods" in kwargs and kwargs["min_periods"] is not None:
min_periods = int(kwargs["min_periods"])
else:
min_periods = length
close = verify_series(close, max(length, min_periods))
offset = get_offset(offset)
mode_tal = bool(talib) if isinstance(talib, bool) else True
+6 -4
View File
@@ -16,8 +16,8 @@ def midprice(
high (pd.Series): Series of 'high's
low (pd.Series): Series of 'low's
length (int): It's period. Default: 2
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
@@ -29,8 +29,10 @@ def midprice(
"""
# Validate
length = int(length) if length and length > 0 else 2
min_periods = int(
kwargs["min_periods"]) if "min_periods" in kwargs and kwargs["min_periods"] is not None else length
if "min_periods" in kwargs and kwargs["min_periods"] is not None:
min_periods = int(kwargs["min_periods"])
else:
min_periods = length
_length = max(length, min_periods)
high = verify_series(high, _length)
low = verify_series(low, _length)
+2 -4
View File
@@ -29,10 +29,8 @@ def ohlc4(
offset = get_offset(offset)
# Calculate
ohlc4 = Series(
0.25 * (open_.values + high.values + low.values + close.values),
index=close.index
)
avg = 0.25 * (open_.values + high.values + low.values + close.values)
ohlc4 = Series(avg, index=close.index)
# Offset
if offset != 0:
+4 -7
View File
@@ -9,8 +9,8 @@ def pwma(
) -> Series:
"""Pascal's Weighted Moving Average (PWMA)
Pascal's Weighted Moving Average is similar to a symmetric triangular window
except PWMA's weights are based on Pascal's Triangle.
Pascal's Weighted Moving Average is similar to a symmetric triangular
window except PWMA's weights are based on Pascal's Triangle.
Source: Kevin Johnson
@@ -38,11 +38,8 @@ def pwma(
# Calculate
triangle = pascals_triangle(n=length - 1, weighted=True)
pwma = close.rolling(
length,
min_periods=length).apply(
weights(triangle),
raw=True)
pwma = close.rolling(length, min_periods=length) \
.apply(weights(triangle), raw=True)
# Offset
if offset != 0:
+2 -2
View File
@@ -9,8 +9,8 @@ def rma(
) -> Series:
"""wildeR's Moving Average (RMA)
The WildeR's Moving Average is simply an Exponential Moving Average (EMA) with
a modified alpha = 1 / length.
The WildeR's Moving Average is simply an EMA with a modified
alpha = 1 / length.
Sources:
https://tlc.thinkorswim.com/center/reference/Tech-Indicators/studies-library/V-Z/WildersSmoothing
+4 -7
View File
@@ -10,8 +10,8 @@ def sinwma(
) -> Series:
"""Sine Weighted Moving Average (SWMA)
A weighted average using sine cycles. The middle term(s) of the average have the
highest weight(s).
A weighted average using sine cycles. The middle term(s) of the average
have the highest weight(s).
Source:
https://www.tradingview.com/script/6MWFvnPO-Sine-Weighted-Moving-Average/
@@ -42,11 +42,8 @@ def sinwma(
for i in range(0, length)])
w = sines / sines.sum()
sinwma = close.rolling(
length,
min_periods=length).apply(
weights(w),
raw=True)
sinwma = close.rolling(length, min_periods=length) \
.apply(weights(w), raw=True)
# Offset
if offset != 0:
+8 -6
View File
@@ -38,8 +38,8 @@ def sma(
) -> Series:
"""Simple Moving Average (SMA)
The Simple Moving Average is the classic moving average that is the equally
weighted average over n periods.
The Simple Moving Average is the classic moving average that is the
equally weighted average over its length.
Sources:
https://www.tradingtechnologies.com/help/x-study/technical-indicator-definitions/simple-moving-average-sma/
@@ -47,8 +47,8 @@ def sma(
Args:
close (pd.Series): Series of 'close's
length (int): It's period. Default: 10
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
@@ -62,8 +62,10 @@ def sma(
"""
# Validate
length = int(length) if length and length > 0 else 10
min_periods = int(
kwargs["min_periods"]) if "min_periods" in kwargs and kwargs["min_periods"] is not None else length
if "min_periods" in kwargs and kwargs["min_periods"] is not None:
min_periods = int(kwargs["min_periods"])
else:
min_periods = length
close = verify_series(close, max(length, min_periods))
offset = get_offset(offset)
mode_tal = bool(talib) if isinstance(talib, bool) else True
+20 -18
View File
@@ -12,14 +12,15 @@ def smma(
) -> Series:
"""SMoothed Moving Average (SMMA)
The SMoothed Moving Average (SMMA) is bootstrapped by default with a Simple
Moving Average (SMA). It tries to reduce noise rather than reduce lag. The
SMMA takes all prices into account and uses a long lookback period. Old prices
are never removed from the calculation, but they have only a minimal impact on
the Moving Average due to a low assigned weight. By reducing the noise it
removes fluctuations and plots the prevailing trend. The SMMA can be used to
confirm trends and define areas of support and resistance. A core component of
Bill Williams Alligator indicator.
The SMoothed Moving Average (SMMA) is bootstrapped by default with a
Simple Moving Average (SMA). It tries to reduce noise rather than reduce
lag. The SMMA takes all prices into account and uses a long lookback
period. Old prices are never removed from the calculation, but they have
only a minimal impact on the Moving Average due to a low assigned
weight. By reducing the noise it removes fluctuations and plots the
prevailing trend. The SMMA can be used to confirm trends and define
areas of support and resistance.
A core component of Bill Williams Alligator indicator.
Sources:
https://www.tradingview.com/scripts/smma/
@@ -29,8 +30,8 @@ def smma(
close (pd.Series): Series of 'close's
length (int): It's period. Default: 10
mamode (str): See ``help(ta.ma)``. Default: 'sma'
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
@@ -42,8 +43,10 @@ def smma(
"""
# Validate
length = int(length) if length and length > 0 else 7
min_periods = int(
kwargs["min_periods"]) if "min_periods" in kwargs and kwargs["min_periods"] is not None else length
if "min_periods" in kwargs and kwargs["min_periods"] is not None:
min_periods = int(kwargs["min_periods"])
else:
min_periods = length
close = verify_series(close, max(length, min_periods))
offset = get_offset(offset)
mamode = mamode.lower() if isinstance(mamode, str) else "sma"
@@ -56,14 +59,13 @@ def smma(
m = close.size
smma = close.copy()
smma[:length - 1] = nan
smma.iloc[length - 1] = ma(mamode,
close[0:length],
length=length,
talib=mode_tal).iloc[-1]
smma.iloc[length - 1] = ma(
mamode, close[0:length], length=length, talib=mode_tal
).iloc[-1]
for i in range(length, m):
smma.iloc[i] = ((length - 1) * smma.iloc[i - 1] +
smma.iloc[i]) / length
smma.iloc[i] = ((length - 1) * smma.iloc[i - 1] + smma.iloc[i])
smma.iloc[i] /= length
# Offset
if offset != 0:
+7 -6
View File
@@ -50,10 +50,11 @@ def ssf(
) -> Series:
"""Ehler's Super Smoother Filter (SSF) © 2013
John F. Ehlers's solution to reduce lag and remove aliasing noise with his
research in aerospace analog filter design. This implementation had two
poles. Since SSF is a (Resursive) Digital Filter, the number of poles
determine how many prior recursive SSF bars to include in the filter design.
John F. Ehlers's solution to reduce lag and remove aliasing noise with
his research in Aerospace analog filter design. This implementation had
two poles. Since SSF is a (Resursive) Digital Filter, the number of
poles determine how many prior recursive SSF bars to include in the
filter design.
For Everget's calculation on TradingView, set arguments:
pi = np.pi, sqrt2 = np.sqrt(2)
@@ -66,8 +67,8 @@ def ssf(
Args:
close (pd.Series): Series of 'close's
length (int): It's period. Default: 20
everget (bool): Everget's implementation of ssf that uses pi instead of
180 for the b factor of ssf. Default: False
everget (bool): Everget's implementation of ssf that uses pi
instead of 180 for the b factor of ssf. Default: False
pi (float): The value of PI to use. The default is Ehler's
truncated value 3.14159. Adjust the value for more precision.
Default: 3.14159
+5 -4
View File
@@ -37,10 +37,11 @@ def ssf3(
):
"""Ehler's 3 Pole Super Smoother Filter (SSF) © 2013
John F. Ehlers's solution to reduce lag and remove aliasing noise with his
research in aerospace analog filter design. This is implementation has three
poles. Since SSF is a (Resursive) Digital Filter, the number of poles
determine how many prior recursive SSF bars to include in the filter design.
John F. Ehlers's solution to reduce lag and remove aliasing noise
with his research in aerospace analog filter design. This is
implementation has three poles. Since SSF is a (Resursive) Digital
Filter, the number of poles determine how many prior recursive SSF bars
to include in the filter design.
For Everget's calculation on TradingView, set arguments:
pi = np.pi, sqrt3 = 1.738
+12 -11
View File
@@ -34,7 +34,8 @@ def supertrend(
fill_method (value, optional): Type of fill method
Returns:
pd.DataFrame: SUPERT (trend), SUPERTd (direction), SUPERTl (long), SUPERTs (short) columns.
pd.DataFrame: SUPERT (trend), SUPERTd (direction),
SUPERTl (long), SUPERTs (short) columns.
"""
# Validate
length = int(length) if length and length > 0 else 7
@@ -54,25 +55,25 @@ def supertrend(
hl2_ = hl2(high, low)
matr = multiplier * atr(high, low, close, length)
upperband = hl2_ + matr
lowerband = hl2_ - matr
ub = hl2_ + matr # Upperband
lb = hl2_ - matr # Lowerband
for i in range(1, m):
if close.iloc[i] > upperband.iloc[i - 1]:
if close.iloc[i] > ub.iloc[i - 1]:
dir_[i] = 1
elif close.iloc[i] < lowerband.iloc[i - 1]:
elif close.iloc[i] < lb.iloc[i - 1]:
dir_[i] = -1
else:
dir_[i] = dir_[i - 1]
if dir_[i] > 0 and lowerband.iloc[i] < lowerband.iloc[i - 1]:
lowerband.iloc[i] = lowerband.iloc[i - 1]
if dir_[i] < 0 and upperband.iloc[i] > upperband.iloc[i - 1]:
upperband.iloc[i] = upperband.iloc[i - 1]
if dir_[i] > 0 and lb.iloc[i] < lb.iloc[i - 1]:
lb.iloc[i] = lb.iloc[i - 1]
if dir_[i] < 0 and ub.iloc[i] > ub.iloc[i - 1]:
ub.iloc[i] = ub.iloc[i - 1]
if dir_[i] > 0:
trend[i] = long[i] = lowerband.iloc[i]
trend[i] = long[i] = lb.iloc[i]
else:
trend[i] = short[i] = upperband.iloc[i]
trend[i] = short[i] = ub.iloc[i]
_props = f"_{length}_{multiplier}"
df = DataFrame({
+4 -7
View File
@@ -11,8 +11,8 @@ def swma(
Symmetric Weighted Moving Average where weights are based on a symmetric
triangle. For example: n=3 -> [1, 2, 1], n=4 -> [1, 2, 2, 1], etc...
This moving average has variable length in contrast to TradingView's fixed
length of 4.
This moving average has variable length in contrast to TradingView's
fixed length of 4.
Source:
https://www.tradingview.com/study-script-reference/#fun_swma
@@ -40,11 +40,8 @@ def swma(
# Calculate
triangle = symmetric_triangle(length, weighted=True)
swma = close.rolling(
length,
min_periods=length).apply(
weights(triangle),
raw=True)
swma = close.rolling(length, min_periods=length) \
.apply(weights(triangle), raw=True)
# Offset
if offset != 0:
+4 -4
View File
@@ -11,8 +11,8 @@ def t3(
) -> Series:
"""Tim Tillson's T3 Moving Average (T3)
Tim Tillson's T3 Moving Average is considered a smoother and more responsive
moving average relative to other moving averages.
Tim Tillson's T3 Moving Average is considered a smoother and more
responsive moving average relative to other moving averages.
Sources:
http://www.binarytribune.com/forex-trading-indicators/t3-moving-average-indicator/
@@ -21,8 +21,8 @@ def t3(
close (pd.Series): Series of 'close's
length (int): It's period. Default: 10
a (float): 0 < a < 1. Default: 0.7
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
+2 -2
View File
@@ -19,8 +19,8 @@ def tema(
Args:
close (pd.Series): Series of 'close's
length (int): It's period. Default: 10
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
+4 -4
View File
@@ -11,8 +11,8 @@ def trima(
) -> Series:
"""Triangular Moving Average (TRIMA)
A weighted moving average where the shape of the weights are triangular and the
greatest weight is in the middle of the period.
A weighted moving average where the shape of the weights are triangular
and the greatest weight is in the middle of the period.
Sources:
https://www.tradingtechnologies.com/help/x-study/technical-indicator-definitions/triangular-moving-average-trima/
@@ -22,8 +22,8 @@ def trima(
Args:
close (pd.Series): Series of 'close's
length (int): It's period. Default: 10
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
+11 -8
View File
@@ -10,11 +10,11 @@ def vidya(
) -> Series:
"""Variable Index Dynamic Average (VIDYA)
Variable Index Dynamic Average (VIDYA) was developed by Tushar Chande. It is
similar to an Exponential Moving Average but it has a dynamically adjusted
lookback period dependent on relative price volatility as measured by Chande
Momentum Oscillator (CMO). When volatility is high, VIDYA reacts faster to
price changes. It is often used as moving average or trend identifier.
Variable Index Dynamic Average (VIDYA) was developed by Tushar Chande.
It is similar to an EMA but it has a dynamically adjusted lookback
period dependent on relative price volatility as measured by CMO. When
volatility is high, VIDYA reacts faster to price changes.
It is often used as moving average or trend identifier.
Sources:
https://www.tradingview.com/script/hdrf0fXV-Variable-Index-Dynamic-Average-VIDYA/
@@ -26,9 +26,12 @@ def vidya(
offset (int): How many periods to offset the result. Default: 0
Kwargs:
adjust (bool, optional): Use adjust option for EMA calculation. Default: False
sma (bool, optional): If True, uses SMA for initial value for EMA calculation. Default: True
talib (bool): If True, uses TA-Libs implementation for CMO. Otherwise uses EMA version. Default: True
adjust (bool, optional): Use adjust option for EMA calculation.
Default: False
sma (bool, optional): If True, uses SMA for initial value for EMA
calculation. Default: True
talib (bool): If True, uses TA-Libs implementation for CMO.
Otherwise uses EMA version. Default: True
fillna (value, optional): pd.DataFrame.fillna(value)
fill_method (value, optional): Type of fill method
+7 -6
View File
@@ -25,8 +25,9 @@ def vwap(
low (pd.Series): Series of 'low's
close (pd.Series): Series of 'close's
volume (pd.Series): Series of 'volume's
anchor (str): How to anchor VWAP. Depending on the index values, it will
implement various Timeseries Offset Aliases as listed here:
anchor (str): How to anchor VWAP. Depending on the index values,
it will implement various Timeseries Offset Aliases
as listed here:
https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases
Default: "D".
offset (int): How many periods to offset the result. Default: 0
@@ -49,11 +50,11 @@ def vwap(
typical_price = hlc3(high=high, low=low, close=close)
if not is_datetime_ordered(volume):
print(
f"[!] VWAP volume series is not datetime ordered. Results may not be as expected.")
_s = "[!] VWAP volume series is not datetime ordered."
print(f"{_s} Results may not be as expected.")
if not is_datetime_ordered(typical_price):
print(
f"[!] VWAP price series is not datetime ordered. Results may not be as expected.")
_s = "[!] VWAP price series is not datetime ordered."
print(f"{_s} Results may not be as expected.")
# Calculate
wp = typical_price * volume
+4 -5
View File
@@ -20,8 +20,8 @@ def wcp(
high (pd.Series): Series of 'high's
low (pd.Series): Series of 'low's
close (pd.Series): Series of 'close's
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
@@ -43,9 +43,8 @@ def wcp(
from talib import WCLPRICE
wcp = WCLPRICE(high, low, close)
else:
wcp = Series(
(high.values + low.values + 2 * close.values),
index=close.index)
weight = high.values + low.values + 2 * close.values
wcp = Series(weight, index=close.index)
# Offset
if offset != 0:
+9 -6
View File
@@ -5,12 +5,15 @@ from pandas_ta.maps import Imports
from pandas_ta.utils import get_offset, verify_series
def wma(close: Series, length: int = None, asc: bool = None, talib: bool = None, offset: int = None,
**kwargs) -> Series:
def wma(
close: Series, length: int = None,
asc: bool = None, talib: bool = None,
offset: int = None, **kwargs
) -> Series:
"""Weighted Moving Average (WMA)
The Weighted Moving Average where the weights are linearly increasing and
the most recent data has the heaviest weight.
The Weighted Moving Average where the weights are linearly increasing
and the most recent data has the heaviest weight.
Sources:
https://en.wikipedia.org/wiki/Moving_average#Weighted_moving_average
@@ -19,8 +22,8 @@ def wma(close: Series, length: int = None, asc: bool = None, talib: bool = None,
close (pd.Series): Series of 'close's
length (int): It's period. Default: 10
asc (bool): Recent values weigh more. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
+2 -1
View File
@@ -27,7 +27,8 @@ def zlma(
"""Zero Lag Moving Average (ZLMA)
The Zero Lag Moving Average attempts to eliminate the lag associated
with moving averages. This is an adaption created by John Ehler and Ric Way.
with moving averages. This is an adaption created by John Ehler
and Ric Way.
Sources:
https://en.wikipedia.org/wiki/Zero_lag_exponential_moving_average
+3 -3
View File
@@ -9,9 +9,9 @@ def drawdown(
) -> DataFrame:
"""Drawdown (DD)
Drawdown is a peak-to-trough decline during a specific period for an investment,
trading account, or fund. It is usually quoted as the percentage between the
peak and the subsequent trough.
Drawdown is a peak-to-trough decline during a specific period for an
investment, trading account, or fund. It is usually quoted as the
percentage between the peak and the subsequent trough.
Sources:
https://www.investopedia.com/terms/d/drawdown.asp
+6 -3
View File
@@ -19,7 +19,8 @@ def log_return(
Args:
close (pd.Series): Series of 'close's
length (int): It's period. Default: 20
cumulative (bool): If True, returns the cumulative returns. Default: False
cumulative (bool): If True, returns the cumulative returns.
Default: False
offset (int): How many periods to offset the result. Default: 0
Kwargs:
@@ -31,8 +32,10 @@ def log_return(
"""
# Validate
length = int(length) if length and length > 0 else 1
cumulative = bool(
cumulative) if cumulative is not None and cumulative else False
if cumulative is not None and cumulative:
cumulative = bool(cumulative)
else:
cumulative = False
close = verify_series(close, length)
offset = get_offset(offset)
+8 -7
View File
@@ -5,14 +5,14 @@ from pandas_ta.utils import get_offset, verify_series
def entropy(
close: Series, length: int = None, base: float = None,
offset: int = None, **kwargs
) -> Series:
close: Series, length: int = None, base: float = None,
offset: int = None, **kwargs
) -> Series:
"""Entropy (ENTP)
Introduced by Claude Shannon in 1948, entropy measures the unpredictability
of the data, or equivalently, of its average information. A die has higher
entropy (p=1/6) versus a coin (p=1/2).
Introduced by Claude Shannon in 1948, entropy measures the
unpredictability of the data, or equivalently, of its average
information. A die has higher entropy (p=1/6) versus a coin (p=1/2).
Sources:
https://en.wikipedia.org/wiki/Entropy_(information_theory)
@@ -36,7 +36,8 @@ def entropy(
close = verify_series(close, length)
offset = get_offset(offset)
if close is None: return
if close is None:
return
# Calculate
p = close / close.rolling(length).sum()
+7 -4
View File
@@ -4,9 +4,9 @@ from pandas_ta.utils import get_offset, verify_series
def kurtosis(
close: Series, length: int = None,
offset: int = None, **kwargs
) -> Series:
close: Series, length: int = None,
offset: int = None, **kwargs
) -> Series:
"""Rolling Kurtosis
Calculates the Kurtosis over a rolling period.
@@ -25,7 +25,10 @@ def kurtosis(
"""
# Validate
length = int(length) if length and length > 0 else 30
min_periods = int(kwargs["min_periods"]) if "min_periods" in kwargs and kwargs["min_periods"] is not None else length
if "min_periods" in kwargs and kwargs["min_periods"] is not None:
min_periods = int(kwargs["min_periods"])
else:
min_periods = length
close = verify_series(close, max(length, min_periods))
offset = get_offset(offset)
+9 -5
View File
@@ -5,9 +5,9 @@ from pandas_ta.utils import get_offset, verify_series
def mad(
close: Series, length: int = None,
offset: int = None, **kwargs
) -> Series:
close: Series, length: int = None,
offset: int = None, **kwargs
) -> Series:
"""Rolling Mean Absolute Deviation
Calculates the Mean Absolute Deviation over a rolling period.
@@ -26,11 +26,15 @@ def mad(
"""
# Validate
length = int(length) if length and length > 0 else 30
min_periods = int(kwargs["min_periods"]) if "min_periods" in kwargs and kwargs["min_periods"] is not None else length
if "min_periods" in kwargs and kwargs["min_periods"] is not None:
min_periods = int(kwargs["min_periods"])
else:
min_periods = length
close = verify_series(close, max(length, min_periods))
offset = get_offset(offset)
if close is None: return
if close is None:
return
# Calculate
def mad_(series):
+10 -6
View File
@@ -4,12 +4,12 @@ from pandas_ta.utils import get_offset, verify_series
def median(
close: Series, length: int = None,
offset: int = None, **kwargs
) -> Series:
close: Series, length: int = None,
offset: int = None, **kwargs
) -> Series:
"""Rolling Median
Calculates the Median over a rolling period. Sibling of a Simple Moving Average.
Calculates the Median over a rolling period.
Sources:
https://www.incrediblecharts.com/indicators/median_price.php
@@ -28,11 +28,15 @@ def median(
"""
# Validate
length = int(length) if length and length > 0 else 30
min_periods = int(kwargs["min_periods"]) if "min_periods" in kwargs and kwargs["min_periods"] is not None else length
if "min_periods" in kwargs and kwargs["min_periods"] is not None:
min_periods = int(kwargs["min_periods"])
else:
min_periods = length
close = verify_series(close, max(length, min_periods))
offset = get_offset(offset)
if close is None: return
if close is None:
return
# Calculate
median = close.rolling(length, min_periods=min_periods).median()
+9 -5
View File
@@ -4,9 +4,9 @@ from pandas_ta.utils import get_offset, verify_series
def quantile(
close: Series, length: int = None, q: float = None,
offset: int = None, **kwargs
) -> Series:
close: Series, length: int = None, q: float = None,
offset: int = None, **kwargs
) -> Series:
"""Rolling Quantile
Calculates the Quantile over a rolling period.
@@ -26,12 +26,16 @@ def quantile(
"""
# Validate
length = int(length) if length and length > 0 else 30
min_periods = int(kwargs["min_periods"]) if "min_periods" in kwargs and kwargs["min_periods"] is not None else length
if "min_periods" in kwargs and kwargs["min_periods"] is not None:
min_periods = int(kwargs["min_periods"])
else:
min_periods = length
q = float(q) if q and q > 0 and q < 1 else 0.5
close = verify_series(close, max(length, min_periods))
offset = get_offset(offset)
if close is None: return
if close is None:
return
# Calculate
quantile = close.rolling(length, min_periods=min_periods).quantile(q)
+9 -5
View File
@@ -4,9 +4,9 @@ from pandas_ta.utils import get_offset, verify_series
def skew(
close: Series, length: int = None,
offset: int = None, **kwargs
) -> Series:
close: Series, length: int = None,
offset: int = None, **kwargs
) -> Series:
"""Rolling Skew
Calculates the Skew over a rolling period.
@@ -25,11 +25,15 @@ def skew(
"""
# Validate
length = int(length) if length and length > 0 else 30
min_periods = int(kwargs["min_periods"]) if "min_periods" in kwargs and kwargs["min_periods"] is not None else length
if "min_periods" in kwargs and kwargs["min_periods"] is not None:
min_periods = int(kwargs["min_periods"])
else:
min_periods = length
close = verify_series(close, max(length, min_periods))
offset = get_offset(offset)
if close is None: return
if close is None:
return
# Calculate
skew = close.rolling(length, min_periods=min_periods).skew()
+18 -11
View File
@@ -7,10 +7,10 @@ from .variance import variance
def stdev(
close: Series, length: int = None,
ddof: int = None, talib: bool = None,
offset: int = None, **kwargs
) -> Series:
close: Series, length: int = None,
ddof: int = None, talib: bool = None,
offset: int = None, **kwargs
) -> Series:
"""Rolling Standard Deviation
Calculates the Standard Deviation over a rolling period.
@@ -20,10 +20,11 @@ def stdev(
length (int): It's period. Default: 30
ddof (int): Delta Degrees of Freedom.
The divisor used in calculations is N - ddof,
where N represents the number of elements. The 'talib' argument
must be false for 'ddof' to work. Default: 1
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. TA Lib does not have a 'ddof' argument. Default: True
where N represents the number of elements. The 'talib'
argument must be false for 'ddof' to work. Default: 1
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. TA Lib does not have a 'ddof' argument.
Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
@@ -35,19 +36,25 @@ def stdev(
"""
# Validate
length = int(length) if isinstance(length, int) and length > 0 else 30
ddof = int(ddof) if isinstance(ddof, int) and ddof >= 0 and ddof < length else 1
if isinstance(ddof, int) and ddof >= 0 and ddof < length:
ddof = int(ddof)
else:
ddof = 1
close = verify_series(close, length)
offset = get_offset(offset)
mode_tal = bool(talib) if isinstance(talib, bool) else True
if close is None: return
if close is None:
return
# Calculate
if Imports["talib"] and mode_tal:
from talib import STDDEV
stdev = STDDEV(close, length)
else:
stdev = variance(close=close, length=length, ddof=ddof, talib=mode_tal).apply(sqrt)
stdev = variance(
close=close, length=length, ddof=ddof, talib=mode_tal
).apply(sqrt)
# Offset
if offset != 0:
+9 -8
View File
@@ -5,15 +5,15 @@ from pandas_ta.utils import get_offset, verify_series
def tos_stdevall(
close: Series, length: int = None,
stds: list = None, ddof: int = None,
offset: int = None, **kwargs
) -> DataFrame:
close: Series, length: int = None,
stds: list = None, ddof: int = None,
offset: int = None, **kwargs
) -> DataFrame:
"""TD Ameritrade's Think or Swim Standard Deviation All (TOS_STDEV)
A port of TD Ameritrade's Think or Swim Standard Deviation All indicator which
returns the standard deviation of data for the entire plot or for the interval
of the last bars defined by the length parameter.
A port of TD Ameritrade's Think or Swim Standard Deviation All indicator
which returns the standard deviation of data for the entire plot or for
the interval of the last bars defined by the length parameter.
Sources:
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Statistical/StDevAll
@@ -54,7 +54,8 @@ def tos_stdevall(
close = verify_series(close, length)
if close is None: return
if close is None:
return
# Calculate
X = src_index = close.index
+16 -10
View File
@@ -5,10 +5,10 @@ from pandas_ta.utils import get_offset, verify_series
def variance(
close: Series, length: int = None,
ddof: int = None, talib: bool = None,
offset: int = None, **kwargs
) -> Series:
close: Series, length: int = None,
ddof: int = None, talib: bool = None,
offset: int = None, **kwargs
) -> Series:
"""Rolling Variance
Calculates the Variance over a rolling period.
@@ -18,10 +18,12 @@ def variance(
length (int): It's period. Default: 30
ddof (int): Delta Degrees of Freedom.
The divisor used in calculations is N - ddof,
where N represents the number of elements. The 'talib' argument
must be false for 'ddof' to work. Default: 1
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. TA Lib does not have a 'ddof' argument. Default: True
where N represents the number of elements.
The 'talib' argument must be false for 'ddof' to work.
Default: 1
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Note: TA Lib does not have a 'ddof' argument.
Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
@@ -34,12 +36,16 @@ def variance(
# Validate
length = int(length) if isinstance(length, int) and length > 1 else 30
ddof = int(ddof) if isinstance(ddof, int) and ddof >= 0 and ddof < length else 1
min_periods = int(kwargs["min_periods"]) if "min_periods" in kwargs and kwargs["min_periods"] is not None else length
if "min_periods" in kwargs and kwargs["min_periods"] is not None:
min_periods = int(kwargs["min_periods"])
else:
min_periods = length
close = verify_series(close, max(length, min_periods))
offset = get_offset(offset)
mode_tal = bool(talib) if isinstance(talib, bool) else True
if close is None: return
if close is None:
return
# Calculate
if Imports["talib"] and mode_tal:
+5 -4
View File
@@ -6,9 +6,9 @@ from pandas_ta.utils import get_offset, verify_series
def zscore(
close: Series, length: int = None, std: float = None,
offset: int = None, **kwargs
) -> Series:
close: Series, length: int = None, std: float = None,
offset: int = None, **kwargs
) -> Series:
"""Rolling Z Score
Calculates the Z Score over a rolling period.
@@ -32,7 +32,8 @@ def zscore(
close = verify_series(close, length)
offset = get_offset(offset)
if close is None: return
if close is None:
return
# Calculate
std *= stdev(close=close, length=length, **kwargs)
+3 -3
View File
@@ -4,9 +4,9 @@ from pandas_ta.utils import get_offset, verify_series
def cube(
close: Series, cubing_exponent: float = None, signal_offset: int = None,
offset: int = None, **kwargs
) -> DataFrame:
close: Series, cubing_exponent: float = None, signal_offset: int = None,
offset: int = None, **kwargs
) -> DataFrame:
"""
Indicator: Cube Transform
+4 -4
View File
@@ -6,10 +6,10 @@ from .remap import remap
def ifisher(
close: Series,
amp: float = None, signal_offset: int = None,
offset: int = None, **kwargs
) -> DataFrame:
close: Series,
amp: float = None, signal_offset: int = None,
offset: int = None, **kwargs
) -> DataFrame:
"""
Indicator: Inverse Fisher Transform
+4 -4
View File
@@ -4,10 +4,10 @@ from pandas_ta.utils import get_offset, verify_series
def remap(
close: Series, from_min: float = None, from_max: float = None,
to_min: float = None, to_max: float = None,
offset: int = None, **kwargs
) -> Series:
close: Series, from_min: float = None, from_max: float = None,
to_min: float = None, to_max: float = None,
offset: int = None, **kwargs
) -> Series:
"""
Indicator: ReMap (REMAP)
+4 -3
View File
@@ -13,8 +13,8 @@ def adx(
) -> DataFrame:
"""Average Directional Movement (ADX)
Average Directional Movement is meant to quantify trend strength by measuring
the amount of movement in a single direction.
Average Directional Movement is meant to quantify trend strength by
measuring the amount of movement in a single direction.
Sources:
TA Lib Correlation: >99%
@@ -25,7 +25,8 @@ def adx(
low (pd.Series): Series of 'low's
close (pd.Series): Series of 'close's
length (int): It's period. Default: 14
lensig (int): Signal Length. Like TradingView's default ADX. Default: length
lensig (int): Signal Length. Like TradingView's default ADX.
Default: length
scalar (float): How much to magnify. Default: 100
mamode (str): See ``help(ta.ma)``. Default: 'rma'
drift (int): The difference period. Default: 1
+2 -2
View File
@@ -16,8 +16,8 @@ def amat(
Archer Moving Averages Trends (AMAT) developed by Kevin Johnson provides
creates both long run ``help(ta.long_run)`` and short run
``help(ta.short_run)`` trend signals given two moving average speeds,
fast and slow. The long runs and short runs are binary Series where '1' is
a trend and '0' is not a trend.
fast and slow. The long runs and short runs are binary Series where '1'
is a trend and '0' is not a trend.
Sources:
https://www.tradingview.com/script/Z2mq63fE-Trade-Archer-Moving-Averages-v1-4F/
+6 -12
View File
@@ -22,8 +22,8 @@ def aroon(
close (pd.Series): Series of 'close's
length (int): It's period. Default: 14
scalar (float): How much to magnify. Default: 100
talib (bool): If TA Lib is installed and talib is True, Returns the TA Lib
version. Default: True
talib (bool): If TA Lib is installed and talib is True, Returns
the TA Lib version. Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
@@ -50,16 +50,10 @@ def aroon(
aroon_down, aroon_up = AROON(high, low, length)
aroon_osc = AROONOSC(high, low, length)
else:
periods_from_hh = high.rolling(
length +
1).apply(
recent_maximum_index,
raw=True)
periods_from_ll = low.rolling(
length +
1).apply(
recent_minimum_index,
raw=True)
periods_from_hh = high.rolling(length + 1) \
.apply(recent_maximum_index,raw=True)
periods_from_ll = low.rolling(length + 1) \
.apply(recent_minimum_index,raw=True)
aroon_up = aroon_down = scalar
aroon_up *= 1 - (periods_from_hh / length)
+4 -2
View File
@@ -43,8 +43,10 @@ def chop(
"""
# Validate
length = int(length) if length and length > 0 else 14
atr_length = int(
atr_length) if atr_length is not None and atr_length > 0 else 1
if atr_length is not None and atr_length > 0:
atr_length = int(atr_length)
else:
atr_length = 1
ln = bool(ln) if isinstance(ln, bool) else False
scalar = float(scalar) if scalar else 100
high = verify_series(high, length)
+7 -6
View File
@@ -16,10 +16,10 @@ def cksp(
“The New Technical Trader”. It is a trend-following indicator,
identifying your stop by calculating the average true range of
the recent market volatility. The indicator defaults to the implementation
found on tradingview but it provides the original book implementation as well,
which differs by the default periods and moving average mode. While the trading
view implementation uses the Welles Wilder moving average, the book uses a
simple moving average.
found on tradingview but it provides the original book implementation as
well, which differs by the default periods and moving average mode. While
the trading view implementation uses the Welles Wilder moving average, the
book uses a simple moving average.
Defaults:
Book: p=10, x=3, q=20
@@ -88,8 +88,9 @@ def cksp(
short_stop.name = f"CKSPs{_props}"
long_stop.category = short_stop.category = "trend"
ckspdf = DataFrame(
{long_stop.name: long_stop, short_stop.name: short_stop})
ckspdf = DataFrame({
long_stop.name: long_stop, short_stop.name: short_stop
})
ckspdf.name = f"CKSP{_props}"
ckspdf.category = long_stop.category
+3 -2
View File
@@ -10,8 +10,9 @@ def decay(
) -> Series:
"""Decay
Creates a decay moving forward from prior signals like crosses. The default is
"linear". Exponential is optional as "exponential" or "exp".
Creates a decay moving forward from prior signals like crosses.
The default is "linear".
Exponential is optional as "exponential" or "exp".
Sources:
https://tulipindicators.org/decay
+6 -6
View File
@@ -11,14 +11,15 @@ def decreasing(
"""Decreasing
Returns True if the series is decreasing over a period, False otherwise.
If the kwarg 'strict' is True, it returns True if it is continuously decreasing
over the period. When using the kwarg 'asint', then it returns 1 for True
or 0 for False.
If the kwarg 'strict' is True, it returns True if it is continuously
decreasing over the period. When using the kwarg 'asint', then it
returns 1 for True or 0 for False.
Args:
close (pd.Series): Series of 'close's
length (int): It's period. Default: 1
strict (bool): If True, checks if the series is continuously decreasing over the period. Default: False
strict (bool): If True, checks if the series is continuously
decreasing over the period. Default: False
percent (float): Percent as an integer. Default: None
asint (bool): Returns as binary. Default: True
drift (int): The difference period. Default: 1
@@ -49,8 +50,7 @@ def decreasing(
# Returns value as float64? Have to cast to bool
decreasing = close < close_.shift(drift)
for x in range(3, length + 1):
decreasing = decreasing & (close.shift(
x - (drift + 1)) < close_.shift(x - drift))
decreasing &= (close.shift(x - (drift + 1)) < close_.shift(x - drift))
decreasing.fillna(0, inplace=True)
decreasing = decreasing.astype(bool)
+2 -1
View File
@@ -21,7 +21,8 @@ def dpo(
Args:
close (pd.Series): Series of 'close's
length (int): It's period. Default: 1
centered (bool): Shift the dpo back by int(0.5 * length) + 1. Default: True
centered (bool): Shift the dpo back by int(0.5 * length) + 1.
Default: True
offset (int): How many periods to offset the result. Default: 0
Kwargs:
+6 -6
View File
@@ -11,14 +11,15 @@ def increasing(
"""Increasing
Returns True if the series is increasing over a period, False otherwise.
If the kwarg 'strict' is True, it returns True if it is continuously increasing
over the period. When using the kwarg 'asint', then it returns 1 for True
or 0 for False.
If the kwarg 'strict' is True, it returns True if it is continuously
increasing over the period. When using the kwarg 'asint', then it
returns 1 for True or 0 for False.
Args:
close (pd.Series): Series of 'close's
length (int): It's period. Default: 1
strict (bool): If True, checks if the series is continuously increasing over the period. Default: False
strict (bool): If True, checks if the series is continuously increasing
over the period. Default: False
percent (float): Percent as an integer. Default: None
asint (bool): Returns as binary. Default: True
drift (int): The difference period. Default: 1
@@ -49,8 +50,7 @@ def increasing(
# Returns value as float64? Have to cast to bool
increasing = close > close_.shift(drift)
for x in range(3, length + 1):
increasing = increasing & (close.shift(
x - (drift + 1)) > close_.shift(x - drift))
increasing &= (close.shift(x - (drift + 1)) > close_.shift(x - drift))
increasing.fillna(0, inplace=True)
increasing = increasing.astype(bool)
+4 -4
View File
@@ -48,10 +48,10 @@ def long_run(
return
# Calculate
pb = increasing(fast, length) & decreasing(
slow, length) # potential bottom or bottom
bi = increasing(fast, length) & increasing(
slow, length) # fast and slow are increasing
# potential bottom or bottom
pb = increasing(fast, length) & decreasing(slow, length)
# fast and slow are increasing
bi = increasing(fast, length) & increasing(slow, length)
long_run = pb | bi
# Offset
+17 -16
View File
@@ -11,15 +11,16 @@ def psar(
) -> DataFrame:
"""Parabolic Stop and Reverse (psar)
Parabolic Stop and Reverse (PSAR) was developed by J. Wells Wilder, that is used
to determine trend direction and it's potential reversals in price. PSAR uses a
trailing stop and reverse method called "SAR," or stop and reverse, to identify
possible entries and exits. It is also known as SAR.
Parabolic Stop and Reverse (PSAR) was developed by J. Wells Wilder, that
is used to determine trend direction and it's potential reversals in
price. PSAR uses a trailing stop and reverse method called "SAR," or stop
and reverse, to identify possible entries and exits. It is also known
as SAR.
PSAR indicator typically appears on a chart as a series of dots, either above or
below an asset's price, depending on the direction the price is moving. A dot is
placed below the price when it is trending upward, and above the price when it
is trending downward.
PSAR indicator typically appears on a chart as a series of dots, either
above or below an asset's price, depending on the direction the price is
moving. A dot is placed below the price when it is trending upward, and
above the price when it is trending downward.
Sources:
https://www.tradingview.com/pine-script-reference/#fun_sar
@@ -49,14 +50,6 @@ def psar(
max_af = float(max_af) if max_af and max_af > 0 else 0.2
offset = get_offset(offset)
def _falling(high, low, drift: int = 1):
"""Returns the last -DM value"""
# Not to be confused with ta.falling()
up = high - high.shift(drift)
dn = low.shift(drift) - low
_dmn = (((dn > up) & (dn > 0)) * dn).apply(zero).iloc[-1]
return _dmn > 0
# Falling if the first NaN -DM is positive
falling = _falling(high.iloc[:2], low.iloc[:2])
if falling:
@@ -149,3 +142,11 @@ def psar(
psardf.category = long.category = short.category = "trend"
return psardf
def _falling(high, low, drift: int = 1):
"""Returns the last -DM value"""
# Not to be confused with ta.falling()
up = high - high.shift(drift)
dn = low.shift(drift) - low
_dmn = (((dn > up) & (dn > 0)) * dn).apply(zero).iloc[-1]
return _dmn > 0

Some files were not shown because too many files have changed in this diff Show More