Files
gocryptotrader/backtester/eventhandlers/statistics/statistics.go
Scott f929b4d51e backtester: Futures handling & FTX Cash and Carry example strategy (#930)
* implements futures functions and GRPC functions on new branch

* lint and test fixes

* Fix uneven split pnl. Adds collateral weight test. docs. New clear func

* Test protection if someone has zero collateral

* Uses string instead of double for accuracy

* Fixes old code panic

* context, match, docs

* Addresses Shazniterinos, var names, expanded tests

* Returns subaccount name, provides USD values when offlinecalc

* Fixes oopsie

* Fixes cool bug which allowed made up subaccount results

* Subaccount override on FTX, subaccount results for collateral

* Strenghten collateral account info checks. Improve FTX test

* English is my first language

* Fixes oopsies

* Adds some conceptual futures order details to track PNL

* Initial design of future order processing in the backtester

* Introduces futures concept for collateral and spot/futures config diffs

* Fixes most tests

* Simple designs for collateral funding pair concept

* Expands interface use so much it hurts

* Implements more collateral interfaces

* Adds liquidation, adds strategy, struggles with Binance

* Attempts at getting FTX to work

* Adds calculatePNL as a wrapper function and adds an `IsFutures` asset check

* Successfully loads backtester with collateral currency

* Fails to really get much going for supporting futures

* Merges master changes

* Fleshes out how FTX processes collateral

* Further FTX collateral workings

* hooks up more ftx collateral and pnl calculations

* more funcs to flesh out handling

* Adds more links, just can't fit the pieces together :(

* Greatly expands futures order processing

* Fleshes out position tracker to also handle asset and exchange +testing

* RM linkedOrderID. rn positioncontroller, unexport

* Successfully tracks futures order positions

* Fails to calculate PNL

* Calculates pnl from orders accurately with exception to flipping orders

* Calculates PNL from orders

* Adds another controller layer to make it ez from orderstore

* Backtester now compiles. Adds test coverage

* labels things add scaling collateral test

* Calculates pnl in line with fees

* Mostly accurate PNL, with exception to appending with diff prices

* Adds locks, adds rpc function

* grpc implementations

* Gracefully handles rpc function

* beautiful tests!

* rejiggles tests to polish

* Finishes FTX testing, adds comments

* Exposes collateral calculations to rpc

* Adds commands and testing for rpcserver.go functions

* Increase testing and fix up backtester code

* Returns cool changes to original branch

* end of day fixes

* Fixing some tests

* Fixing tests 🎉

* Fixes all the tests

* Splits the backtester setup and running into different files

* Merge, minor fixes

* Messing with some strategy updates

* Failed understanding at collateral usage

* Begins the creation of cash and carry strategy

* Adds underlying pair, adds filldependentevent for futures

* Completes fill prerequsite event implementation. Can't short though

* Some bug fixes

* investigating funds

* CAN NOW CREATE A SHORT ORDER

* Minor change in short size

* Fixes for unrealised PNL & collateral rendering

* Fixes lint and tests

* Adds some verbosity

* Updates to pnl calc

* Tracks pnl for short orders, minor update to strategy

* Close and open event based on conditions

* Adds pnl data for currency statistics

* Working through PNL calculation automatically. Now panics

* Adds tracking, is blocked from design

* Work to flesh out closing a position

* vain attempts at tracking zeroing out bugs

* woww, super fun new subloggers 🎉

* Begins attempt at automatically handling contracts and collateral based on direction

* Merge master + fixes

* Investigating issues with pnl and holdings

* Minor pnl fixes

* Fixes future position sizing, needs contract sizing

* Can render pnl results, focussing on funding statistics

* tracking candles for futures, but why not btc

* Improves funding statistics

* Colours and stats

* Fixes collateral and snapshot bugs

* Completes test

* Fixes totals bug

* Fix double buy, expand stats, fixes usd totals, introduce interface

* Begins report formatting and calculations

* Appends pnl to receiving curr. Fixes map[time]. accurate USD

* Improves report output rendering

* PNL stats in report. New tests for futures

* Fixes existing tests before adding new coverage

* Test coverage

* Completes portfolio coverage

* Increase coverage exchange, portfolio. fix size bug. NEW CHART

* WHAT IS GOING ON WITH PNL

* Fixes PNL calculation. Adds ability to skip om futures tracking

* minor commit before merge

* Adds basic liquidation to backtester

* Changes liquidation to order based

* Liquidationnnnnn

* Further fleshes out liquidations

* Completes liquidations in a honorable manner. Adds AppendReasonf

* Beginnings of spot futures gap chart. Needs to link currencies to render difference

* Removes fake liquidation. Adds cool new chart

* Fixes somet tests,allows for zero fee value v nil distinction,New tests

* Some annoying test fixes that took too long

* portfolio coverage

* holding coverage, privatisation funding

* Testwork

* boring tests

* engine coverage

* More backtesting coverage

* Funding, strategy, report test coverage

* Completes coverage of report package

* Documentation, fixes some assumptions on asset errors

* Changes before master merge

* Lint and Tests

* defaults to non-coloured rendering

* Chart rendering

* Fixes surprise non-local-lints

* Niterinos to the extremeos

* Fixes merge problems

* The linter splintered across the glinting plinths

* Many nits addressed. Now sells spot position on final candle

* Adds forgotten coverage

* Adds ability to size futures contracts to match spot positions.

* fixes order sell sizing

* Adds tests to sizing. Fixes charting issue

* clint splintered the linters with flint

* Improves stats, stat rendering

* minifix

* Fixes tests and fee bug

* Merge fixeroos

* Microfixes

* Updates orderPNL on first Correctly utilises fees. Adds committed funds

* New base funcs. New order summary

* Fun test updates

* Fix logo colouring

* Fixes niteroonies

* Fix report

* BAD COMMIT

* Fixes funding issues.Updates default fee rates.Combines cashcarry case

* doc regen

* Now returns err

* Fixes sizing bug issue introduced in PR

* Fixes fun fee/total US value bug

* Fix chart bug. Show log charts with disclaimer

* sellside fee

* fixes fee and slippage view

* Fixed slippage price issue

* Fixes calculation and removes rendering

* Fixes stats and some rendering

* Merge fix

* Fixes merge issues

* go mod tidy, lint updates

* New linter attempt

* Version bump in appveyor and makefile

* Regex filename, config fixes, template h2 fixes

* Removes bad stats.

* neatens config builder. Moves filename generator

* Fixes issue where linter wants to fix my spelling

* Fixes pointers and starts
2022-06-30 15:43:41 +10:00

307 lines
9.8 KiB
Go

package statistics
import (
"encoding/json"
"fmt"
"time"
"github.com/thrasher-corp/gocryptotrader/backtester/common"
"github.com/thrasher-corp/gocryptotrader/backtester/eventhandlers/portfolio"
"github.com/thrasher-corp/gocryptotrader/backtester/eventhandlers/portfolio/compliance"
"github.com/thrasher-corp/gocryptotrader/backtester/eventhandlers/portfolio/holdings"
"github.com/thrasher-corp/gocryptotrader/backtester/eventtypes/fill"
"github.com/thrasher-corp/gocryptotrader/backtester/eventtypes/order"
"github.com/thrasher-corp/gocryptotrader/backtester/eventtypes/signal"
"github.com/thrasher-corp/gocryptotrader/currency"
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
"github.com/thrasher-corp/gocryptotrader/log"
)
// Reset returns the struct to defaults
func (s *Statistic) Reset() {
*s = Statistic{}
}
// SetupEventForTime sets up the big map for to store important data at each time interval
func (s *Statistic) SetupEventForTime(ev common.DataEventHandler) error {
if ev == nil {
return common.ErrNilEvent
}
ex := ev.GetExchange()
a := ev.GetAssetType()
p := ev.Pair()
s.setupMap(ex, a)
lookup := s.ExchangeAssetPairStatistics[ex][a][p]
if lookup == nil {
lookup = &CurrencyPairStatistic{
Exchange: ev.GetExchange(),
Asset: ev.GetAssetType(),
Currency: ev.Pair(),
UnderlyingPair: ev.GetUnderlyingPair(),
}
}
for i := range lookup.Events {
if lookup.Events[i].Offset == ev.GetOffset() {
return ErrAlreadyProcessed
}
}
lookup.Events = append(lookup.Events,
DataAtOffset{
DataEvent: ev,
Offset: ev.GetOffset(),
Time: ev.GetTime(),
},
)
s.ExchangeAssetPairStatistics[ex][a][p] = lookup
return nil
}
func (s *Statistic) setupMap(ex string, a asset.Item) {
if s.ExchangeAssetPairStatistics == nil {
s.ExchangeAssetPairStatistics = make(map[string]map[asset.Item]map[currency.Pair]*CurrencyPairStatistic)
}
if s.ExchangeAssetPairStatistics[ex] == nil {
s.ExchangeAssetPairStatistics[ex] = make(map[asset.Item]map[currency.Pair]*CurrencyPairStatistic)
}
if s.ExchangeAssetPairStatistics[ex][a] == nil {
s.ExchangeAssetPairStatistics[ex][a] = make(map[currency.Pair]*CurrencyPairStatistic)
}
}
// SetEventForOffset sets the event for the time period in the event
func (s *Statistic) SetEventForOffset(ev common.EventHandler) error {
if ev == nil {
return common.ErrNilEvent
}
if s.ExchangeAssetPairStatistics == nil {
return errExchangeAssetPairStatsUnset
}
exch := ev.GetExchange()
a := ev.GetAssetType()
p := ev.Pair()
offset := ev.GetOffset()
lookup := s.ExchangeAssetPairStatistics[exch][a][p]
if lookup == nil {
return fmt.Errorf("%w for %v %v %v to set signal event", errCurrencyStatisticsUnset, exch, a, p)
}
for i := len(lookup.Events) - 1; i >= 0; i-- {
if lookup.Events[i].Offset == offset {
return applyEventAtOffset(ev, lookup, i)
}
}
return fmt.Errorf("%w for event %v %v %v at offset %v", errNoRelevantStatsFound, exch, a, p, ev.GetOffset())
}
func applyEventAtOffset(ev common.EventHandler, lookup *CurrencyPairStatistic, i int) error {
switch t := ev.(type) {
case common.DataEventHandler:
lookup.Events[i].DataEvent = t
case signal.Event:
lookup.Events[i].SignalEvent = t
case order.Event:
lookup.Events[i].OrderEvent = t
case fill.Event:
lookup.Events[i].FillEvent = t
default:
return fmt.Errorf("unknown event type received: %v", ev)
}
lookup.Events[i].Time = ev.GetTime()
lookup.Events[i].ClosePrice = ev.GetClosePrice()
lookup.Events[i].Offset = ev.GetOffset()
return nil
}
// AddHoldingsForTime adds all holdings to the statistics at the time period
func (s *Statistic) AddHoldingsForTime(h *holdings.Holding) error {
if s.ExchangeAssetPairStatistics == nil {
return errExchangeAssetPairStatsUnset
}
lookup := s.ExchangeAssetPairStatistics[h.Exchange][h.Asset][h.Pair]
if lookup == nil {
return fmt.Errorf("%w for %v %v %v to set holding event", errCurrencyStatisticsUnset, h.Exchange, h.Asset, h.Pair)
}
for i := len(lookup.Events) - 1; i >= 0; i-- {
if lookup.Events[i].Offset == h.Offset {
lookup.Events[i].Holdings = *h
return nil
}
}
return fmt.Errorf("%v %v %v %w %v", h.Exchange, h.Asset, h.Pair, errNoDataAtOffset, h.Offset)
}
// AddPNLForTime stores PNL data for tracking purposes
func (s *Statistic) AddPNLForTime(pnl *portfolio.PNLSummary) error {
if pnl == nil {
return fmt.Errorf("%w requires PNL", common.ErrNilArguments)
}
if s.ExchangeAssetPairStatistics == nil {
return errExchangeAssetPairStatsUnset
}
lookup := s.ExchangeAssetPairStatistics[pnl.Exchange][pnl.Item][pnl.Pair]
if lookup == nil {
return fmt.Errorf("%w for %v %v %v to set pnl", errCurrencyStatisticsUnset, pnl.Exchange, pnl.Item, pnl.Pair)
}
for i := len(lookup.Events) - 1; i >= 0; i-- {
if lookup.Events[i].Offset == pnl.Offset {
lookup.Events[i].PNL = pnl
lookup.Events[i].Holdings.BaseSize = pnl.Result.Exposure
return nil
}
}
return fmt.Errorf("%v %v %v %w %v", pnl.Exchange, pnl.Item, pnl.Pair, errNoDataAtOffset, pnl.Offset)
}
// AddComplianceSnapshotForTime adds the compliance snapshot to the statistics at the time period
func (s *Statistic) AddComplianceSnapshotForTime(c compliance.Snapshot, e fill.Event) error {
if e == nil {
return common.ErrNilEvent
}
if s.ExchangeAssetPairStatistics == nil {
return errExchangeAssetPairStatsUnset
}
exch := e.GetExchange()
a := e.GetAssetType()
p := e.Pair()
lookup := s.ExchangeAssetPairStatistics[exch][a][p]
if lookup == nil {
return fmt.Errorf("%w for %v %v %v to set compliance snapshot", errCurrencyStatisticsUnset, exch, a, p)
}
for i := len(lookup.Events) - 1; i >= 0; i-- {
if lookup.Events[i].Offset == e.GetOffset() {
lookup.Events[i].Transactions = c
return nil
}
}
return fmt.Errorf("%v %v %v %w %v", e.GetExchange(), e.GetAssetType(), e.Pair(), errNoDataAtOffset, e.GetOffset())
}
// CalculateAllResults calculates the statistics of all exchange asset pair holdings,
// orders, ratios and drawdowns
func (s *Statistic) CalculateAllResults() error {
log.Info(common.Statistics, "calculating backtesting results")
s.PrintAllEventsChronologically()
currCount := 0
var finalResults []FinalResultsHolder
var err error
for exchangeName, exchangeMap := range s.ExchangeAssetPairStatistics {
for assetItem, assetMap := range exchangeMap {
for pair, stats := range assetMap {
currCount++
last := stats.Events[len(stats.Events)-1]
if last.PNL != nil {
s.HasCollateral = true
}
err = stats.CalculateResults(s.RiskFreeRate)
if err != nil {
log.Error(common.Statistics, err)
}
stats.FinalHoldings = last.Holdings
stats.InitialHoldings = stats.Events[0].Holdings
stats.FinalOrders = last.Transactions
s.StartDate = stats.Events[0].Time
s.EndDate = last.Time
stats.PrintResults(exchangeName, assetItem, pair, s.FundManager.IsUsingExchangeLevelFunding())
finalResults = append(finalResults, FinalResultsHolder{
Exchange: exchangeName,
Asset: assetItem,
Pair: pair,
MaxDrawdown: stats.MaxDrawdown,
MarketMovement: stats.MarketMovement,
StrategyMovement: stats.StrategyMovement,
})
s.TotalLongOrders += stats.LongOrders
s.TotalShortOrders += stats.ShortOrders
s.TotalBuyOrders += stats.BuyOrders
s.TotalSellOrders += stats.SellOrders
s.TotalOrders += stats.TotalOrders
if stats.ShowMissingDataWarning {
s.WasAnyDataMissing = true
}
}
}
}
s.FundingStatistics, err = CalculateFundingStatistics(s.FundManager, s.ExchangeAssetPairStatistics, s.RiskFreeRate, s.CandleInterval)
if err != nil {
return err
}
err = s.FundingStatistics.PrintResults(s.WasAnyDataMissing)
if err != nil {
return err
}
if currCount > 1 {
s.BiggestDrawdown = s.GetTheBiggestDrawdownAcrossCurrencies(finalResults)
s.BestMarketMovement = s.GetBestMarketPerformer(finalResults)
s.BestStrategyResults = s.GetBestStrategyPerformer(finalResults)
s.PrintTotalResults()
}
return nil
}
// GetBestMarketPerformer returns the best final market movement
func (s *Statistic) GetBestMarketPerformer(results []FinalResultsHolder) *FinalResultsHolder {
var result FinalResultsHolder
for i := range results {
if results[i].MarketMovement.GreaterThan(result.MarketMovement) || result.MarketMovement.IsZero() {
result = results[i]
}
}
return &result
}
// GetBestStrategyPerformer returns the best performing strategy result
func (s *Statistic) GetBestStrategyPerformer(results []FinalResultsHolder) *FinalResultsHolder {
result := &FinalResultsHolder{}
for i := range results {
if results[i].StrategyMovement.GreaterThan(result.StrategyMovement) || result.StrategyMovement.IsZero() {
result = &results[i]
}
}
return result
}
// GetTheBiggestDrawdownAcrossCurrencies returns the biggest drawdown across all currencies in a backtesting run
func (s *Statistic) GetTheBiggestDrawdownAcrossCurrencies(results []FinalResultsHolder) *FinalResultsHolder {
result := &FinalResultsHolder{}
for i := range results {
if results[i].MaxDrawdown.DrawdownPercent.GreaterThan(result.MaxDrawdown.DrawdownPercent) || result.MaxDrawdown.DrawdownPercent.IsZero() {
result = &results[i]
}
}
return result
}
func addEventOutputToTime(events []eventOutputHolder, t time.Time, message string) []eventOutputHolder {
for i := range events {
if events[i].Time.Equal(t) {
events[i].Events = append(events[i].Events, message)
return events
}
}
events = append(events, eventOutputHolder{Time: t, Events: []string{message}})
return events
}
// SetStrategyName sets the name for statistical identification
func (s *Statistic) SetStrategyName(name string) {
s.StrategyName = name
}
// Serialise outputs the Statistic struct in json
func (s *Statistic) Serialise() (string, error) {
resp, err := json.MarshalIndent(s, "", " ")
if err != nil {
return "", err
}
return string(resp), nil
}