utils

package
v0.1.30 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2025 License: AGPL-3.0 Imports: 57 Imported by: 2

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoNegativeResults is returned when no negative results are allowed
	ErrNoNegativeResults = errors.New("cannot calculate with no negative values")
)

Functions

func ArrToMap

func ArrToMap[T1 comparable, T2 any](arr []T2, doMap func(T2) T1) map[T1][]T2

func AutoCorrPenalty

func AutoCorrPenalty(returns []float64) float64

AutoCorrPenalty Metric to account for auto correlation

func BuildOHLCV

func BuildOHLCV(arr []*banexg.Kline, toTFMSecs int64, preFire float64, resOHLCV []*banexg.Kline, fromTFMS, offMS int64) ([]*banexg.Kline, bool)

BuildOHLCV Build or update coarser grained OHLC arrays from transactions or sub OHLC arrays. Arr: List of sub OHLC. ToTFSecs: Specify the time granularity to be built, in milliseconds PreFire: The rate at which builds are triggered ahead of schedule; ResOHLCV: Existing array to be updated From TFSets: The interval between the arr subarrays passed in, calculated when not provided, in milliseconds OffMS: offset of alignment time 从交易或子OHLC数组中,构建或更新更粗粒度OHLC数组。 arr: 子OHLC列表。 toTFSecs: 指定要构建的时间粒度,单位:毫秒 preFire: 提前触发构建完成的比率; resOHLCV: 已有的待更新数组 fromTFSecs: 传入的arr子数组间隔,未提供时计算,单位:毫秒 offMS: 对齐时间的偏移

func CalcCorrMat

func CalcCorrMat(arrLen int, dataArr [][]float64, useChgRate bool) (*mat.SymDense, []float64, error)

CalcCorrMat calculate Correlation Matrix for given data

func CalcEnvsCorr added in v0.1.7

func CalcEnvsCorr(envs []*ta.BarEnv, hisNum int) (*mat.SymDense, []float64, error)

func CalcExpectancy

func CalcExpectancy(profits []float64) (float64, float64)

CalcExpectancy Calculate expected returns and risk return ratio 计算收益期望、风险回报率

func CalcMaxDrawDown

func CalcMaxDrawDown(profits []float64, initBalance float64) (float64, float64, int, int, float64, float64)

CalcMaxDrawDown Calculate maximum drawdown Calculate the maximum drawdown percentage position when initBalance is provided; No location provided for calculating the maximum loss Return: Maximum drawdown percentage, maximum drawdown amount, maximum value index, minimum value index, maximum value, minimum value 计算最大回撤 initBalance 提供时计算最大回撤百分比位置;未提供计算亏损最多时位置 返回:最大回撤百分比、最大回撤额、最大值索引、最小值索引、最大值、最小值

func Check

func Check(err error)

func ConvertArr

func ConvertArr[T1, T2 any](arr []T1, doMap func(T1) T2) []T2

func ConvertFloat64

func ConvertFloat64(i interface{}) float64

func ConvertInt64

func ConvertInt64(i interface{}) int64

func Copy

func Copy(srcFile, dstFile string) error

func CopyDir

func CopyDir(src, dst string) error
func CopySymLink(source, dest string) error

func CreateNumFile added in v0.1.24

func CreateNumFile(outDir string, prefix string, ext string) (*os.File, error)

func CutMap

func CutMap[M ~map[K]V, K comparable, V any](m M, keys ...K) M

func DecArithMean

func DecArithMean(values []decimal.Decimal) (decimal.Decimal, error)

DecArithMean is the basic form of calculating an average. Divide the sum of all values by the length of values

func DecArrToFloats

func DecArrToFloats(arr []decimal.Decimal) []float64

func DecFinaGeomMean

func DecFinaGeomMean(values []decimal.Decimal) (decimal.Decimal, error)

DecFinaGeomMean is a modified geometric average to assess the negative returns of investments. It accepts It adds +1 to each This does impact the final figures as it is modifying values It is still ultimately calculating a geometric average which should only be compared to other financial geometric averages

func DecPow

func DecPow(x, y decimal.Decimal) decimal.Decimal

DecPow is lovely because shopspring decimal cannot handle ^0.x and instead returns 1

func DecSharpeRatio

func DecSharpeRatio(moReturns []decimal.Decimal, riskFree decimal.Decimal) (decimal.Decimal, error)

DecSharpeRatio use 252 as default periods to calculate annualize

func DecSharpeRatioAdv

func DecSharpeRatioAdv(moReturns []decimal.Decimal, riskFree decimal.Decimal, periods int, annualize, smart bool) (decimal.Decimal, error)

func DecSharpeRatioBy

func DecSharpeRatioBy(moReturns []decimal.Decimal, riskFree decimal.Decimal, periods int, annualize bool) (decimal.Decimal, error)

func DecSharpeRatioSmart

func DecSharpeRatioSmart(moReturns []decimal.Decimal, riskFree decimal.Decimal, periods int, annualize bool) (decimal.Decimal, error)

func DecSortinoRatio

func DecSortinoRatio(moReturns []decimal.Decimal, riskFree decimal.Decimal) (decimal.Decimal, error)

func DecSortinoRatioAdv

func DecSortinoRatioAdv(moReturns []decimal.Decimal, riskFree decimal.Decimal, periods int, annualize, smart bool) (decimal.Decimal, error)

DecSortinoRatioAdv returns sortino ratio of backtest compared to risk-free

func DecSortinoRatioBy

func DecSortinoRatioBy(moReturns []decimal.Decimal, riskFree decimal.Decimal, periods int, annualize bool) (decimal.Decimal, error)

func DecSortinoRatioSmart

func DecSortinoRatioSmart(moReturns []decimal.Decimal, riskFree decimal.Decimal, periods int, annualize bool) (decimal.Decimal, error)

func DecStdDev

func DecStdDev(values []decimal.Decimal) (decimal.Decimal, error)

DecStdDev calculates standard deviation using population based calculation

func DeepCopyMap

func DeepCopyMap(dst, src map[string]interface{})

func DelNetLock

func DelNetLock(key string, lockVal int32) *errs.Error

func DoHttp

func DoHttp(client *http.Client, req *http.Request) *banexg.HttpRes

func EnsureDir

func EnsureDir(dir string, perm os.FileMode) error

func EqualIn

func EqualIn(a, b, thres float64) bool

EqualIn Determine whether two floats are approximately equal within a certain range 判断两个float是否在一定范围内近似相等

func EqualNearly

func EqualNearly(a, b float64) bool

EqualNearly Determine whether two floats are approximately equal and solve the problem of inequality caused by floating-point close reading 判断两个float是否近似相等,解决浮点精读导致不等

func Exists

func Exists(filePath string) bool

func FindSubPath added in v0.1.12

func FindSubPath(parDir, tgtName string, maxDepth int) (string, error)

FindSubPath searches for the first occurrence of a directory named tgtName within the specified workDir and its subdirectories up to two levels deep.

func FloatsToDecArr

func FloatsToDecArr(arr []float64) []decimal.Decimal

func FormatWithMap

func FormatWithMap(text string, args map[string]interface{}) string

func GcdInts

func GcdInts(numbers []int) int

GcdMultiple Calculate the greatest common divisor of all elements in a slice 计算一个切片中所有元素的最大公约数

func GenCorrImg

func GenCorrImg(m *mat.SymDense, title string, names []string, fontName string, fontSize float64) ([]byte, error)

func GetFilesWithPrefix added in v0.1.7

func GetFilesWithPrefix(filePath string) ([]string, error)

func GetFontData

func GetFontData(name string) ([]byte, error)

func GetNetLock

func GetNetLock(key string, timeout int) (int32, *errs.Error)

func GetOpenFont

func GetOpenFont(name string) (*opentype.Font, error)

func GetServerData

func GetServerData(key string) (string, *errs.Error)

func GetSystemLanguage added in v0.1.25

func GetSystemLanguage() string

GetSystemLanguage returns the current system language code. Possible return values (ISO 639-1 with optional ISO 3166-1 country code): - en-US: English - zh-CN: Chinese (Simplified) ...

func IntToBytes added in v0.1.24

func IntToBytes(n uint32) ([]byte, error)

IntToBytes convert uint32 to [4]byte

func IsDocker added in v0.1.14

func IsDocker() bool

func IsTextContent added in v0.1.12

func IsTextContent(data []byte) bool

IsTextContent 检查字节数组是否可能是文本内容 返回 true 表示可能是文本内容,false 表示可能是二进制内容

func KeysOfMap

func KeysOfMap[M ~map[K]V, K comparable, V any](m M) []K

func KlineToStr

func KlineToStr(klines []*banexg.Kline, loc *time.Location) [][]string

func MD5 added in v0.1.7

func MD5(data []byte) string

func MapToStr

func MapToStr(m map[string]float64) (string, int)

func MergeYamlStr added in v0.1.12

func MergeYamlStr(paths []string, skips ...string) (string, error)

MergeYamlStr 合并多个yaml文件内容,保持键的顺序

func MovePath added in v0.1.12

func MovePath(src, tgt string) error

func NanInfTo added in v0.1.12

func NanInfTo(v, to float64) float64

func NearScore

func NearScore(x, mid, rate float64) float64

NearScore Formula: y=e ^ - abs (x-a) At the given maxAt, i.e. a, y takes its maximum value of 1, x moves towards both sides, y gradually approaches 0, and the slope decreases from large to small The default rate is 1, and when x is offset by 40, it decays by 70%; When rate>1, attenuation accelerates 公式:y=e^-abs(x-a) 在给定的maxAt即a处,y取最大值1,x向两侧移动,y逐渐趋近于0,斜率由大变小 rate默认1,x偏移40时,衰减70%;rate>1时,衰减加速

func NumSign

func NumSign(obj interface{}) int

NumSign Obtain the direction of numbers; 1, -1 or 0 获取数字的方向;1,-1或0

func OpenBrowser added in v0.1.22

func OpenBrowser(url string) error

func OpenBrowserDelay added in v0.1.22

func OpenBrowserDelay(url string, delayMS int)

func PadCenter

func PadCenter(s string, width int, padText string) string

func ParallelRun

func ParallelRun[T any](items []T, concurNum int, handle func(int, T) *errs.Error) *errs.Error

func PrintErr

func PrintErr(e error) string

func RandomStr added in v0.1.8

func RandomStr(length int) string

func ReadCSV

func ReadCSV(path string) ([][]string, *errs.Error)

func ReadConfirm

func ReadConfirm(tips []string, ok, fail string, exitAny bool) bool

func ReadInput

func ReadInput(tips []string) (string, error)

func ReadLastNLines

func ReadLastNLines(filePath string, lineCount int) ([]string, error)

func ReadTextFile added in v0.1.12

func ReadTextFile(path string) (string, *errs.Error)

func ReadXlsx

func ReadXlsx(path, sheet string) ([][]string, *errs.Error)

ReadXlsx use first if `sheet` is empty

func RemoveFromArr

func RemoveFromArr[T comparable](arr []T, it T, num int) []T

func ReverseArr

func ReverseArr[T any](s []T)

func SetServerData

func SetServerData(args *KeyValExpire) *errs.Error

func SharpeRatio

func SharpeRatio(moReturns []float64, riskFree float64) (float64, error)

func SharpeRatioAdv

func SharpeRatioAdv(moReturns []float64, riskFree float64, periods int, annualize, smart bool) (float64, error)

func SharpeRatioBy

func SharpeRatioBy(moReturns []float64, riskFree float64, periods int, annualize bool) (float64, error)

func SharpeRatioSmart

func SharpeRatioSmart(moReturns []float64, riskFree float64, periods int, annualize bool) (float64, error)

func SnakeToCamel

func SnakeToCamel(input string) string

func SortinoRatio

func SortinoRatio(moReturns []float64, riskFree float64) (float64, error)

func SortinoRatioAdv

func SortinoRatioAdv(moReturns []float64, riskFree float64, periods int, annualize, smart bool) (float64, error)

func SortinoRatioBy

func SortinoRatioBy(moReturns []float64, riskFree float64, periods int, annualize bool) (float64, error)

func SortinoRatioSmart

func SortinoRatioSmart(moReturns []float64, riskFree float64, periods int, annualize bool) (float64, error)

func SplitLines added in v0.1.23

func SplitLines(text string) []string

func SplitSolid

func SplitSolid(text string, sep string) []string

SplitSolid String segmentation, ignore empty strings in the return result 字符串分割,忽略返回结果中的空字符串

func StdDevVolatility

func StdDevVolatility(data []float64, rate float64) float64

StdDevVolatility Calculate the standard deviation of K-line volatility Data: It should be a set of numbers with a slight fluctuation above and below the mean of 1 Rate: default 1. If you need to enlarge the difference, pass in a value between 1-1000 计算K线的波动性标准差

data: 应该是均值为1的上下轻微浮动的一组数
rate: 默认1,如需要放大差异,则传入1~1000之间的值

func UnionArr

func UnionArr[T comparable](arrs ...[]T) []T

func UniqueItems

func UniqueItems[T comparable](arr []T) ([]T, []T)

func ValsOfMap

func ValsOfMap[M ~map[K]V, K comparable, V any](m M) []V

func WriteCsvFile

func WriteCsvFile(path string, rows [][]string, compress bool) *errs.Error

func WriteFile

func WriteFile(path string, data []byte) *errs.Error

Types

type BanConn

type BanConn struct {
	Conn      net.Conn          // Original socket connection 原始的socket连接
	Tags      map[string]bool   // Message subscription list 消息订阅列表
	Remote    string            // Remote Name 远端名称
	Listens   map[string]ConnCB // Message processing function 消息处理函数
	RefreshMS int64             // Connection ready timestamp 连接就绪的时间戳
	Ready     bool
	IsReading bool

	DoConnect  func(conn *BanConn) // Reconnect function, no attempt to reconnect provided 重新连接函数,未提供不尝试重新连接
	ReInitConn func()              // Initialize callback function after successful reconnection 重新连接成功后初始化回调函数
	// contains filtered or unexported fields
}

func (*BanConn) GetRemote

func (c *BanConn) GetRemote() string

func (*BanConn) HasTag

func (c *BanConn) HasTag(tag string) bool

func (*BanConn) IsClosed

func (c *BanConn) IsClosed() bool

func (*BanConn) LoopPing added in v0.1.12

func (c *BanConn) LoopPing(intvSecs int)

func (*BanConn) Read

func (c *BanConn) Read() ([]byte, *errs.Error)

func (*BanConn) ReadMsg

func (c *BanConn) ReadMsg() (*IOMsgRaw, *errs.Error)

func (*BanConn) RunForever

func (c *BanConn) RunForever() *errs.Error

RunForever Monitor the information sent by the connection and process it. According to the action of the message: Call the corresponding member function for processing; Directly input msd_data Or find the corresponding processing function from listeners. If there is an exact match, pass msd_data. Otherwise, pass action and msd_data Both the server-side and client-side will call this method 监听连接发送的信息并处理。 根据消息的action:

调用对应成员函数处理;直接传入msg_data
或从listens中找对应的处理函数,如果精确匹配,传入msg_data,否则传入action, msg_data

服务器端和客户端都会调用此方法

func (*BanConn) Subscribe

func (c *BanConn) Subscribe(tags ...string)

func (*BanConn) UnSubscribe

func (c *BanConn) UnSubscribe(tags ...string)

func (*BanConn) Write

func (c *BanConn) Write(data []byte, locked bool) *errs.Error

func (*BanConn) WriteMsg

func (c *BanConn) WriteMsg(msg *IOMsg) *errs.Error

type ClientIO

type ClientIO struct {
	BanConn
	Addr string
	// contains filtered or unexported fields
}

func NewClientIO

func NewClientIO(addr string) (*ClientIO, *errs.Error)

func (*ClientIO) GetVal

func (c *ClientIO) GetVal(key string, timeout int) (string, *errs.Error)

func (*ClientIO) SetVal

func (c *ClientIO) SetVal(args *KeyValExpire) *errs.Error

type Cluster

type Cluster struct {
	Center float64
	Items  []float64
}

type ClusterRes

type ClusterRes struct {
	Clusters []*Cluster
	RowGIds  []int
}

func KMeansVals

func KMeansVals(vals []float64, num int) *ClusterRes

type ConnCB

type ConnCB = func(string, []byte)

type FnTaskPrg added in v0.1.21

type FnTaskPrg = func(task string, rate float64)

type IBanConn

type IBanConn interface {
	WriteMsg(msg *IOMsg) *errs.Error
	Write(data []byte, locked bool) *errs.Error
	ReadMsg() (*IOMsgRaw, *errs.Error)
	Subscribe(tags ...string)
	UnSubscribe(tags ...string)
	GetRemote() string
	IsClosed() bool
	HasTag(tag string) bool
	RunForever() *errs.Error
}

type IOKeyVal

type IOKeyVal struct {
	Key string `json:"key"`
	Val string `json:"val"`
}

type IOMsg

type IOMsg struct {
	Action string      `json:"action"`
	Data   interface{} `json:"data"`
}

type IOMsgRaw added in v0.1.12

type IOMsgRaw struct {
	Action string          `json:"action"`
	Data   json.RawMessage `json:"data"`
}

type KeyValExpire

type KeyValExpire struct {
	Key        string
	Val        string
	ExpireSecs int `json:"expireSecs"`
}

type PrgBar

type PrgBar struct {
	DoneNum  int
	TotalNum int
	Last     int64 // for outer usage
	PrgCbs   []PrgCB
	// contains filtered or unexported fields
}

func NewPrgBar

func NewPrgBar(totalNum int, title string) *PrgBar

func (*PrgBar) Add

func (p *PrgBar) Add(num int)

func (*PrgBar) Close

func (p *PrgBar) Close()

func (*PrgBar) NewJob

func (p *PrgBar) NewJob(num int) *PrgBarJob

type PrgBarJob

type PrgBarJob struct {
	*PrgBar
	// contains filtered or unexported fields
}

func (*PrgBarJob) Add

func (j *PrgBarJob) Add(num int)

func (*PrgBarJob) Done

func (j *PrgBarJob) Done()

type PrgCB added in v0.1.12

type PrgCB = func(done int, total int)

type PrgTask added in v0.1.21

type PrgTask struct {
	ID       int
	Name     string
	Progress float64
	Weight   float64
}

type ServerIO

type ServerIO struct {
	Addr     string
	Name     string
	Conns    []IBanConn
	Data     map[string]string // Cache data available for remote access 缓存的数据,可供远程端访问
	DataExp  map[string]int64  // Cache data expiration timestamp, 13 bits 缓存数据的过期时间戳,13位
	InitConn func(*BanConn)
}

func NewBanServer

func NewBanServer(addr, name string) *ServerIO

func (*ServerIO) Broadcast

func (s *ServerIO) Broadcast(msg *IOMsg) *errs.Error

func (*ServerIO) GetVal

func (s *ServerIO) GetVal(key string) string

func (*ServerIO) RunForever

func (s *ServerIO) RunForever() *errs.Error

func (*ServerIO) SetVal

func (s *ServerIO) SetVal(args *KeyValExpire)

func (*ServerIO) WrapConn

func (s *ServerIO) WrapConn(conn net.Conn) *BanConn

type StagedPrg added in v0.1.21

type StagedPrg struct {
	Progress float64 // [0,1]
	// contains filtered or unexported fields
}

func NewStagedPrg added in v0.1.21

func NewStagedPrg(tasks []string, weights []float64) *StagedPrg

NewStagedPrg 创建多任务复合进度提示器 tasks: 子任务代码列表,按执行顺序,不可重复 weights: 各个子任务权重,>0,内部会自动归一化

func (*StagedPrg) AddTrigger added in v0.1.21

func (p *StagedPrg) AddTrigger(name string, cb FnTaskPrg)

func (*StagedPrg) DelTrigger added in v0.1.21

func (p *StagedPrg) DelTrigger(name string)

func (*StagedPrg) SetMinInterval added in v0.1.21

func (p *StagedPrg) SetMinInterval(intvMSecs int)

func (*StagedPrg) SetProgress added in v0.1.21

func (p *StagedPrg) SetProgress(task string, progress float64)

Jump to

Keyboard shortcuts

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