gobacktest

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2018 License: MIT Imports: 6 Imported by: 1

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/dirkolbrich/gobacktest"
  "github.com/dirkolbrich/gobacktest/data"
  "github.com/dirkolbrich/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 added in v0.3.0

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

Algo is a base algo structure, implements AlgoHandler

func (Algo) Always added in v0.3.0

func (a Algo) Always() bool

Always returns the runAlways property.

func (Algo) Run added in v0.3.0

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

Run implements the Algo interface.

func (*Algo) SetAlways added in v0.3.0

func (a *Algo) SetAlways()

SetAlways set the runAlways property.

func (*Algo) Value added in v0.3.0

func (a *Algo) Value() float64

Value returns the value of this Algo.

type AlgoHandler added in v0.3.0

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

AlgoHandler defines the base algorythm functionality.

func RunAlways added in v0.3.0

func RunAlways(a AlgoHandler) AlgoHandler

RunAlways set the runAlways property on the AlgoHandler

type AlgoStack added in v0.3.0

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

AlgoStack represents a single stack of algos.

func (AlgoStack) Run added in v0.3.0

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

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

type Asset added in v0.3.0

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 added in v0.3.0

func NewAsset(name string) *Asset

NewAsset return a new strategy node ready to use.

func (Asset) Children added in v0.3.0

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

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

func (*Asset) SetChildren added in v0.3.0

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

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

type Backtest added in v0.3.0

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 added in v0.3.0

func (t *Backtest) Reset() error

Reset the backtest into a clean state with loaded data.

func (*Backtest) Run added in v0.3.0

func (t *Backtest) Run() error

Run starts the backtest.

func (*Backtest) SetData added in v0.3.0

func (t *Backtest) SetData(data DataHandler)

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

func (*Backtest) SetExchange added in v0.3.0

func (t *Backtest) SetExchange(exchange ExecutionHandler)

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

func (*Backtest) SetPortfolio added in v0.3.0

func (t *Backtest) SetPortfolio(portfolio PortfolioHandler)

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

func (*Backtest) SetStatistic added in v0.3.0

func (t *Backtest) SetStatistic(statistic StatisticHandler)

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

func (*Backtest) SetStrategy added in v0.3.0

func (t *Backtest) SetStrategy(strategy StrategyHandler)

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

func (*Backtest) SetSymbols added in v0.3.0

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

SetSymbols sets the symbols to include into the backtest.

func (*Backtest) Stats added in v0.3.0

func (t *Backtest) Stats() StatisticHandler

Stats returns the statistic handler of the backtest.

type Bar added in v0.3.0

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 added in v0.3.0

func (b Bar) Price() float64

Price returns the close price of the bar event.

type BarEvent added in v0.3.0

type BarEvent interface {
	DataEvent
}

BarEvent declares a bar event interface.

type Booker added in v0.3.0

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

Booker defines methods for handling the order book of the portfolio

type Casher added in v0.3.0

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

Casher handles basic portolio info

type CommissionHandler added in v0.3.0

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

CommissionHandler is the basic interface for executing orders

type Data added in v0.3.0

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

Data is a basic data provider struct.

func (*Data) History added in v0.3.0

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

History returns the historic data stream.

func (*Data) Latest added in v0.3.0

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

Latest returns the last known data event for a symbol.

func (*Data) List added in v0.3.0

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

List returns the data event list for a symbol.

func (*Data) Load added in v0.3.0

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 added in v0.3.0

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 added in v0.3.0

func (d *Data) Reset() error

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

func (*Data) SetStream added in v0.3.0

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

SetStream sets the data stream.

func (*Data) SortStream added in v0.3.0

func (d *Data) SortStream()

SortStream sorts the data stream in ascending order.

func (*Data) Stream added in v0.3.0

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

Stream returns the data stream.

type DataEvent added in v0.3.0

type DataEvent interface {
	EventHandler
	MetricHandler
	Pricer
}

DataEvent declares a data event interface

type DataHandler added in v0.3.0

type DataHandler interface {
	DataLoader
	DataStreamer
	Reseter
}

DataHandler is the combined data interface.

type DataLoader added in v0.3.0

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

DataLoader defines how to load data into the data stream.

type DataStreamer added in v0.3.0

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

DataStreamer defines data stream functionality.

type Direction added in v0.3.0

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 added in v0.3.0

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

Directioner defines a direction interface

type Event added in v0.3.0

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

Event is the implementation of the basic event interface.

func (*Event) SetSymbol added in v0.3.0

func (e *Event) SetSymbol(s string)

SetSymbol returns the symbol string of the event

func (*Event) SetTime added in v0.3.0

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

SetTime returns the timestamp of an event

func (Event) Symbol added in v0.3.0

func (e Event) Symbol() string

Symbol returns the symbol string of the event

func (Event) Time added in v0.3.0

func (e Event) Time() time.Time

Time returns the timestamp of an event

type EventHandler added in v0.3.0

type EventHandler interface {
	Timer
	Symboler
}

EventHandler declares the basic event interface

type EventTracker added in v0.3.0

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

EventTracker is responsible for all event tracking during a backtest

type Exchange added in v0.3.0

type Exchange struct {
	Symbol      string
	Commission  CommissionHandler
	ExchangeFee ExchangeFeeHandler
}

Exchange is a basic execution handler implementation

func NewExchange added in v0.3.0

func NewExchange() *Exchange

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

func (*Exchange) OnData added in v0.3.0

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

OnData executes any open order on new data

func (*Exchange) OnOrder added in v0.3.0

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

OnOrder executes an order event

type ExchangeFeeHandler added in v0.3.0

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

ExchangeFeeHandler is the basic interface for managing the exchange fee

type ExecutionHandler added in v0.3.0

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

ExecutionHandler is the basic interface for executing orders

type Fill added in v0.3.0

type Fill struct {
	Event

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

Fill declares a basic fill event

func (Fill) Commission added in v0.3.0

func (f Fill) Commission() float64

Commission returns the Commission field of a fill.

func (Fill) Cost added in v0.3.0

func (f Fill) Cost() float64

Cost returns the Cost field of a Fill

func (Fill) Direction added in v0.3.0

func (f Fill) Direction() Direction

Direction returns the direction of a Fill

func (Fill) ExchangeFee added in v0.3.0

func (f Fill) ExchangeFee() float64

ExchangeFee returns the ExchangeFee Field of a fill

func (Fill) NetValue added in v0.3.0

func (f Fill) NetValue() float64

NetValue returns the net value including cost.

func (Fill) Price added in v0.3.0

func (f Fill) Price() float64

Price returns the Price field of a fill

func (Fill) Qty added in v0.3.0

func (f Fill) Qty() int64

Qty returns the qty field of a fill

func (*Fill) SetDirection added in v0.3.0

func (f *Fill) SetDirection(dir Direction)

SetDirection sets the Directions field of a Fill

func (*Fill) SetQty added in v0.3.0

func (f *Fill) SetQty(i int64)

SetQty sets the Qty field of a Fill

func (Fill) Value added in v0.3.0

func (f Fill) Value() float64

Value returns the value without cost.

type FillEvent added in v0.3.0

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 added in v0.3.0

type FixedCommission struct {
	Commission float64
}

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

func (*FixedCommission) Calculate added in v0.3.0

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

Calculate calculates the commission of the trade

type FixedExchangeFee added in v0.3.0

type FixedExchangeFee struct {
	ExchangeFee float64
}

FixedExchangeFee returns a fixed exchange fee

func (*FixedExchangeFee) Fee added in v0.3.0

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

Fee returns the set exchange fee of the trade

type IDer added in v0.3.0

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

IDer declares setting and retrieving of an Id.

type Investor added in v0.3.0

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 added in v0.3.0

type Metric map[string]float64

Metric holds metric propertys to a data point.

func (Metric) Add added in v0.3.0

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

Add ads a value to the metrics map

func (Metric) Get added in v0.3.0

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

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

type MetricHandler added in v0.3.0

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

MetricHandler defines the handling of metrics to a data event

type Node added in v0.3.0

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 added in v0.3.0

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

Children returns the children of this Node.

func (Node) Name added in v0.3.0

func (n Node) Name() string

Name returns the name of Node.

func (Node) Root added in v0.3.0

func (n Node) Root() bool

Root checks if this Node is a root node.

func (*Node) SetChildren added in v0.3.0

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

SetChildren sets the Children of this Node.

func (*Node) SetName added in v0.3.0

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

SetName sets the name of Node.

func (*Node) SetRoot added in v0.3.0

func (n *Node) SetRoot(b bool)

SetRoot sets the root status of this Node.

func (*Node) SetTolerance added in v0.3.0

func (n *Node) SetTolerance(t float64)

SetTolerance of the Node

func (*Node) SetWeight added in v0.3.0

func (n *Node) SetWeight(w float64)

SetWeight of the node

func (Node) Tolerance added in v0.3.0

func (n Node) Tolerance() float64

Tolerance spcifies the possible tollerance from the weight.

func (Node) Weight added in v0.3.0

func (n Node) Weight() float64

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

type NodeHandler added in v0.3.0

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 added in v0.3.0

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

OnFiller is an interface for the OnFill method

type OnSignaler added in v0.3.0

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

OnSignaler is an interface for the OnSignal method

type Order added in v0.3.0

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

Order declares a basic order event.

func (*Order) Cancel added in v0.3.0

func (o *Order) Cancel()

Cancel cancels an order

func (Order) Direction added in v0.3.0

func (o Order) Direction() Direction

Direction returns the Direction of an Order

func (Order) ID added in v0.3.0

func (o Order) ID() int

ID returns the id of the Order.

func (Order) Limit added in v0.3.0

func (o Order) Limit() float64

Limit returns the limit price of an Order

func (Order) Qty added in v0.3.0

func (o Order) Qty() int64

Qty returns the Qty field of an Order

func (*Order) SetDirection added in v0.3.0

func (o *Order) SetDirection(dir Direction)

SetDirection sets the Directions field of an Order

func (*Order) SetID added in v0.3.0

func (o *Order) SetID(id int)

SetID of the Order.

func (*Order) SetQty added in v0.3.0

func (o *Order) SetQty(i int64)

SetQty sets the Qty field of an Order

func (Order) Status added in v0.3.0

func (o Order) Status() OrderStatus

Status returns the status of an Order

func (Order) Stop added in v0.3.0

func (o Order) Stop() float64

Stop returns the stop price of an Order

func (*Order) Update added in v0.3.0

func (o *Order) Update(fill FillEvent)

Update updates an order on a fill event

type OrderBook added in v0.3.0

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

OrderBook represents an order book.

func (*OrderBook) Add added in v0.3.0

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

Add an order to the order book.

func (OrderBook) OrderBy added in v0.3.0

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 added in v0.3.0

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

Orders returns all Orders from the order book

func (OrderBook) OrdersAskBySymbol added in v0.3.0

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

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

func (OrderBook) OrdersBidBySymbol added in v0.3.0

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

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

func (OrderBook) OrdersBySymbol added in v0.3.0

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

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

func (OrderBook) OrdersCanceled added in v0.3.0

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

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

func (OrderBook) OrdersOpen added in v0.3.0

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

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

func (*OrderBook) Remove added in v0.3.0

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

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

type OrderEvent added in v0.3.0

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

OrderEvent declares the order event interface.

type OrderStatus added in v0.3.0

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 added in v0.3.0

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 added in v0.3.0

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 added in v0.3.0

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

Calculate calculates the commission of the trade

type Portfolio added in v0.3.0

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

Portfolio represent a simple portfolio struct.

func NewPortfolio added in v0.3.0

func NewPortfolio() *Portfolio

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

func (Portfolio) Cash added in v0.3.0

func (p Portfolio) Cash() float64

Cash returns the current cash value of the portfolio

func (Portfolio) Holdings added in v0.3.0

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

Holdings returns the holdings of the portfolio

func (Portfolio) InitialCash added in v0.3.0

func (p Portfolio) InitialCash() float64

InitialCash returns the initial cash value of the portfolio

func (Portfolio) IsInvested added in v0.3.0

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 added in v0.3.0

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 added in v0.3.0

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 added in v0.3.0

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

OnFill handles an incomming fill event

func (*Portfolio) OnSignal added in v0.3.0

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

OnSignal handles an incomming signal event

func (Portfolio) OrderBook added in v0.3.0

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

OrderBook returns the order book of the portfolio

func (Portfolio) OrdersBySymbol added in v0.3.0

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

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

func (*Portfolio) Reset added in v0.3.0

func (p *Portfolio) Reset() error

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

func (Portfolio) RiskManager added in v0.3.0

func (p Portfolio) RiskManager() RiskHandler

RiskManager returns the risk manager of the portfolio.

func (*Portfolio) SetCash added in v0.3.0

func (p *Portfolio) SetCash(cash float64)

SetCash sets the current cash value of the portfolio

func (*Portfolio) SetInitialCash added in v0.3.0

func (p *Portfolio) SetInitialCash(initial float64)

SetInitialCash sets the initial cash value of the portfolio

func (*Portfolio) SetRiskManager added in v0.3.0

func (p *Portfolio) SetRiskManager(risk RiskHandler)

SetRiskManager sets the risk manager to be used with the portfolio.

func (*Portfolio) SetSizeManager added in v0.3.0

func (p *Portfolio) SetSizeManager(size SizeHandler)

SetSizeManager sets the size manager to be used with the portfolio.

func (Portfolio) SizeManager added in v0.3.0

func (p Portfolio) SizeManager() SizeHandler

SizeManager return the size manager of the portfolio.

func (*Portfolio) Update added in v0.3.0

func (p *Portfolio) Update(d DataEvent)

Update updates the holding on a data event

func (Portfolio) Value added in v0.3.0

func (p Portfolio) Value() float64

Value return the current total value of the portfolio

type PortfolioHandler added in v0.3.0

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

PortfolioHandler is the combined interface building block for a portfolio.

type Position added in v0.3.0

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

Position represents the holdings position

func (*Position) Create added in v0.3.0

func (p *Position) Create(fill FillEvent)

Create a new position based on a fill event

func (*Position) Update added in v0.3.0

func (p *Position) Update(fill FillEvent)

Update a position on a new fill event

func (*Position) UpdateValue added in v0.3.0

func (p *Position) UpdateValue(data DataEvent)

UpdateValue updates the current market value of a position

type Pricer added in v0.3.0

type Pricer interface {
	Price() float64
}

Pricer defines the handling otf the latest Price Information

type Quantifier added in v0.3.0

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

Quantifier defines a qty interface.

type Reseter added in v0.3.0

type Reseter interface {
	Reset() error
}

Reseter provides a resting interface.

type Resulter added in v0.3.0

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 added in v0.3.0

type Risk struct {
}

Risk is a basic risk handler implementation

func (*Risk) EvaluateOrder added in v0.3.0

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 added in v0.3.0

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

RiskHandler is the basic interface for accessing risks of a portfolio

type Signal added in v0.3.0

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

Signal declares a basic signal event

func (Signal) Direction added in v0.3.0

func (s Signal) Direction() Direction

Direction returns the Direction of a Signal

func (*Signal) SetDirection added in v0.3.0

func (s *Signal) SetDirection(dir Direction)

SetDirection sets the Directions field of a Signal

type SignalEvent added in v0.3.0

type SignalEvent interface {
	EventHandler
	Directioner
}

SignalEvent declares the signal event interface.

type Size added in v0.3.0

type Size struct {
	DefaultSize  int64
	DefaultValue float64
}

Size is a basic size handler implementation

func (*Size) SizeOrder added in v0.3.0

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

SizeOrder adjusts the size of an order

type SizeHandler added in v0.3.0

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

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

type Spreader added in v0.3.0

type Spreader interface {
	Spread() float64
}

Spreader declares functionality to get spre spread of a tick.

type Statistic added in v0.3.0

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

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

func (Statistic) Events added in v0.3.0

func (s Statistic) Events() []EventHandler

Events returns the complete events history

func (Statistic) MaxDrawdown added in v0.3.0

func (s Statistic) MaxDrawdown() float64

MaxDrawdown returns the maximum draw down value in percent.

func (Statistic) MaxDrawdownDuration added in v0.3.0

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

MaxDrawdownDuration returns the maximum draw down value in percent

func (Statistic) MaxDrawdownTime added in v0.3.0

func (s Statistic) MaxDrawdownTime() time.Time

MaxDrawdownTime returns the time of the maximum draw down value.

func (Statistic) PrintResult added in v0.3.0

func (s Statistic) PrintResult()

PrintResult prints the backtest statistics to the screen

func (*Statistic) Reset added in v0.3.0

func (s *Statistic) Reset() error

Reset the statistic to a clean state

func (*Statistic) SharpRatio added in v0.3.0

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

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

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

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

func (*Statistic) TrackEvent added in v0.3.0

func (s *Statistic) TrackEvent(e EventHandler)

TrackEvent tracks an event

func (*Statistic) TrackTransaction added in v0.3.0

func (s *Statistic) TrackTransaction(f FillEvent)

TrackTransaction tracks a transaction aka a fill event

func (Statistic) Transactions added in v0.3.0

func (s Statistic) Transactions() []FillEvent

Transactions returns the complete events history

func (*Statistic) Update added in v0.3.0

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

Update the complete statistics to a given data event.

type StatisticHandler added in v0.3.0

StatisticHandler is a basic statistic interface

type StatisticPrinter added in v0.3.0

type StatisticPrinter interface {
	PrintResult()
}

StatisticPrinter handles printing of the statistics to screen

type StatisticUpdater added in v0.3.0

type StatisticUpdater interface {
	Update(DataEvent, PortfolioHandler)
}

StatisticUpdater handles the updateing of the statistics

type Strategy added in v0.3.0

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

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

func NewStrategy added in v0.3.0

func NewStrategy(name string) *Strategy

NewStrategy return a new strategy node ready to use.

func (*Strategy) AddSignal added in v0.3.0

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

AddSignal sets the data property.

func (*Strategy) Assets added in v0.3.0

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

Assets return all children which are a strategy.

func (*Strategy) Data added in v0.3.0

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

Data returns the underlying data property.

func (*Strategy) Event added in v0.3.0

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

Event returns the underlying data property.

func (*Strategy) OnData added in v0.3.0

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 added in v0.3.0

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

Portfolio returns the underlying portfolio property.

func (*Strategy) SetAlgo added in v0.3.0

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

SetAlgo sets the algo stack for the Strategy

func (*Strategy) SetData added in v0.3.0

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

SetData sets the data property.

func (*Strategy) SetEvent added in v0.3.0

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

SetEvent sets the event property.

func (*Strategy) SetPortfolio added in v0.3.0

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

SetPortfolio sets the portfolio property.

func (*Strategy) Signals added in v0.3.0

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

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

func (*Strategy) Strategies added in v0.3.0

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

Strategies return all children which are a strategy.

type StrategyHandler added in v0.3.0

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 added in v0.3.0

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

Symboler declares the symboler interface

type Tick added in v0.3.0

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 added in v0.3.0

func (t Tick) Price() float64

Price returns the middle of Bid and Ask.

func (Tick) Spread added in v0.3.0

func (t Tick) Spread() float64

Spread returns the difference or spread of Bid and Ask.

type TickEvent added in v0.3.0

type TickEvent interface {
	DataEvent
	Spreader
}

TickEvent declares a bar event interface.

type Timer added in v0.3.0

type Timer interface {
	Time() time.Time
	SetTime(time.Time)
}

Timer declares the timer interface

type TransactionTracker added in v0.3.0

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

TransactionTracker is responsible for all transaction tracking during a backtest

type TresholdFixedCommission added in v0.3.0

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 added in v0.3.0

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

Calculate calculates the commission of the trade

type Updater added in v0.3.0

type Updater interface {
	Update(DataEvent)
}

Updater handles the updating of the portfolio on data events

type ValueCommission added in v0.3.0

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 added in v0.3.0

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

Calculate calculates the commission of the trade

type Valuer added in v0.3.0

type Valuer interface {
	Value() float64
}

Valuer returns the values of the portfolio

type WeightHandler added in v0.3.0

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