Documentation
¶
Overview ¶
Package dsl 定义策略 DSL 的数据结构、严格解析、校验与表达式编译。
DSL 只描述截面上的选股与配权逻辑:规则是列表,每条规则有稳定的 id、展示用的 name 和 固定词表的 type(rank 截面选股)。时序计算一律在因子层完成, 策略表达式只在当期一帧数据上求值,可选地引用上一根(bars[-1])。
Index ¶
- Constants
- Variables
- func ColumnsBySource(columns []string) map[string][]string
- func Hash(raw []byte) string
- func InferPoolMemberMarkets(members map[string]Strategy, boundEquity bool) (map[string]Strategy, error)
- func MemberSides(pool StrategyPool, members map[string]Strategy) map[string]string
- func PoolWarmBars(pool Strategy, members []Strategy, clock BarClock) int
- func ReferencedColumns(strategy Strategy) ([]string, error)
- func RuleMarket(mode Market, rule Rule) string
- func SourceColumn(source, column string) string
- func SplitSourceColumn(name string) (source, column string)
- func SplitTaskKey(key string) (source, market string)
- func SpotLike(market string) bool
- func TaskKey(source, market string) string
- func ValidColumnName(name string) bool
- func ValidSourceName(name string) bool
- func Validate(s *Strategy) error
- func ValidateMode(s Strategy, mode Market) error
- func ValidatePoolMember(pool Strategy, id string, member Strategy) error
- type Anchor
- type BarClock
- type CompiledParam
- type CompiledRule
- type ExposureBand
- type Expression
- type Hold
- type Holding
- type Market
- type Normalizer
- type OnMissing
- type ParamDecl
- type ParamExpr
- type ParamOutput
- type ParamRef
- type Pool
- type PoolAllocation
- type PoolExposure
- type PoolFees
- type PoolFreeze
- type PoolGross
- type PoolInitial
- type PoolMember
- type PoolRotation
- type PoolSide
- type PoolSwitch
- type PoolTiming
- type Portfolio
- type PortfolioLimits
- type Program
- type RotationFactor
- type Rule
- type RuleUniverse
- type Scale
- type Select
- type SelectGroup
- type SelectThen
- type Source
- type Stage
- type Stop
- type Strategy
- func (s Strategy) Direction() string
- func (s Strategy) FactorParamOutputs() []ParamOutput
- func (s Strategy) HasOnMissing() bool
- func (s Strategy) HasRuleAges() bool
- func (s Strategy) HasRuleMarket() bool
- func (s Strategy) HasSources() bool
- func (s Strategy) IsPool() bool
- func (s Strategy) LongestAgeBars() int
- func (s Strategy) MaxHoldBars(clock BarClock) int
- func (s Strategy) RuleUniverse(rule Rule) Universe
- func (s Strategy) SourceNames() []string
- type StrategyPool
- type Universe
- type Weight
Constants ¶
const ( CalendarTradingDays = "trading_days" CalendarWeek = "week" CalendarMonth = "month" // HoldingAtFirst、HoldingAtLast 是日内帧上建仓所在的那一根:交易日的第一根或最后一根(默认)。 HoldingAtFirst = "first" HoldingAtLast = "last" // HoldingOffsetsAll 是 holding.offsets 的简写:每根都建一个批次,解析时展开成 0 到 bars-1。 HoldingOffsetsAll = "all" )
holding.calendar 的取值:按交易日计数的周期、自然周、自然月。
const ( MarketSpot = "spot" MarketSwap = "swap" MarketBoth = "both" MarketEquity = "equity" )
市场取值。select 可以是 spot、swap、both,prefer 可以是 spot、swap;equity 只由绑定解析写入(股票不允许在 DSL 里写 market)。
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 )
const ( AdjustAuto = "auto" // 总敞口大于 pivot 时同 reduce_larger,否则同 raise_smaller AdjustReduceLarger = "reduce_larger" // 缩小超出方向的一侧:净敞口高于 max 时缩多头,低于 min 时缩空头 AdjustRaiseSmaller = "raise_smaller" // 放大另一侧:净敞口高于 max 时放大空头,低于 min 时放大多头 )
净敞口区间超出时的修正方式。
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" // 按成员资金收益漂移,盈利的成员占比变大 )
const ( // MaxScale 是 scale.max 的上限。 MaxScale = 10.0 // MaxKeepBars 是 on_missing.keep_bars 的上限。 MaxKeepBars = 1000 )
仓位系数与缺数冻结的取值范围。
const ( CountRoundFloor = "floor" CountRoundCeil = "ceil" CountRoundRound = "round" )
比例换算个数的取整方式。
const ( StopPriceClose = "close" // 判断与更新最有利价格都用本期 close StopPriceExtreme = "extreme" // 止损看不利方向的极值、止盈与最有利价格看有利方向的极值(多头 low/high,空头 high/low) )
止损止盈(设计 4.1):写在规则上。按 K 线收盘判断,触发后平掉该持仓单位。
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" )
const ( AgeMarketsEach = "each" AgeMarketsAll = "all" )
universe.age_markets 的取值:each(默认)按标的在下单市场上的数据判断年龄;all 要求在实例绑定的全部市场上都通过。
const ( // MaxCount 是 min_age_bars、min_universe、select.top / bottom / buffer 与 holding.bars 的上限。 MaxCount = 10000 // MaxHoldingOffsets 是 holding.offsets 个数的上限:每个批次都随规则状态逐期保存。 MaxHoldingOffsets = 64 )
取值上限:超出这些量级的写法没有实际意义,却会让时间换算溢出、权重变成天文数字。
const MaxGroupQuotas = 64
MaxGroupQuotas 是 select.group.quotas 的个数上限。
const MaxLimitRounds = 3
MaxLimitRounds 是超限转移的最多轮数:分配后又超限的部分再分一轮,三轮之后剩下的留现金。
const MaxSources = 2
MaxSources 是附加来源的个数上限。
Variables ¶
var MaxLeverage = quant.Must("10")
MaxLeverage 是 portfolio.leverage 的上限(各规则 weight.total 之和不超过 leverage,因此也限住了权重)。
Functions ¶
func ColumnsBySource ¶
ColumnsBySource 把帧里的列名按来源分组:键为空串的是主帧的列,其余键是来源名,值是去掉来源前缀的列名(排序)。
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 ¶
PoolWarmBars 是策略池预热需要推进的期数:轮动因子与择时里最长的窗口、成员里最长的持有期(含 hold.max_bars 与日历周期), 取大者再加 1。窗口决定成员净值序列要读满多少期;持有期决定长持有期的成员从空仓起步时前段净值的偏差要多久才消化,所以也要算进去。
func ReferencedColumns ¶
ReferencedColumns 在不知道 View 列的情况下返回 DSL 引用的全部列名(当期与上一根的并集)。 用于启用前的列解析与提示。
func RuleMarket ¶
RuleMarket 返回规则在模式 mode 下实际使用的规则级市场:只有模式涉及两个市场时才生效,单市场模式下(规则 market 只能与策略相同)返回空串, 与没写相同。
func SourceColumn ¶
SourceColumn 返回来源列在帧里的名字:来源名.列名。整个管线(编译、缺数划分、冻结、解释明细)都用这个名字。
func SplitSourceColumn ¶
SplitSourceColumn 把帧里的列名拆成来源名与列名;主帧的列返回空来源名。
func SplitTaskKey ¶
SplitTaskKey 把任务键拆成来源名与市场;主帧与参考市场的键返回空来源名。
func ValidColumnName ¶
ValidColumnName 报告 name 是普通列名(不是表达式,也不是以 __ 开头的内部列)。
func ValidSourceName ¶
ValidSourceName 报告来源名的写法合法:小写字母开头的 snake_case,且不是表达式的保留标识符。
func Validate ¶
Validate 校验结构、字段取值和表达式语法;不需要知道 View 的列,列的存在性在 Compile 时检查。 校验会就地规范化 side 与 method 的默认值;portfolio 的默认值在解析时填入,显式写出的 0 按原值校验。
func ValidateMode ¶
ValidateMode 校验策略与有效市场模式(DSL 写出的,或没写时按绑定任务的市场取的默认值)能否同时成立: 纯现货与股票不能做空、不能加杠杆。 绑定了任务之后、启用与试算之前调用。
func ValidatePoolMember ¶
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 ¶
ParseAnchor 解析 holding.anchor:RFC3339 时刻,或交易日期 YYYY-MM-DD。
type CompiledParam ¶
type CompiledParam struct {
Member string
Name string
Default *Expression
PerSubject *Expression
}
CompiledParam 是一个参数输出的已编译表达式。
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) 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 返回包括截面函数参数在内的全部上一根列。
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)。
type Market ¶
Market 是策略的市场模式:Select 决定从哪个市场的币里选,Prefer 决定一个币在两个市场都可用时优先在哪个市场下单。 参考市场(market.reference)不属于模式,见 Strategy.ReferenceMarkets。
func SingleMarket ¶
SingleMarket 返回只在一个市场(spot、swap 或 equity)里选币、下单的模式。
func UnionMarket ¶
UnionMarket 返回策略池的有效市场模式:成员市场的并集。只涉及一个市场时就是该市场的单市场模式,涉及现货与永续时是 select=both、prefer=spot(只用来表示“两个市场都涉及”:决定要绑定的因子任务、账户要求的可交易市场与组合约束的口径, 成员各自的选币与下单仍按成员自己的模式)。成员是股票时为股票模式(股票与加密成员不能混用,由 ValidatePoolMembers 拒绝); 还没确定市场的成员(没写 market,保存时)不参与。
func ValidatePoolMembers ¶
ValidatePoolMembers 在成员定义都取到之后校验整个池:每个成员都能进池,池的 portfolio 与成员市场的并集相容。 members 的键是成员 id,必须覆盖池的全部成员。
func (Market) CanOutputSpotLike ¶
CanOutputSpotLike 报告模式可能输出现货(或股票)目标。
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 ¶
ParamExpr 是一个参数的输出表达式:Default 是这一期的统一值,PerSubject 可选,按标的求值,与统一值不同的标的进入覆盖。 两者都是数值表达式(与 score 相同,可用 rank、zscore 与 bars[-1]);Default 按标的求值后取中位数,不引用列时就是常数。
type ParamOutput ¶
ParamOutput 是一个成员的一个参数的输出。
type ParamRef ¶
ParamRef 是表达式里一处 params(成员键, 参数名) 的引用:求值时它被改写成变量 Variable,值来自这一行的 __params。
func ReferencedParamRefs ¶
ReferencedParamRefs 在不知道任务的情况下返回 DSL 里 params(成员键, 参数名) 引用的全部参数(去重排序), 以及 factor_params 输出的参数;用于启用前对照任务的成员与定义的参数声明做检查。
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 ¶
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 PoolInitial ¶
PoolInitial 是 allocation.initial:漂移从 At 这一根开始,分配系数在这一根置为 Ratios。
type PoolMember ¶
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 ¶
type PoolSwitch ¶
PoolSwitch 是一条条件转移:WhenEmpty 成员本期的有效目标为空时,把 From 的分配比例全部转给 To(按它们的比例分,都为 0 时平分)。
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 (*Program) MainColumns ¶
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 ¶
DirectColumns 是规则直接写列名(不经表达式)引用的当期列:select.group.by(主帧的列名,或写作 来源名.列名 的来源列, 与表达式引用的来源列走同一条路:计入必需列、SourceColumns 与缺数划分)。
func (Rule) StopColumns ¶
StopColumns 返回规则的止损需要读取的列(可选列:缺值不算缺数,只是本期不判止损)。
type RuleUniverse ¶
RuleUniverse 是规则级 universe:Fields 是规则里写了的字段,只有这些字段覆盖策略级。
func (*RuleUniverse) OverridesMembers ¶
func (u *RuleUniverse) OverridesMembers() bool
OverridesMembers 报告规则级 universe 是否改写了标的范围(标签与黑白名单);只写年龄类字段时规则沿用策略级的默认集合。
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 ¶
Count 返回第一段的选择个数。sample 是比例的分母:通过 filter 且分数有效的样本数。 比例按 count_round 取整后与 count_min 取大;整数与 range 不受样本数影响。
func (Select) FixedCount ¶
FixedCount 返回不依赖样本数的选择个数:整数 top/bottom 是该数,range 是区间长度;写比例时返回 0 与 false。
func (Select) UsesBottom ¶
UsesBottom 报告第一段是否按低分优先排序(bottom)。range 按分数从高到低排名。
type SelectGroup ¶
SelectGroup 是按分组列限制入选个数:By 是主帧的列名,或写作 来源名.列名 的附加来源列(分组值取这一根主帧按 as-of 读到的来源值); Max 是每组上限;Quotas 按组内最优名次给组排序后,第 i 组的名额是 Quotas[i],其余组是 Rest。 Max 与 Quotas 二选一。
type SelectThen ¶
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 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 表示不启用该项。
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 (Strategy) Direction ¶
Direction 返回策略的方向:规则全部做多为 long,全部做空为 short;混合方向或没有规则时为空串。 规则的 side 默认 long。
func (Strategy) FactorParamOutputs ¶
func (s Strategy) FactorParamOutputs() []ParamOutput
FactorParamOutputs 按(成员键、参数名)排序返回全部参数输出。
func (Strategy) HasOnMissing ¶
HasOnMissing 报告策略里是否有规则写了 on_missing:只有这时冻结才按“只由持有该标的的规则决定”合并(见 engine 的 frozenSet)。
func (Strategy) HasRuleAges ¶
HasRuleAges 报告是否有规则的年龄要求不同于“策略级 min_age_bars、按下单市场判断”:写了规则级年龄字段、max_age_bars 或 age_markets: all。 为假时各规则都只按策略级 min_age_bars 判断(现状)。
func (Strategy) HasRuleMarket ¶
HasRuleMarket 报告是否有规则写了规则级 market。
func (Strategy) LongestAgeBars ¶
LongestAgeBars 返回策略里最长的年龄判定根数(策略级与各规则的 min_age_bars、max_age_bars 取大),用于历史覆盖与回看的检查。
func (Strategy) MaxHoldBars ¶
MaxHoldBars 返回策略里最长的持有期(bar 数):规则的 holding.bars、hold.max_bars, 以及日历换仓一个周期内最多的 bar 数(clock 换算,见 BarClock);没有持有期时为 0。
func (Strategy) RuleUniverse ¶
RuleUniverse 返回规则实际使用的 universe:规则级写了的字段逐项覆盖策略级,没写的沿用策略级。
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 ¶
AllMarkets 报告 universe 是否要求在全部绑定市场上判断年龄(age_markets: all)。