ENH ulcer index with everget kwarg indicator

This commit is contained in:
Kevin Johnson
2020-07-26 14:24:52 -07:00
parent 2c1766ac96
commit fa24a4d96b
6 changed files with 117 additions and 6 deletions
+4 -3
View File
@@ -14,7 +14,7 @@ All the indicators return a named Series or a DataFrame in uppercase underscore
## __Features__
* Has 100+ indicators and utility functions.
* Has 110+ indicators and utility functions.
* Option to use __multiprocessing__ when using df.ta.strategy(). See below.
* Example Jupyter Notebooks under the [examples](https://github.com/twopirllc/pandas-ta/tree/master/examples) directory, including how to create Custom Strategies using the new [__Strategy__ Class](https://github.com/twopirllc/pandas-ta/tree/master/examples/PandaTA_Strategy_Examples.ipynb)
* A new 'ta' method called 'strategy'. By default, it runs __all__ the indicators.
@@ -30,7 +30,7 @@ All the indicators return a named Series or a DataFrame in uppercase underscore
* Improved the calculation performance of indicators: _Exponential Moving Averagage_
and _Weighted Moving Average_.
* Removed internal core optimizations when running ```df.ta.strategy('all')``` with multiprocessing. See the ```ta.strategy()``` method for more details.
* __New Indicators:__ Kaufman's _Efficiency Ratio_ **er**, Johnson's _Pretty Good Oscillator_ **pgo**, _Elder Ray Index_ **eri**
* __New Indicators:__ Kaufman's _Efficiency Ratio_ **er**, Johnson's _Pretty Good Oscillator_ **pgo**, _Elder Ray Index_ **eri**, Martin's _Ulcer Index_ **ui**
## What is a Pandas DataFrame Extension?
@@ -399,7 +399,7 @@ Use parameter: cumulative=**True** for cumulative results.
* _Below Value_: **below_value**
* _Cross_: **cross**
## _Volatility_ (11)
## _Volatility_ (12)
* _Aberration_: **aberration**
* _Acceleration Bands_: **accbands**
@@ -412,6 +412,7 @@ Use parameter: cumulative=**True** for cumulative results.
* _Price Distance_: **pdist**
* _Relative Volatility Index_: **rvi**
* _True Range_: **true_range**
* _Ulcer Index_: **ui**
| _Average True Range_ (ATR) |
|:--------:|
+6
View File
@@ -1381,6 +1381,12 @@ class AnalysisIndicators(BasePandasObject):
result = true_range(high=high, low=low, close=close, drift=drift, offset=offset, **kwargs)
return result
@finalize
def ui(self, close=None, length=None, scalar=None, offset=None, **kwargs):
close = self._get_column(close, 'close')
result = ui(close=close, length=length, scalar=scalar, offset=offset, **kwargs)
return result
# Volume Indicators
+2 -1
View File
@@ -9,4 +9,5 @@ from .massi import massi
from .pdist import pdist
from .natr import natr
from .rvi import rvi
from .true_range import true_range
from .true_range import true_range
from .ui import ui
+85
View File
@@ -0,0 +1,85 @@
# -*- coding: utf-8 -*-
from numpy import sqrt as npsqrt
from pandas_ta.overlap import sma
from ..utils import get_offset, non_zero_range, verify_series
def ui(close, length=None, scalar=None, offset=None, **kwargs):
"""Indicator: Ulcer Index (UI)"""
# Validate arguments
close = verify_series(close)
length = int(length) if length and length > 0 else 14
scalar = float(scalar) if scalar and scalar > 0 else 100
offset = get_offset(offset)
# Calculate Result
highest_close = close.rolling(length).max()
downside = scalar * (close - highest_close)
downside /= highest_close
d2 = downside * downside
everget = kwargs.pop("everget", False)
if everget:
# Everget uses SMA instead of SUM for calculation
ui = (sma(d2, length) / length).apply(npsqrt)
else:
ui = (d2.rolling(length).sum() / length).apply(npsqrt)
# Offset
if offset != 0:
ui = ui.shift(offset)
# Handle fills
if 'fillna' in kwargs:
ui.fillna(kwargs['fillna'], inplace=True)
if 'fill_method' in kwargs:
ui.fillna(method=kwargs['fill_method'], inplace=True)
# Name and Categorize it
ui.name = f"UI{'' if not everget else 'e'}_{length}"
ui.category = "volatility"
return ui
ui.__doc__ = \
"""Ulcer Index (UI)
The Ulcer Index by Peter Martin measures the downside volatility with the use of
the Quadratic Mean, which has the effect of emphasising large drawdowns.
Sources:
https://library.tradingtechnologies.com/trade/chrt-ti-ulcer-index.html
https://en.wikipedia.org/wiki/Ulcer_index
http://www.tangotools.com/ui/ui.htm
Calculation:
Default Inputs:
length=14, scalar=100
HC = Highest Close
SMA = Simple Moving Average
HCN = HC(close, length)
DOWNSIDE = scalar * (close - HCN) / HCN
if kwargs["everget"]:
UI = SQRT(SMA(DOWNSIDE^2, length) / length)
else:
UI = SQRT(SUM(DOWNSIDE^2, length) / length)
Args:
high (pd.Series): Series of 'high's
close (pd.Series): Series of 'close's
length (int): The short period. Default: 14
scalar (float): A positive float to scale the bands. Default: 100
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
everget (value, optional): TradingView's Evergets SMA instead of SUM
calculation. Default: False
Returns:
pd.Series: New feature
"""
+10 -1
View File
@@ -153,4 +153,13 @@ class TestVolatility(TestCase):
corr = pandas_ta.utils.df_error_analysis(result, expected, col=CORRELATION)
self.assertGreater(corr, CORRELATION_THRESHOLD)
except Exception as ex:
error_analysis(result, CORRELATION, ex)
error_analysis(result, CORRELATION, ex)
def test_ui(self):
result = pandas_ta.ui(self.close)
self.assertIsInstance(result, Series)
self.assertEqual(result.name, "UI_14")
result = pandas_ta.ui(self.close, everget=True)
self.assertIsInstance(result, Series)
self.assertEqual(result.name, "UIe_14")
+10 -1
View File
@@ -83,4 +83,13 @@ class TestVolatilityExtension(TestCase):
def test_true_range_ext(self):
self.data.ta.true_range(append=True)
self.assertIsInstance(self.data, DataFrame)
self.assertEqual(self.data.columns[-1], "TRUERANGE_1")
self.assertEqual(self.data.columns[-1], "TRUERANGE_1")
def test_ui_ext(self):
self.data.ta.ui(append=True)
self.assertIsInstance(self.data, DataFrame)
self.assertEqual(self.data.columns[-1], "UI_14")
self.data.ta.ui(append=True, everget=True)
self.assertIsInstance(self.data, DataFrame)
self.assertEqual(self.data.columns[-1], "UIe_14")