indicator

package module
v0.0.0-...-5f731eb Latest Latest
Warning

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

Go to latest
Published: Feb 16, 2023 License: MIT Imports: 5 Imported by: 0

README

GoDoc License Build Status Go Report Card codecov CodeQL Analysis

Indicator Go

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

I also have a TypeScript version of this module now at Indicator TS.

Indicators Provided

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

Trend Indicators
Momentum Indicators
Volatility Indicators
Volume Indicators

Strategies Provided

Strategies relies on the following:

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

Trend Strategies
Momentum Strategies
Volatility Strategies
Volume Strategies
Compound Strategies

Backtest

Backtesting is the method for seeing how well a strategy would have done. The following backtesting functions are provided for evaluating strategies.

Usage

Install package.

go get github.com/cinar/indicator

Import indicator.

import (
    "github.com/cinar/indicator"
)

Disclaimer

The information provided on this project is strictly for informational purposes and is not to be construed as advice or solicitation to buy or sell any security.

License

Copyright (c) 2021 Onur Cinar. All Rights Reserved.

The source code is provided under MIT License.

Documentation

Index

Constants

View Source
const CMF_DEFAULT_PERIOD = 20

Default period of CMF.

View Source
const NVI_STARTING_VALUE = 1000

Starting value for NVI.

Variables

This section is empty.

Functions

func AbsolutePriceOscillator

func AbsolutePriceOscillator(fastPeriod, slowPeriod int, values []float64) []float64

The AbsolutePriceOscillator function calculates a technical indicator that is used to follow trends. APO crossing above zero indicates bullish, while crossing below zero indicates bearish. Positive value is upward trend, while negative value is downward trend.

Fast = Ema(fastPeriod, values) Slow = Ema(slowPeriod, values) APO = Fast - Slow

Returns apo.

func AccelerationBands

func AccelerationBands(high, low, closing []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(Closing) Lower Band = SMA(Low * (1 - 4 * (High - Low) / (High + Low)))

Returns upper band, middle band, lower band.

func AccumulationDistribution

func AccumulationDistribution(high, low, closing []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 = ((Closing - Low) - (High - Closing)) / (High - Low) MFV = MFM * Period Volume AD = Previous AD + CMFV

Returns ad.

func ApplyActions

func ApplyActions(prices []float64, actions []Action) []float64

The ApplyActions takes the given list of prices, applies the given list of normalized actions, and returns the gains.

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, closing []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 - Closing), (Closing - 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 BalanceOfPower

func BalanceOfPower(opening, high, low, closing []float64) []float64

The BalanceOfPower function calculates the strength of buying and selling pressure. Positive value indicates an upward trend, and negative value indicates a downward trend. Zero indicates a balance between the two.

BOP = (Closing - Opening) / (High - Low)

Returns bop.

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(closing []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 ChaikinMoneyFlow

func ChaikinMoneyFlow(high, low, closing []float64, volume []int64) []float64

The Chaikin Money Flow (CMF) measures the amount of money flow volume over a given period.

Money Flow Multiplier = ((Closing - Low) - (High - Closing)) / (High - Low) Money Flow Volume = Money Flow Multiplier * Volume Chaikin Money Flow = Sum(20, Money Flow Volume) / Sum(20, Volume)

func ChaikinOscillator

func ChaikinOscillator(fastPeriod, slowPeriod int, low, high, closing []float64, volume []int64) ([]float64, []float64)

The ChaikinOscillator function measures the momentum of the Accumulation/Distribution (A/D) using the Moving Average Convergence Divergence (MACD) formula. It takes the difference between fast and slow periods EMA of the A/D. Cross above the A/D line indicates bullish.

CO = Ema(fastPeriod, AD) - Ema(slowPeriod, AD)

Returns co, ad.

func ChandeForecastOscillator

func ChandeForecastOscillator(closing []float64) []float64

The Chande Forecast Oscillator developed by Tushar Chande The Forecast Oscillator plots the percentage difference between the closing price and the n-period linear regression forecasted price. The oscillator is above zero when the forecast price is greater than the closing price and less than zero if it is below.

R = Linreg(Closing) CFO = ((Closing - R) / Closing) * 100

Returns cfo.

func ChandelierExit

func ChandelierExit(high, low, closing []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 CommunityChannelIndex

func CommunityChannelIndex(period int, high, low, closing []float64) []float64

The Community Channel Index (CMI) is a momentum-based oscillator used to help determine when an investment vehicle is reaching a condition of being overbought or oversold.

Moving Average = Sma(Period, Typical Price) Mean Deviation = Sma(Period, Abs(Typical Price - Moving Average)) CMI = (Typical Price - Moving Average) / (0.015 * Mean Deviation)

Returns cmi.

func CountTransactions

func CountTransactions(actions []Action) int

The CountTransactions takes a list of normalized actions, and counts the BUY and SELL actions.

func DefaultAbsolutePriceOscillator

func DefaultAbsolutePriceOscillator(values []float64) []float64

The DefaultAbsolutePriceOscillator function calculates APO with the most frequently used fast and short periods are 14 and 30.

Returns apo.

func DefaultChaikinOscillator

func DefaultChaikinOscillator(low, high, closing []float64, volume []int64) ([]float64, []float64)

The DefaultChaikinOscillator function calculates Chaikin Oscillator with the most frequently used fast and short periods, 3 and 10.

Returns co, ad.

func DefaultCommunityChannelIndex

func DefaultCommunityChannelIndex(high, low, closing []float64) []float64

The default community channel index with the period of 20.

func DefaultEaseOfMovement

func DefaultEaseOfMovement(high, low []float64, volume []int64) []float64

The default Ease of Movement with the default period of 14.

func DefaultForceIndex

func DefaultForceIndex(closing []float64, volume []int64) []float64

The default Force Index (FI) with window size of 13.

func DefaultKdj

func DefaultKdj(high, low, closing []float64) ([]float64, []float64, []float64)

The DefaultKdj function calculates KDJ based on default periods consisting of rPeriod of 9, kPeriod of 3, and dPeriod of 3.

Returns k, d, j.

func DefaultKeltnerChannel

func DefaultKeltnerChannel(high, low, closing []float64) ([]float64, []float64, []float64)

The default keltner channel with the default period of 20.

func DefaultMoneyFlowIndex

func DefaultMoneyFlowIndex(high, low, closing []float64, volume []int64) []float64

Default money flow index with period 14.

func DefaultPercentagePriceOscillator

func DefaultPercentagePriceOscillator(price []float64) ([]float64, []float64, []float64)

Default Percentage Price Oscillator calculates it with the default periods of 12, 26, 9.

Returns ppo, signal, histogram

func DefaultPercentageVolumeOscillator

func DefaultPercentageVolumeOscillator(volume []int64) ([]float64, []float64, []float64)

Default Percentage Volume Oscillator calculates it with the default periods of 12, 26, 9.

Returns pvo, signal, histogram

func DefaultUlcerIndex

func DefaultUlcerIndex(closing []float64) []float64

The default ulcer index with the default period of 14.

func DefaultVolumeWeightedAveragePrice

func DefaultVolumeWeightedAveragePrice(closing []float64, volume []int64) []float64

Default volume weighted average price with period of 14.

func DefaultVwma

func DefaultVwma(closing []float64, volume []int64) []float64

The DefaultVwma function calculates VWMA with a period of 20.

func Dema

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

Dema calculates the Double Exponential Moving Average (DEMA).

DEMA = (2 * EMA(values)) - EMA(EMA(values))

Returns dema.

func DonchianChannel

func DonchianChannel(period int, closing []float64) ([]float64, []float64, []float64)

The Donchian Channel (DC) calculates three lines generated by moving average calculations that comprise an indicator formed by upper and lower bands around a midrange or median band. The upper band marks the highest price of an asset while the lower band marks the lowest price of an asset, and the area between the upper and lower bands represents the Donchian Channel.

Upper Channel = Mmax(period, closings) Lower Channel = Mmin(period, closings) Middle Channel = (Upper Channel + Lower Channel) / 2

Returns upperChannel, middleChannel, lowerChannel.

func EaseOfMovement

func EaseOfMovement(period int, high, low []float64, volume []int64) []float64

The Ease of Movement (EMV) is a volume based oscillator measuring the ease of price movement.

Distance Moved = ((High + Low) / 2) - ((Priod High + Prior Low) /2) Box Ratio = ((Volume / 100000000) / (High - Low)) EMV(1) = Distance Moved / Box Ratio EMV(14) = SMA(14, EMV(1))

Returns ease of movement values.

func Ema

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

Exponential Moving Average (EMA).

func ForceIndex

func ForceIndex(period int, closing []float64, volume []int64) []float64

The Force Index (FI) uses the closing price and the volume to assess the power behind a move and identify turning points.

Force Index = EMA(period, (Current - Previous) * Volume)

Returns force index.

func IchimokuCloud

func IchimokuCloud(high, low, closing []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) = Closing plotted 26 days in the past.

Returns conversionLine, baseLine, leadingSpanA, leadingSpanB, laggingSpan

func Kdj

func Kdj(rPeriod, kPeriod, dPeriod int, high, low, closing []float64) ([]float64, []float64, []float64)

The Kdj function calculates the KDJ indicator, also known as the Random Index. KDJ is calculated similar to the Stochastic Oscillator with the difference of having the J line. It is used to analyze the trend and entry points.

The K and D lines show if the asset is overbought when they crosses above 80%, and oversold when they crosses below 20%. The J line represents the divergence.

RSV = ((Closing - Min(Low, rPeriod))

/ (Max(High, rPeriod) - Min(Low, rPeriod))) * 100

K = Sma(RSV, kPeriod) D = Sma(K, dPeriod) J = (3 * K) - (2 * D)

Returns k, d, j.

func KeltnerChannel

func KeltnerChannel(period int, high, low, closing []float64) ([]float64, []float64, []float64)

The Keltner Channel (KC) provides volatility-based bands that are placed on either side of an asset's price and can aid in determining the direction of a trend.

Middle Line = EMA(period, closings) Upper Band = EMA(period, closings) + 2 * ATR(period, highs, lows, closings) Lower Band = EMA(period, closings) - 2 * ATR(period, highs, lows, closings)

Returns upperBand, middleLine, lowerBand.

func LeastSquare

func LeastSquare(x, y []float64) (float64, float64)

Least square.

y = mx + b b = y-intercept y = slope

m = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX) b = (sumY - m * sumX) / n

func LinearRegressionUsingLeastSquare

func LinearRegressionUsingLeastSquare(x, y []float64) []float64

Linear regression using least square method.

y = mx + b

func Macd

func Macd(closing []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 MassIndex

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

The Mass Index (MI) uses the high-low range to identify trend reversals based on range expansions.

Singe EMA = EMA(9, Highs - Lows) Double EMA = EMA(9, Single EMA) Ratio = Single EMA / Double EMA MI = Sum(25, Ratio)

Returns mi.

func Max

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

Moving max for the given period.

func Min

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

Moving min for the given period.

func MoneyFlowIndex

func MoneyFlowIndex(period int, high, low, closing []float64, volume []int64) []float64

The Money Flow Index (MFI) analyzes both the closing price and the volume to measure to identify overbought and oversold states. It is similar to the Relative Strength Index (RSI), but it also uses the volume.

Raw Money Flow = Typical Price * Volume Money Ratio = Positive Money Flow / Negative Money Flow Money Flow Index = 100 - (100 / (1 + Money Ratio))

Retruns money flow index values.

func MovingChandeForecastOscillator

func MovingChandeForecastOscillator(period int, closing []float64) []float64

Moving Chande Forecast Oscillator calculates based on the given period.

The Chande Forecast Oscillator developed by Tushar Chande The Forecast Oscillator plots the percentage difference between the closing price and the n-period linear regression forecasted price. The oscillator is above zero when the forecast price is greater than the closing price and less than zero if it is below.

R = Linreg(Closing) CFO = ((Closing - R) / Closing) * 100

Returns cfo.

func MovingLeastSquare

func MovingLeastSquare(period int, x, y []float64) ([]float64, []float64)

Moving least square over a period.

y = mx + b b = y-intercept y = slope

m = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX) b = (sumY - m * sumX) / n

func MovingLinearRegressionUsingLeastSquare

func MovingLinearRegressionUsingLeastSquare(period int, x, y []float64) []float64

Moving linear regression using least square.

y = mx + b

func NegativeVolumeIndex

func NegativeVolumeIndex(closing []float64, volume []int64) []float64

The Negative Volume Index (NVI) is a cumulative indicator using the change in volume to decide when the smart money is active.

If Volume is greather than Previous Volume:

NVI = Previous NVI

Otherwise:

NVI = Previous NVI + (((Closing - Previous Closing) / Previous Closing) * Previous NVI)

Returns nvi values.

func NormalizeGains

func NormalizeGains(prices, gains []float64) []float64

The NormalizeGains takes the given list of prices, calculates the price gains, subtracts it from the given list of gains.

func Obv

func Obv(closing []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 Closing > Closing-Prev

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

-volume, if Closing < Closing-Prev

Returns obv

func PercentagePriceOscillator

func PercentagePriceOscillator(fastPeriod, slowPeriod, signalPeriod int, price []float64) ([]float64, []float64, []float64)

Percentage Price Oscillator (PPO). It is a momentum oscillator for the price. It is used to indicate the ups and downs based on the price. A breakout is confirmed when PPO is positive.

PPO = ((EMA(fastPeriod, prices) - EMA(slowPeriod, prices)) / EMA(longPeriod, prices)) * 100 Signal = EMA(9, PPO) Histogram = PPO - Signal

Returns ppo, signal, histogram

func PercentageVolumeOscillator

func PercentageVolumeOscillator(fastPeriod, slowPeriod, signalPeriod int, volume []int64) ([]float64, []float64, []float64)

Percentage Volume Oscillator (PVO). It is a momentum oscillator for the volume. It is used to indicate the ups and downs based on the volume. A breakout is confirmed when PVO is positive.

PVO = ((EMA(fastPeriod, volumes) - EMA(slowPeriod, volumes)) / EMA(longPeriod, volumes)) * 100 Signal = EMA(9, PVO) Histogram = PVO - Signal

Returns pvo, signal, histogram

func ProjectionOscillator

func ProjectionOscillator(period, smooth int, high, low, closing []float64) ([]float64, []float64)

ProjectionOscillator calculates the Projection Oscillator (PO). The PO uses the linear regression slope, along with highs and lows.

Period defines the moving window to calculates the PO, and the smooth period defines the moving windows to take EMA of PO.

PL = Min(period, (high + MLS(period, x, high))) PU = Max(period, (low + MLS(period, x, low))) PO = 100 * (Closing - PL) / (PU - PL) SPO = EMA(smooth, PO)

Returns po, spo.

func Qstick

func Qstick(period int, opening, closing []float64) []float64

The Qstick function calculates the ratio of recent up and down bars.

QS = Sma(Closing - Opening)

Returns qs.

func Rma

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

Rolling Moving Average (RMA).

R[0] to R[p-1] is SMA(values) R[p] and after is R[i] = ((R[i-1]*(p-1)) + v[i]) / p

Returns r.

func Rsi

func Rsi(closing []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 Rsi2

func Rsi2(closing []float64) ([]float64, []float64)

RSI with 2 period, a mean-reversion trading strategy developed by Larry Connors.

REturns rs, rsi

func RsiPeriod

func RsiPeriod(period int, closing []float64) ([]float64, []float64)

RsiPeriod allows to calculate the RSI indicator with a non-standard period.

func RunStrategies

func RunStrategies(asset *Asset, strategies ...StrategyFunction) [][]Action

The RunStrategies takes one or more StrategyFunction and returns the acitions for each.

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 StdFromSma

func StdFromSma(period int, values, sma []float64) []float64

Standard deviation from the given SMA.

func StochasticOscillator

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

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

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

Returns k, d

func Sum

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

Moving sum for the given period.

func Tema

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

Tema calculates the Triple Exponential Moving Average (TEMA).

TEMA = (3 * EMA1) - (3 * EMA2) + EMA3 EMA1 = EMA(values) EMA2 = EMA(EMA1) EMA3 = EMA(EMA2)

Returns tema.

func Trima

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

Trima function calculates the Triangular Moving Average (TRIMA).

If period is even:

TRIMA = SMA(period / 2, SMA((period / 2) + 1, values))

If period is odd:

TRIMA = SMA((period + 1) / 2, SMA((period + 1) / 2, values))

Returns trima.

func Trix

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

Triple Exponential Average (TRIX) indicator is an oscillator used to identify oversold and overbought markets, and it can also be used as a momentum indicator. Like many oscillators, TRIX oscillates around a zero line.

EMA1 = EMA(period, values) EMA2 = EMA(period, EMA1) EMA3 = EMA(period, EMA2) TRIX = (EMA3 - Previous EMA3) / Previous EMA3

Returns trix.

func TypicalPrice

func TypicalPrice(low, high, closing []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 + Closing) / 3

Returns typical price, 20-Period SMA.

func UlcerIndex

func UlcerIndex(period int, closing []float64) []float64

The Ulcer Index (UI) measures downside risk. The index increases in value as the price moves farther away from a recent high and falls as the price rises to new highs.

High Closings = Max(period, Closings) Percentage Drawdown = 100 * ((Closings - High Closings) / High Closings) Squared Average = Sma(period, Percent Drawdown * Percent Drawdown) Ulcer Index = Sqrt(Squared Average)

Returns ui.

func VolumePriceTrend

func VolumePriceTrend(closing []float64, volume []int64) []float64

The Volume Price Trend (VPT) provides a correlation between the volume and the price.

VPT = Previous VPT + (Volume * (Current Closing - Previous Closing) / Previous Closing)

Returns volume price trend values.

func VolumeWeightedAveragePrice

func VolumeWeightedAveragePrice(period int, closing []float64, volume []int64) []float64

The Volume Weighted Average Price (VWAP) provides the average price the asset has traded.

VWAP = Sum(Closing * Volume) / Sum(Volume)

Returns vwap values.

func Vortex

func Vortex(high, low, closing []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]-Closing[i-1]), Abs(Low[i]-Closing[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 Vwma

func Vwma(period int, closing []float64, volume []int64) []float64

The Vwma function calculates the Volume Weighted Moving Average (VWMA) averaging the price data with an emphasis on volume, meaning areas with higher volume will have a greater weight.

VWMA = Sum(Price * Volume) / Sum(Volume) for a given Period.

Returns vwma

func WilliamsR

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

Williams R. Determine overbought and oversold.

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

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

Returns wr.

Types

type Action

type Action int

Strategy action.

const (
	SELL Action = -1
	HOLD Action = 0
	BUY  Action = 1
)

func AwesomeOscillatorStrategy

func AwesomeOscillatorStrategy(asset *Asset) []Action

Awesome oscillator strategy function.

func BollingerBandsStrategy

func BollingerBandsStrategy(asset *Asset) []Action

Bollinger bands strategy function.

func BuyAndHoldStrategy

func BuyAndHoldStrategy(asset *Asset) []Action

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

func ChaikinMoneyFlowStrategy

func ChaikinMoneyFlowStrategy(asset *Asset) []Action

Chaikin money flow strategy.

func ChandeForecastOscillatorStrategy

func ChandeForecastOscillatorStrategy(asset *Asset) []Action

Chande forecast oscillator strategy.

func DefaultKdjStrategy

func DefaultKdjStrategy(asset *Asset) []Action

Default KDJ strategy function.

func DefaultRsiStrategy

func DefaultRsiStrategy(asset *Asset) []Action

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

func DefaultVwmaStrategy

func DefaultVwmaStrategy(asset *Asset) []Action

Default VWMA strategy function.

func EaseOfMovementStrategy

func EaseOfMovementStrategy(asset *Asset) []Action

Ease of movement strategy.

func ForceIndexStrategy

func ForceIndexStrategy(asset *Asset) []Action

Force index strategy function.

func KdjStrategy

func KdjStrategy(rPeriod, kPeriod, dPeriod int, asset *Asset) []Action

The KdjStrategy function uses the k, d, j values that are generated by the Kdj indicator function to provide a BUY action when k crosses above d and j. It is stronger when below 20%. Also the SELL action is when k crosses below d and j. It is strong when above 80%.

Returns actions.

func MacdAndRsiStrategy

func MacdAndRsiStrategy(asset *Asset) []Action

MACD and RSI strategy.

func MacdStrategy

func MacdStrategy(asset *Asset) []Action

MACD strategy.

func MoneyFlowIndexStrategy

func MoneyFlowIndexStrategy(asset *Asset) []Action

Money flow index strategy.

func MovingChandeForecastOscillatorStrategy

func MovingChandeForecastOscillatorStrategy(period int, asset *Asset) []Action

Moving chande forecast oscillator strategy function.

func NegativeVolumeIndexStrategy

func NegativeVolumeIndexStrategy(asset *Asset) []Action

Negative volume index strategy.

func NormalizeActions

func NormalizeActions(actions []Action) []Action

The NormalizeActions takes a list of independenc actions, such as SELL, SELL, BUY, SELL, HOLD, SELL, and produces a normalized list where the actions are following the proper BUY, HOLD, SELL, HOLD order.

func ProjectionOscillatorStrategy

func ProjectionOscillatorStrategy(period, smooth int, asset *Asset) []Action

Projection oscillator strategy function.

func Rsi2Strategy

func Rsi2Strategy(asset *Asset) []Action

RSI 2 strategy. When 2-period RSI moves below 10, it is considered deeply oversold, and the other way around when moves above 90.

func RsiStrategy

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

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

func TrendStrategy

func TrendStrategy(asset *Asset, count uint) []Action

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

func VolumeWeightedAveragePriceStrategy

func VolumeWeightedAveragePriceStrategy(asset *Asset) []Action

Volume weighted average price strategy function.

func VwmaStrategy

func VwmaStrategy(asset *Asset, period int) []Action

The VwmaStrategy function uses SMA and VWMA indicators to provide a BUY action when VWMA is above SMA, and a SELL signal when VWMA is below SMA, a HOLD signal otherwse.

Returns actions

func WilliamsRStrategy

func WilliamsRStrategy(asset *Asset) []Action

Williams R strategy function.

type Asset

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

Asset values.

type StockRsi

type StockRsi struct {
	RsiPeriod   int
	StockPeriod int
	KPeriod     int
	DPeriod     int
}

func (*StockRsi) StochasticOscillatorRSI

func (params *StockRsi) StochasticOscillatorRSI(slice []float64) ([]float64, []float64)

Stochastic Oscillator RSI

type StrategyFunction

type StrategyFunction func(*Asset) []Action

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

func AllStrategies

func AllStrategies(strategies ...StrategyFunction) StrategyFunction

The AllStrategies function takes one or more StrategyFunction and provides a StrategyFunction that will return a BUY or SELL action if all strategies are returning the same action, otherwise it will return a HOLD action.

func MakeKdjStrategy

func MakeKdjStrategy(rPeriod, kPeriod, dPeriod int) StrategyFunction

Make KDJ strategy function.

func MakeMovingChandeForecastOscillatorStrategy

func MakeMovingChandeForecastOscillatorStrategy(period int) StrategyFunction

Make moving chande forecast oscillator strategy.

func MakeProjectionOscillatorStrategy

func MakeProjectionOscillatorStrategy(period, smooth int) StrategyFunction

Make projection oscillator strategy.

func MakeRsiStrategy

func MakeRsiStrategy(sellAt, buyAt float64) StrategyFunction

Make RSI strategy function.

func MakeTrendStrategy

func MakeTrendStrategy(count uint) StrategyFunction

Make trend strategy function.

func MakeVwmaStrategy

func MakeVwmaStrategy(period int) StrategyFunction

Makes a VWMA strategy for the given period.

func SeparateStategies

func SeparateStategies(buyStrategy, sellStrategy StrategyFunction) StrategyFunction

The SeparateStrategies function takes a buy strategy and a sell strategy.

It returns a BUY action if the buy strategy returns a BUY action and the the sell strategy returns a HOLD action.

It returns a SELL action if the sell strategy returns a SELL action and the buy strategy returns a HOLD action.

It returns HOLD otherwise.

type Trend

type Trend int

Trend indicator.

const (
	Falling Trend = -1
	Rising  Trend = 1
)

func ParabolicSar

func ParabolicSar(high, low, closing []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
bst

Jump to

Keyboard shortcuts

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