dsl

package
v0.0.0-...-0cf2214 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 27 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package dsl 定义策略 DSL 的数据结构、严格解析、校验与表达式编译。

DSL 只描述截面上的选股与配权逻辑:规则是列表,每条规则有稳定的 id、展示用的 name 和 固定词表的 type(rank 截面选股)。时序计算一律在因子层完成, 策略表达式只在当期一帧数据上求值,可选地引用上一根(bars[-1])。

Index

Constants

View Source
const (
	CalendarTradingDays = "trading_days"
	CalendarWeek        = "week"
	CalendarMonth       = "month"

	// HoldingAtFirst、HoldingAtLast 是日内帧上建仓所在的那一根:交易日的第一根或最后一根(默认)。
	HoldingAtFirst = "first"
	HoldingAtLast  = "last"

	// HoldingOffsetsAll 是 holding.offsets 的简写:每根都建一个批次,解析时展开成 0 到 bars-1。
	HoldingOffsetsAll = "all"
)

holding.calendar 的取值:按交易日计数的周期、自然周、自然月。

View Source
const (
	MarketSpot   = "spot"
	MarketSwap   = "swap"
	MarketBoth   = "both"
	MarketEquity = "equity"
)

市场取值。select 可以是 spot、swap、both,prefer 可以是 spot、swap;equity 只由绑定解析写入(股票不允许在 DSL 里写 market)。

View Source
const (
	// AllocationFixed 按 allocation.ratios 的固定比例分配。
	AllocationFixed = "fixed"
	// AllocationRotation 按成员净值序列上的轮动因子排名,取前 top 名平分。
	AllocationRotation = "rotation"

	// 轮动因子(都作用在成员净值序列上)。
	FactorReturn   = "return"   // 区间收益:净值 ÷ window 期之前的净值 − 1
	FactorMARatio  = "ma_ratio" // 净值 ÷ window 期均线 − 1
	FactorDrawdown = "drawdown" // window 期区间的最大回撤,越小越好

	// OrderAsc、OrderDesc 是轮动因子的排序方向:降序时因子值大的名次靠前。
	OrderAsc  = "asc"
	OrderDesc = "desc"

	// MaxPoolMembers 是策略池成员数的上限:每个成员每期各自求值并各自维护账本。
	MaxPoolMembers = 20
	// MaxPoolWindow 是轮动因子与择时窗口的上限(预热要把它们读满)。
	MaxPoolWindow = 2016
	// MaxPoolFeeBps 是成员账本手续费的上限(基点)。
	MaxPoolFeeBps = 1000

	// 成员账本手续费的默认值(基点),与研究回放界面的默认值一致。
	DefaultPoolSpotFeeBps   = 10
	DefaultPoolSwapFeeBps   = 5
	DefaultPoolEquityFeeBps = 3
)
View Source
const (
	AdjustAuto         = "auto"          // 总敞口大于 pivot 时同 reduce_larger,否则同 raise_smaller
	AdjustReduceLarger = "reduce_larger" // 缩小超出方向的一侧:净敞口高于 max 时缩多头,低于 min 时缩空头
	AdjustRaiseSmaller = "raise_smaller" // 放大另一侧:净敞口高于 max 时放大空头,低于 min 时放大多头
)

净敞口区间超出时的修正方式。

View Source
const (
	// AllocationDrift 让分配系数随成员持仓的名义价值漂移,再按 allocation.sides 侧内再平衡。
	AllocationDrift = "drift"

	// 侧内再平衡的方式。
	RebalanceNone      = "none"      // 不再平衡(默认)
	RebalanceEveryBar  = "every_bar" // 每根拉回目标构成
	RebalancePeriodic  = "periodic"  // 从 anchor 起每 period_bars 根触发一次
	RebalanceThreshold = "threshold" // 任一成员的侧内占比相对目标偏离超过 threshold 时触发
	RebalanceBoth      = "both"      // periodic 与 threshold 都开

	// 侧内构成的漂移口径。
	DriftByNotional = "notional" // 按持仓名义价值漂移(默认)
	DriftByNAV      = "nav"      // 按成员资金收益漂移,盈利的成员占比变大
)
View Source
const (
	// MaxScale 是 scale.max 的上限。
	MaxScale = 10.0
	// MaxKeepBars 是 on_missing.keep_bars 的上限。
	MaxKeepBars = 1000
)

仓位系数与缺数冻结的取值范围。

View Source
const (
	CountRoundFloor = "floor"
	CountRoundCeil  = "ceil"
	CountRoundRound = "round"
)

比例换算个数的取整方式。

View Source
const (
	StopPriceClose   = "close"   // 判断与更新最有利价格都用本期 close
	StopPriceExtreme = "extreme" // 止损看不利方向的极值、止盈与最有利价格看有利方向的极值(多头 low/high,空头 high/low)

)

止损止盈(设计 4.1):写在规则上。按 K 线收盘判断,触发后平掉该持仓单位。

View Source
const (
	// RuleTypeRank 是截面选股规则:filter → score → select → weight → filter_after。
	RuleTypeRank = "rank"

	SideLong  = "long"
	SideShort = "short"

	// WeightMethodEqual 让选中标的平分规则预算。
	WeightMethodEqual = "equal"
	// WeightMethodRank 按名次线性配权:最优 N 份、最差 1 份,方向与 select 一致。
	WeightMethodRank = "rank"

	// DefaultMaxMissing 是缺数守门的默认阈值:缺数标的占预期集合的比例超过它则整期跳过。
	DefaultMaxMissing = "0.2"
)
View Source
const (
	AgeMarketsEach = "each"
	AgeMarketsAll  = "all"
)

universe.age_markets 的取值:each(默认)按标的在下单市场上的数据判断年龄;all 要求在实例绑定的全部市场上都通过。

View Source
const (
	// MaxCount 是 min_age_bars、min_universe、select.top / bottom / buffer 与 holding.bars 的上限。
	MaxCount = 10000
	// MaxHoldingOffsets 是 holding.offsets 个数的上限:每个批次都随规则状态逐期保存。
	MaxHoldingOffsets = 64
)

取值上限:超出这些量级的写法没有实际意义,却会让时间换算溢出、权重变成天文数字。

View Source
const MaxGroupQuotas = 64

MaxGroupQuotas 是 select.group.quotas 的个数上限。

View Source
const MaxLimitRounds = 3

MaxLimitRounds 是超限转移的最多轮数:分配后又超限的部分再分一轮,三轮之后剩下的留现金。

View Source
const MaxSources = 2

MaxSources 是附加来源的个数上限。

Variables

View Source
var MaxLeverage = quant.Must("10")

MaxLeverage 是 portfolio.leverage 的上限(各规则 weight.total 之和不超过 leverage,因此也限住了权重)。

Functions

func ColumnsBySource

func ColumnsBySource(columns []string) map[string][]string

ColumnsBySource 把帧里的列名按来源分组:键为空串的是主帧的列,其余键是来源名,值是去掉来源前缀的列名(排序)。

func Hash

func Hash(raw []byte) string

Hash 返回 DSL 文本的内容哈希,作为定义版本标识。

func InferPoolMemberMarkets

func InferPoolMemberMarkets(members map[string]Strategy, boundEquity bool) (map[string]Strategy, error)

InferPoolMemberMarkets 在启用时按池绑定的任务确定没写 market 的成员的市场:绑的是 equity 任务就是股票成员,否则拒绝 (加密成员必须显式写 market)。返回填好市场的成员副本,members 不变。

func MemberSides

func MemberSides(pool StrategyPool, members map[string]Strategy) map[string]string

MemberSides 返回各成员的方向(成员 id → long、short;混合方向的成员为空串),池的组合约束按它汇总多头与空头敞口。

func PoolWarmBars

func PoolWarmBars(pool Strategy, members []Strategy, clock BarClock) int

PoolWarmBars 是策略池预热需要推进的期数:轮动因子与择时里最长的窗口、成员里最长的持有期(含 hold.max_bars 与日历周期), 取大者再加 1。窗口决定成员净值序列要读满多少期;持有期决定长持有期的成员从空仓起步时前段净值的偏差要多久才消化,所以也要算进去。

func ReferencedColumns

func ReferencedColumns(strategy Strategy) ([]string, error)

ReferencedColumns 在不知道 View 列的情况下返回 DSL 引用的全部列名(当期与上一根的并集)。 用于启用前的列解析与提示。

func RuleMarket

func RuleMarket(mode Market, rule Rule) string

RuleMarket 返回规则在模式 mode 下实际使用的规则级市场:只有模式涉及两个市场时才生效,单市场模式下(规则 market 只能与策略相同)返回空串, 与没写相同。

func SourceColumn

func SourceColumn(source, column string) string

SourceColumn 返回来源列在帧里的名字:来源名.列名。整个管线(编译、缺数划分、冻结、解释明细)都用这个名字。

func SplitSourceColumn

func SplitSourceColumn(name string) (source, column string)

SplitSourceColumn 把帧里的列名拆成来源名与列名;主帧的列返回空来源名。

func SplitTaskKey

func SplitTaskKey(key string) (source, market string)

SplitTaskKey 把任务键拆成来源名与市场;主帧与参考市场的键返回空来源名。

func SpotLike

func SpotLike(market string) bool

SpotLike 报告市场按现货规则约束:现货与股票都不能做空、不能加杠杆。

func TaskKey

func TaskKey(source, market string) string

TaskKey 返回实例登记因子任务用的键:主帧与参考市场的任务就是市场,附加来源的任务是 来源名:市场。

func ValidColumnName

func ValidColumnName(name string) bool

ValidColumnName 报告 name 是普通列名(不是表达式,也不是以 __ 开头的内部列)。

func ValidSourceName

func ValidSourceName(name string) bool

ValidSourceName 报告来源名的写法合法:小写字母开头的 snake_case,且不是表达式的保留标识符。

func Validate

func Validate(s *Strategy) error

Validate 校验结构、字段取值和表达式语法;不需要知道 View 的列,列的存在性在 Compile 时检查。 校验会就地规范化 side 与 method 的默认值;portfolio 的默认值在解析时填入,显式写出的 0 按原值校验。

func ValidateMode

func ValidateMode(s Strategy, mode Market) error

ValidateMode 校验策略与有效市场模式(DSL 写出的,或没写时按绑定任务的市场取的默认值)能否同时成立: 纯现货与股票不能做空、不能加杠杆。 绑定了任务之后、启用与试算之前调用。

func ValidatePoolMember

func ValidatePoolMember(pool Strategy, id string, member Strategy) error

ValidatePoolMember 校验一个成员策略能不能进池:不能是池(不嵌套)、不能用 factor_params、写了 bar 的要与池一致。 加密成员必须显式写 market;股票策略不允许写 market,保存时分不出来,没写 market 的成员一律放行,启用时按池绑定的任务判断 (绑的是 equity 任务就按股票成员处理,否则拒绝,见 InferPoolMemberMarkets)。

Types

type Anchor

type Anchor struct {
	Date marketcalendar.CivilDate
	At   time.Time
}

Anchor 是解析后的锚点:Date 非零表示写的是交易日期(该日第一根),否则 At 是 RFC3339 时刻(某根的 bar_start)。

func ParseAnchor

func ParseAnchor(text string) (Anchor, error)

ParseAnchor 解析 holding.anchor:RFC3339 时刻,或交易日期 YYYY-MM-DD。

type BarClock

type BarClock struct {
	PerDay int
	Stock  bool
}

BarClock 是换算日历周期用的每日根数:PerDay 是一个交易日的 bar 数,Stock 为真表示 A 股交易日历(周、月按交易日估算)。

type CompiledParam

type CompiledParam struct {
	Member     string
	Name       string
	Default    *Expression
	PerSubject *Expression
}

CompiledParam 是一个参数输出的已编译表达式。

func (CompiledParam) Columns

func (p CompiledParam) Columns() []string

Columns 返回参数表达式引用的全部当期列。

func (CompiledParam) PreviousColumns

func (p CompiledParam) PreviousColumns() []string

PreviousColumns 返回参数表达式经 bars[-1] 引用的列。

type CompiledRule

type CompiledRule struct {
	Rule        Rule
	Filter      *Expression
	Score       *Expression
	SelectWhere *Expression
	FilterAfter *Expression
	ThenScore   *Expression
	HoldEntry   *Expression
	HoldExit    *Expression
	Scale       *Expression
}

CompiledRule 是一条规则及其各阶段已编译的表达式。

func (*CompiledRule) Columns

func (r *CompiledRule) Columns() []string

Columns 返回该规则引用的全部当期列。

func (*CompiledRule) Expressions

func (r *CompiledRule) Expressions() []*Expression

Expressions 按固定顺序返回非空的阶段表达式。

func (*CompiledRule) PreviousColumns

func (r *CompiledRule) PreviousColumns() []string

PreviousColumns 返回该规则通过 bars[-1] 引用的上一根列。

type ExposureBand

type ExposureBand struct {
	Min, Max                       float64
	Adjust                         string
	Pivot                          float64
	WhenGrossBelow, WhenGrossAbove float64
	HasBelow, HasAbove             bool
}

ExposureBand 是一段净敞口区间 [Min, Max]。HasBelow、HasAbove 为真时只在总敞口小于 WhenGrossBelow(大于 WhenGrossAbove)时执行; Pivot 只在 Adjust 为 auto 时使用。

type Expression

type Expression struct {
	Source          string
	Stage           Stage
	Rewritten       string
	Program         *vm.Program
	Normalizers     []*Normalizer
	ParamRefs       []ParamRef
	Columns         []string // 直接引用的当期列(不含截面函数参数内部的引用);来源列写作 来源名.列名
	PreviousColumns []string // 通过 bars[-1] 引用的上一根列
	// Sources 是直接引用的附加来源名(排序,不含截面函数参数内部的引用):求值环境里每个来源是一个 列名 → 值 的字典。
	Sources []string
	Numeric bool
}

Expression 是一条已分析(可选已编译)的表达式。

func Analyze

func Analyze(source string, stage Stage) (*Expression, error)

Analyze 解析并校验一条表达式,不编译。用于保存 DSL 时的语法检查。

func CompileExpression

func CompileExpression(source string, stage Stage, columns map[string]struct{}) (*Expression, error)

CompileExpression 分析并编译一条表达式。columns 是绑定 View 的全部列,引用不存在的列会报错。

func (*Expression) AllColumns

func (e *Expression) AllColumns() []string

AllColumns 返回包括截面函数参数在内的全部当期列。

func (*Expression) AllParamRefs

func (e *Expression) AllParamRefs() []ParamRef

AllParamRefs 返回包括截面函数参数在内的全部 params() 引用(去重,按成员键与参数名排序;Variable 取各自表达式里的变量名)。

func (*Expression) AllPreviousColumns

func (e *Expression) AllPreviousColumns() []string

AllPreviousColumns 返回包括截面函数参数在内的全部上一根列。

func (*Expression) Run

func (e *Expression) Run(env map[string]any) (any, error)

Run 对一行环境求值。env 由引擎构造:列名 → float64,bars → []map[string]float64{当期, 上一根}, score、instrument_id 与各 Normalizer.Variable。

type Hold

type Hold struct {
	Entry        string
	Exit         string
	MaxBars      int
	CooldownBars int
	// AllowReentry 为真时,候选只看 Entry:出场条件为真的标的也可以入场,本根刚出场的标的也可以当根补回(持有根数重新计)。
	// 只能与 cooldown_bars 为 0 同用(冷却与当根补回互相矛盾)。
	AllowReentry bool
}

Hold 是 rank 规则的进出场持有:持有中满足 Exit、不再满足 filter、持满 MaxBars 根(0 表示不限)就出场; 空位按 score 名次从满足 Entry(不写表示不限制)的候选里补足,目标持有数由 select 换算。出场后 CooldownBars 根内不能再入场。

type Holding

type Holding struct {
	Bars     int
	Offsets  []int
	Anchor   string
	Calendar string
	Every    int
	Days     []int
	At       string
}

Holding 是 rank 规则的分批换仓(见 holding.go):每 Bars 根为一个周期,在 Offsets 指定的偏移处重建对应批次; 写了 Calendar 时改按交易日历换仓,Days 的每个值是一个批次。Anchor 是相位锚点(某根 bar 的 bar_start)。

func (*Holding) AtLast

func (h *Holding) AtLast() bool

AtLast 报告日内帧是否在交易日的最后一根建仓。

func (*Holding) BatchKeys

func (h *Holding) BatchKeys() []int

BatchKeys 返回批次的键:bars 写法是 offsets,日历写法是 days 的值。

func (*Holding) IsCalendar

func (h *Holding) IsCalendar() bool

IsCalendar 报告 holding 是否按交易日历换仓。

type Market

type Market struct {
	Select string `json:"select"`
	Prefer string `json:"prefer"`
}

Market 是策略的市场模式:Select 决定从哪个市场的币里选,Prefer 决定一个币在两个市场都可用时优先在哪个市场下单。 参考市场(market.reference)不属于模式,见 Strategy.ReferenceMarkets。

func SingleMarket

func SingleMarket(market string) Market

SingleMarket 返回只在一个市场(spot、swap 或 equity)里选币、下单的模式。

func UnionMarket

func UnionMarket(modes []Market) Market

UnionMarket 返回策略池的有效市场模式:成员市场的并集。只涉及一个市场时就是该市场的单市场模式,涉及现货与永续时是 select=both、prefer=spot(只用来表示“两个市场都涉及”:决定要绑定的因子任务、账户要求的可交易市场与组合约束的口径, 成员各自的选币与下单仍按成员自己的模式)。成员是股票时为股票模式(股票与加密成员不能混用,由 ValidatePoolMembers 拒绝); 还没确定市场的成员(没写 market,保存时)不参与。

func ValidatePoolMembers

func ValidatePoolMembers(pool Strategy, members map[string]Strategy) (Market, error)

ValidatePoolMembers 在成员定义都取到之后校验整个池:每个成员都能进池,池的 portfolio 与成员市场的并集相容。 members 的键是成员 id,必须覆盖池的全部成员。

func (Market) CanOutputSpotLike

func (m Market) CanOutputSpotLike() bool

CanOutputSpotLike 报告模式可能输出现货(或股票)目标。

func (Market) Has

func (m Market) Has(market string) bool

Has 报告模式是否涉及某个市场。

func (Market) IsZero

func (m Market) IsZero() bool

IsZero 报告模式还没有确定(DSL 没写 market,也还没有按绑定的任务填入默认值)。

func (Market) Markets

func (m Market) Markets() []string

Markets 返回模式涉及的市场(输出可能落在这些市场,也需要这些市场的 View),现货在前、永续在后。

func (Market) Single

func (m Market) Single() bool

Single 报告模式只涉及一个市场。

func (Market) String

func (m Market) String() string

String 返回 select/prefer 的简写,用在错误提示里。

type Normalizer

type Normalizer struct {
	Variable string
	Kind     string
	Inner    *Expression
}

Normalizer 是一次截面预计算:先对样本内每行求 Inner,再把 rank 或 zscore 的结果写入 Variable。

type OnMissing

type OnMissing struct {
	KeepBars int
}

OnMissing 是持有标的缺数时的处理:连续缺数不超过 KeepBars 根时按冻结保持上期目标,超过后按现状移出。

type ParamDecl

type ParamDecl struct {
	Name    string  `json:"name"`
	Type    string  `json:"type"` // int 或 float
	Min     float64 `json:"min"`
	Max     float64 `json:"max"`
	Default float64 `json:"default"`
}

ParamDecl 是因子定义声明的一个可调参数。

type ParamExpr

type ParamExpr struct {
	Default    string
	PerSubject string
}

ParamExpr 是一个参数的输出表达式:Default 是这一期的统一值,PerSubject 可选,按标的求值,与统一值不同的标的进入覆盖。 两者都是数值表达式(与 score 相同,可用 rank、zscore 与 bars[-1]);Default 按标的求值后取中位数,不引用列时就是常数。

type ParamOutput

type ParamOutput struct {
	Member string
	Name   string
	Expr   ParamExpr
}

ParamOutput 是一个成员的一个参数的输出。

type ParamRef

type ParamRef struct {
	Variable string
	Member   string
	Name     string
}

ParamRef 是表达式里一处 params(成员键, 参数名) 的引用:求值时它被改写成变量 Variable,值来自这一行的 __params。

func ReferencedParamRefs

func ReferencedParamRefs(strategy Strategy) ([]ParamRef, error)

ReferencedParamRefs 在不知道任务的情况下返回 DSL 里 params(成员键, 参数名) 引用的全部参数(去重排序), 以及 factor_params 输出的参数;用于启用前对照任务的成员与定义的参数声明做检查。

type Pool

type Pool struct {
	Explicit bool
	Fixed    []string
	Tags     []string
}

Pool 是规则级标的池。Explicit 为 true 时替代 universe 的标签与黑白名单。

type PoolAllocation

type PoolAllocation struct {
	Method string
	// Ratios 是 fixed 用的固定比例(成员 id → 比例),可以不归一,总敞口受 portfolio.leverage 约束。
	Ratios   map[string]quant.Decimal
	Rotation *PoolRotation
	// Switch 是条件转移(按顺序判断,第一个成立的生效),只用于 fixed 与 drift。
	Switch []PoolSwitch
	// Sides 是 drift 两侧(键是 long、short)的侧内再平衡;Start 与 Initial 是漂移起点,二选一(见 pool_drift.go)。
	Sides   map[string]*PoolSide
	Start   string
	Initial *PoolInitial
}

PoolAllocation 是资金分配方式。

func (PoolAllocation) DriftStart

func (a PoolAllocation) DriftStart() string

DriftStart 返回漂移起点的时刻文本(allocation.start 或 allocation.initial.at),都没写时为空。

func (PoolAllocation) StartRatios

func (a PoolAllocation) StartRatios() map[string]quant.Decimal

StartRatios 返回漂移起点的分配系数:写了 initial 时是 initial.ratios,否则是 ratios。

type PoolExposure

type PoolExposure struct {
	Bands []ExposureBand
}

PoolExposure 是净敞口区间:各段按书写顺序执行。

type PoolFees

type PoolFees struct {
	SpotBps       float64
	SwapBps       float64
	EquityBps     float64
	FundingColumn string
}

PoolFees 是成员账本的单边手续费(基点)与资金费列。股票成员的账本用 EquityBps;FundingColumn 非空时永续持仓按这一列 (本根累计的资金费率)结算资金费。

type PoolFreeze

type PoolFreeze struct {
	WatchSide    string
	WatchMembers []string
	WindowBars   int
	Threshold    float64
	Bars         int
}

PoolFreeze 是波动冻结:被观察成员按 ratios 加权的净值在 WindowBars 根内的涨跌幅绝对值超过 Threshold 时, 从触发那根起冻结 Bars 根(跳过侧内再平衡、净敞口与总杠杆区间)。WatchSide 与 WatchMembers 只写一个。

type PoolGross

type PoolGross struct {
	Min, Max       float64
	HasMin, HasMax bool
}

PoolGross 是总杠杆区间:大于 Max 时整体缩小,小于 Min 时整体放大(池的第一根不放大)。

type PoolInitial

type PoolInitial struct {
	At     string
	Ratios map[string]quant.Decimal
}

PoolInitial 是 allocation.initial:漂移从 At 这一根开始,分配系数在这一根置为 Ratios。

type PoolMember

type PoolMember struct {
	ID         string
	StrategyID string
}

PoolMember 是池的一个成员:引用已有策略定义,启用时固化其 DSL 与版本。

type PoolRotation

type PoolRotation struct {
	Factors []RotationFactor
	Top     int
}

PoolRotation 是 rotation 的参数:多个因子在成员之间排名,按因子权重加权,取前 Top 名(并列的平分)平分 1。

type PoolSide

type PoolSide struct {
	Rebalance string
	// PeriodBars 与 Anchor 只用于 periodic、both;Anchor 是相位起点(某根 bar 的 bar_start 或交易日期),没写时取漂移起点。
	PeriodBars int
	Anchor     string
	// Threshold 只用于 threshold、both:|侧内占比 ÷ 目标侧内占比 − 1| 超过它时触发。
	Threshold float64
	// SpreadBars 是触发后分几根走完(1 表示一次到位)。
	SpreadBars int
	DriftBy    string
}

PoolSide 是 drift 一侧(多头或空头)的侧内再平衡配置。

func (PoolSide) ByThreshold

func (s PoolSide) ByThreshold() bool

func (PoolSide) Periodic

func (s PoolSide) Periodic() bool

Periodic、ByThreshold 报告这一侧是否按周期、按偏离触发。

type PoolSwitch

type PoolSwitch struct {
	WhenEmpty string
	From      string
	To        []string
}

PoolSwitch 是一条条件转移:WhenEmpty 成员本期的有效目标为空时,把 From 的分配比例全部转给 To(按它们的比例分,都为 0 时平分)。

type PoolTiming

type PoolTiming struct {
	Window int
}

PoolTiming 是择时参数。

type Portfolio

type Portfolio struct {
	Leverage     quant.Decimal
	MaxWeight    quant.Decimal
	HasMaxWeight bool
	MinUniverse  int
	MaxMissing   quant.Decimal
	// Limits 是单标的分方向上限与超限转移(见 limits.go),没写时为空。
	Limits *PortfolioLimits
}

Portfolio 是组合级约束与守门参数。

type PortfolioLimits

type PortfolioLimits struct {
	LongMax, ShortMax       quant.Decimal
	HasLongMax, HasShortMax bool
	// OverflowTo 是超出部分的去向:规则 id 或成员 id;空串表示留现金。
	OverflowTo string
}

PortfolioLimits 是 portfolio.limits:单标的的多头、空头上限(占权益的比例,不随杠杆换算,同一标的各市场同方向的权重合计), 超出部分按 Overflow 转给一个来源(普通策略写规则 id,池写成员 id)本期同方向的其他标的;没写 Overflow 时留现金。

type Program

type Program struct {
	Strategy Strategy
	Rules    []CompiledRule
	// Params 是 factor_params 的已编译表达式(按成员键、参数名排序)。
	Params []CompiledParam
	// ParamRefs 是规则与参数表达式里 params(成员键, 参数名) 引用的全部参数(去重排序);非空时求值需要读取 __params 列。
	ParamRefs []ParamRef
	// Columns 是引用的全部当期列(排序):主帧的列,以及写作 来源名.列名 的来源列。
	Columns         []string
	PreviousColumns []string
	UsesPreviousBar bool
	// SourceColumns 是各附加来源被引用的列(来源名 → 去掉前缀的列名,排序);没有来源时为空。
	SourceColumns map[string][]string
}

Program 是启用实例时编译出的可执行策略;它只存在于内存,重启后由 DSL 文本与 View 列重新编译。

func Compile

func Compile(strategy Strategy, columns []string) (*Program, error)

Compile 用绑定 View 的列编译全部表达式。引用不存在的列、类型不匹配都会在这里报错。

func (*Program) MainColumns

func (p *Program) MainColumns() []string

MainColumns 返回主帧的当期列(不含来源列):读主帧 View 的行用它。

type RotationFactor

type RotationFactor struct {
	Name   string
	Window int
	Weight quant.Decimal
	// Order 是排序方向(asc、desc);没写时 return 与 ma_ratio 取 desc,drawdown 取 asc。
	Order string
}

RotationFactor 是一个轮动因子。

func (RotationFactor) EffectiveOrder

func (f RotationFactor) EffectiveOrder() string

EffectiveOrder 返回因子的排序方向:写了用写的,没写按因子取默认(drawdown 越小越好,其余越大越好)。

type Rule

type Rule struct {
	ID   string
	Name string
	Type string
	Pool Pool
	// Universe 是规则级 universe(见 universe.go);AllowEmpty 为真时这条规则不参与整期守门,候选为空或缺数时只是不出目标。
	Universe    *RuleUniverse
	AllowEmpty  bool
	Filter      string
	Score       string
	Select      Select
	HasSelect   bool
	Weight      Weight
	Side        string
	FilterAfter string
	Holding     *Holding
	// Hold 是 rank 规则的进出场持有(见 hold.go)。
	Hold *Hold
	// Scale 是规则输出权重上的仓位系数;OnMissing 是持有标的缺数时的冻结保持(见 scale.go)。
	Scale     *Scale
	OnMissing *OnMissing
	// Stop 是规则的止损止盈(见 stop.go)。
	Stop *Stop
	// Market 是规则级市场(spot 或 swap,见 market.go):策略涉及两个市场时,这条规则只从该市场的序列选择,目标也落在该市场;
	// 空串表示沿用策略的选币池与定市场。
	Market string
}

Rule 是一条规则(类型只有 rank)。

func (Rule) DirectColumns

func (r Rule) DirectColumns() []string

DirectColumns 是规则直接写列名(不经表达式)引用的当期列:select.group.by(主帧的列名,或写作 来源名.列名 的来源列, 与表达式引用的来源列走同一条路:计入必需列、SourceColumns 与缺数划分)。

func (Rule) StopColumns

func (r Rule) StopColumns() []string

StopColumns 返回规则的止损需要读取的列(可选列:缺值不算缺数,只是本期不判止损)。

type RuleUniverse

type RuleUniverse struct {
	Universe
	Fields map[string]struct{}
}

RuleUniverse 是规则级 universe:Fields 是规则里写了的字段,只有这些字段覆盖策略级。

func (*RuleUniverse) OverridesMembers

func (u *RuleUniverse) OverridesMembers() bool

OverridesMembers 报告规则级 universe 是否改写了标的范围(标签与黑白名单);只写年龄类字段时规则沿用策略级的默认集合。

type Scale

type Scale struct {
	Expr string
	Max  float64
}

Scale 是规则输出权重上逐标的乘的系数:Expr 是数值表达式(逐行求值),结果截到 [0, Max],乘掉的部分留现金。

type Select

type Select struct {
	Top        float64
	Bottom     float64
	CountRound string
	CountMin   int
	Range      [2]int
	Group      *SelectGroup
	Then       *SelectThen
	Where      string
	Buffer     int
}

Select 描述选择阶段(见 select.go):top、bottom、range 三选一;top/bottom 是正整数个数或 (0, 1) 的比例,比例按 CountRound 取整后与 CountMin 取大;Range 是名次闭区间(未写时为零值);Group 限制每组入选个数;Then 在第一段的结果上二次排序。 where 可选,buffer 是排名缓冲区。

func (Select) Count

func (s Select) Count(sample int) int

Count 返回第一段的选择个数。sample 是比例的分母:通过 filter 且分数有效的样本数。 比例按 count_round 取整后与 count_min 取大;整数与 range 不受样本数影响。

func (Select) FixedCount

func (s Select) FixedCount() (int, bool)

FixedCount 返回不依赖样本数的选择个数:整数 top/bottom 是该数,range 是区间长度;写比例时返回 0 与 false。

func (Select) HasRange

func (s Select) HasRange() bool

HasRange 报告 select 是否写了名次区间。

func (Select) IsRatio

func (s Select) IsRatio() bool

IsRatio 报告 top/bottom 是否写成 (0, 1) 的比例。

func (Select) UsesBottom

func (s Select) UsesBottom() bool

UsesBottom 报告第一段是否按低分优先排序(bottom)。range 按分数从高到低排名。

type SelectGroup

type SelectGroup struct {
	By     string
	Max    int
	Quotas []int
	Rest   int
}

SelectGroup 是按分组列限制入选个数:By 是主帧的列名,或写作 来源名.列名 的附加来源列(分组值取这一根主帧按 as-of 读到的来源值); Max 是每组上限;Quotas 按组内最优名次给组排序后,第 i 组的名额是 Quotas[i],其余组是 Rest。 Max 与 Quotas 二选一。

type SelectThen

type SelectThen struct {
	Score      string
	Top        float64
	Bottom     float64
	CountRound string
	CountMin   int
}

SelectThen 是二次排序:在第一段选中的集合里按 Score 重新排序,取 Top 或 Bottom 个。 Top、Bottom 与第一段同口径:整数是个数,(0, 1) 是比例(分母是第一段选中且二次排序分数有效的个数),比例按 CountRound 取整后与 CountMin 取大。

func (SelectThen) Count

func (t SelectThen) Count(sample int) int

Count 返回二次排序要取的个数,sample 是比例的分母。

func (SelectThen) FixedCount

func (t SelectThen) FixedCount() (int, bool)

FixedCount 返回不依赖样本数的二次排序个数;写比例时返回 0 与 false。

type Source

type Source struct {
	Name string
	Bar  string
}

Source 是一个附加列来源:实例另外绑定一个周期为 Bar 的因子任务,规则用 Name.列名 读它的列。

type Stage

type Stage string

Stage 是表达式所在的阶段,决定返回类型与可用标识符。

const (
	StageFilter      Stage = "filter"
	StageScore       Stage = "score"
	StageSelectWhere Stage = "select.where"
	StageFilterAfter Stage = "filter_after"
	// StageThenScore 是 select.then 的二次排序分数(数值,可用 rank/zscore,在第一段选中的集合上计算)。
	StageThenScore Stage = "select.then.score"
	// StageHoldEntry、StageHoldExit 是 rank 规则 hold 块的入场、出场条件(布尔)。
	StageHoldEntry Stage = "hold.entry"
	StageHoldExit  Stage = "hold.exit"
	// StageScale 是仓位系数(数值,逐行求值,不能用截面函数)。
	StageScale Stage = "scale.expr"
)

type Stop

type Stop struct {
	Loss         float64 `json:"loss,omitempty"`
	Trailing     float64 `json:"trailing,omitempty"`
	Profit       float64 `json:"profit,omitempty"`
	Price        string  `json:"price"`
	CooldownBars int     `json:"cooldown_bars,omitempty"`
}

Stop 是一组止损止盈参数;比例为 0 表示不启用该项。

func (*Stop) Columns

func (s *Stop) Columns() []string

Columns 返回判断止损需要读取的列:入场价总是 close,extreme 时还要 high 与 low。

type Strategy

type Strategy struct {
	Name string
	Bar  string // 可选断言,规范频率;实际周期由绑定的 View 决定
	// Market 是市场模式;DSL 没写 market 时为零值,由绑定的因子任务的市场填入默认值(见 Market)。
	Market Market
	// MarketDeclared 为真表示 DSL 里显式写了 market。
	MarketDeclared bool
	// ReferenceMarkets 是 market.reference 写出的参考市场(S3):单市场策略额外绑定的另一个市场的任务,只用于 age_markets: all
	// 的年龄判定,不参与选择与下单。
	ReferenceMarkets []string
	Universe         Universe
	Rules            []Rule
	// Pool 非空表示策略池:与 Rules 互斥(见 pool.go)。
	Pool      *StrategyPool
	Portfolio Portfolio
	// FactorParams 是可变成员的成员键 → 参数名 → 下一期参数的输出表达式(见 factors.go)。
	FactorParams map[string]map[string]ParamExpr
	// Sources 是附加列来源(见 sources.go),按声明顺序。
	Sources []Source
}

Strategy 是解析并校验后的策略定义。

func Parse

func Parse(raw []byte) (Strategy, error)

Parse 解析并校验一份 DSL。解析经由 yaml.Node 完成:拒绝重复键、未知字段和多文档, 让配置错误在保存时就暴露,而不是等到求值。

func (Strategy) Direction

func (s Strategy) Direction() string

Direction 返回策略的方向:规则全部做多为 long,全部做空为 short;混合方向或没有规则时为空串。 规则的 side 默认 long。

func (Strategy) FactorParamOutputs

func (s Strategy) FactorParamOutputs() []ParamOutput

FactorParamOutputs 按(成员键、参数名)排序返回全部参数输出。

func (Strategy) HasOnMissing

func (s Strategy) HasOnMissing() bool

HasOnMissing 报告策略里是否有规则写了 on_missing:只有这时冻结才按“只由持有该标的的规则决定”合并(见 engine 的 frozenSet)。

func (Strategy) HasRuleAges

func (s Strategy) HasRuleAges() bool

HasRuleAges 报告是否有规则的年龄要求不同于“策略级 min_age_bars、按下单市场判断”:写了规则级年龄字段、max_age_bars 或 age_markets: all。 为假时各规则都只按策略级 min_age_bars 判断(现状)。

func (Strategy) HasRuleMarket

func (s Strategy) HasRuleMarket() bool

HasRuleMarket 报告是否有规则写了规则级 market。

func (Strategy) HasSources

func (s Strategy) HasSources() bool

HasSources 报告策略声明了附加来源。

func (Strategy) IsPool

func (s Strategy) IsPool() bool

IsPool 报告策略是策略池。

func (Strategy) LongestAgeBars

func (s Strategy) LongestAgeBars() int

LongestAgeBars 返回策略里最长的年龄判定根数(策略级与各规则的 min_age_bars、max_age_bars 取大),用于历史覆盖与回看的检查。

func (Strategy) MaxHoldBars

func (s Strategy) MaxHoldBars(clock BarClock) int

MaxHoldBars 返回策略里最长的持有期(bar 数):规则的 holding.bars、hold.max_bars, 以及日历换仓一个周期内最多的 bar 数(clock 换算,见 BarClock);没有持有期时为 0。

func (Strategy) RuleUniverse

func (s Strategy) RuleUniverse(rule Rule) Universe

RuleUniverse 返回规则实际使用的 universe:规则级写了的字段逐项覆盖策略级,没写的沿用策略级。

func (Strategy) SourceNames

func (s Strategy) SourceNames() []string

SourceNames 返回声明的来源名(声明顺序)。

type StrategyPool

type StrategyPool struct {
	Members    []PoolMember
	Allocation PoolAllocation
	// Timing 非空时,成员净值在 window 期均线之上取 1,否则取 0。
	Timing *PoolTiming
	// Step 是每期每个成员的比例变化上限;HasStep 为假表示不限制。
	Step    quant.Decimal
	HasStep bool
	// Fees 是成员模拟账本的手续费。
	Fees PoolFees
	// Exposure 与 Gross 是净敞口区间与总杠杆区间(见 pool_constraints.go),没写时为空。
	Exposure *PoolExposure
	Gross    *PoolGross
	// Freeze 是波动冻结(只用于 drift,见 pool_drift.go),没写时为空。
	Freeze *PoolFreeze
}

StrategyPool 是策略池的定义。

func (StrategyPool) HasConstraints

func (p StrategyPool) HasConstraints() bool

HasConstraints 报告池写了净敞口或总杠杆区间。

func (StrategyPool) MaxWindow

func (p StrategyPool) MaxWindow() int

MaxWindow 返回轮动因子、择时与波动冻结里最长的窗口(都没有时为 0)。

func (StrategyPool) MemberIDs

func (p StrategyPool) MemberIDs() []string

MemberIDs 返回成员 id(按定义顺序)。

func (StrategyPool) NeedsSingleSide

func (p StrategyPool) NeedsSingleSide() bool

NeedsSingleSide 报告池用了要求成员单方向的分配方式或字段(drift、switch、exposure、gross)。

func (StrategyPool) Side

func (p StrategyPool) Side(side string) PoolSide

Side 返回 drift 一侧的配置:没写时不再平衡、按名义价值漂移、一次到位。

type Universe

type Universe struct {
	Tags        []string
	ExcludeTags []string
	Include     []string
	Exclude     []string
	MinAgeBars  int
	MaxAgeBars  int
	AgeMarkets  string
}

Universe 是策略级默认标的池:省略即 all。规则可以写规则级 universe 逐项覆盖(见 universe.go)。 MinAgeBars、MaxAgeBars 是年龄下限与上限(只保留年龄小于上限的新标的);AgeMarkets 为 all 时要求在全部绑定市场上判断年龄。

func (Universe) AllMarkets

func (u Universe) AllMarkets() bool

AllMarkets 报告 universe 是否要求在全部绑定市场上判断年龄(age_markets: all)。

type Weight

type Weight struct {
	Total  quant.Decimal
	Method string
	Cap    quant.Decimal
	HasCap bool
}

Weight 描述配权:Total 是规则预算上限,Cap 是规则内单标的上限(HasCap 为 false 表示不限)。

Jump to

Keyboard shortcuts

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