indicator

package module
v1.2.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 20, 2021 License: MIT Imports: 4 Imported by: 10

README

GoDoc License Build Status

Indicator Go

Indicator is a Golang module providing various stock technical analysis indicators, and strategies for trading.

Indicators Provided

The following list of indicators are currently supported by this package:

Strategies Provided

The following list of strategies are currently supported by this package:

Usage

Install package.

go get github.com/cinar/indicator

Import indicator.

import (
    "github.com/cinar/indicator"
)
Moving Averages
Simple Moving Average (SMA)

The Sma function calculates the simple moving average for a given period.

result := indicator.Sma(2, []float64{2, 4, 6, 8, 10})
Moving Standard Deviation (Std)

The Std function calculates the moving standard deviation for a given period.

result := indicator.Std(2, []float64{2, 4, 6, 8, 12, 14, 16, 18, 20})
Exponential Moving Average (EMA)

The Ema function calculates the exponential moving average for a given period.

result := indicator.Ema(2, []float64{2, 4, 6, 8, 12, 14, 16, 18, 20})
Indicators
Moving Average Convergence Divergence (MACD)

The Macd function calculates a trend-following momentum indicator that shows the relationship between two moving averages of price.

MACD = 12-Period EMA - 26-Period EMA.
Signal = 9-Period EMA of MACD.
macd, signal := indicator.Macd(close)
Bollinger Bands

The BollingerBands function calculates the bollinger bands, middle band, upper band, lower band, provides identification of when a stock is oversold or overbought.

Middle Band = 20-Period SMA.
Upper Band = 20-Period SMA + 2 (20-Period Std)
Lower Band = 20-Period SMA - 2 (20-Period Std)
middleBand, upperBand, lowerBand := indicator.BollingerBands(close)
Bollinger Band Width

The BollingerBandWidth function measures the percentage difference between the upper band and the lower band. It decreases as Bollinger Bands narrows and increases as Bollinger Bands widens.

During a period of rising price volatility the band width widens, and during a period of low market volatility band width contracts.

Band Width = (Upper Band - Lower Band) / Middle Band
bandWidth, bandWidthEma90 := indicator.BollingerBandWidth(middleBand, upperBand, lowerBand)
Awesome Oscillator

The AwesomeOscillator function calculates the awesome oscillator based on low and high daily prices for a given stock. It is an indicator used to measure market momentum.

Median Price = ((Low + High) / 2)
AO = 5-Period SMA - 34-Period SMA.
result := indicator.AwesomeOscillator(low, high)
Williams R

The WilliamsR function calculates the Williams R based on low, high, and close prices. It is a type of momentum indicator that moves between 0 and -100 and measures overbought and oversold levels.

WR = (Highest High - Close) / (Highest High - Lowest Low)
result := indicator.WilliamsR(low, high, close)
Typical Price

The TypicalPrice function calculates another approximation of average price for each period and can be used as a filter for moving average systems.

Typical Price = (High + Low + Close) / 3
ta, sma20 := indicator.TypicalPrice(high, low, close)
Relative Strength Index (RSI)

The Rsi function calculates a momentum indicator that measures the magnitude of recent price changes to evaluate overbought and oversold conditions.

RS = Average Gain / Average Loss
RSI = 100 - (100 / (1 + RS))
rs, rsi := indicator.Rsi(close)
On-Balance Volume (OBV)

The Obv function calculates a technical trading momentum indicator that uses volume flow to predict changes in stock price.

                  volume, if Close > Close-Prev
OBV = OBV-Prev +       0, if Close = Close-Prev
                 -volume, if Close < Close-Prev
result := indicator.Obv(close, volume)
Actual True Range (ATR)

The Atr function calculates a technical analysis indicator that measures market volatility by decomposing the entire range of stock prices for that period.

TR = Max((High - Low), (High - Close), (Close - Low))
ATR = 14-Period SMA TR
tr, atr := indicator.Atr(14, high, low, close)
Chandelier Exit

The ChandelierExit function sets a trailing stop-loss based on the Average True Value (ATR).

Chandelier Exit Long = 22-Period SMA High - ATR(22) * 3
Chandelier Exit Short = 22-Period SMA Low + ATR(22) * 3
chandelierExitLong, chandelierExitShort := indicator.ChandelierExit(high, low, close)
Ichimoku Cloud

The IchimokuCloud, also known as Ichimoku Kinko Hyo, calculates a versatile indicator that defines support and resistence, identifies tred direction, gauges momentum, and provides trading signals.

Tenkan-sen (Conversion Line) = (9-Period High + 9-Period Low) / 2
Kijun-sen (Base Line) = (26-Period High + 26-Period Low) / 2
Senkou Span A (Leading Span A) = (Conversion Line + Base Line) / 2
Senkou Span B (Leading Span B) = (52-Period High + 52-Period Low) / 2
Chikou Span (Lagging Span) = Close plotted 26 days in the past.
conversionLine, baseLine, leadingSpanA, leadingSpanB, laggingLine := indicator.IchimokuCloud(high, low, close)
Stochastic Oscillator

The StochasticOscillator function calculates a momentum indicator that shows the location of the close relative to high-low range over a set number of periods.

K = (Close - Lowest Low) / (Highest High - Lowest Low) * 100
D = 3-Period SMA of K
k, d := indicator.StochasticOscillator(high, low, close)
Aroon Indicator

The Aroon function calculates a technical indicator that is used to identify trend changes in the price of a stock, as well as the strength of that trend. It consists of two lines, Aroon Up, and Aroon Down. The Aroon Up line measures measures the strength of the uptrend, and the Aroon Down measures the strength of the downtrend. When Aroon Up is above Aroon Down, it indicates bullish price, and when Aroon Down is above Aroon Up, it indicates bearish price.

Aroon Up = ((25 - Period Since Last 25 Period High) / 25) * 100
Aroon Down = ((25 - Period Since Last 25 Period Low) / 25) * 100
aroonUp, aroonDown := indicator.Aroon(high, low)
Parabolic SAR

The ParabolicSar function calculates an identifier for the trend and the trailing stop.

PSAR = PSAR[i - 1] - ((PSAR[i - 1] - EP) * AF)

If the trend is Falling:

  • PSAR is the maximum of PSAR or the previous two high values.
  • If the current high is greather than or equals to PSAR, use EP.

If the trend is Rising:

  • PSAR is the minimum of PSAR or the previous two low values.
  • If the current low is less than or equials to PSAR, use EP.

If PSAR is greather than the closing, trend is falling, and the EP is set to the minimum of EP or the low.

If PSAR is lower than or equals to the closing, trend is rising, and the EP is set to the maximum of EP or the high.

If the trend is the same, and AF is less than 0.20, increment it by 0.02. If the trend is not the same, set AF to 0.02.

Based on video How to Calculate the PSAR Using Excel - Revised Version.

psar, trend := indicator.ParabolicSar(high, low, close)
Vortex Indicator

The Vortex function provides two oscillators that capture positive and negative trend movement. A bullish signal triggers when the positive trend indicator crosses above the negative trend indicator or a key level. A bearish signal triggers when the negative trend indicator crosses above the positive trend indicator or a key level.

+VM = Abs(Current High - Prior Low)
-VM = Abs(Current Low - Prior High)

+VM14 = 14-Period Sum of +VM
-VM14 = 14-Period Sum of -VM

TR = Max((High[i]-Low[i]), Abs(High[i]-Close[i-1]), Abs(Low[i]-Close[i-1]))
TR14 = 14-Period Sum of TR

+VI14 = +VM14 / TR14
-VI14 = -VM14 / TR14

Based on Vortex Indicator

plusVi, minusVi := indicator.Vortex(high, low, close)
Acceleration Bands

The AccelerationBands plots upper and lower envelope bands around a simple moving average.

Upper Band = SMA(High * (1 + 4 * (High - Low) / (High + Low)))
Middle Band = SMA(Close)
Lower Band = SMA(Low * (1 + 4 * (High - Low) / (High + Low)))
upperBand, middleBand, lowerBand := indicator.AccelerationBands(high, low, close)
Accumulation/Distribution (A/D)

The AccumulationDistribution is a cumulative indicator that uses volume and price to assess whether a stock is being accumulated or distributed.

The Accumulation/Distribution seeks to identify divergences between the stock price and the volume flow.

MFM = ((Close - Low) - (High - Close)) / (High - Low)
MFV = MFM * Period Volume
AD = Previous AD + CMFV

Based on Accumulation/Distribution Indicator (A/D).

ad := indicator.AccumulationDistribution(high, low, close,
Strategies

The strategies are where the results from one or more indicators gets combined to produce a recommended action.

The stragies operates on an Asset with the following members.

type Asset struct {
	Date   []time.Time
	Open   []float64
	Close  []float64
	High   []float64
	Low    []float64
	Volume []int64
}

The StrategyFunction takes an Asset, and provides an array of Action for each row.

// Strategy function.
type StrategyFunction func(Asset) []Action

The following Action values are currently provided.

type Action int

const (
	HOLD Action = iota
	BUY
	SELL
)
Buy and Hold Strategy

The BuyAndHoldStrategy provides a simple strategy to buy the given asset and hold it. It provides a good indicator for the change of asset's value without any other strategy is used.

actions := indicator.BuyAndHoldStrategy(asset)
Trend Strategy

The TrendStrategy provides a simply strategy to buy the given asset following the asset's closing value increases in count subsequent rows. Produces the sell action following the asset's closing value decreases in count subsequent rows.

actions := indicator.TrendStrategy(asset, 4)

The function signature of TrendStrategy does not match the StrategyFunction type, as it requires an additional count parameter. The MakeTrendStrategy function can be used to return a StrategyFunction instance based on the given count value.

strategy := indicator.MakeTrendStrategy(4)
actions := strategy(asset)
MACD Strategy

The MacdStrategy uses the macd, and signal values that are generated by the Macd indicator function to provide a BUY action when macd crosses above signal, and SELL action when macd crosses below signal.

actions := indicator.MacdStrategy(asset)
RSI Strategy

The RsiStrategy uses the rsi values that are generated by the Rsi indicator function to provide a BUY action when rsi is below the buyAt parameter, and a SELL action when rsi is above the sellAt parameter.

actions := indicator.RsiStrategy(asset, 70, 30)

The RSI strategy is usually used with 70-30, or 80-20 values. The DefaultRsiStrategy function uses the 70-30 values.

actions := indicator.DefaultRsiStrategy(asset)

The function signature of RsiStrategy does not match the StrategyFunction type, as it requires an additional sellAt, and buyAt parameters. The MakeRsiStrategy function can be used to return a StrategyFunction instance based on the given sellAt, and buyAt values.

strategy := indicator.MakeRsiStrategy(80, 20)
actions := strategy(asset)
MACD and RSI Strategy

The MacdAndRsiStrategy function uses the actions generated by the MacdStrategy and the DefaultRsiStrategy to provide BUY and SELL actions.

actions := indicator.MacdAndRsiStrategy(asset)
Bollinger Bands Strategy

The BollingerBandsStrategy uses the upperBand, and lowerBand values that are generated by the BollingerBands indicator function to provide a SELL action when the asset's closing is above the upperBand, and a BUY action when the asset's closing is below the lowerBand values.

actions := indicator.BollingerBandsStrategy(asset)
Awesome Oscillator Strategy

The AwesomeOscillatorStrategy uses the ao values that are generated by the AwesomeOscillator indicator function to provide a SELL action when the ao is below zero, and a BUY action when ao is above zero.

actions := indicator.AwesomeOscillatorStrategy(asset)
Williams R Strategy

The WilliamsRStrategy uses the wr values that are generated by the WilliamsR indicator function to provide a SELL action when the wr is below -20, and a BUY action when wr is above -80.

actions := indicator.WilliamsRStrategy(asset)

License

The source code is provided under MIT License.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AccelerationBands added in v1.2.0

func AccelerationBands(high, low, close []float64) ([]float64, []float64, []float64)

Acceleration Bands. Plots upper and lower envelope bands around a simple moving average.

Upper Band = SMA(High * (1 + 4 * (High - Low) / (High + Low))) Middle Band = SMA(Close) Lower Band = SMA(Low * (1 - 4 * (High - Low) / (High + Low)))

Returns upper band, middle band, lower band.

func AccumulationDistribution added in v1.2.0

func AccumulationDistribution(high, low, close []float64, volume []int64) []float64

Accumulation/Distribution Indicator (A/D). Cumulative indicator that uses volume and price to assess whether a stock is being accumulated or distributed.

MFM = ((Close - Low) - (High - Close)) / (High - Low) MFV = MFM * Period Volume AD = Previous AD + CMFV

Returns ad.

func Aroon

func Aroon(high, low []float64) ([]float64, []float64)

Aroon Indicator. It is a technical indicator that is used to identify trend changes in the price of a stock, as well as the strength of that trend. It consists of two lines, Arron Up, and Aroon Down. The Aroon Up line measures the strength of the uptrend, and the Aroon Down measures the strength of the downtrend. When Aroon Up is above Aroon Down, it indicates bullish price, and when Aroon Down is above Aroon Up, it indicates bearish price.

Aroon Up = ((25 - Period Since Last 25 Period High) / 25) * 100 Aroon Down = ((25 - Period Since Last 25 Period Low) / 25) * 100

Returns aroonUp, aroonDown

func Atr

func Atr(period int, high, low, close []float64) ([]float64, []float64)

Average True Range (ATR). It is a technical analysis indicator that measures market volatility by decomposing the entire range of stock prices for that period.

TR = Max((High - Low), (High - Close), (Close - Low)) ATR = SMA TR

Returns tr, atr

func AwesomeOscillator

func AwesomeOscillator(low, high []float64) []float64

Awesome Oscillator.

Median Price = ((Low + High) / 2). AO = 5-Period SMA - 34-Period SMA.

Returns ao.

func BollingerBandWidth

func BollingerBandWidth(middleBand, upperBand, lowerBand []float64) ([]float64, []float64)

Bollinger Band Width. It measures the percentage difference between the upper band and the lower band. It decreases as Bollinger Bands narrows and increases as Bollinger Bands widens

During a period of rising price volatity the band width widens, and during a period of low market volatity band width contracts.

Band Width = (Upper Band - Lower Band) / Middle Band

Returns bandWidth, bandWidthEma90

func BollingerBands

func BollingerBands(close []float64) ([]float64, []float64, []float64)

Bollinger Bands.

Middle Band = 20-Period SMA. Upper Band = 20-Period SMA + 2 (20-Period Std) Lower Band = 20-Period SMA - 2 (20-Period Std)

Returns middle band, upper band, lower band.

func ChandelierExit

func ChandelierExit(high, low, close []float64) ([]float64, []float64)

Chandelier Exit. It sets a trailing stop-loss based on the Average True Value (ATR).

Chandelier Exit Long = 22-Period SMA High - ATR(22) * 3 Chandelier Exit Short = 22-Period SMA Low + ATR(22) * 3

Returns chandelierExitLong, chandelierExitShort

func Ema

func Ema(period int, values []float64) []float64

Exponential Moving Average (EMA).

func IchimokuCloud

func IchimokuCloud(high, low, close []float64) ([]float64, []float64, []float64, []float64, []float64)

Ichimoku Cloud. Also known as Ichimoku Kinko Hyo, is a versatile indicator that defines support and resistence, identifies trend direction, gauges momentum, and provides trading signals.

Tenkan-sen (Conversion Line) = (9-Period High + 9-Period Low) / 2 Kijun-sen (Base Line) = (26-Period High + 26-Period Low) / 2 Senkou Span A (Leading Span A) = (Conversion Line + Base Line) / 2 Senkou Span B (Leading Span B) = (52-Period High + 52-Period Low) / 2 Chikou Span (Lagging Span) = Close plotted 26 days in the past.

Returns conversionLine, baseLine, leadingSpanA, leadingSpanB, laggingSpan

func Macd

func Macd(close []float64) ([]float64, []float64)

Moving Average Convergence Divergence (MACD).

MACD = 12-Period EMA - 26-Period EMA. Signal = 9-Period EMA of MACD.

Returns MACD, signal.

func Max

func Max(period int, values []float64) []float64

Moving max for the given period. TODO: Not optimal. Needs to be done with a binary tree and a ring buffer.

func Min

func Min(period int, values []float64) []float64

Moving min for the given period. TODO: Not optimal. Needs to be done with a binary tree and a ring buffer.

func Obv

func Obv(close []float64, volume []int64) []int64

On-Balance Volume (OBV). It is a technical trading momentum indicator that uses volume flow to predict changes in stock price.

volume, if Close > Close-Prev

OBV = OBV-Prev + 0, if Close = Close-Prev

-volume, if Close < Close-Prev

Returns obv

func Rsi

func Rsi(close []float64) ([]float64, []float64)

Relative Strength Index (RSI). It is a momentum indicator that measures the magnitude of recent price changes to evaluate overbought and oversold conditions.

RS = Average Gain / Average Loss RSI = 100 - (100 / (1 + RS))

Returns rs, rsi

func Since

func Since(values []float64) []int

Since last values change.

func Sma

func Sma(period int, values []float64) []float64

Simple Moving Average (SMA).

func Std

func Std(period int, values []float64) []float64

Standard deviation.

func StochasticOscillator

func StochasticOscillator(high, low, close []float64) ([]float64, []float64)

Stochastic Oscillator. It is a momentum indicator that shows the location of the close relative to high-low range over a set number of periods.

K = (Close - Lowest Low) / (Highest High - Lowest Low) * 100 D = 3-Period SMA of K

Returns k, d

func TypicalPrice

func TypicalPrice(low, high, close []float64) ([]float64, []float64)

Typical Price. It is another approximation of average price for each period and can be used as a filter for moving average systems.

Typical Price = (High + Low + Close) / 3

Returns typical price, 20-Period SMA.

func Vortex

func Vortex(high, low, close []float64) ([]float64, []float64)

Vortex Indicator. It provides two oscillators that capture positive and negative trend movement. A bullish signal triggers when the positive trend indicator crosses above the negative trend indicator or a key level. A bearish signal triggers when the negative trend indicator crosses above the positive trend indicator or a key level.

+VM = Abs(Current High - Prior Low) -VM = Abd(Current Low - Prior High)

+VM14 = 14-Period Sum of +VM -VM14 = 14-Period Sum of -VM

TR = Max((High[i]-Low[i]), Abs(High[i]-Close[i-1]), Abs(Low[i]-Close[i-1])) TR14 = 14-Period Sum of TR

+VI14 = +VM14 / TR14 -VI14 = -VM14 / TR14

Based on https://school.stockcharts.com/doku.php?id=technical_indicators:vortex_indicator

Returns plusVi, minusVi

func WilliamsR

func WilliamsR(low, high, close []float64) []float64

Williams R. Determine overbought and oversold.

WR = (Highest High - Close) / (Highest High - Lowest Low) * -100.

Buy when -80 and below. Sell when -20 and above.

Returns wr.

Types

type Action added in v1.2.3

type Action int

Strategy action.

const (
	HOLD Action = iota
	BUY
	SELL
)

func AwesomeOscillatorStrategy added in v1.2.3

func AwesomeOscillatorStrategy(asset Asset) []Action

Awesome oscillator strategy function.

func BollingerBandsStrategy added in v1.2.3

func BollingerBandsStrategy(asset Asset) []Action

Bollinger bands strategy function.

func BuyAndHoldStrategy added in v1.2.3

func BuyAndHoldStrategy(asset Asset) []Action

Buy and hold strategy. Buys at the beginning and holds.

func DefaultRsiStrategy added in v1.2.3

func DefaultRsiStrategy(asset Asset) []Action

Default RSI strategy function. It buys below 30 and sells above 70.

func MacdAndRsiStrategy added in v1.2.3

func MacdAndRsiStrategy(asset Asset) []Action

MACD and RSI strategy.

func MacdStrategy added in v1.2.3

func MacdStrategy(asset Asset) []Action

MACD strategy.

func RsiStrategy added in v1.2.3

func RsiStrategy(asset Asset, sellAt, buyAt float64) []Action

RSI strategy. Sells above sell at, buys below buy at.

func TrendStrategy added in v1.2.3

func TrendStrategy(asset Asset, count int) []Action

Trend strategy. Buy when trending up for count times, sell when trending down for count times.

func WilliamsRStrategy added in v1.2.3

func WilliamsRStrategy(asset Asset) []Action

Williams R strategy function.

type Asset added in v1.2.3

type Asset struct {
	Date   []time.Time
	Open   []float64
	Close  []float64
	High   []float64
	Low    []float64
	Volume []int64
}

Asset values.

type StrategyFunction added in v1.2.3

type StrategyFunction func(Asset) []Action

Strategy function. It takes an Asset and returns actions for each row.

func MakeRsiStrategy added in v1.2.3

func MakeRsiStrategy(sellAt, buyAt float64) StrategyFunction

Make RSI strategy function.

func MakeTrendStrategy added in v1.2.3

func MakeTrendStrategy(count int) StrategyFunction

Make trend strategy function.

type Trend

type Trend int

Trend indicator.

const (
	// Falling trend.
	Falling Trend = iota

	// Rising trend.
	Rising
)

func ParabolicSar

func ParabolicSar(high, low, close []float64) ([]float64, []Trend)

Parabolic SAR. It is a popular technical indicator for identifying the trend and as a trailing stop.

PSAR = PSAR[i - 1] - ((PSAR[i - 1] - EP) * AF)

If the trend is Falling:

  • PSAR is the maximum of PSAR or the previous two high values.
  • If the current high is greather than or equals to PSAR, use EP.

If the trend is Rising:

  • PSAR is the minimum of PSAR or the previous two low values.
  • If the current low is less than or equals to PSAR, use EP.

If PSAR is greater than the closing, trend is falling, and the EP is set to the minimum of EP or the low.

If PSAR is lower than or equals to the closing, trend is rising, and the EP is set to the maximum of EP or the high.

If the trend is the same, and AF is less than 0.20, increment it by 0.02. If the trend is not the same, set AF to 0.02.

Based on video https://www.youtube.com/watch?v=MuEpGBAH7pw&t=0s.

Returns psar, trend

Directories

Path Synopsis
mcp module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL