mirror of
https://github.com/wassname/pandas-ta.git
synced 2026-09-09 11:28:26 +08:00
@@ -25,7 +25,7 @@ Pandas TA - A Technical Analysis Library in Python 3
|
||||

|
||||
|
||||
|
||||
_Pandas Technical Analysis_ (**Pandas TA**) is an easy to use library that leverages the Pandas package with more than 130 Indicators and Utility functions and more than 60 TA Lib Candlestick Patterns. Many commonly used indicators are included, such as: _Candle Pattern_(**cdl_pattern**), _Simple Moving Average_ (**sma**) _Moving Average Convergence Divergence_ (**macd**), _Hull Exponential Moving Average_ (**hma**), _Bollinger Bands_ (**bbands**), _On-Balance Volume_ (**obv**), _Aroon & Aroon Oscillator_ (**aroon**), _Squeeze_ (**squeeze**) and **_many more_**.
|
||||
_Pandas Technical Analysis_ (**Pandas TA**) is an easy to use library that leverages the Pandas package with more than 140 Indicators and Utility functions and more than 60 TA Lib Candlestick Patterns. Many commonly used indicators are included, such as: _Candle Pattern_(**cdl_pattern**), _Simple Moving Average_ (**sma**) _Moving Average Convergence Divergence_ (**macd**), _Hull Exponential Moving Average_ (**hma**), _Bollinger Bands_ (**bbands**), _On-Balance Volume_ (**obv**), _Aroon & Aroon Oscillator_ (**aroon**), _Squeeze_ (**squeeze**) and **_many more_**.
|
||||
|
||||
|
||||
**Note:** _TA Lib_ must be installed to use **all** the Candlestick Patterns. ```pip install TA-Lib```. If _TA Lib_ is not installed, then only the builtin Candlestick Patterns will be available.
|
||||
@@ -56,7 +56,7 @@ _Pandas Technical Analysis_ (**Pandas TA**) is an easy to use library that lever
|
||||
* [Candles](#candles-64)
|
||||
* [Cycles](#cycles-1)
|
||||
* [Momentum](#momentum-41)
|
||||
* [Overlap](#overlap-34)
|
||||
* [Overlap](#overlap-35)
|
||||
* [Performance](#performance-3)
|
||||
* [Statistics](#statistics-11)
|
||||
* [Trend](#trend-18)
|
||||
@@ -113,7 +113,7 @@ $ pip install pandas_ta
|
||||
|
||||
Latest Version
|
||||
--------------
|
||||
Best choice! Version: *0.3.16b*
|
||||
Best choice! Version: *0.3.17b*
|
||||
* Includes all fixes and updates between **pypi** and what is covered in this README.
|
||||
```sh
|
||||
$ pip install -U git+https://github.com/twopirllc/pandas-ta
|
||||
@@ -723,8 +723,9 @@ df = df.ta.cdl_pattern(name=["doji", "inside"])
|
||||
|
||||
<br/>
|
||||
|
||||
### **Overlap** (34)
|
||||
### **Overlap** (35)
|
||||
|
||||
* _Bill Williams Alligator_: **alligator**
|
||||
* _Arnaud Legoux Moving Average_: **alma**
|
||||
* _Double Exponential Moving Average_: **dema**
|
||||
* _Exponential Moving Average_: **ema**
|
||||
@@ -958,56 +959,31 @@ print(pf.returns_stats())
|
||||
|
||||
## **Breaking / Depreciated Indicators**
|
||||
* _Trend Return_ (**trend_return**) has been removed and replaced with **tsignals**. When given a trend Series like ```close > sma(close, 50)``` it returns the Trend, Trade Entries and Trade Exits of that trend to make it compatible with [**vectorbt**](https://github.com/polakowo/vectorbt) by setting ```asbool=True``` to get boolean Trade Entries and Exits. See ```help(ta.tsignals)```
|
||||
* _Zero Lag Moving Average_ (**zlma**) now using available Moving Averages from ```ta.ma```. See ```help(ta.zlma)``` and ```help(ta.ma)```.
|
||||
|
||||
<br/>
|
||||
|
||||
## **New Indicators**
|
||||
* _Arnaud Legoux Moving Average_ (**alma**) uses the curve of the Normal (Gauss) distribution to allow regulating the smoothness and high sensitivity of the indicator. See: ```help(ta.alma)```
|
||||
trading account, or fund. See ```help(ta.drawdown)```
|
||||
* _Candle Patterns_ (**cdl_pattern**) If TA Lib is installed, then all those Candle Patterns are available. See the list and examples above on how to call the patterns. See ```help(ta.cdl_pattern)```
|
||||
* _Candle Z Score_ (**cdl_z**) normalizes OHLC Candles with a rolling Z Score. See ```help(ta.cdl_z)```
|
||||
* _Correlation Trend Indicator_ (**cti**) is an oscillator created by John Ehler in 2020. See ```help(ta.cti)```
|
||||
* _Bill Williams Alligator_ (**alligator**) attempts to identify if an asset is trending. See ```help(ta.alligator)```
|
||||
* _Cross Signals_ (**xsignals**) was created by Kevin Johnson. It is a wrapper of Trade Signals that returns Trends, Trades, Entries and Exits. Cross Signals are commonly used for **bbands**, **rsi**, **zscore** crossing some value either above or below two values at different times. See ```help(ta.xsignals)```
|
||||
* _Directional Movement_ (**dm**) developed by J. Welles Wilder in 1978 attempts to determine which direction the price of an asset is moving. See ```help(ta.dm)```
|
||||
* _Even Better Sinewave_ (**ebsw**) measures market cycles and uses a low pass filter to remove noise. See: ```help(ta.ebsw)```
|
||||
* _Jurik Moving Average_ (**jma**) attempts to eliminate noise to see the "true" underlying activity. See: ```help(ta.jma)```
|
||||
* _Klinger Volume Oscillator_ (**kvo**) was developed by Stephen J. Klinger. It is designed to predict price reversals in a market by comparing volume to price. See ```help(ta.kvo)```
|
||||
* _Smoothed Moving Average_ (**smma**) can be used to confirm trends and define areas of support and resistance. See: ```help(ta.smma)```
|
||||
* _Schaff Trend Cycle_ (**stc**) is an evolution of the popular MACD incorportating two cascaded stochastic calculations with additional smoothing. See ```help(ta.stc)```
|
||||
* _Squeeze Pro_ (**squeeze_pro**) is an extended version of "TTM Squeeze" from John Carter. See ```help(ta.squeeze_pro)```
|
||||
* _Tom DeMark's Sequential_ (**td_seq**) attempts to identify a price point where an uptrend or a downtrend exhausts itself and reverses. Currently exlcuded from ```df.ta.strategy()``` for performance reasons. See ```help(ta.td_seq)```
|
||||
* _Think or Swim Standard Deviation All_ (**tos_stdevall**) 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. See ```help(ta.tos_stdevall)```
|
||||
* _Vertical Horizontal Filter_ (**vhf**) was created by Adam White to identify trending and ranging markets. See ```help(ta.vhf)```
|
||||
* _Think or Swim Standard Deviation All_ (**tos_stdevall**) 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. See ```help(ta.tos_stdevall)```
|
||||
|
||||
<br/>
|
||||
|
||||
## **Updated Indicators**
|
||||
|
||||
* _Acceleration Bands_ (**accbands**) Argument ```mamode``` renamed to ```mode```. See ```help(ta.accbands)```.
|
||||
* _ADX_ (**adx**): Added ```mamode``` with default "**RMA**" and with the same ```mamode``` options as TradingView. New argument ```lensig``` so it behaves like TradingView's builtin ADX indicator. See ```help(ta.adx)```.
|
||||
* _Archer Moving Averages Trends_ (**amat**): Added ```drift``` argument and more descriptive column names.
|
||||
* _Average True Range_ (**atr**): The default ```mamode``` is now "**RMA**" and with the same ```mamode``` options as TradingView. See ```help(ta.atr)```.
|
||||
* _Bollinger Bands_ (**bbands**): New argument ```ddoff``` to control the Degrees of Freedom. Also included BB Percent (BBP) as the final column. Default is 0. See ```help(ta.bbands)```.
|
||||
* _Choppiness Index_ (**chop**): New argument ```ln``` to use Natural Logarithm (True) instead of the Standard Logarithm (False). Default is False. See ```help(ta.chop)```.
|
||||
* _Chande Kroll Stop_ (**cksp**): Added ```tvmode``` with default ```True```. When ```tvmode=False```, **cksp** implements “The New Technical Trader” with default values. See ```help(ta.cksp)```.
|
||||
* _Chande Momentum Oscillator_ (**cmo**): New argument ```talib``` will use TA Lib's version and if TA Lib is installed. Default is True. See ```help(ta.cmo)```.
|
||||
* _Decreasing_ (**decreasing**): New argument ```strict``` checks if the series is continuously decreasing over period ```length``` with a faster calculation. Default: ```False```. The ```percent``` argument has also been added with default None. See ```help(ta.decreasing)```.
|
||||
* _Increasing_ (**increasing**): New argument ```strict``` checks if the series is continuously increasing over period ```length``` with a faster calculation. Default: ```False```. The ```percent``` argument has also been added with default None. See ```help(ta.increasing)```.
|
||||
* _Klinger Volume Oscillator_ (**kvo**): Implements TradingView's Klinger Volume Oscillator version. See ```help(ta.kvo)```.
|
||||
* _Linear Regression_ (**linreg**): Checks **numpy**'s version to determine whether to utilize the ```as_strided``` method or the newer ```sliding_window_view``` method. This should resolve Issues with Google Colab and it's delayed dependency updates as well as TensorFlow's dependencies as discussed in Issues [#285](https://github.com/twopirllc/pandas-ta/issues/285) and [#329](https://github.com/twopirllc/pandas-ta/issues/329).
|
||||
* _Moving Average Convergence Divergence_ (**macd**): New argument ```asmode``` enables AS version of MACD. Default is False. See ```help(ta.macd)```.
|
||||
* _Parabolic Stop and Reverse_ (**psar**): Bug fix and adjustment to match TradingView's ```sar```. New argument ```af0``` to initialize the Acceleration Factor. See ```help(ta.psar)```.
|
||||
* _Percentage Price Oscillator_ (**ppo**): Included new argument ```mamode``` as an option. Default is **sma** to match TA Lib. See ```help(ta.ppo)```.
|
||||
* _Standard Deviation_ (**stdev**): To use ```ddof``` argument, also set ```talib=False```. The ```ddof``` argument is not available if you have TA Lib installed in your environment. Same goes for **variance**. See ```help(ta.stdev)```.
|
||||
* _True Strength Index_ (**tsi**): Added ```signal``` with default ```13``` and Signal MA Mode ```mamode``` with default **ema** as arguments. See ```help(ta.tsi)```.
|
||||
* _Variance_ (**variance**): To use ```ddof``` argument, also set ```talib=False```. The ```ddof``` argument is not available if you have TA Lib installed in your environment. Same goes for **stdev**. See ```help(ta.variance)```.
|
||||
* _Volume Profile_ (**vp**): Calculation improvements. See [Pull Request #320](https://github.com/twopirllc/pandas-ta/pull/320) See ```help(ta.vp)```.
|
||||
* _Volume Weighted Moving Average_ (**vwma**): Fixed bug in DataFrame Extension call. See ```help(ta.vwma)```.
|
||||
* _Volume Weighted Average Price_ (**vwap**): Added a new parameter called ```anchor```. Default: "D" for "Daily". See [Timeseries Offset Aliases](https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases) for additional options. **Requires** the DataFrame index to be a DatetimeIndex. See ```help(ta.vwap)```.
|
||||
* _Volume Weighted Moving Average_ (**vwma**): Fixed bug in DataFrame Extension call. See ```help(ta.vwma)```.
|
||||
* _Z Score_ (**zscore**): Changed return column name from ```Z_length``` to ```ZS_length```. See ```help(ta.zscore)```.
|
||||
|
||||
|
||||
<br />
|
||||
|
||||
|
||||
@@ -49,15 +49,16 @@ Category = {
|
||||
"ao", "apo", "bias", "bop", "brar", "cci", "cfo", "cg", "cmo",
|
||||
"coppock", "cti", "er", "eri", "fisher", "inertia", "kdj", "kst", "macd",
|
||||
"mom", "pgo", "ppo", "psl", "pvo", "qqe", "roc", "rsi", "rsx", "rvgi",
|
||||
"slope", "smi", "squeeze", "squeeze_pro", "stc", "stoch", "stochrsi", "td_seq", "trix",
|
||||
"tsi", "uo", "willr"
|
||||
"slope", "smi", "squeeze", "squeeze_pro", "stc", "stoch", "stochrsi",
|
||||
"td_seq", "trix", "tsi", "uo", "willr"
|
||||
],
|
||||
# Overlap
|
||||
"overlap": [
|
||||
"alma", "dema", "ema", "fwma", "hilo", "hl2", "hlc3", "hma", "ichimoku",
|
||||
"jma", "kama", "linreg", "mcgd", "midpoint", "midprice", "ohlc4",
|
||||
"pwma", "rma", "sinwma", "sma", "smma", "ssf", "supertrend", "swma",
|
||||
"t3", "tema", "trima", "vidya", "vwap", "vwma", "wcp", "wma", "zlma"
|
||||
"alligator", "alma", "dema", "ema", "fwma", "hilo", "hl2", "hlc3",
|
||||
"hma", "ichimoku", "jma", "kama", "linreg", "mcgd", "midpoint",
|
||||
"midprice", "ohlc4", "pwma", "rma", "sinwma", "sma", "smma", "ssf",
|
||||
"supertrend", "swma", "t3", "tema", "trima", "vidya", "vwap", "vwma",
|
||||
"wcp", "wma", "zlma"
|
||||
],
|
||||
# Performance
|
||||
"performance": ["log_return", "percent_return"],
|
||||
|
||||
+16
-6
@@ -602,13 +602,18 @@ class AnalysisIndicators(BasePandasObject):
|
||||
if as_list:
|
||||
return ta_indicators
|
||||
|
||||
total_indicators = len(ta_indicators)
|
||||
indicator_count = len(ta_indicators)
|
||||
header = f"Pandas TA - Technical Analysis Indicators - v{self.version}"
|
||||
s = f"{header}\nTotal Indicators & Utilities: {total_indicators + len(ALL_PATTERNS)}\n"
|
||||
if total_indicators > 0:
|
||||
print(f"{s}Abbreviations:\n {', '.join(ta_indicators)}\n\nCandle Patterns:\n {', '.join(ALL_PATTERNS)}")
|
||||
else:
|
||||
print(s)
|
||||
|
||||
s, _count = f"{header}\n", 0
|
||||
if indicator_count > 0:
|
||||
s += f"\nIndicators and Utilities [{indicator_count}]:\n {', '.join(ta_indicators)}\n"
|
||||
_count += indicator_count
|
||||
if Imports["talib"]:
|
||||
s += f"\nCandle Patterns [{len(ALL_PATTERNS)}]:\n {', '.join(ALL_PATTERNS)}\n"
|
||||
_count += len(ALL_PATTERNS)
|
||||
s += f"\nTotal Candles, Indicators and Utilities: {_count}"
|
||||
print(s)
|
||||
|
||||
def strategy(self, *args, **kwargs):
|
||||
"""Strategy Method
|
||||
@@ -1144,6 +1149,11 @@ class AnalysisIndicators(BasePandasObject):
|
||||
return self._post_process(result, **kwargs)
|
||||
|
||||
# Overlap
|
||||
def alligator(self, jaw=None, teeth=None, lips=None, offset=None, **kwargs):
|
||||
close = self._get_column(kwargs.pop("close", "close"))
|
||||
result = alligator(close=close, jaw=jaw, teeth=teeth, lips=lips, offset=offset, **kwargs)
|
||||
return self._post_process(result, **kwargs)
|
||||
|
||||
def alma(self, length=None, sigma=None, distribution_offset=None, offset=None, **kwargs):
|
||||
close = self._get_column(kwargs.pop("close", "close"))
|
||||
result = alma(close=close, length=length, sigma=sigma, distribution_offset=distribution_offset, offset=offset, **kwargs)
|
||||
|
||||
@@ -47,7 +47,7 @@ def squeeze(high, low, close, bb_length=None, bb_std=None, kc_length=None, kc_sc
|
||||
if lazybear:
|
||||
highest_high = high.rolling(kc_length).max()
|
||||
lowest_low = low.rolling(kc_length).min()
|
||||
avg_ = 0.25 * (highest_high + lowest_low) + 0.5 * kch.b
|
||||
avg_ = 0.5 * (0.5 * (highest_high + lowest_low) + kch.b)
|
||||
|
||||
squeeze = linreg(close - avg_, length=kc_length)
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ def stoch(high, low, close, k=None, d=None, smooth_k=None, mamode=None, offset=N
|
||||
|
||||
# Prepare DataFrame to return
|
||||
data = {stoch_k.name: stoch_k, stoch_d.name: stoch_d}
|
||||
df = DataFrame(data)
|
||||
df = DataFrame(data, index=close.index)
|
||||
df.name = f"{_name}{_props}"
|
||||
df.category = stoch_k.category
|
||||
return df
|
||||
|
||||
@@ -66,7 +66,8 @@ def td_seq(close, asint=None, offset=None, **kwargs):
|
||||
up_seq.category = down_seq.category = "momentum"
|
||||
|
||||
# Prepare Dataframe to return
|
||||
df = DataFrame({up_seq.name: up_seq, down_seq.name: down_seq})
|
||||
data = {up_seq.name: up_seq, down_seq.name: down_seq}
|
||||
df = DataFrame(data, index=close.index)
|
||||
df.name = "TD_SEQ"
|
||||
df.category = up_seq.category
|
||||
|
||||
|
||||
@@ -43,7 +43,8 @@ def trix(close, length=None, signal=None, scalar=None, drift=None, offset=None,
|
||||
trix.category = trix_signal.category = "momentum"
|
||||
|
||||
# Prepare DataFrame to return
|
||||
df = DataFrame({trix.name: trix, trix_signal.name: trix_signal})
|
||||
data = {trix.name: trix, trix_signal.name: trix_signal}
|
||||
df = DataFrame(data, index=close.index)
|
||||
df.name = f"TRIX_{length}_{signal}"
|
||||
df.category = "momentum"
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from .alligator import alligator
|
||||
from .alma import alma
|
||||
from .dema import dema
|
||||
from .ema import ema
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# from numpy import nan as npNaN
|
||||
from pandas import DataFrame
|
||||
from .smma import smma
|
||||
from pandas_ta.utils import get_offset, verify_series
|
||||
|
||||
|
||||
def alligator(close, jaw=None, teeth=None, lips=None, talib=None, offset=None, **kwargs):
|
||||
"""Indicator: Bill Williams Alligator (ALLIGATOR)"""
|
||||
# Validate Arguments
|
||||
jaw = int(jaw) if jaw and jaw > 0 else 13
|
||||
teeth = int(teeth) if teeth and teeth > 0 else 8
|
||||
lips = int(lips) if lips and lips > 0 else 5
|
||||
close = verify_series(close, max(jaw, teeth, lips))
|
||||
offset = get_offset(offset)
|
||||
mode_tal = bool(talib) if isinstance(talib, bool) else True
|
||||
|
||||
if close is None: return
|
||||
|
||||
# Calculate Result
|
||||
gator_jaw = smma(close, length=jaw, talib=mode_tal)
|
||||
gator_teeth = smma(close, length=teeth, talib=mode_tal)
|
||||
gator_lips = smma(close, length=lips, talib=mode_tal)
|
||||
|
||||
# Offset
|
||||
if offset != 0:
|
||||
gator_jaw = gator_jaw.shift(offset)
|
||||
gator_teeth = gator_teeth.shift(offset)
|
||||
gator_lips = gator_lips.shift(offset)
|
||||
|
||||
# Handle fills
|
||||
if "fillna" in kwargs:
|
||||
gator_jaw.fillna(kwargs["fillna"], inplace=True)
|
||||
gator_teeth.fillna(kwargs["fillna"], inplace=True)
|
||||
gator_lips.fillna(kwargs["fillna"], inplace=True)
|
||||
if "fill_method" in kwargs:
|
||||
gator_jaw.fillna(method=kwargs["fill_method"], inplace=True)
|
||||
gator_teeth.fillna(method=kwargs["fill_method"], inplace=True)
|
||||
gator_lips.fillna(method=kwargs["fill_method"], inplace=True)
|
||||
|
||||
# Name & Category
|
||||
_props = f"_{jaw}_{teeth}_{lips}"
|
||||
data = {
|
||||
f"AGj{_props}": gator_jaw,
|
||||
f"AGt{_props}": gator_teeth,
|
||||
f"AGl{_props}": gator_lips
|
||||
}
|
||||
df = DataFrame(data, index=close.index)
|
||||
|
||||
df.name = f"AG{_props}"
|
||||
df.category = "overlap"
|
||||
|
||||
return df
|
||||
|
||||
|
||||
alligator.__doc__ = \
|
||||
"""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.
|
||||
|
||||
Sources:
|
||||
https://www.tradingview.com/scripts/alligator/
|
||||
https://www.sierrachart.com/index.php?page=doc/StudiesReference.php&ID=175&Name=Bill_Williams_Alligator
|
||||
|
||||
Calculation:
|
||||
Default Inputs:
|
||||
jaw=13, teeth=8, lips=5, mamode="sma"
|
||||
SMMA = SMoothed Moving Average
|
||||
|
||||
JAW = SMMA(close, jaw)
|
||||
TEETH = SMMA(close, teeth)
|
||||
LIPS = SMMA(close, lips)
|
||||
|
||||
Args:
|
||||
close (pd.Series): Series of 'close's
|
||||
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
|
||||
offset (int): How many periods to offset the result. Default: 0
|
||||
|
||||
Kwargs:
|
||||
fillna (value, optional): pd.DataFrame.fillna(value)
|
||||
fill_method (value, optional): Type of fill method
|
||||
|
||||
Returns:
|
||||
pd.DataFrame: JAW, TEETH, LIPS columns.
|
||||
"""
|
||||
@@ -71,7 +71,7 @@ def ichimoku(high, low, close, tenkan=None, kijun=None, senkou=None, include_chi
|
||||
if include_chikou:
|
||||
data[chikou_span.name] = chikou_span
|
||||
|
||||
ichimokudf = DataFrame(data)
|
||||
ichimokudf = DataFrame(data, index=close.index)
|
||||
ichimokudf.name = f"ICHIMOKU_{tenkan}_{kijun}_{senkou}"
|
||||
ichimokudf.category = "overlap"
|
||||
|
||||
|
||||
+62
-45
@@ -5,10 +5,11 @@ from numpy import nan as npNaN
|
||||
from numpy import pi as npPi
|
||||
from numpy.version import version as npVersion
|
||||
from pandas import Series
|
||||
from pandas_ta import Imports
|
||||
from pandas_ta.utils import get_offset, verify_series
|
||||
|
||||
|
||||
def linreg(close, length=None, offset=None, **kwargs):
|
||||
def linreg(close, length=None, talib=None, offset=None, **kwargs):
|
||||
"""Indicator: Linear Regression"""
|
||||
# Validate arguments
|
||||
length = int(length) if length and length > 0 else 14
|
||||
@@ -20,54 +21,68 @@ def linreg(close, length=None, offset=None, **kwargs):
|
||||
r = kwargs.pop("r", False)
|
||||
slope = kwargs.pop("slope", False)
|
||||
tsf = kwargs.pop("tsf", False)
|
||||
mode_tal = bool(talib) if isinstance(talib, bool) else True
|
||||
|
||||
if close is None: return
|
||||
|
||||
# Calculate Result
|
||||
x = range(1, length + 1) # [1, 2, ..., n] from 1 to n keeps Sum(xy) low
|
||||
x_sum = 0.5 * length * (length + 1)
|
||||
x2_sum = x_sum * (2 * length + 1) / 3
|
||||
divisor = length * x2_sum - x_sum * x_sum
|
||||
|
||||
def linear_regression(series):
|
||||
y_sum = series.sum()
|
||||
xy_sum = (x * series).sum()
|
||||
|
||||
m = (length * xy_sum - x_sum * y_sum) / divisor
|
||||
if slope:
|
||||
return m
|
||||
b = (y_sum * x2_sum - x_sum * xy_sum) / divisor
|
||||
if intercept:
|
||||
return b
|
||||
|
||||
if angle:
|
||||
theta = npAtan(m)
|
||||
if degrees:
|
||||
theta *= 180 / npPi
|
||||
return theta
|
||||
|
||||
if r:
|
||||
y2_sum = (series * series).sum()
|
||||
rn = length * xy_sum - x_sum * y_sum
|
||||
rd = (divisor * (length * y2_sum - y_sum * y_sum)) ** 0.5
|
||||
return rn / rd
|
||||
|
||||
return m * length + b if tsf else m * (length - 1) + b
|
||||
|
||||
def rolling_window(array, length):
|
||||
"""https://github.com/twopirllc/pandas-ta/issues/285"""
|
||||
strides = array.strides + (array.strides[-1],)
|
||||
shape = array.shape[:-1] + (array.shape[-1] - length + 1, length)
|
||||
return as_strided(array, shape=shape, strides=strides)
|
||||
|
||||
if npVersion >= "1.20.0":
|
||||
from numpy.lib.stride_tricks import sliding_window_view
|
||||
linreg_ = [linear_regression(_) for _ in sliding_window_view(npArray(close), length)]
|
||||
if Imports["talib"] and mode_tal:
|
||||
from talib import LINEARREG, LINEARREG_ANGLE, LINEARREG_INTERCEPT, LINEARREG_SLOPE, TSF
|
||||
if tsf:
|
||||
linreg = TSF(close, timeperiod=length)
|
||||
elif slope:
|
||||
linreg = LINEARREG_SLOPE(close, timeperiod=length)
|
||||
elif intercept:
|
||||
linreg = LINEARREG_INTERCEPT(close, timeperiod=length)
|
||||
elif angle:
|
||||
linreg = LINEARREG_ANGLE(close, timeperiod=length)
|
||||
else:
|
||||
linreg = LINEARREG(close, timeperiod=length)
|
||||
else:
|
||||
from numpy.lib.stride_tricks import as_strided
|
||||
linreg_ = [linear_regression(_) for _ in rolling_window(npArray(close), length)]
|
||||
x = range(1, length + 1) # [1, 2, ..., n] from 1 to n keeps Sum(xy) low
|
||||
x_sum = 0.5 * length * (length + 1)
|
||||
x2_sum = x_sum * (2 * length + 1) / 3
|
||||
divisor = length * x2_sum - x_sum * x_sum
|
||||
|
||||
linreg = Series([npNaN] * (length - 1) + linreg_, index=close.index)
|
||||
def linear_regression(series):
|
||||
y_sum = series.sum()
|
||||
xy_sum = (x * series).sum()
|
||||
|
||||
m = (length * xy_sum - x_sum * y_sum) / divisor
|
||||
if slope:
|
||||
return m
|
||||
b = (y_sum * x2_sum - x_sum * xy_sum) / divisor
|
||||
if intercept:
|
||||
return b
|
||||
|
||||
if angle:
|
||||
theta = npAtan(m)
|
||||
if degrees:
|
||||
theta *= 180 / npPi
|
||||
return theta
|
||||
|
||||
if r:
|
||||
y2_sum = (series * series).sum()
|
||||
rn = length * xy_sum - x_sum * y_sum
|
||||
rd = (divisor * (length * y2_sum - y_sum * y_sum)) ** 0.5
|
||||
return rn / rd
|
||||
|
||||
return m * length + b if not tsf else m * (length - 1) + b
|
||||
|
||||
def rolling_window(array, length):
|
||||
"""https://github.com/twopirllc/pandas-ta/issues/285"""
|
||||
strides = array.strides + (array.strides[-1],)
|
||||
shape = array.shape[:-1] + (array.shape[-1] - length + 1, length)
|
||||
return as_strided(array, shape=shape, strides=strides)
|
||||
|
||||
if npVersion >= "1.20.0":
|
||||
from numpy.lib.stride_tricks import sliding_window_view
|
||||
linreg_ = [linear_regression(_) for _ in sliding_window_view(npArray(close), length)]
|
||||
else:
|
||||
from numpy.lib.stride_tricks import as_strided
|
||||
linreg_ = [linear_regression(_) for _ in rolling_window(npArray(close), length)]
|
||||
|
||||
linreg = Series([npNaN] * (length - 1) + linreg_, index=close.index)
|
||||
|
||||
# Offset
|
||||
if offset != 0:
|
||||
@@ -122,8 +137,10 @@ Calculation:
|
||||
|
||||
Args:
|
||||
close (pd.Series): Series of 'close's
|
||||
length (int): It's period. Default: 10
|
||||
offset (int): How many periods to offset the result. Default: 0
|
||||
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
|
||||
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.
|
||||
|
||||
@@ -17,7 +17,6 @@ from .tema import tema
|
||||
from .trima import trima
|
||||
from .vidya import vidya
|
||||
from .wma import wma
|
||||
from .zlma import zlma
|
||||
|
||||
|
||||
def ma(name:str = None, source:Series = None, **kwargs) -> Series:
|
||||
@@ -25,7 +24,7 @@ def ma(name:str = None, source:Series = None, **kwargs) -> Series:
|
||||
|
||||
Available MAs:
|
||||
dema, ema, fwma, hma, linreg, midpoint, pwma, rma,
|
||||
sinwma, sma, swma, t3, tema, trima, vidya, wma, zlma
|
||||
sinwma, sma, swma, t3, tema, trima, vidya, wma
|
||||
|
||||
Examples:
|
||||
ema8 = ta.ma("ema", df.close, length=8)
|
||||
@@ -45,7 +44,7 @@ def ma(name:str = None, source:Series = None, **kwargs) -> Series:
|
||||
|
||||
_mas = [
|
||||
"dema", "ema", "fwma", "hma", "linreg", "midpoint", "pwma", "rma",
|
||||
"sinwma", "sma", "swma", "t3", "tema", "trima", "vidya", "wma", "zlma"
|
||||
"sinwma", "sma", "swma", "t3", "tema", "trima", "vidya", "wma"
|
||||
]
|
||||
if name is None and source is None:
|
||||
return _mas
|
||||
@@ -69,5 +68,4 @@ def ma(name:str = None, source:Series = None, **kwargs) -> Series:
|
||||
elif name == "trima": return trima(source, **kwargs)
|
||||
elif name == "vidya": return vidya(source, **kwargs)
|
||||
elif name == "wma": return wma(source, **kwargs)
|
||||
elif name == "zlma": return zlma(source, **kwargs)
|
||||
else: return ema(source, **kwargs)
|
||||
@@ -1,6 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from numpy import nan as npNaN
|
||||
from pandas_ta.overlap import ma
|
||||
from pandas_ta.overlap.ma import ma
|
||||
from pandas_ta.utils import get_offset, verify_series
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ 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 William's Alligator indicator.
|
||||
Bill Williams Alligator indicator.
|
||||
|
||||
Sources:
|
||||
https://www.tradingview.com/scripts/smma/
|
||||
@@ -75,8 +75,6 @@ Args:
|
||||
offset (int): How many periods to offset the result. Default: 0
|
||||
|
||||
Kwargs:
|
||||
adjust (bool): Default: True
|
||||
presma (bool, optional): If True, uses SMA for initial value.
|
||||
fillna (value, optional): pd.DataFrame.fillna(value)
|
||||
fill_method (value, optional): Type of fill method
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from . import (
|
||||
dema, ema, hma, linreg, rma, sma, swma, t3, tema, trima, vidya, wma
|
||||
)
|
||||
# from . import (
|
||||
# dema, ema, hma, linreg, rma, sma, swma, t3, tema, trima, vidya, wma
|
||||
# )
|
||||
from pandas_ta.overlap import ma
|
||||
from pandas_ta.utils import get_offset, verify_series
|
||||
|
||||
|
||||
@@ -18,18 +19,7 @@ def zlma(close, length=None, mamode=None, offset=None, **kwargs):
|
||||
# Calculate Result
|
||||
lag = int(0.5 * (length - 1))
|
||||
close_ = 2 * close - close.shift(lag)
|
||||
if mamode == "dema": zlma = dema(close_, length=length, **kwargs)
|
||||
elif mamode == "hma": zlma = hma(close_, length=length, **kwargs)
|
||||
elif mamode == "linreg": zlma = linreg(close_, length=length, **kwargs)
|
||||
elif mamode == "rma": zlma = rma(close_, length=length, **kwargs)
|
||||
elif mamode == "sma": zlma = sma(close_, length=length, **kwargs)
|
||||
elif mamode == "swma": zlma = swma(close_, length=length, **kwargs)
|
||||
elif mamode == "t3": zlma = t3(close_, length=length, **kwargs)
|
||||
elif mamode == "tema": zlma = tema(close_, length=length, **kwargs)
|
||||
elif mamode == "trima": zlma = trima(close_, length=length, **kwargs)
|
||||
elif mamode == "vidya": zlma = vidya(close_, length=length, **kwargs)
|
||||
elif mamode == "wma": zlma = wma(close_, length=length, **kwargs)
|
||||
else: zlma = ema(close_, length=length, **kwargs) # "ema"
|
||||
zlma = ma(mamode, close_, length=length, **kwargs)
|
||||
|
||||
# Offset
|
||||
if offset != 0:
|
||||
|
||||
@@ -12,7 +12,7 @@ def bbands(close, length=None, std=None, ddof=0, mamode=None, talib=None, offset
|
||||
length = int(length) if length and length > 0 else 5
|
||||
std = float(std) if std and std > 0 else 2.0
|
||||
mamode = mamode if isinstance(mamode, str) else "sma"
|
||||
ddof = int(ddof) if ddof >= 0 and ddof < length else 1
|
||||
ddof = int(ddof) if isinstance(ddof, int) and ddof >= 0 and ddof < length else 1
|
||||
close = verify_series(close, length)
|
||||
offset = get_offset(offset)
|
||||
mode_tal = bool(talib) if isinstance(talib, bool) else True
|
||||
@@ -113,6 +113,10 @@ Args:
|
||||
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
|
||||
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
|
||||
offset (int): How many periods to offset the result. Default: 0
|
||||
|
||||
Kwargs:
|
||||
|
||||
@@ -48,7 +48,7 @@ def kvo(high, low, close, volume, fast=None, slow=None, signal=None, mamode=None
|
||||
|
||||
# Prepare DataFrame to return
|
||||
data = {kvo.name: kvo, kvo_signal.name: kvo_signal}
|
||||
df = DataFrame(data)
|
||||
df = DataFrame(data, index=close.index)
|
||||
df.name = f"KVO{_props}"
|
||||
df.category = kvo.category
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from distutils.core import setup
|
||||
|
||||
long_description = "An easy to use Python 3 Pandas Extension with 130+ Technical Analysis Indicators. Can be called from a Pandas DataFrame or standalone like TA-Lib. Correlation tested with TA-Lib."
|
||||
long_description = "An easy to use Python 3 Pandas Extension with 140+ Technical Analysis Indicators. Can be called from a Pandas DataFrame or standalone like TA-Lib. Correlation tested with TA-Lib."
|
||||
|
||||
setup(
|
||||
name="pandas_ta",
|
||||
@@ -19,7 +19,7 @@ setup(
|
||||
"pandas_ta.volatility",
|
||||
"pandas_ta.volume"
|
||||
],
|
||||
version=".".join(("0", "3", "16b")),
|
||||
version=".".join(("0", "3", "17b")),
|
||||
description=long_description,
|
||||
long_description=long_description,
|
||||
author="Kevin Johnson",
|
||||
|
||||
@@ -18,6 +18,11 @@ class TestOverlapExtension(TestCase):
|
||||
def tearDown(self): pass
|
||||
|
||||
|
||||
def test_alligator_ext(self):
|
||||
self.data.ta.alligator(append=True)
|
||||
self.assertIsInstance(self.data, DataFrame)
|
||||
self.assertEqual(list(self.data.columns[-3:]), ["AGj_13_8_5", "AGt_13_8_5", "AGl_13_8_5"])
|
||||
|
||||
def test_alma_ext(self):
|
||||
self.data.ta.alma(append=True)
|
||||
self.assertIsInstance(self.data, DataFrame)
|
||||
|
||||
@@ -34,6 +34,11 @@ class TestOverlap(TestCase):
|
||||
def tearDown(self): pass
|
||||
|
||||
|
||||
def test_alligator(self):
|
||||
result = pandas_ta.alligator(self.close)
|
||||
self.assertIsInstance(result, DataFrame)
|
||||
self.assertEqual(result.name, "AG_13_8_5")
|
||||
|
||||
def test_alma(self):
|
||||
result = pandas_ta.alma(self.close)# , length=None, sigma=None, distribution_offset=)
|
||||
self.assertIsInstance(result, Series)
|
||||
|
||||
Reference in New Issue
Block a user