# README
Techan
TechAn is a technical analysis library for Go! It provides a suite of tools and frameworks to analyze financial data and make trading decisions.
Features
- Basic and advanced technical analysis indicators
- Profit and trade analysis
- Strategy building
Installation
$ go get github.com/sdcoffey/techan
Quickstart
series := techan.NewTimeSeries()
// fetch this from your preferred exchange
dataset := [][]string{
// Timestamp, Open, Close, High, Low, volume
{"1234567", "1", "2", "3", "5", "6"},
}
for _, datum := range dataset {
start, _ := strconv.ParseInt(datum[0], 10, 64)
period := techan.NewTimePeriod(time.Unix(start, 0), time.Hour*24)
candle := techan.NewCandle(period)
candle.OpenPrice = big.NewFromString(datum[1])
candle.ClosePrice = big.NewFromString(datum[2])
candle.MaxPrice = big.NewFromString(datum[3])
candle.MinPrice = big.NewFromString(datum[4])
series.AddCandle(candle)
}
closePrices := techan.NewClosePriceIndicator(series)
movingAverage := techan.NewEMAIndicator(closePrices, 10) // Create an exponential moving average with a window of 10
fmt.Println(movingAverage.Calculate(0).FormattedString(2))
Creating trading strategies
indicator := techan.NewClosePriceIndicator(series)
// record trades on this object
record := techan.NewTradingRecord()
entryConstant := techan.NewConstantIndicator(30)
exitConstant := techan.NewConstantIndicator(10)
// Is satisfied when the price ema moves above 30 and the current position is new
entryRule := techan.And(
techan.NewCrossUpIndicatorRule(entryConstant, indicator),
techan.PositionNewRule{})
// Is satisfied when the price ema moves below 10 and the current position is open
exitRule := techan.And(
techan.NewCrossDownIndicatorRule(indicator, exitConstant),
techan.PositionOpenRule{})
strategy := techan.RuleStrategy{
UnstablePeriod: 10, // Period before which ShouldEnter and ShouldExit will always return false
EntryRule: entryRule,
ExitRule: exitRule,
}
strategy.ShouldEnter(0, record) // returns false
Credits
Techan is heavily influenced by the great ta4j. Many of the ideas and frameworks in this library owe their genesis to the great work done over there.
License
Techan is released under the MIT license. See LICENSE for details.
# Functions
Abs returns the absolute value of the passed-in integer.
And returns a new rule whereby BOTH of the passed-in rules must be satisfied for the rule to be satisfied.
Max returns the larger of the two integers passed in.
Min returns the smaller integer of the two integers passed in.
NewAroonDownIndicator returns a derivative indicator that will return a value based on the number of ticks since the lowest price in the window https://www.investopedia.com/terms/a/aroon.asp
Note: this indicator should be constructed with a either a LowPriceIndicator or a derivative thereof.
NewAroonUpIndicator returns a derivative indicator that will return a value based on the number of ticks since the highest price in the window https://www.investopedia.com/terms/a/aroon.asp
Note: this indicator should be constructed with a either a HighPriceIndicator or a derivative thereof.
NewAverageGainsIndicator Returns a new average gains indicator, which returns the average gains in the given window based on the given indicator.
NewAverageLossesIndicator Returns a new average losses indicator, which returns the average losses in the given window based on the given indicator.
NewAverageTrueRangeIndicator returns a base indicator that calculates the average true range of the underlying over a window https://www.investopedia.com/terms/a/atr.asp.
NewBollingerLowerBandIndicator returns a a derivative indicator which returns the lower bound of a bollinger band on the underlying indicator.
NewBollingerUpperBandIndicator a a derivative indicator which returns the upper bound of a bollinger band on the underlying indicator.
NewCandle returns a new *Candle for a given time period.
NewCCIIndicator Returns a new Commodity Channel Index Indicator http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:commodity_channel_index_cci.
NewClosePriceIndicator returns an Indicator which returns the close price of a candle for a given index.
NewConstantIndicator returns an indicator which always returns the same value for any index.
NewCrossDownIndicatorRule returns a new rule that is satisfied when the upper indicator has crossed below the lower indicator.
NewCrossUpIndicatorRule returns a new rule that is satisfied when the lower indicator has crossed above the upper indicator.
NewCumulativeGainsIndicator returns a derivative indicator which returns all gains made in a base indicator for a given window.
NewCumulativeLossesIndicator returns a derivative indicator which returns all losses in a base indicator for a given window.
NewDifferenceIndicator returns an indicator which returns the difference between one indicator (minuend) and a second indicator (subtrahend).
NewEMAIndicator returns a derivative indicator which returns the average of the current and preceding values in the given windowSize, with values closer to current index given more weight.
NewFastStochasticIndicator returns a derivative Indicator which returns the fast stochastic indicator (%K) for the given window.
NewFixedIndicator returns an indicator with a fixed set of values that are returned when an index is passed in.
NewGainIndicator returns a derivative indicator that returns the gains in the underlying indicator in the last bar, if any.
NewHighPriceIndicator returns an Indicator which returns the high price of a candle for a given index.
NewLossIndicator returns a derivative indicator that returns the losses in the underlying indicator in the last bar, if any.
NewLowPriceIndicator returns an Indicator which returns the low price of a candle for a given index.
NewMACDHistogramIndicator returns a derivative Indicator based on the MACDIndicator, the result of which is the macd indicator minus it's signalLinewindow EMA.
NewMACDIndicator returns a derivative Indicator which returns the difference between two EMAIndicators with long and short windows.
NewMaximumDrawdownIndicator returns a derivative Indicator which returns the maximum drawdown of the underlying indicator over a window.
NewMaximumValueIndicator returns a derivative Indicator which returns the maximum value present in a given window.
NewMeanDeviationIndicator returns a derivative Indicator which returns the mean deviation of a base indicator in a given window.
NewMinimumValueIndicator returns a derivative Indicator which returns the minimum value present in a given window.
NewMMAIndicator returns a derivative indciator which returns the modified moving average of the underlying indictator.
NewOpenPriceIndicator returns an Indicator which returns the open price of a candle for a given index.
NewPercentChangeIndicator returns a derivative indicator which returns the percent change (positive or negative) made in a base indicator up until the given indicator.
NewPercentChangeRule returns a rule whereby the given Indicator must have changed by a given percentage to be satisfied.
NewPosition returns a new Position with the passed-in order as the open order.
NewRelativeStrengthIndexIndicator returns a derivative Indicator which returns the relative strength index of the base indicator in a given time frame.
NewRelativeStrengthIndicator returns a derivative Indicator which returns the relative strength of the base indicator in a given time frame.
NewRelativeVigorIndexIndicator returns an Indicator which returns the index of the relative vigor of the prices of a sercurity.
NewRelativeVigorSignalLine returns an Indicator intended to be used in conjunction with Relative vigor index, which returns the average value of the last 4 indices of the RVI indicator.
NewSimpleMovingAverage returns a derivative Indicator which returns the average of the current value and preceding values in the given windowSize.
NewSlowStochasticIndicator returns a derivative Indicator which returns the slow stochastic indicator (%D) for the given window.
NewStandardDeviationIndicator calculates the standard deviation of a base indicator.
NewStopLossRule returns a new rule that is satisfied when the given loss tolerance (a percentage) is met or exceeded.
NewTimePeriod returns a TimePeriod starting at the given time and ending at the given time plus the given duration.
NewTimeSeries returns a new, empty, TimeSeries.
NewTradingRecord returns a new TradingRecord.
NewTrendlineIndicator returns an indicator whose output is the slope of the trend line given by the values in the window.
NewTrueRangeIndicator returns a base indicator which calculates the true range at the current point in time for a series https://www.investopedia.com/terms/a/atr.asp.
NewTypicalPriceIndicator returns an Indicator which returns the typical price of a candle for a given index.
NewVarianceIndicator provides a way to find the variance in a base indicator, where variances is the sum of squared deviations from the mean at any given index in the time series.
NewVolumeIndicator returns an indicator which returns the volume of a candle for a given index.
NewWindowedStandardDeviationIndicator returns a indicator which calculates the standard deviation of the underlying indicator over a window.
Or returns a new rule whereby ONE OF the passed-in rules must be satisfied for the rule to be satisfied.
Parse takes a string in one of the following formats and returns a new TimePeriod, and optionally, an error
Deprecated: Please use ParseTimePeriod instead.
ParseTimePeriod parses two datetimes as one string and returns it as a TimePeriod.
Pow returns the first integer to the power of the second integer.
# Constants
BUY and SELL enumerations.
BUY and SELL enumerations.
Constants representing basic, human-readable and writable date formats.
Constants representing basic, human-readable and writable date formats.
Constants representing basic, human-readable and writable date formats.
Constants representing basic, human-readable and writable date formats.
# Variables
Constants representing regexes for parsing datetimes.
Constants representing regexes for parsing datetimes.
# Structs
AverageProfitAnalysis returns the average profit for the trading record.
BuyAndHoldAnalysis returns the profit based on a hypothetical where a purchase order was made on the first period available and held until the date on the last trade of the trading record.
Candle represents basic market information for a security over a given time period.
DecreaseRule is satisfied when the given Indicator at the given index is less than the value at the previous index.
DerivativeIndicator returns an indicator that calculates the derivative of the underlying Indicator.
IncreaseRule is satisfied when the given Indicator at the given index is greater than the value at the previous index.
LogTradesAnalysis is a wrapper around an io.Writer, which logs every trade executed to that writer.
Order represents a trade execution (buy or sell) with associated metadata.
OverIndicatorRule is a rule where the First Indicator must be greater than the Second Indicator to be Satisfied.
PercentGainAnalysis analyzes the trading record for the percentage profit gained relative to start.
PeriodProfitAnalysis analyzes the trading record for the average profit based on the time period provided.
Position is a pair of two Order objects.
PositionNewRule is satisfied when the current position in the trading record is new (no open positions).
PositionOpenRule is satisfied when the current position in the trading record is open (position has been entered but not exited).
ProfitableTradesAnalysis analyzes the trading record for the number of profitable trades.
RuleStrategy is a strategy based on rules and an unstable period.
TimePeriod is a simple struct that describes a period of time with a Start and End time.
TimeSeries represents an array of candles.
TotalProfitAnalysis analyzes the trading record for total profit.
TradingRecord is an object describing a series of trades made and a current position.
UnderIndicatorRule is a rule where the First Indicator must be less than the Second Indicator to be Satisfied.
# Interfaces
Analysis is an interface that describes a methodology for taking a TradingRecord as input, and giving back some float value that describes it's performance with respect to that methodology.
Indicator is an interface that describes a methodology by which to analyze a trading record for a specific property or trend.
Rule is an interface describing an algorithm by which a set of criteria may be satisfied.
Strategy is an interface that describes desired entry and exit trading behavior.
# Type aliases
NumTradesAnalysis analyzes the trading record for the number of trades executed.
OrderSide is a simple enumeration representing the side of an Order (buy or sell).