gobacktest

package module
v0.0.0-...-ffd4c39 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2022 License: MIT Imports: 6 Imported by: 0

README

Go Doc Travis Coverage Status Go Report Card Software License

Heads up: This is a framework in development, with only basic functionality.


gobacktest - Fundamental stock analysis backtesting

An event-driven backtesting framework to test stock trading strategies based on fundamental analysis. Preferably this package will be the core of a backend service exposed via a REST API.

Usage

Basic example:

package main

import (
  "github.com/cavan-black/gobacktest"
  "github.com/cavan-black/gobacktest/data"
  "github.com/cavan-black/gobacktest/strategy"
)

func main() {
  // initiate a new backtester
  test := gobacktest.New()

  // define and load symbols
  symbols := []string{"TEST.DE"}
  test.SetSymbols(symbols)

  // create a data provider and load the data into the backtest
  data := &data.BarEventFromCSVFile{FileDir: "../testdata/test/"}
  data.Load(symbols)
  test.SetData(data)

  // choose a strategy
  strategy := strategy.BuyAndHold()

  // create an asset and append it to the strategy
  strategy.SetChildren(gobacktest.NewAsset("TEST.DE"))
  
  // load the strategy into the backtest
  test.SetStrategy(strategy)

  // run the backtest
  test.Run()

  // print the results of the test
  test.Stats().PrintResult()
}

More example tests are in the /examples folder.

The single parts of the backtester can be set independently:

// initiate new backtester
test := &Backtest{}

// set the portfolio with initial cash and a default size and risk manager
portfolio := &gobacktest.Portfolio{}
portfolio.SetInitialCash(10000)

sizeManager := &gobacktest.Size{DefaultSize: 100, DefaultValue: 1000}
portfolio.SetSizeManager(sizeManager)

riskManager := &gobacktest.Risk{}
portfolio.SetRiskManager(riskManager)

test.SetPortfolio(portfolio)

// create a new strategy with an algo stack
strategy := gobacktest.NewStrategy("basic")
strategy.SetAlgo(
    algo.CreateSignal("buy"), // always create a buy signal on a data event
)

// create an asset and append to strategy
strategy.SetChildren(gobacktest.NewAsset("TEST.DE"))

// load the strategy into the backtest
test.SetStrategy(strategy)

// create an execution provider and load it into the backtest
exchange := &gobacktest.Exchange{
    Symbol:      "TEST",
    Commission:  &FixedCommission{Commission: 0},
    ExchangeFee: &FixedExchangeFee{ExchangeFee: 0},
}
test.SetExchange(exchange)

// choose a statistic and load into it the backtest
statistic := &gobacktest.Statistic{}
test.SetStatistic(statistic)

Dependencies

None so far. Only the standard library.

Basic components

These are the basic components of an event-driven framework.

  1. BackTester - general test case, bundles the following elements into a single test
  2. EventHandler - the different types of events, which travel through this system - data event, signal event, order event and fill event
  3. DataHandler - interface to a set of data, e.g historical quotes, fundamental data, dividends etc.
  4. StrategyHandler - generates a buy/sell signal based on the data
  5. PortfolioHandler - generates orders and manages profit & loss
    • (SizeHandler) - manages the size of an order
    • (RiskHandler) - manages the risk allocation of a portfolio
  6. ExecutionHandler - sends orders to the broker and receives the “fills” or signals that the stock has been bought or sold
  7. StatisticHandler - tracks all events during the backtests and calculates useful statistics like equity return, drawdown or sharp ratio etc., could be used to replay the complete backtest for later reference
    • (ComplianceHandler) - tracks and documents all trades to the portfolio for compliance reasons

Infrastructure example

An overviev of the infrastructure of a complete backtesting and trading environment. Taken from the production roadmap of QuantRocket.

  • General
    • API gateway
    • configuration loader
    • logging service
    • cron service
  • Data
    • database backup and download service
    • securities master services
    • historical market data service
    • fundamental data service
    • earnings data service
    • dividend data service
    • real-time market data service
    • exchange calendar service
  • Strategy
    • performance analysis service - tearsheet
  • Portfolio
    • account and portfolio service
    • risk management service
  • Execution
    • trading platform gateway service
    • order management and trade ledger service
    • backtesting and trading engine

Resources

Articles

These links to articles are a good starting point to understand the intentions and basic functions of an event-driven backtesting framework.

Other backtesting frameworks
General information on Quantitative Finance

Documentation

Overview

Package gobacktest is a simple placeholder to root all gobacktest documentation

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

This section is empty.

Types

type Algo

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

Algo is a base algo structure, implements AlgoHandler

func (Algo) Always

func (a Algo) Always() bool

Always returns the runAlways property.

func (Algo) Run

func (a Algo) Run(_ StrategyHandler) (bool, error)

Run implements the Algo interface.

func (*Algo) SetAlways

func (a *Algo) SetAlways()

SetAlways set the runAlways property.

func (*Algo) Value

func (a *Algo) Value() float64

Value returns the value of this Algo.

type AlgoHandler

type AlgoHandler interface {
	Run(StrategyHandler) (bool, error)
	Always() bool
	SetAlways()
	Value() float64
}

AlgoHandler defines the base algorythm functionality.

func RunAlways

func RunAlways(a AlgoHandler) AlgoHandler

RunAlways set the runAlways property on the AlgoHandler

type AlgoStack

type AlgoStack struct {
	Algo
	// contains filtered or unexported fields
}

AlgoStack represents a single stack of algos.

func (AlgoStack) Run

func (as AlgoStack) Run(s StrategyHandler) (bool, error)

Run implements the Algo interface on the AlgoStack, which makes it itself an Algo.

type Asset

type Asset struct {
	Node
}

Asset is a data building block for the tree structure, eg. Stock, Option, Cash etc. It implements the NodeHandler interface via the promoted Node field.

func NewAsset

func NewAsset(name string) *Asset

NewAsset return a new strategy node ready to use.

func (Asset) Children

func (a Asset) Children() ([]NodeHandler, bool)

Children returns an empty slice and false, an Asset is not allowed to have children.

func (*Asset) SetChildren

func (a *Asset) SetChildren(c ...NodeHandler) NodeHandler

SetChildren return itself without change, as an Asset ist not allowed to have children.

type Backtest

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

Backtest is the main struct which holds all elements.

func New

func New() *Backtest

New creates a default backtest with sensible defaults ready for use.

func (*Backtest) Reset

func (t *Backtest) Reset() error

Reset the backtest into a clean state with loaded data.

func (*Backtest) Run

func (t *Backtest) Run() error

Run starts the backtest.

func (*Backtest) SetData

func (t *Backtest) SetData(data DataHandler)

SetData sets the data provider to be used within the backtest.

func (*Backtest) SetExchange

func (t *Backtest) SetExchange(exchange ExecutionHandler)

SetExchange sets the execution provider to be used within the backtest.

func (*Backtest) SetPortfolio

func (t *Backtest) SetPortfolio(portfolio PortfolioHandler)

SetPortfolio sets the portfolio provider to be used within the backtest.

func (*Backtest) SetStatistic

func (t *Backtest) SetStatistic(statistic StatisticHandler)

SetStatistic sets the statistic provider to be used within the backtest.

func (*Backtest) SetStrategy

func (t *Backtest) SetStrategy(strategy StrategyHandler)

SetStrategy sets the strategy provider to be used within the backtest.

func (*Backtest) SetSymbols

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

SetSymbols sets the symbols to include into the backtest.

func (*Backtest) Stats

func (t *Backtest) Stats() StatisticHandler

Stats returns the statistic handler of the backtest.

type Bar

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

Bar declares a data event for an OHLCV bar.

func (Bar) Price

func (b Bar) Price() float64

Price returns the close price of the bar event.

type BarEvent

type BarEvent interface {
	DataEvent
}

BarEvent declares a bar event interface.

type Booker

type Booker interface {
	OrderBook() ([]OrderEvent, bool)
	OrdersBySymbol(symbol string) ([]OrderEvent, bool)
}

Booker defines methods for handling the order book of the portfolio

type Casher

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

Casher handles basic portolio info

type CommissionHandler

type CommissionHandler interface {
	Calculate(qty, price float64) (float64, error)
}

CommissionHandler is the basic interface for executing orders

type Data

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

Data is a basic data provider struct.

func (*Data) History

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

History returns the historic data stream.

func (*Data) Latest

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

Latest returns the last known data event for a symbol.

func (*Data) List

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

List returns the data event list for a symbol.

func (*Data) Load

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

Load data events into a stream. This method satisfies the DataLoader interface, but should be overwritten by the specific data loading implementation.

func (*Data) Next

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

Next returns the first element of the data stream, deletes it from the data stream and appends it to the historic data stream.

func (*Data) Reset

func (d *Data) Reset() error

Reset implements Reseter to reset the data struct to a clean state with loaded data events.

func (*Data) SetStream

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

SetStream sets the data stream.

func (*Data) SortStream

func (d *Data) SortStream()

SortStream sorts the data stream in ascending order.

func (*Data) Stream

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

Stream returns the data stream.

type DataEvent

type DataEvent interface {
	EventHandler
	MetricHandler
	Pricer
}

DataEvent 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 defines how to load data into the data stream.

type DataStreamer

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

DataStreamer defines data stream functionality.

type Direction

type Direction int

Direction defines which direction a signal indicates

const (
	// Buy
	BOT Direction = iota // 0
	// Sell
	SLD
	// Hold
	HLD
	// Exit
	EXT
)

different types of order directions

type Directioner

type Directioner interface {
	Direction() Direction
	SetDirection(Direction)
}

Directioner defines a direction interface

type Event

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

Event is the implementation of the basic event interface.

func (*Event) SetSymbol

func (e *Event) SetSymbol(s string)

SetSymbol returns the symbol string of the event

func (*Event) SetTime

func (e *Event) SetTime(t time.Time)

SetTime returns the timestamp of an event

func (Event) Symbol

func (e Event) Symbol() string

Symbol returns the symbol string of the event

func (Event) Time

func (e Event) Time() time.Time

Time returns the timestamp of an event

type EventHandler

type EventHandler interface {
	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
	Commission  CommissionHandler
	ExchangeFee ExchangeFeeHandler
}

Exchange is a basic execution handler implementation

func NewExchange

func NewExchange() *Exchange

NewExchange creates a default exchange with sensible defaults ready for use.

func (*Exchange) OnData

func (e *Exchange) OnData(data DataEvent) (*Fill, error)

OnData executes any open order on new data

func (*Exchange) OnOrder

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

OnOrder executes an order event

type ExchangeFeeHandler

type ExchangeFeeHandler interface {
	Fee() (float64, error)
}

ExchangeFeeHandler is the basic interface for managing the exchange fee

type ExecutionHandler

type ExecutionHandler interface {
	OnData(DataEvent) (*Fill, error)
	OnOrder(OrderEvent, DataHandler) (*Fill, error)
}

ExecutionHandler is the basic interface for executing orders

type Fill

type Fill struct {
	Event

	Exchange string // exchange symbol
	// contains filtered or unexported fields
}

Fill declares a basic fill event

func (Fill) Commission

func (f Fill) Commission() float64

Commission returns the Commission field of a fill.

func (Fill) Cost

func (f Fill) Cost() float64

Cost returns the Cost field of a Fill

func (Fill) Direction

func (f Fill) Direction() Direction

Direction returns the direction of a Fill

func (Fill) ExchangeFee

func (f Fill) ExchangeFee() float64

ExchangeFee returns the ExchangeFee Field of a fill

func (Fill) NetValue

func (f Fill) NetValue() float64

NetValue returns the net value including cost.

func (Fill) Price

func (f Fill) Price() float64

Price returns the Price field of a fill

func (Fill) Qty

func (f Fill) Qty() int64

Qty returns the qty field of a fill

func (*Fill) SetDirection

func (f *Fill) SetDirection(dir Direction)

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
	Price() float64
	Commission() float64
	ExchangeFee() float64
	Cost() float64
	Value() float64
	NetValue() float64
}

FillEvent declares fill event functionality.

type FixedCommission

type FixedCommission struct {
	Commission float64
}

FixedCommission is a commission handler implementation which returns a fixed price commission

func (*FixedCommission) Calculate

func (c *FixedCommission) Calculate(qty, price float64) (float64, error)

Calculate calculates the commission of the trade

type FixedExchangeFee

type FixedExchangeFee struct {
	ExchangeFee float64
}

FixedExchangeFee returns a fixed exchange fee

func (*FixedExchangeFee) Fee

func (e *FixedExchangeFee) Fee() (float64, error)

Fee returns the set exchange fee of the trade

type IDer

type IDer interface {
	ID() int
	SetID(int)
}

IDer declares setting and retrieving of an Id.

type Investor

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

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

type Metric

type Metric map[string]float64

Metric holds metric propertys to a data point.

func (Metric) Add

func (m Metric) Add(key string, value float64) error

Add ads a value to the metrics map

func (Metric) Get

func (m Metric) Get(key string) (float64, bool)

Get return a metric by name, if not found it returns false.

type MetricHandler

type MetricHandler interface {
	Add(string, float64) error
	Get(string) (float64, bool)
}

MetricHandler defines the handling of metrics to a data event

type Node

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

Node implements NodeHandler. It represents the base information of each tree node. This is the main building block of the tree.

func (Node) Children

func (n Node) Children() ([]NodeHandler, bool)

Children returns the children of this Node.

func (Node) Name

func (n Node) Name() string

Name returns the name of Node.

func (Node) Root

func (n Node) Root() bool

Root checks if this Node is a root node.

func (*Node) SetChildren

func (n *Node) SetChildren(children ...NodeHandler) NodeHandler

SetChildren sets the Children of this Node.

func (*Node) SetName

func (n *Node) SetName(s string) NodeHandler

SetName sets the name of Node.

func (*Node) SetRoot

func (n *Node) SetRoot(b bool)

SetRoot sets the root status of this Node.

func (*Node) SetTolerance

func (n *Node) SetTolerance(t float64)

SetTolerance of the Node

func (*Node) SetWeight

func (n *Node) SetWeight(w float64)

SetWeight of the node

func (Node) Tolerance

func (n Node) Tolerance() float64

Tolerance spcifies the possible tollerance from the weight.

func (Node) Weight

func (n Node) Weight() float64

Weight returns the weight of this node within this strategy level.

type NodeHandler

type NodeHandler interface {
	WeightHandler
	Name() string
	SetName(string) NodeHandler
	Root() bool
	SetRoot(bool)
	Children() ([]NodeHandler, bool)
	SetChildren(...NodeHandler) NodeHandler
}

NodeHandler defines the basic node functionality.

type OnFiller

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

OnFiller is an interface for the OnFill method

type OnSignaler

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

OnSignaler is an interface for the OnSignal method

type Order

type Order struct {
	Event
	// contains filtered or unexported fields
}

Order declares a basic order event.

func (*Order) Cancel

func (o *Order) Cancel()

Cancel cancels an order

func (Order) Direction

func (o Order) Direction() Direction

Direction returns the Direction of an Order

func (Order) ID

func (o Order) ID() int

ID returns the id of the Order.

func (Order) Limit

func (o Order) Limit() float64

Limit returns the limit price of an Order

func (Order) Qty

func (o Order) Qty() int64

Qty returns the Qty field of an Order

func (*Order) SetDirection

func (o *Order) SetDirection(dir Direction)

SetDirection sets the Directions field of an Order

func (*Order) SetID

func (o *Order) SetID(id int)

SetID of the Order.

func (*Order) SetQty

func (o *Order) SetQty(i int64)

SetQty sets the Qty field of an Order

func (Order) Status

func (o Order) Status() OrderStatus

Status returns the status of an Order

func (Order) Stop

func (o Order) Stop() float64

Stop returns the stop price of an Order

func (*Order) Update

func (o *Order) Update(fill FillEvent)

Update updates an order on a fill event

type OrderBook

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

OrderBook represents an order book.

func (*OrderBook) Add

func (ob *OrderBook) Add(order OrderEvent) error

Add an order to the order book.

func (OrderBook) OrderBy

func (ob OrderBook) OrderBy(fn func(order OrderEvent) bool) ([]OrderEvent, bool)

OrderBy returns the order by a select function from the order book.

func (OrderBook) Orders

func (ob OrderBook) Orders() ([]OrderEvent, bool)

Orders returns all Orders from the order book

func (OrderBook) OrdersAskBySymbol

func (ob OrderBook) OrdersAskBySymbol(symbol string) ([]OrderEvent, bool)

OrdersAskBySymbol returns all bid orders of a specific symbol from the order book.

func (OrderBook) OrdersBidBySymbol

func (ob OrderBook) OrdersBidBySymbol(symbol string) ([]OrderEvent, bool)

OrdersBidBySymbol returns all bid orders of a specific symbol from the order book.

func (OrderBook) OrdersBySymbol

func (ob OrderBook) OrdersBySymbol(symbol string) ([]OrderEvent, bool)

OrdersBySymbol returns the order of a specific symbol from the order book.

func (OrderBook) OrdersCanceled

func (ob OrderBook) OrdersCanceled() ([]OrderEvent, bool)

OrdersCanceled returns all orders which are canceled from the order book.

func (OrderBook) OrdersOpen

func (ob OrderBook) OrdersOpen() ([]OrderEvent, bool)

OrdersOpen returns all orders which are open from the order book.

func (*OrderBook) Remove

func (ob *OrderBook) Remove(id int) error

Remove an order from the order book, append it to history.

type OrderEvent

type OrderEvent interface {
	EventHandler
	Directioner
	Quantifier
	IDer
	Status() OrderStatus
	Limit() float64
	Stop() float64
}

OrderEvent declares the order event interface.

type OrderStatus

type OrderStatus int

OrderStatus defines an order status

const (
	OrderNone OrderStatus = iota // 0
	OrderNew
	OrderSubmitted
	OrderPartiallyFilled
	OrderFilled
	OrderCanceled
	OrderCancelPending
	OrderInvalid
)

different types of order status

type OrderType

type OrderType int

OrderType defines which type an order is

const (
	MarketOrder OrderType = iota // 0
	MarketOnOpenOrder
	MarketOnCloseOrder
	StopMarketOrder
	LimitOrder
	StopLimitOrder
)

different types of orders

type PercentageCommission

type PercentageCommission struct {
	Commission float64
}

PercentageCommission is a commission handler implementation which returns a percentage price commission calculated of the value of the trade

func (*PercentageCommission) Calculate

func (c *PercentageCommission) Calculate(qty, price float64) (float64, error)

Calculate calculates the commission of the trade

type Portfolio

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

Portfolio represent a simple portfolio struct.

func NewPortfolio

func NewPortfolio() *Portfolio

NewPortfolio creates a default portfolio with sensible defaults ready for use.

func (Portfolio) Cash

func (p Portfolio) Cash() float64

Cash returns the current cash value of the portfolio

func (Portfolio) Holdings

func (p Portfolio) Holdings() map[string]Position

Holdings returns the holdings 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) OrderBook

func (p Portfolio) OrderBook() ([]OrderEvent, bool)

OrderBook returns the order book of the portfolio

func (Portfolio) OrdersBySymbol

func (p Portfolio) OrdersBySymbol(symbol string) ([]OrderEvent, bool)

OrdersBySymbol returns the order of a specific symbol from the order book.

func (*Portfolio) Reset

func (p *Portfolio) Reset() error

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

func (Portfolio) RiskManager

func (p Portfolio) RiskManager() RiskHandler

RiskManager returns the risk manager of the portfolio.

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) SizeManager

func (p Portfolio) SizeManager() SizeHandler

SizeManager return the size manager of the portfolio.

func (*Portfolio) Update

func (p *Portfolio) Update(d DataEvent)

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 Position

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

Position represents the holdings position

func (*Position) Create

func (p *Position) Create(fill FillEvent)

Create a new position based on a fill event

func (*Position) Update

func (p *Position) Update(fill FillEvent)

Update a position on a new fill event

func (*Position) UpdateValue

func (p *Position) UpdateValue(data DataEvent)

UpdateValue updates the current market value of a position

type Pricer

type Pricer interface {
	Price() float64
}

Pricer defines the handling otf the latest Price Information

type Quantifier

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

Quantifier defines a qty interface.

type Reseter

type Reseter interface {
	Reset() error
}

Reseter provides a resting interface.

type Resulter

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 DataEvent, positions map[string]Position) (*Order, error)

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

type RiskHandler

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

RiskHandler is the basic interface for accessing risks of a portfolio

type Signal

type Signal struct {
	Event
	// contains filtered or unexported fields
}

Signal declares a basic signal event

func (Signal) Direction

func (s Signal) Direction() Direction

Direction returns the Direction of a Signal

func (*Signal) SetDirection

func (s *Signal) SetDirection(dir Direction)

SetDirection sets the Directions field of a Signal

type SignalEvent

type SignalEvent interface {
	EventHandler
	Directioner
}

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 DataEvent, pf PortfolioHandler) (*Order, error)

SizeOrder adjusts the size of an order

type SizeHandler

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

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

type Spreader

type Spreader interface {
	Spread() float64
}

Spreader declares functionality to get spre spread of a tick.

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

func (s Statistic) MaxDrawdown() float64

MaxDrawdown returns the maximum draw down value in percent.

func (Statistic) MaxDrawdownDuration

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

MaxDrawdownDuration returns the maximum draw down value in percent

func (Statistic) MaxDrawdownTime

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

func (s *Statistic) Reset() error

Reset the statistic to a clean state

func (*Statistic) SharpRatio

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

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

func (*Statistic) SortinoRatio

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

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

func (Statistic) TotalEquityReturn

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

func (s *Statistic) Update(d DataEvent, p PortfolioHandler)

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

type StatisticUpdater interface {
	Update(DataEvent, PortfolioHandler)
}

StatisticUpdater handles the updateing of the statistics

type Strategy

type Strategy struct {
	Node
	// contains filtered or unexported fields
}

Strategy implements NodeHandler via Node, used as a strategy building block.

func NewStrategy

func NewStrategy(name string) *Strategy

NewStrategy return a new strategy node ready to use.

func (*Strategy) AddSignal

func (s *Strategy) AddSignal(signals ...SignalEvent) error

AddSignal sets the data property.

func (*Strategy) Assets

func (s *Strategy) Assets() ([]*Asset, bool)

Assets return all children which are a strategy.

func (*Strategy) Data

func (s *Strategy) Data() (DataHandler, bool)

Data returns the underlying data property.

func (*Strategy) Event

func (s *Strategy) Event() (DataEvent, bool)

Event returns the underlying data property.

func (*Strategy) OnData

func (s *Strategy) OnData(event DataEvent) (signals []SignalEvent, err error)

OnData handles an incoming data event. It runs the algo stack on this data.

func (*Strategy) Portfolio

func (s *Strategy) Portfolio() (PortfolioHandler, bool)

Portfolio returns the underlying portfolio property.

func (*Strategy) SetAlgo

func (s *Strategy) SetAlgo(algos ...AlgoHandler) *Strategy

SetAlgo sets the algo stack for the Strategy

func (*Strategy) SetData

func (s *Strategy) SetData(data DataHandler) error

SetData sets the data property.

func (*Strategy) SetEvent

func (s *Strategy) SetEvent(event DataEvent) error

SetEvent sets the event property.

func (*Strategy) SetPortfolio

func (s *Strategy) SetPortfolio(portfolio PortfolioHandler) error

SetPortfolio sets the portfolio property.

func (*Strategy) Signals

func (s *Strategy) Signals() ([]SignalEvent, bool)

Signals returns a slice of all from th ealgo loop created signals.

func (*Strategy) Strategies

func (s *Strategy) Strategies() ([]StrategyHandler, bool)

Strategies return all children which are a strategy.

type StrategyHandler

type StrategyHandler interface {
	Data() (DataHandler, bool)
	SetData(d DataHandler) error
	Portfolio() (PortfolioHandler, bool)
	SetPortfolio(p PortfolioHandler) error
	Event() (DataEvent, bool)
	SetEvent(DataEvent) error
	Signals() ([]SignalEvent, bool)
	AddSignal(...SignalEvent) error
	Strategies() ([]StrategyHandler, bool)
	Assets() ([]*Asset, bool)
	OnData(DataEvent) ([]SignalEvent, error)
}

StrategyHandler is a basic strategy interface.

type Symboler

type Symboler interface {
	Symbol() string
	SetSymbol(string)
}

Symboler declares the symboler interface

type Tick

type Tick struct {
	Event
	Metric
	Bid       float64
	Ask       float64
	BidVolume int64
	AskVolume int64
}

Tick declares a data event for a price tick.

func (Tick) Price

func (t Tick) Price() float64

Price returns the middle of Bid and Ask.

func (Tick) Spread

func (t Tick) Spread() float64

Spread returns the difference or spread of Bid and Ask.

type TickEvent

type TickEvent interface {
	DataEvent
	Spreader
}

TickEvent declares a bar event interface.

type Timer

type Timer interface {
	Time() time.Time
	SetTime(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 TresholdFixedCommission

type TresholdFixedCommission struct {
	Commission float64
	MinValue   float64
}

TresholdFixedCommission is a commission handler implementation which returns a fixed price commission if the value of the trade is above a set treshold

func (*TresholdFixedCommission) Calculate

func (c *TresholdFixedCommission) Calculate(qty, price float64) (float64, error)

Calculate calculates the commission of the trade

type Updater

type Updater interface {
	Update(DataEvent)
}

Updater handles the updating of the portfolio on data events

type ValueCommission

type ValueCommission struct {
	Commission    float64
	MinCommission float64
	MaxCommission float64
}

ValueCommission is a commission handler implementation which returns a percentage price commission calculated of the value of the trade, if the value of the trade is within a given commission span

func (*ValueCommission) Calculate

func (c *ValueCommission) Calculate(qty, price float64) (float64, error)

Calculate calculates the commission of the trade

type Valuer

type Valuer interface {
	Value() float64
}

Valuer returns the values of the portfolio

type WeightHandler

type WeightHandler interface {
	Weight() float64
	SetWeight(float64)
	Tolerance() float64
	SetTolerance(float64)
}

WeightHandler defines weight functionality.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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