backtest

package
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2017 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package backtest provides a simple stock backtesting framework.

Index

Constants

View Source
const DP = 4 // DP

DP sets the the precision of rounded floating numbers used after calculations to format

Variables

This section is empty.

Functions

func CalculateSMA added in v0.2.1

func CalculateSMA(i int, data []DataEventHandler) (sma float64, err error)

CalculateSMA calculates the simple moving average of a given slice of data points.

Types

type Bar

type Bar struct {
	Event
	DataEvent
	Open     float64
	High     float64
	Low      float64
	Close    float64
	AdjClose float64
	Volume   int64
}

Bar declares an event for an OHLCV bar (Open, High, Low, Close, Volume).

func (Bar) IsBar

func (b Bar) IsBar() bool

IsBar declares a Bar event

func (Bar) LatestPrice

func (b Bar) LatestPrice() float64

LatestPrice returns the close proce of the bar event.

type BarEvent

type BarEvent interface {
	DataEventHandler
	IsBar() bool
}

BarEvent declares a bar event interface.

type Casher

type Casher interface {
	SetInitialCash(float64)
	InitialCash() float64
	SetCash(float64)
	Cash() float64
}

Casher handles basic portolio info

type Data

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

Data is a basic data struct

func (*Data) History

func (d *Data) History() []DataEventHandler

History returns the historic data stream

func (*Data) Latest

func (d *Data) Latest(symbol string) DataEventHandler

Latest returns the last known data event for a symbol.

func (*Data) List

func (d *Data) List(symbol string) []DataEventHandler

List returns the data event list for a symbol.

func (*Data) Load

func (d *Data) Load(s []string) error

Load loads data endpoints into a stream. This method satisfies the DataLoeder interface, but should be overwritten by the specific data loading implamentation.

func (*Data) Next

func (d *Data) Next() (dh DataEventHandler, ok bool)

Next returns the first element of the data stream deletes it from the stream and appends it to history

func (*Data) Reset added in v0.2.2

func (d *Data) Reset()

Reset implements the Reseter interface and rests the data struct to a clean state with loaded data points

func (*Data) SetStream

func (d *Data) SetStream(stream []DataEventHandler)

SetStream sets the data stream

func (*Data) SortStream

func (d *Data) SortStream()

SortStream sorts the dataStream

func (*Data) Stream

func (d *Data) Stream() []DataEventHandler

Stream returns the data stream

type DataEvent

type DataEvent struct {
	Metrics map[string]float64
}

DataEvent is the basic implementation of a data event handler.

func (DataEvent) IsDataEvent

func (d DataEvent) IsDataEvent() bool

IsDataEvent declares a data event

type DataEventHandler

type DataEventHandler interface {
	EventHandler
	IsDataEvent() bool
	LatestPrice() float64
}

DataEventHandler declares a data event interface

type DataHandler

type DataHandler interface {
	DataLoader
	DataStreamer
	Reseter
}

DataHandler is the combined data interface

type DataLoader

type DataLoader interface {
	Load([]string) error
}

DataLoader is the interface loading the data into the data stream

type DataStreamer

type DataStreamer interface {
	Next() (DataEventHandler, bool)
	Stream() []DataEventHandler
	History() []DataEventHandler
	Latest(string) DataEventHandler
	List(string) []DataEventHandler
}

DataStreamer is the interface returning the data streams

type Directioner

type Directioner interface {
	SetDirection(string)
	GetDirection() string
}

Directioner defines a direction interface

type Event

type Event struct {
	Timestamp time.Time
	Symbol    string
}

Event is the implementation of the basic event interface.

func (Event) GetSymbol

func (e Event) GetSymbol() string

GetSymbol returns the symbol string of the event

func (Event) GetTime

func (e Event) GetTime() time.Time

GetTime returns the timestamp of an event

func (Event) IsEvent

func (e Event) IsEvent() bool

IsEvent declares an event interface implementation.

type EventHandler

type EventHandler interface {
	IsEvent() bool
	Timer
	Symboler
}

EventHandler declares the basic event interface

type EventTracker

type EventTracker interface {
	TrackEvent(EventHandler)
	Events() []EventHandler
}

EventTracker is responsible for all event tracking during a backtest

type Exchange

type Exchange struct {
	Symbol      string
	ExchangeFee float64
}

Exchange is a basic execution handler implementation

func (*Exchange) ExecuteOrder

func (e *Exchange) ExecuteOrder(order OrderEvent, data DataHandler) (*Fill, error)

ExecuteOrder executes an order event

type ExecutionHandler

type ExecutionHandler interface {
	ExecuteOrder(OrderEvent, DataHandler) (*Fill, error)
}

ExecutionHandler is the basic interface for executing orders

type Fill

type Fill struct {
	Event
	Exchange    string // exchange symbol
	Direction   string // BOT for buy or SLD for sell
	Qty         int64
	Price       float64
	Commission  float64
	ExchangeFee float64
	Cost        float64 // the total cost of the filled order incl commission and fees
}

Fill declares a basic fill event

func (Fill) GetCommission

func (f Fill) GetCommission() float64

GetCommission returns the Commission field of a fill.

func (Fill) GetCost

func (f Fill) GetCost() float64

GetCost returns the Cost field of a Fill

func (Fill) GetDirection

func (f Fill) GetDirection() string

GetDirection returns the direction of a Fill

func (Fill) GetExchangeFee

func (f Fill) GetExchangeFee() float64

GetExchangeFee returns the ExchangeFee Field of a fill

func (Fill) GetPrice

func (f Fill) GetPrice() float64

GetPrice returns the Price field of a fill

func (Fill) GetQty

func (f Fill) GetQty() int64

GetQty returns the qty field of a fill

func (Fill) IsFill

func (f Fill) IsFill() bool

IsFill declares a fill event.

func (Fill) NetValue

func (f Fill) NetValue() float64

NetValue returns the net value including cost.

func (*Fill) SetDirection

func (f *Fill) SetDirection(s string)

SetDirection sets the Directions field of a Fill

func (*Fill) SetQty

func (f *Fill) SetQty(i int64)

SetQty sets the Qty field of a Fill

func (Fill) Value

func (f Fill) Value() float64

Value returns the value without cost.

type FillEvent

type FillEvent interface {
	EventHandler
	Directioner
	Quantifier
	IsFill() bool
	GetPrice() float64
	GetCommission() float64
	GetExchangeFee() float64
	GetCost() float64
	Value() float64
	NetValue() float64
}

FillEvent declares the fill event interface.

type Investor

type Investor interface {
	IsInvested(string) (position, bool)
	IsLong(string) (position, bool)
	IsShort(string) (position, bool)
}

Investor is an inteface to check if a portfolio has a position of a symbol

type OnFiller

type OnFiller interface {
	OnFill(FillEvent, DataHandler) (*Fill, error)
}

OnFiller as an intercafe for the OnFill method

type OnSignaler

type OnSignaler interface {
	OnSignal(SignalEvent, DataHandler) (*Order, error)
}

OnSignaler as an intercafe for the OnSignal method

type Order

type Order struct {
	Event
	Direction string  // buy or sell
	Qty       int64   // quantity of the order
	OrderType string  // market or limit
	Limit     float64 // limit for the order
}

Order declares a basic order event

func (Order) GetDirection

func (o Order) GetDirection() string

GetDirection returns the Direction of an Order

func (Order) GetQty

func (o Order) GetQty() int64

GetQty returns the Qty field of an Order

func (Order) IsOrder

func (o Order) IsOrder() bool

IsOrder declares an order event.

func (*Order) SetDirection

func (o *Order) SetDirection(s string)

SetDirection sets the Directions field of an Order

func (*Order) SetQty

func (o *Order) SetQty(i int64)

SetQty sets the Qty field of an Order

type OrderEvent

type OrderEvent interface {
	EventHandler
	Directioner
	Quantifier
	IsOrder() bool
}

OrderEvent declares the order event interface.

type Portfolio

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

Portfolio represent a simple portfolio struct.

func (Portfolio) Cash

func (p Portfolio) Cash() float64

Cash returns the current cash value of the portfolio

func (Portfolio) InitialCash

func (p Portfolio) InitialCash() float64

InitialCash returns the initial cash value of the portfolio

func (Portfolio) IsInvested

func (p Portfolio) IsInvested(symbol string) (pos position, ok bool)

IsInvested checks if the portfolio has an open position on the given symbol

func (Portfolio) IsLong

func (p Portfolio) IsLong(symbol string) (pos position, ok bool)

IsLong checks if the portfolio has an open long position on the given symbol

func (Portfolio) IsShort

func (p Portfolio) IsShort(symbol string) (pos position, ok bool)

IsShort checks if the portfolio has an open short position on the given symbol

func (*Portfolio) OnFill

func (p *Portfolio) OnFill(fill FillEvent, data DataHandler) (*Fill, error)

OnFill handles an incomming fill event

func (*Portfolio) OnSignal

func (p *Portfolio) OnSignal(signal SignalEvent, data DataHandler) (*Order, error)

OnSignal handles an incomming signal event

func (*Portfolio) Reset added in v0.2.2

func (p *Portfolio) Reset()

Reset the portfolio into a clean state with set initial cash.

func (*Portfolio) SetCash

func (p *Portfolio) SetCash(cash float64)

SetCash sets the current cash value of the portfolio

func (*Portfolio) SetInitialCash

func (p *Portfolio) SetInitialCash(initial float64)

SetInitialCash sets the initial cash value of the portfolio

func (*Portfolio) SetRiskManager

func (p *Portfolio) SetRiskManager(risk RiskHandler)

SetRiskManager sets the risk manager to be used with the portfolio

func (*Portfolio) SetSizeManager

func (p *Portfolio) SetSizeManager(size SizeHandler)

SetSizeManager sets the size manager to be used with the portfolio

func (*Portfolio) Update

func (p *Portfolio) Update(d DataEventHandler)

Update updates the holding on a data event

func (Portfolio) Value

func (p Portfolio) Value() float64

Value return the current total value of the portfolio

type PortfolioHandler

type PortfolioHandler interface {
	OnSignaler
	OnFiller
	Investor
	Updater
	Casher
	Valuer
	Reseter
}

PortfolioHandler is the combined interface building block for a portfolio.

type Quantifier

type Quantifier interface {
	SetQty(int64)
	GetQty() int64
}

Quantifier defines a qty interface

type Reseter added in v0.2.2

type Reseter interface {
	Reset()
}

Reseter provides a resting interface.

type Resulter added in v0.2.2

type Resulter interface {
	TotalEquityReturn() (float64, error)
	MaxDrawdown() float64
	MaxDrawdownTime() time.Time
	MaxDrawdownDuration() time.Duration
	SharpRatio(float64) float64
	SortinoRatio(float64) float64
}

Resulter bundles all methods which return the results of the backtest

type Risk

type Risk struct {
}

Risk is a basic risk handler implementation

func (*Risk) EvaluateOrder

func (r *Risk) EvaluateOrder(order OrderEvent, data DataEventHandler, positions map[string]position) (*Order, error)

EvaluateOrder handles the risk of an order, refines or cancel it

type RiskHandler

type RiskHandler interface {
	EvaluateOrder(OrderEvent, DataEventHandler, map[string]position) (*Order, error)
}

RiskHandler is the basic interface for accessing risks of a portfolio

type Signal

type Signal struct {
	Event
	Direction string // long or short
}

Signal declares a basic signal event

func (Signal) GetDirection

func (s Signal) GetDirection() string

GetDirection returns the Direction of a Signal

func (Signal) IsSignal

func (s Signal) IsSignal() bool

IsSignal implements the Signal interface.

func (*Signal) SetDirection

func (s *Signal) SetDirection(st string)

SetDirection sets the Directions field of a Signal

type SignalEvent

type SignalEvent interface {
	EventHandler
	Directioner
	IsSignal() bool
}

SignalEvent declares the signal event interface.

type Size

type Size struct {
	DefaultSize  int64
	DefaultValue float64
}

Size is a basic size handler implementation

func (*Size) SizeOrder

func (s *Size) SizeOrder(order OrderEvent, data DataEventHandler, pf PortfolioHandler) (*Order, error)

SizeOrder adjusts the size of an order

type SizeHandler

type SizeHandler interface {
	SizeOrder(OrderEvent, DataEventHandler, PortfolioHandler) (*Order, error)
}

SizeHandler is the basic interface for setting the size of an order

type Statistic

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

Statistic is a basic test statistic, which holds simple lists of historic events

func (Statistic) Events

func (s Statistic) Events() []EventHandler

Events returns the complete events history

func (Statistic) MaxDrawdown added in v0.2.3

func (s Statistic) MaxDrawdown() float64

MaxDrawdown returns the maximum draw down value in percent.

func (Statistic) MaxDrawdownDuration added in v0.2.3

func (s Statistic) MaxDrawdownDuration() (d time.Duration)

MaxDrawdownDuration returns the maximum draw down value in percent

func (Statistic) MaxDrawdownTime added in v0.2.3

func (s Statistic) MaxDrawdownTime() time.Time

MaxDrawdownTime returns the time of the maximum draw down value.

func (Statistic) PrintResult

func (s Statistic) PrintResult()

PrintResult prints the backtest statistics to the screen

func (*Statistic) Reset added in v0.2.2

func (s *Statistic) Reset()

Reset the statistic to a clean state

func (*Statistic) SharpRatio added in v0.2.3

func (s *Statistic) SharpRatio(riskfree float64) float64

SharpRatio returns the Sharp ratio compared to a risk free benchmark return.

func (*Statistic) SortinoRatio added in v0.2.3

func (s *Statistic) SortinoRatio(riskfree float64) float64

SortinoRatio returns the Sortino ratio compared to a risk free benchmark return.

func (Statistic) TotalEquityReturn added in v0.2.2

func (s Statistic) TotalEquityReturn() (r float64, err error)

TotalEquityReturn calculates the the total return on the first and last equity point

func (*Statistic) TrackEvent

func (s *Statistic) TrackEvent(e EventHandler)

TrackEvent tracks an event

func (*Statistic) TrackTransaction

func (s *Statistic) TrackTransaction(f FillEvent)

TrackTransaction tracks a transaction aka a fill event

func (Statistic) Transactions

func (s Statistic) Transactions() []FillEvent

Transactions returns the complete events history

func (*Statistic) Update

Update the complete statistics to a given data event.

type StatisticHandler

StatisticHandler is a basic statistic interface

type StatisticPrinter

type StatisticPrinter interface {
	PrintResult()
}

StatisticPrinter handles printing of the statistics to screen

type StatisticUpdater added in v0.2.2

type StatisticUpdater interface {
	Update(DataEventHandler, PortfolioHandler)
}

StatisticUpdater handles the updateing of the statistics

type StrategyHandler

type StrategyHandler interface {
	CalculateSignal(DataEventHandler, DataHandler, PortfolioHandler) (SignalEvent, error)
}

StrategyHandler is a basic strategy interface

type Symboler

type Symboler interface {
	GetSymbol() string
}

Symboler declares the symboler interface

type Test

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

Test is a basic back test struct

func New

func New() *Test

New creates a default test backtest value for use.

func (*Test) Reset added in v0.2.2

func (t *Test) Reset()

Reset rests the backtest into a clean state with loaded data

func (*Test) Run

func (t *Test) Run() error

Run starts the test.

func (*Test) SetData

func (t *Test) SetData(data DataHandler)

SetData sets the data provider to to be used within the test

func (*Test) SetExchange

func (t *Test) SetExchange(exchange ExecutionHandler)

SetExchange sets the execution provider to to be used within the test

func (*Test) SetPortfolio

func (t *Test) SetPortfolio(portfolio PortfolioHandler)

SetPortfolio sets the portfolio provider to to be used within the test

func (*Test) SetStatistic

func (t *Test) SetStatistic(statistic StatisticHandler)

SetStatistic sets the statistic provider to to be used within the test

func (*Test) SetStrategy

func (t *Test) SetStrategy(strategy StrategyHandler)

SetStrategy sets the strategy provider to to be used within the test

func (*Test) SetSymbols

func (t *Test) SetSymbols(symbols []string)

SetSymbols sets the symbols to include into the test

func (*Test) Stats added in v0.2.2

func (t *Test) Stats() StatisticHandler

Stats returns the statistic handler of the backtest

type Tick

type Tick struct {
	Event
	DataEvent
	Bid float64
	Ask float64
}

Tick declares an tick event

func (Tick) IsTick

func (t Tick) IsTick() bool

IsTick declares a tick event

func (Tick) LatestPrice

func (t Tick) LatestPrice() float64

LatestPrice returns the middle of Bid and Ask.

type TickEvent

type TickEvent interface {
	DataEventHandler
	IsTick() bool
}

TickEvent declares a tick event interface.

type Timer

type Timer interface {
	GetTime() time.Time
}

Timer declares the timer interface

type TransactionTracker

type TransactionTracker interface {
	TrackTransaction(FillEvent)
	Transactions() []FillEvent
}

TransactionTracker is responsible for all transaction tracking during a backtest

type Updater

type Updater interface {
	Update(DataEventHandler)
}

Updater handles the updating of the portfolio on data events

type Valuer

type Valuer interface {
	Value() float64
}

Valuer returns the values of the portfolio

Jump to

Keyboard shortcuts

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