techan: github.com/sdcoffey/techan Index | Files | Directories

package techan

import "github.com/sdcoffey/techan"

Index

Package Files

analysis.go candle.go indicator.go indicator_average.go indicator_basic.go indicator_cci.go indicator_constant.go indicator_derivative.go indicator_difference.go indicator_fixed.go indicator_gains.go indicator_mean_deviation.go indicator_moving_average.go indicator_relative_strength.go indicator_relative_vigor_index.go indicator_standard_deviation.go indicator_variance.go math.go order.go position.go rule.go rule_cross.go rule_increase_decrease.go rule_position.go rule_stop.go strategy.go testutils.go timeperiod.go timeseries.go tradingrecord.go

Constants

const (
    SimpleDateTimeFormat = "01/02/2006T15:04:05"
    SimpleDateFormat     = "01/02/2006"
)

Constants representing basic, human-readable and writable date formats

func Abs Uses

func Abs(b int) int

Abs returns the absolute value of the passed-in integer

func Max Uses

func Max(i, j int) int

Max returns the larger of the two integers passed in

func Min Uses

func Min(i, j int) int

Min returns the smaller integer of the two integers passed in

func Pow Uses

func Pow(i, j int) int

Pow returns the first integer to the power of the second integer

type Analysis Uses

type Analysis interface {
    Analyze(*TradingRecord) float64
}

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.

type AverageProfitAnalysis Uses

type AverageProfitAnalysis struct{}

AverageProfitAnalysis returns the average profit for the trading record. Average profit is represented as the total profit divided by the number of trades executed.

func (AverageProfitAnalysis) Analyze Uses

func (apa AverageProfitAnalysis) Analyze(record *TradingRecord) float64

Analyze returns the average profit of the trading record

type BuyAndHoldAnalysis Uses

type BuyAndHoldAnalysis struct {
    TimeSeries    *TimeSeries
    StartingMoney float64
}

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. It's useful for comparing the performance of your strategy against a simple long position.

func (BuyAndHoldAnalysis) Analyze Uses

func (baha BuyAndHoldAnalysis) Analyze(record *TradingRecord) float64

Analyze returns the profit based on a simple buy and hold strategy

type Candle Uses

type Candle struct {
    Period     TimePeriod
    OpenPrice  big.Decimal `json:",string"`
    ClosePrice big.Decimal `json:",string"`
    MaxPrice   big.Decimal `json:",string"`
    MinPrice   big.Decimal `json:",string"`
    Volume     big.Decimal `json:",string"`
    TradeCount uint
}

Candle represents basic market information for a security over a given time period

func NewCandle Uses

func NewCandle(period TimePeriod) (c *Candle)

NewCandle returns a new *Candle for a given time period

func (*Candle) AddTrade Uses

func (c *Candle) AddTrade(tradeAmount, tradePrice big.Decimal)

AddTrade adds a trade to this candle. It will determine if the current price is higher or lower than the min or max price and increment the tradecount.

func (*Candle) String Uses

func (c *Candle) String() string

type DecreaseRule Uses

type DecreaseRule struct {
    Indicator
}

DecreaseRule is satisfied when the given Indicator at the given index is less than the value at the previous index.

func (DecreaseRule) IsSatisfied Uses

func (dr DecreaseRule) IsSatisfied(index int, record *TradingRecord) bool

IsSatisfied returns true when the given Indicator at the given index is less than the value at the previous index.

type DerivativeIndicator Uses

type DerivativeIndicator struct {
    Indicator Indicator
}

DerivativeIndicator returns an indicator that calculates the derivative of the underlying Indicator. The derivative is defined as the difference between the value at the previous index and the value at the current index. Eg series [1, 1, 2, 3, 5, 8] -> [0, 0, 1, 1, 2, 3]

func (DerivativeIndicator) Calculate Uses

func (di DerivativeIndicator) Calculate(index int) big.Decimal

Calculate returns the derivative of the underlying indicator. At index 0, it will always return 0.

type IncreaseRule Uses

type IncreaseRule struct {
    Indicator
}

IncreaseRule is satisfied when the given Indicator at the given index is greater than the value at the previous index.

func (IncreaseRule) IsSatisfied Uses

func (ir IncreaseRule) IsSatisfied(index int, record *TradingRecord) bool

IsSatisfied returns true when the given Indicator at the given index is greater than the value at the previous index.

type Indicator Uses

type Indicator interface {
    Calculate(int) big.Decimal
}

Indicator is an interface that describes a methodology by which to analyze a trading record for a specific property or trend. For example. MovingAverageIndicator implements the Indicator interface and, for a given index in the timeSeries, returns the current moving average of the prices in that series.

func NewAverageGainsIndicator Uses

func NewAverageGainsIndicator(indicator Indicator, window int) Indicator

NewAverageGainsIndicator Returns a new average gains indicator, which returns the average gains in the given window based on the given indicator.

func NewAverageLossesIndicator Uses

func NewAverageLossesIndicator(indicator Indicator, window int) Indicator

NewAverageLossesIndicator Returns a new average losses indicator, which returns the average losses in the given window based on the given indicator.

func NewCCIIndicator Uses

func NewCCIIndicator(ts *TimeSeries, window int) Indicator

NewCCIIndicator Returns a new Commodity Channel Index Indicator http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:commodity_channel_index_cci

func NewClosePriceIndicator Uses

func NewClosePriceIndicator(series *TimeSeries) Indicator

NewClosePriceIndicator returns an Indicator which returns the close price of a candle for a given index

func NewConstantIndicator Uses

func NewConstantIndicator(constant float64) Indicator

NewConstantIndicator returns an indicator which always returns the same value for any index. It's useful when combined with other, fluxuating indicators to determine when an indicator has crossed a threshold.

func NewCumulativeGainsIndicator Uses

func NewCumulativeGainsIndicator(indicator Indicator, window int) Indicator

NewCumulativeGainsIndicator returns a derivative indicator which returns all gains made in a base indicator for a given window.

func NewCumulativeLossesIndicator Uses

func NewCumulativeLossesIndicator(indicator Indicator, window int) Indicator

NewCumulativeLossesIndicator returns a derivative indicator which returns all losses in a base indicator for a given window.

func NewDifferenceIndicator Uses

func NewDifferenceIndicator(minuend, subtrahend Indicator) Indicator

NewDifferenceIndicator returns an indicator which returns the difference between one indicator (minuend) and a second indicator (subtrahend).

func NewEMAIndicator Uses

func NewEMAIndicator(indicator Indicator, window int) Indicator

NewEMAIndicator returns a derivative indicator which returns the average of the current and preceding values in the given window, with values closer to current index given more weight. A more in-depth explanation can be found here: http://www.investopedia.com/terms/e/ema.asp

func NewFixedIndicator Uses

func NewFixedIndicator(vals ...float64) Indicator

NewFixedIndicator returns an indicator with a fixed set of values that are returned when an index is passed in

func NewHighPriceIndicator Uses

func NewHighPriceIndicator(series *TimeSeries) Indicator

NewHighPriceIndicator returns an Indicator which returns the high price of a candle for a given index

func NewLowPriceIndicator Uses

func NewLowPriceIndicator(series *TimeSeries) Indicator

NewLowPriceIndicator returns an Indicator which returns the low price of a candle for a given index

func NewMACDHistogramIndicator Uses

func NewMACDHistogramIndicator(macdIdicator Indicator, signalLinewindow int) Indicator

NewMACDHistogramIndicator returns a derivative Indicator based on the MACDIndicator, the result of which is the macd indicator minus it's signalLinewindow EMA. A more in-depth explanation can be found here: http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:macd-histogram

func NewMACDIndicator Uses

func NewMACDIndicator(baseIndicator Indicator, shortwindow, longwindow int) Indicator

NewMACDIndicator returns a derivative Indicator which returns the difference between two EMAIndicators with long and short windows. It's useful for gauging the strength of price movements. A more in-depth explanation can be found here: http://www.investopedia.com/terms/m/macd.asp

func NewMeanDeviationIndicator Uses

func NewMeanDeviationIndicator(indicator Indicator, window int) Indicator

NewMeanDeviationIndicator returns a derivative Indicator which returns the mean deviation of a base indicator in a given window. Mean deviation is an average of all values on the base indicator from the mean of that indicator.

func NewOpenPriceIndicator Uses

func NewOpenPriceIndicator(series *TimeSeries) Indicator

NewOpenPriceIndicator returns an Indicator which returns the open price of a candle for a given index

func NewPercentChangeIndicator Uses

func NewPercentChangeIndicator(indicator Indicator) Indicator

NewPercentChangeIndicator returns a derivative indicator which returns the percent change (positive or negative) made in a base indicator up until the given indicator

func NewRelativeStrengthIndexIndicator Uses

func NewRelativeStrengthIndexIndicator(indicator Indicator, timeframe int) Indicator

NewRelativeStrengthIndexIndicator returns a derivative Indicator which returns the relative strength index of the base indicator in a given time frame. A more in-depth explanation of relative strength index can be found here: https://www.investopedia.com/terms/r/rsi.asp

func NewRelativeStrengthIndicator Uses

func NewRelativeStrengthIndicator(indicator Indicator, timeframe int) Indicator

NewRelativeStrengthIndicator returns a derivative Indicator which returns the relative strength of the base indicator in a given time frame. Relative strength is the average again of up periods during the time frame divided by the average loss of down period during the same time frame

func NewRelativeVigorIndexIndicator Uses

func NewRelativeVigorIndexIndicator(series *TimeSeries) Indicator

NewRelativeVigorIndexIndicator returns an Indicator which returns the index of the relative vigor of the prices of a sercurity. Relative Vigor Index is simply the difference of the previous four days' close and open prices divided by the difference between the previous four days high and low prices. A more in-depth explanation of relative vigor index can be found here: https://www.fidelity.com/learning-center/trading-investing/technical-analysis/technical-indicator-guide/relative-vigor-index

func NewRelativeVigorSignalLine Uses

func NewRelativeVigorSignalLine(series *TimeSeries) Indicator

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.

func NewSimpleMovingAverage Uses

func NewSimpleMovingAverage(indicator Indicator, window int) Indicator

NewSimpleMovingAverage returns a derivative Indicator which returns the average of the current value and preceding values in the given window.

func NewTypicalPriceIndicator Uses

func NewTypicalPriceIndicator(series *TimeSeries) Indicator

NewTypicalPriceIndicator returns an Indicator which returns the typical price of a candle for a given index. The typical price is an average of the high, low, and close prices for a given candle.

func NewVolumeIndicator Uses

func NewVolumeIndicator(series *TimeSeries) Indicator

NewVolumeIndicator returns an indicator which returns the volume of a candle for a given index

type LogTradesAnalysis Uses

type LogTradesAnalysis struct {
    io.Writer
}

LogTradesAnalysis is a wrapper around an io.Writer, which logs every trade executed to that writer

func (LogTradesAnalysis) Analyze Uses

func (lta LogTradesAnalysis) Analyze(record *TradingRecord) float64

Analyze logs trades to provided io.Writer

type NumTradesAnalysis Uses

type NumTradesAnalysis string

NumTradesAnalysis analyzes the trading record for the number of trades executed

func (NumTradesAnalysis) Analyze Uses

func (nta NumTradesAnalysis) Analyze(record *TradingRecord) float64

Analyze analyzes the trading record for the number of trades executed

type Order Uses

type Order struct {
    Side          OrderSide
    Security      string
    Price         big.Decimal
    Amount        big.Decimal
    ExecutionTime time.Time
}

Order represents a trade execution (buy or sell) with associated metadata.

type OrderSide Uses

type OrderSide int

OrderSide is a simple enumeration representing the side of an Order (buy or sell)

const (
    BUY OrderSide = iota
    SELL
)

BUY and SELL enumerations

type OverIndicatorRule Uses

type OverIndicatorRule struct {
    First  Indicator
    Second Indicator
}

OverIndicatorRule is a rule where the First Indicator must be greater than the Second Indicator to be Satisfied

func (OverIndicatorRule) IsSatisfied Uses

func (oir OverIndicatorRule) IsSatisfied(index int, record *TradingRecord) bool

IsSatisfied returns true when the First Indicator is greater than the Second Indicator

type PercentGainAnalysis Uses

type PercentGainAnalysis struct{}

PercentGainAnalysis analyzes the trading record for the percentage profit gained relative to start

func (PercentGainAnalysis) Analyze Uses

func (pga PercentGainAnalysis) Analyze(record *TradingRecord) float64

Analyze analyzes the trading record for the percentage profit gained relative to start

type PeriodProfitAnalysis Uses

type PeriodProfitAnalysis struct {
    Period time.Duration
}

PeriodProfitAnalysis analyzes the trading record for the average profit based on the time period provided. i.e., if the trading record spans a year of trading, and PeriodProfitAnalysis wraps one month, Analyze will return the total profit for the whole time period divided by 12.

func (PeriodProfitAnalysis) Analyze Uses

func (ppa PeriodProfitAnalysis) Analyze(record *TradingRecord) float64

Analyze returns the average profit for the trading record based on the given duration

type Position Uses

type Position struct {
    // contains filtered or unexported fields
}

Position is a pair of two Order objects

func NewPosition Uses

func NewPosition(openOrder Order) (t *Position)

NewPosition returns a new Position with the passed-in order as the open order

func (*Position) CostBasis Uses

func (p *Position) CostBasis() big.Decimal

CostBasis returns the price to enter this order

func (*Position) Enter Uses

func (p *Position) Enter(order Order)

Enter sets the open order to the order passed in

func (*Position) EntranceOrder Uses

func (p *Position) EntranceOrder() *Order

EntranceOrder returns the entrance order of this position

func (*Position) Exit Uses

func (p *Position) Exit(order Order)

Exit sets the exit order to the order passed in

func (*Position) ExitOrder Uses

func (p *Position) ExitOrder() *Order

ExitOrder returns the exit order of this position

func (*Position) ExitValue Uses

func (p *Position) ExitValue() big.Decimal

ExitValue returns the value accrued by closing the position

func (*Position) IsClosed Uses

func (p *Position) IsClosed() bool

IsClosed returns true of there are both entrance and exit orders

func (*Position) IsLong Uses

func (p *Position) IsLong() bool

IsLong returns true if the entrance order is a buy order

func (*Position) IsNew Uses

func (p *Position) IsNew() bool

IsNew returns true if there is neither an entrance or exit order

func (*Position) IsOpen Uses

func (p *Position) IsOpen() bool

IsOpen returns true if there is an entrance order but no exit order

func (*Position) IsShort Uses

func (p *Position) IsShort() bool

IsShort returns true if the entrance order is a sell order

type PositionNewRule Uses

type PositionNewRule struct{}

PositionNewRule is satisfied when the current position in the trading record is new (no open positions).

func (PositionNewRule) IsSatisfied Uses

func (pnr PositionNewRule) IsSatisfied(index int, record *TradingRecord) bool

IsSatisfied returns true if the current position in the record is new

type PositionOpenRule Uses

type PositionOpenRule struct{}

PositionOpenRule is satisfied when the current position in the trading record is open (position has been entered but not exited).

func (PositionOpenRule) IsSatisfied Uses

func (pnr PositionOpenRule) IsSatisfied(index int, record *TradingRecord) bool

IsSatisfied returns true if the current position in the record is Open

type ProfitableTradesAnalysis Uses

type ProfitableTradesAnalysis struct{}

ProfitableTradesAnalysis analyzes the trading record for the number of profitable trades

func (ProfitableTradesAnalysis) Analyze Uses

func (pta ProfitableTradesAnalysis) Analyze(record *TradingRecord) float64

Analyze returns the number of profitable trades in a trading record

type Rule Uses

type Rule interface {
    IsSatisfied(index int, record *TradingRecord) bool
}

Rule is an interface describing an algorithm by which a set of criteria may be satisfied

func And Uses

func And(r1, r2 Rule) Rule

And returns a new rule whereby BOTH of the passed-in rules must be satisfied for the rule to be satisfied

func NewCrossDownIndicatorRule Uses

func NewCrossDownIndicatorRule(upper, lower Indicator) Rule

NewCrossDownIndicatorRule returns a new rule that is satisfied when the upper indicator has crossed below the lower indicator.

func NewCrossUpIndicatorRule Uses

func NewCrossUpIndicatorRule(upper, lower Indicator) Rule

NewCrossUpIndicatorRule returns a new rule that is satisfied when the lower indicator has crossed above the upper indicator.

func NewPercentChangeRule Uses

func NewPercentChangeRule(indicator Indicator, percent float64) Rule

NewPercentChangeRule returns a rule whereby the given Indicator must have changed by a given percentage to be satisfied. You should specify percent as a float value between -1 and 1

func NewStopLossRule Uses

func NewStopLossRule(series *TimeSeries, lossTolerance float64) Rule

NewStopLossRule returns a new rule that is satisfied when the given loss tolerance (a percentage) is met or exceeded. Loss tolerance should be a value between -1 and 1.

func Or Uses

func Or(r1, r2 Rule) Rule

Or returns a new rule whereby ONE OF the passed-in rules must be satisfied for the rule to be satisfied

type RuleStrategy Uses

type RuleStrategy struct {
    EntryRule      Rule
    ExitRule       Rule
    UnstablePeriod int
}

RuleStrategy is a strategy based on rules and an unstable period. The two rules determine whether a position should be created or closed, and the unstable period is an index before no positions should be created or exited

func (RuleStrategy) ShouldEnter Uses

func (rs RuleStrategy) ShouldEnter(index int, record *TradingRecord) bool

ShouldEnter will return true when the index is less than the unstable period and the entry rule is satisfied

func (RuleStrategy) ShouldExit Uses

func (rs RuleStrategy) ShouldExit(index int, record *TradingRecord) bool

ShouldExit will return true when the index is less than the unstable period and the exit rule is satisfied

type StandardDeviationIndicator Uses

type StandardDeviationIndicator struct {
    Indicator Indicator
}

StandardDeviationIndicator calculates the standard deviation of a base indicator. See https://www.investopedia.com/terms/s/standarddeviation.asp

func (StandardDeviationIndicator) Calculate Uses

func (sdi StandardDeviationIndicator) Calculate(index int) big.Decimal

Calculate returns the standard deviation of a base indicator

type Strategy Uses

type Strategy interface {
    ShouldEnter(index int, record *TradingRecord) bool
    ShouldExit(index int, record *TradingRecord) bool
}

Strategy is an interface that describes desired entry and exit trading behavior

type TimePeriod Uses

type TimePeriod struct {
    Start time.Time
    End   time.Time
}

TimePeriod is a simple struct that describes a period of time with a Start and End time

func NewTimePeriod Uses

func NewTimePeriod(start time.Time, period time.Duration) TimePeriod

NewTimePeriod returns a TimePeriod starting at the given time and ending at the given time plus the given duration

func Parse Uses

func Parse(timerange string) (tr TimePeriod, err error)

Parse takes a string in one of the following formats and returns a new TimePeriod, and optionally, an error

Supported Formats: SimpleDateTimeFormat:SimpleDateTimeFormat SimpleDateTimeFormat: (to now) SimpleDateFormat: SimpleDateFormat:SimpleDateFormat

func (TimePeriod) Advance Uses

func (tp TimePeriod) Advance(iterations int) TimePeriod

Advance will return a new TimePeriod with the start and end periods moved forwards or backwards in time in accordance with the number of iterations given.

Example: A timePeriod that is one hour long, starting at unix time 0 and ending at unix time 3600, and advanced by one, will return a time period starting at unix time 3600 and ending at unix time 7200

func (TimePeriod) Format Uses

func (tp TimePeriod) Format(layout string) string

Format returns the string representation of this timePeriod in the given format

func (TimePeriod) Length Uses

func (tp TimePeriod) Length() time.Duration

Length returns the length of the period as a time.Duration value

func (TimePeriod) Since Uses

func (tp TimePeriod) Since(other TimePeriod) time.Duration

Since returns the amount of time elapsed since the end of another TimePeriod as a time.Duration value

func (TimePeriod) String Uses

func (tp TimePeriod) String() string

type TimeSeries Uses

type TimeSeries struct {
    Candles []*Candle
}

TimeSeries represents an array of candles

func NewTimeSeries Uses

func NewTimeSeries() (t *TimeSeries)

NewTimeSeries returns a new, empty, TimeSeries

func (*TimeSeries) AddCandle Uses

func (ts *TimeSeries) AddCandle(candle *Candle) bool

AddCandle adds the given candle to this TimeSeries if it is not nil and after the last candle in this timeseries. If the candle is added, AddCandle will return true, otherwise it will return false.

func (*TimeSeries) LastCandle Uses

func (ts *TimeSeries) LastCandle() *Candle

LastCandle will return the lastCandle in this series, or nil if this series is empty

func (*TimeSeries) LastIndex Uses

func (ts *TimeSeries) LastIndex() int

LastIndex will return the index of the last candle in this series

type TotalProfitAnalysis Uses

type TotalProfitAnalysis struct{}

TotalProfitAnalysis analyzes the trading record for total profit.

func (TotalProfitAnalysis) Analyze Uses

func (tps TotalProfitAnalysis) Analyze(record *TradingRecord) float64

Analyze analyzes the trading record for total profit.

type TradingRecord Uses

type TradingRecord struct {
    Trades []*Position
    // contains filtered or unexported fields
}

TradingRecord is an object describing a series of trades made and a current position

func NewTradingRecord Uses

func NewTradingRecord() (t *TradingRecord)

NewTradingRecord returns a new TradingRecord

func (*TradingRecord) CurrentPosition Uses

func (tr *TradingRecord) CurrentPosition() *Position

CurrentPosition returns the current position in this record

func (*TradingRecord) LastTrade Uses

func (tr *TradingRecord) LastTrade() *Position

LastTrade returns the last trade executed in this record

func (*TradingRecord) Operate Uses

func (tr *TradingRecord) Operate(order Order)

Operate takes an order and adds it to the current TradingRecord. It will only add the order if: - The current position is open and the passed order was executed after the entrance order - The current position is new and the passed order was executed after the last exit order

type UnderIndicatorRule Uses

type UnderIndicatorRule struct {
    First  Indicator
    Second Indicator
}

UnderIndicatorRule is a rule where the First Indicator must be less than the Second Indicator to be Satisfied

func (UnderIndicatorRule) IsSatisfied Uses

func (uir UnderIndicatorRule) IsSatisfied(index int, record *TradingRecord) bool

IsSatisfied returns true when the First Indicator is less than the Second Indicator

type VarianceIndicator Uses

type VarianceIndicator struct {
    Indicator Indicator
}

VarianceIndicator 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.

func (VarianceIndicator) Calculate Uses

func (vi VarianceIndicator) Calculate(index int) big.Decimal

Calculate returns the Variance for this indicator at the given index

Directories

PathSynopsis
example

Package techan imports 9 packages (graph) and is imported by 1 packages. Updated 2018-04-16. Refresh now. Tools for package owners.