Compare commits
2 Commits
v2026.04.2
...
v2026.4.28
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c73649012f | ||
|
|
236ec62e44 |
@@ -574,6 +574,18 @@ impl SymbolPriceSeries {
|
|||||||
Some(sum / lookback as f64)
|
Some(sum / lookback as f64)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn decision_prev_close_values(&self, date: NaiveDate, lookback: usize) -> Option<Vec<f64>> {
|
||||||
|
if lookback == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let end = self.decision_end_index(date)?;
|
||||||
|
if end < lookback {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let start = end - lookback;
|
||||||
|
Some(self.prev_closes[start..end].to_vec())
|
||||||
|
}
|
||||||
|
|
||||||
fn decision_volume_moving_average(&self, date: NaiveDate, lookback: usize) -> Option<f64> {
|
fn decision_volume_moving_average(&self, date: NaiveDate, lookback: usize) -> Option<f64> {
|
||||||
if lookback == 0 {
|
if lookback == 0 {
|
||||||
return None;
|
return None;
|
||||||
@@ -587,6 +599,23 @@ impl SymbolPriceSeries {
|
|||||||
Some(sum / lookback as f64)
|
Some(sum / lookback as f64)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn decision_volume_values(&self, date: NaiveDate, lookback: usize) -> Option<Vec<f64>> {
|
||||||
|
if lookback == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let end = self.previous_completed_end_index(date)?;
|
||||||
|
if end < lookback {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let start = end - lookback;
|
||||||
|
Some(
|
||||||
|
self.snapshots[start..end]
|
||||||
|
.iter()
|
||||||
|
.map(|snapshot| snapshot.volume as f64)
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
fn end_index(&self, date: NaiveDate) -> Option<usize> {
|
fn end_index(&self, date: NaiveDate) -> Option<usize> {
|
||||||
match self.dates.binary_search(&date) {
|
match self.dates.binary_search(&date) {
|
||||||
Ok(idx) => Some(idx + 1),
|
Ok(idx) => Some(idx + 1),
|
||||||
@@ -625,6 +654,7 @@ impl SymbolPriceSeries {
|
|||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
struct BenchmarkPriceSeries {
|
struct BenchmarkPriceSeries {
|
||||||
dates: Vec<NaiveDate>,
|
dates: Vec<NaiveDate>,
|
||||||
|
opens: Vec<f64>,
|
||||||
closes: Vec<f64>,
|
closes: Vec<f64>,
|
||||||
open_prefix: Vec<f64>,
|
open_prefix: Vec<f64>,
|
||||||
close_prefix: Vec<f64>,
|
close_prefix: Vec<f64>,
|
||||||
@@ -641,6 +671,7 @@ impl BenchmarkPriceSeries {
|
|||||||
let close_prefix = prefix_sums(&closes);
|
let close_prefix = prefix_sums(&closes);
|
||||||
Self {
|
Self {
|
||||||
dates,
|
dates,
|
||||||
|
opens,
|
||||||
closes,
|
closes,
|
||||||
open_prefix,
|
open_prefix,
|
||||||
close_prefix,
|
close_prefix,
|
||||||
@@ -678,13 +709,20 @@ impl BenchmarkPriceSeries {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn trailing_values(&self, date: NaiveDate, lookback: usize) -> Vec<f64> {
|
fn trailing_values(&self, date: NaiveDate, lookback: usize) -> Vec<f64> {
|
||||||
|
self.trailing_values_for(date, lookback, PriceField::Close)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn trailing_values_for(&self, date: NaiveDate, lookback: usize, field: PriceField) -> Vec<f64> {
|
||||||
let end = match self.dates.binary_search(&date) {
|
let end = match self.dates.binary_search(&date) {
|
||||||
Ok(idx) => idx + 1,
|
Ok(idx) => idx + 1,
|
||||||
Err(0) => return Vec::new(),
|
Err(0) => return Vec::new(),
|
||||||
Err(idx) => idx,
|
Err(idx) => idx,
|
||||||
};
|
};
|
||||||
let start = end.saturating_sub(lookback);
|
let start = end.saturating_sub(lookback);
|
||||||
self.closes[start..end].to_vec()
|
match field {
|
||||||
|
PriceField::DayOpen | PriceField::Open => self.opens[start..end].to_vec(),
|
||||||
|
PriceField::Close | PriceField::Last => self.closes[start..end].to_vec(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -944,6 +982,7 @@ impl DataSet {
|
|||||||
) -> Result<Self, DataSetError> {
|
) -> Result<Self, DataSetError> {
|
||||||
let benchmark_code = collect_benchmark_code(&benchmarks)?;
|
let benchmark_code = collect_benchmark_code(&benchmarks)?;
|
||||||
let calendar = TradingCalendar::new(benchmarks.iter().map(|item| item.date).collect());
|
let calendar = TradingCalendar::new(benchmarks.iter().map(|item| item.date).collect());
|
||||||
|
let factors = normalize_factor_snapshots(factors);
|
||||||
|
|
||||||
let instruments = instruments
|
let instruments = instruments
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@@ -2009,6 +2048,65 @@ impl DataSet {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn market_decision_numeric_values(
|
||||||
|
&self,
|
||||||
|
date: NaiveDate,
|
||||||
|
symbol: &str,
|
||||||
|
field: &str,
|
||||||
|
lookback: usize,
|
||||||
|
) -> Vec<f64> {
|
||||||
|
if lookback == 0 {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
let field = normalize_field(field);
|
||||||
|
match field.as_str() {
|
||||||
|
"close" | "prev_close" | "stock_close" | "price" => self
|
||||||
|
.market_series_by_symbol
|
||||||
|
.get(symbol)
|
||||||
|
.and_then(|series| series.decision_prev_close_values(date, lookback))
|
||||||
|
.unwrap_or_default(),
|
||||||
|
"volume" | "stock_volume" => self
|
||||||
|
.market_series_by_symbol
|
||||||
|
.get(symbol)
|
||||||
|
.and_then(|series| series.decision_volume_values(date, lookback))
|
||||||
|
.unwrap_or_default(),
|
||||||
|
"day_open" | "dayopen" => self
|
||||||
|
.market_series_by_symbol
|
||||||
|
.get(symbol)
|
||||||
|
.map(|series| series.trailing_values(date, lookback, PriceField::DayOpen))
|
||||||
|
.unwrap_or_default(),
|
||||||
|
"open" => self
|
||||||
|
.market_series_by_symbol
|
||||||
|
.get(symbol)
|
||||||
|
.map(|series| series.trailing_values(date, lookback, PriceField::Open))
|
||||||
|
.unwrap_or_default(),
|
||||||
|
"last" | "last_price" => self
|
||||||
|
.market_series_by_symbol
|
||||||
|
.get(symbol)
|
||||||
|
.map(|series| series.trailing_values(date, lookback, PriceField::Last))
|
||||||
|
.unwrap_or_default(),
|
||||||
|
other => self.factor_numeric_values(date, symbol, other, lookback),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn factor_numeric_values(
|
||||||
|
&self,
|
||||||
|
date: NaiveDate,
|
||||||
|
symbol: &str,
|
||||||
|
field: &str,
|
||||||
|
lookback: usize,
|
||||||
|
) -> Vec<f64> {
|
||||||
|
if lookback == 0 {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
self.calendar
|
||||||
|
.trailing_days(date, lookback)
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|trading_day| self.factor(trading_day, symbol))
|
||||||
|
.filter_map(|snapshot| factor_numeric_value(snapshot, field))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
pub fn market_moving_average(
|
pub fn market_moving_average(
|
||||||
&self,
|
&self,
|
||||||
date: NaiveDate,
|
date: NaiveDate,
|
||||||
@@ -2030,6 +2128,21 @@ impl DataSet {
|
|||||||
.moving_average_for(date, lookback, PriceField::Open)
|
.moving_average_for(date, lookback, PriceField::Open)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn benchmark_numeric_values(
|
||||||
|
&self,
|
||||||
|
date: NaiveDate,
|
||||||
|
field: &str,
|
||||||
|
lookback: usize,
|
||||||
|
) -> Vec<f64> {
|
||||||
|
let field = normalize_field(field);
|
||||||
|
match field.as_str() {
|
||||||
|
"open" | "day_open" | "dayopen" | "benchmark_open" => self
|
||||||
|
.benchmark_series_cache
|
||||||
|
.trailing_values_for(date, lookback, PriceField::Open),
|
||||||
|
_ => self.benchmark_series_cache.trailing_values(date, lookback),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn market_open_moving_average(
|
pub fn market_open_moving_average(
|
||||||
&self,
|
&self,
|
||||||
date: NaiveDate,
|
date: NaiveDate,
|
||||||
@@ -2400,6 +2513,26 @@ fn factor_numeric_value(snapshot: &DailyFactorSnapshot, field: &str) -> Option<f
|
|||||||
"pe_ttm" => Some(snapshot.pe_ttm),
|
"pe_ttm" => Some(snapshot.pe_ttm),
|
||||||
"turnover_ratio" => snapshot.turnover_ratio,
|
"turnover_ratio" => snapshot.turnover_ratio,
|
||||||
"effective_turnover_ratio" => snapshot.effective_turnover_ratio,
|
"effective_turnover_ratio" => snapshot.effective_turnover_ratio,
|
||||||
|
"ths_market_value_stock" | "ths_market_value_stock_bn" => snapshot
|
||||||
|
.extra_factors
|
||||||
|
.get(field.as_str())
|
||||||
|
.copied()
|
||||||
|
.or(Some(snapshot.market_cap_bn)),
|
||||||
|
"ths_current_mv_stock" | "ths_current_mv_stock_bn" => snapshot
|
||||||
|
.extra_factors
|
||||||
|
.get(field.as_str())
|
||||||
|
.copied()
|
||||||
|
.or(Some(snapshot.free_float_cap_bn)),
|
||||||
|
"ths_turnover_ratio_stock" => snapshot
|
||||||
|
.extra_factors
|
||||||
|
.get(field.as_str())
|
||||||
|
.copied()
|
||||||
|
.or(snapshot.turnover_ratio),
|
||||||
|
"ths_vaild_turnover_stock" | "ths_valid_turnover_stock" => snapshot
|
||||||
|
.extra_factors
|
||||||
|
.get(field.as_str())
|
||||||
|
.copied()
|
||||||
|
.or(snapshot.effective_turnover_ratio),
|
||||||
other => snapshot.extra_factors.get(other).copied(),
|
other => snapshot.extra_factors.get(other).copied(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2509,6 +2642,27 @@ fn normalize_field(field: &str) -> String {
|
|||||||
.to_ascii_lowercase()
|
.to_ascii_lowercase()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn normalize_factor_snapshots(factors: Vec<DailyFactorSnapshot>) -> Vec<DailyFactorSnapshot> {
|
||||||
|
factors
|
||||||
|
.into_iter()
|
||||||
|
.map(|mut snapshot| {
|
||||||
|
snapshot.extra_factors = snapshot
|
||||||
|
.extra_factors
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|(field, value)| {
|
||||||
|
let normalized = normalize_field(&field);
|
||||||
|
if normalized.is_empty() || !value.is_finite() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some((normalized, value))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
snapshot
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
fn normalize_history_frequency(frequency: &str) -> Option<String> {
|
fn normalize_history_frequency(frequency: &str) -> Option<String> {
|
||||||
let normalized = normalize_field(frequency);
|
let normalized = normalize_field(frequency);
|
||||||
match normalized.as_str() {
|
match normalized.as_str() {
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ pub mod futures;
|
|||||||
pub mod instrument;
|
pub mod instrument;
|
||||||
pub mod metrics;
|
pub mod metrics;
|
||||||
pub mod platform_expr_strategy;
|
pub mod platform_expr_strategy;
|
||||||
|
pub mod platform_strategy_spec;
|
||||||
pub mod portfolio;
|
pub mod portfolio;
|
||||||
pub mod rules;
|
pub mod rules;
|
||||||
pub mod scheduler;
|
pub mod scheduler;
|
||||||
@@ -49,6 +50,15 @@ pub use platform_expr_strategy::{
|
|||||||
PlatformRebalanceSchedule, PlatformScheduleFrequency, PlatformTradeAction,
|
PlatformRebalanceSchedule, PlatformScheduleFrequency, PlatformTradeAction,
|
||||||
PlatformUniverseActionKind,
|
PlatformUniverseActionKind,
|
||||||
};
|
};
|
||||||
|
pub use platform_strategy_spec::{
|
||||||
|
DynamicRangeConfig, IndexThrottleConfig, MovingAverageFilterConfig, SkipWindowConfig,
|
||||||
|
StrategyBenchmarkSpec, StrategyEngineConfig, StrategyExecutionSpec,
|
||||||
|
StrategyExpressionActionConfig, StrategyExpressionAllocationConfig,
|
||||||
|
StrategyExpressionOrderingConfig, StrategyExpressionRiskConfig,
|
||||||
|
StrategyExpressionScheduleConfig, StrategyExpressionSelectionConfig,
|
||||||
|
StrategyExpressionTradingConfig, StrategyRuntimeEnvironment, StrategyRuntimeExpressions,
|
||||||
|
StrategyRuntimeSpec, platform_expr_config_from_spec, platform_expr_config_from_value,
|
||||||
|
};
|
||||||
pub use portfolio::{CashReceivable, HoldingSummary, PendingCashFlow, PortfolioState, Position};
|
pub use portfolio::{CashReceivable, HoldingSummary, PendingCashFlow, PortfolioState, Position};
|
||||||
pub use rules::{ChinaEquityRuleHooks, EquityRuleHooks, RuleCheck};
|
pub use rules::{ChinaEquityRuleHooks, EquityRuleHooks, RuleCheck};
|
||||||
pub use scheduler::{
|
pub use scheduler::{
|
||||||
|
|||||||
@@ -641,7 +641,16 @@ impl PlatformExprStrategy {
|
|||||||
"factor"
|
"factor"
|
||||||
| "day_factor"
|
| "day_factor"
|
||||||
| "rolling_mean"
|
| "rolling_mean"
|
||||||
|
| "ma"
|
||||||
| "sma"
|
| "sma"
|
||||||
|
| "vma"
|
||||||
|
| "rolling_sum"
|
||||||
|
| "rolling_min"
|
||||||
|
| "rolling_max"
|
||||||
|
| "rolling_stddev"
|
||||||
|
| "stddev"
|
||||||
|
| "rolling_zscore"
|
||||||
|
| "pct_change"
|
||||||
| "factor_value"
|
| "factor_value"
|
||||||
| "get_factor_value"
|
| "get_factor_value"
|
||||||
| "factor_text"
|
| "factor_text"
|
||||||
@@ -1275,6 +1284,7 @@ impl PlatformExprStrategy {
|
|||||||
.extra_factors
|
.extra_factors
|
||||||
.get("touched_upper_limit")
|
.get("touched_upper_limit")
|
||||||
.or_else(|| factor.extra_factors.get("hit_upper_limit"))
|
.or_else(|| factor.extra_factors.get("hit_upper_limit"))
|
||||||
|
.or_else(|| factor.extra_factors.get("limit_up_touched"))
|
||||||
.copied()
|
.copied()
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
>= 0.5;
|
>= 0.5;
|
||||||
@@ -1282,6 +1292,7 @@ impl PlatformExprStrategy {
|
|||||||
.extra_factors
|
.extra_factors
|
||||||
.get("touched_lower_limit")
|
.get("touched_lower_limit")
|
||||||
.or_else(|| factor.extra_factors.get("hit_lower_limit"))
|
.or_else(|| factor.extra_factors.get("hit_lower_limit"))
|
||||||
|
.or_else(|| factor.extra_factors.get("limit_down_touched"))
|
||||||
.copied()
|
.copied()
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
>= 0.5;
|
>= 0.5;
|
||||||
@@ -2136,7 +2147,7 @@ impl PlatformExprStrategy {
|
|||||||
)?);
|
)?);
|
||||||
Ok(format!("day_factors[{}]", Self::quote_rhai_string(&key)))
|
Ok(format!("day_factors[{}]", Self::quote_rhai_string(&key)))
|
||||||
}
|
}
|
||||||
"rolling_mean" | "sma" => {
|
"rolling_mean" | "sma" | "ma" => {
|
||||||
if args.len() != 2 {
|
if args.len() != 2 {
|
||||||
return Err(BacktestError::Execution(format!(
|
return Err(BacktestError::Execution(format!(
|
||||||
"{helper} expects 2 arguments"
|
"{helper} expects 2 arguments"
|
||||||
@@ -2147,6 +2158,60 @@ impl PlatformExprStrategy {
|
|||||||
let value = self.resolve_rolling_mean(ctx, day, stock, &field, lookback)?;
|
let value = self.resolve_rolling_mean(ctx, day, stock, &field, lookback)?;
|
||||||
Ok(format!("{value:.12}"))
|
Ok(format!("{value:.12}"))
|
||||||
}
|
}
|
||||||
|
"vma" => {
|
||||||
|
if args.len() != 1 {
|
||||||
|
return Err(BacktestError::Execution(
|
||||||
|
"vma expects 1 lookback argument".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let lookback = Self::parse_positive_usize(&args[0])?;
|
||||||
|
let value = self.resolve_rolling_mean(ctx, day, stock, "volume", lookback)?;
|
||||||
|
Ok(format!("{value:.12}"))
|
||||||
|
}
|
||||||
|
"rolling_sum" | "rolling_min" | "rolling_max" | "rolling_stddev" | "stddev"
|
||||||
|
| "rolling_zscore" => {
|
||||||
|
if args.len() != 2 {
|
||||||
|
return Err(BacktestError::Execution(format!(
|
||||||
|
"{helper} expects field and lookback"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let field = Self::parse_string_or_identifier(&args[0])?;
|
||||||
|
let lookback = Self::parse_positive_usize(&args[1])?;
|
||||||
|
let values = self.resolve_rolling_values(ctx, day, stock, &field, lookback)?;
|
||||||
|
let value = match helper {
|
||||||
|
"rolling_sum" => values.iter().sum::<f64>(),
|
||||||
|
"rolling_min" => values.iter().copied().fold(f64::INFINITY, f64::min),
|
||||||
|
"rolling_max" => values.iter().copied().fold(f64::NEG_INFINITY, f64::max),
|
||||||
|
"rolling_stddev" | "stddev" => rolling_stddev(&values),
|
||||||
|
"rolling_zscore" => rolling_zscore(&values),
|
||||||
|
_ => 0.0,
|
||||||
|
};
|
||||||
|
Ok(Self::format_rhai_float(value))
|
||||||
|
}
|
||||||
|
"pct_change" => {
|
||||||
|
if args.len() != 2 {
|
||||||
|
return Err(BacktestError::Execution(
|
||||||
|
"pct_change expects field and lookback".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let field = Self::parse_string_or_identifier(&args[0])?;
|
||||||
|
let lookback = Self::parse_positive_usize(&args[1])?;
|
||||||
|
let values = self.resolve_rolling_values(
|
||||||
|
ctx,
|
||||||
|
day,
|
||||||
|
stock,
|
||||||
|
&field,
|
||||||
|
lookback.saturating_add(1),
|
||||||
|
)?;
|
||||||
|
let first = values.first().copied().unwrap_or_default();
|
||||||
|
let last = values.last().copied().unwrap_or_default();
|
||||||
|
let value = if first.abs() <= f64::EPSILON {
|
||||||
|
0.0
|
||||||
|
} else {
|
||||||
|
last / first - 1.0
|
||||||
|
};
|
||||||
|
Ok(Self::format_rhai_float(value))
|
||||||
|
}
|
||||||
"factor_value" | "get_factor_value" => {
|
"factor_value" | "get_factor_value" => {
|
||||||
if args.is_empty() || args.len() > 2 {
|
if args.is_empty() || args.len() > 2 {
|
||||||
return Err(BacktestError::Execution(format!(
|
return Err(BacktestError::Execution(format!(
|
||||||
@@ -2639,6 +2704,60 @@ impl PlatformExprStrategy {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn resolve_rolling_values(
|
||||||
|
&self,
|
||||||
|
ctx: &StrategyContext<'_>,
|
||||||
|
day: &DayExpressionState,
|
||||||
|
stock: Option<&StockExpressionState>,
|
||||||
|
field: &str,
|
||||||
|
lookback: usize,
|
||||||
|
) -> Result<Vec<f64>, BacktestError> {
|
||||||
|
if lookback == 0 {
|
||||||
|
return Err(BacktestError::Execution(
|
||||||
|
"rolling lookback must be positive".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let values = match field {
|
||||||
|
"benchmark_open" => ctx
|
||||||
|
.data
|
||||||
|
.benchmark_numeric_values(day.date, "open", lookback),
|
||||||
|
"benchmark_close" => ctx
|
||||||
|
.data
|
||||||
|
.benchmark_numeric_values(day.date, "close", lookback),
|
||||||
|
"signal_open" => ctx.data.market_decision_numeric_values(
|
||||||
|
day.date,
|
||||||
|
&self.config.signal_symbol,
|
||||||
|
"open",
|
||||||
|
lookback,
|
||||||
|
),
|
||||||
|
"signal_close" => ctx.data.market_decision_numeric_values(
|
||||||
|
day.date,
|
||||||
|
&self.config.signal_symbol,
|
||||||
|
"close",
|
||||||
|
lookback,
|
||||||
|
),
|
||||||
|
"signal_volume" => ctx.data.market_decision_numeric_values(
|
||||||
|
day.date,
|
||||||
|
&self.config.signal_symbol,
|
||||||
|
"volume",
|
||||||
|
lookback,
|
||||||
|
),
|
||||||
|
other => {
|
||||||
|
let stock = stock.ok_or_else(|| {
|
||||||
|
BacktestError::Execution(format!("rolling_{other} requires stock context"))
|
||||||
|
})?;
|
||||||
|
ctx.data
|
||||||
|
.market_decision_numeric_values(day.date, &stock.symbol, other, lookback)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if values.len() < lookback {
|
||||||
|
return Err(BacktestError::Execution(format!(
|
||||||
|
"missing rolling mean for field {field} with lookback {lookback}"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(values)
|
||||||
|
}
|
||||||
|
|
||||||
fn is_missing_rolling_mean_error(error: &BacktestError) -> bool {
|
fn is_missing_rolling_mean_error(error: &BacktestError) -> bool {
|
||||||
matches!(
|
matches!(
|
||||||
error,
|
error,
|
||||||
@@ -4514,6 +4633,35 @@ impl Strategy for PlatformExprStrategy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn rolling_stddev(values: &[f64]) -> f64 {
|
||||||
|
if values.is_empty() {
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
let mean = values.iter().sum::<f64>() / values.len() as f64;
|
||||||
|
let variance = values
|
||||||
|
.iter()
|
||||||
|
.map(|value| {
|
||||||
|
let diff = value - mean;
|
||||||
|
diff * diff
|
||||||
|
})
|
||||||
|
.sum::<f64>()
|
||||||
|
/ values.len() as f64;
|
||||||
|
variance.sqrt()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rolling_zscore(values: &[f64]) -> f64 {
|
||||||
|
let Some(latest) = values.last().copied() else {
|
||||||
|
return 0.0;
|
||||||
|
};
|
||||||
|
let mean = values.iter().sum::<f64>() / values.len() as f64;
|
||||||
|
let stddev = rolling_stddev(values);
|
||||||
|
if stddev <= f64::EPSILON {
|
||||||
|
0.0
|
||||||
|
} else {
|
||||||
|
(latest - mean) / stddev
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use std::collections::{BTreeMap, BTreeSet};
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
@@ -5248,6 +5396,144 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn platform_helpers_support_generic_rolling_stats_and_normalized_factors() {
|
||||||
|
let dates = [d(2025, 1, 2), d(2025, 1, 3), d(2025, 1, 6)];
|
||||||
|
let market_rows = dates
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(index, date)| DailyMarketSnapshot {
|
||||||
|
date: *date,
|
||||||
|
symbol: "000001.SZ".to_string(),
|
||||||
|
timestamp: None,
|
||||||
|
day_open: 10.0 + index as f64,
|
||||||
|
open: 10.0 + index as f64,
|
||||||
|
high: 10.5 + index as f64,
|
||||||
|
low: 9.5 + index as f64,
|
||||||
|
close: 10.2 + index as f64,
|
||||||
|
last_price: 10.2 + index as f64,
|
||||||
|
bid1: 10.2 + index as f64,
|
||||||
|
ask1: 10.2 + index as f64,
|
||||||
|
prev_close: 10.0 + index as f64,
|
||||||
|
volume: 100 + index as u64 * 100,
|
||||||
|
tick_volume: 0,
|
||||||
|
bid1_volume: 0,
|
||||||
|
ask1_volume: 0,
|
||||||
|
trading_phase: None,
|
||||||
|
paused: false,
|
||||||
|
upper_limit: 20.0,
|
||||||
|
lower_limit: 5.0,
|
||||||
|
price_tick: 0.01,
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let factor_rows = dates
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(index, date)| DailyFactorSnapshot {
|
||||||
|
date: *date,
|
||||||
|
symbol: "000001.SZ".to_string(),
|
||||||
|
market_cap_bn: 12.0,
|
||||||
|
free_float_cap_bn: 10.0,
|
||||||
|
pe_ttm: 8.0,
|
||||||
|
turnover_ratio: Some(1.0),
|
||||||
|
effective_turnover_ratio: Some(1.0),
|
||||||
|
extra_factors: BTreeMap::from([("Mixed_Factor".to_string(), index as f64 + 5.0)]),
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let candidate_rows = dates
|
||||||
|
.iter()
|
||||||
|
.map(|date| CandidateEligibility {
|
||||||
|
date: *date,
|
||||||
|
symbol: "000001.SZ".to_string(),
|
||||||
|
is_st: false,
|
||||||
|
is_new_listing: false,
|
||||||
|
is_paused: false,
|
||||||
|
allow_buy: true,
|
||||||
|
allow_sell: true,
|
||||||
|
is_kcb: false,
|
||||||
|
is_one_yuan: false,
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let benchmark_rows = dates
|
||||||
|
.iter()
|
||||||
|
.map(|date| BenchmarkSnapshot {
|
||||||
|
date: *date,
|
||||||
|
benchmark: "000852.SH".to_string(),
|
||||||
|
open: 1000.0,
|
||||||
|
close: 1002.0,
|
||||||
|
prev_close: 998.0,
|
||||||
|
volume: 1_000_000,
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let data = DataSet::from_components(
|
||||||
|
vec![Instrument {
|
||||||
|
symbol: "000001.SZ".to_string(),
|
||||||
|
name: "Ping An Bank".to_string(),
|
||||||
|
board: "SZ".to_string(),
|
||||||
|
round_lot: 100,
|
||||||
|
listed_at: Some(d(2020, 1, 1)),
|
||||||
|
delisted_at: None,
|
||||||
|
status: "active".to_string(),
|
||||||
|
}],
|
||||||
|
market_rows,
|
||||||
|
factor_rows,
|
||||||
|
candidate_rows,
|
||||||
|
benchmark_rows,
|
||||||
|
)
|
||||||
|
.expect("dataset");
|
||||||
|
let portfolio = PortfolioState::new(1_000_000.0);
|
||||||
|
let subscriptions = BTreeSet::new();
|
||||||
|
let ctx = StrategyContext {
|
||||||
|
execution_date: dates[2],
|
||||||
|
decision_date: dates[2],
|
||||||
|
decision_index: 2,
|
||||||
|
data: &data,
|
||||||
|
portfolio: &portfolio,
|
||||||
|
futures_account: None,
|
||||||
|
open_orders: &[],
|
||||||
|
dynamic_universe: None,
|
||||||
|
subscriptions: &subscriptions,
|
||||||
|
process_events: &[],
|
||||||
|
active_process_event: None,
|
||||||
|
active_datetime: None,
|
||||||
|
order_events: &[],
|
||||||
|
fills: &[],
|
||||||
|
};
|
||||||
|
let mut cfg = PlatformExprStrategyConfig::microcap_rotation();
|
||||||
|
cfg.signal_symbol = "000001.SZ".to_string();
|
||||||
|
cfg.rotation_enabled = false;
|
||||||
|
cfg.benchmark_short_ma_days = 1;
|
||||||
|
cfg.benchmark_long_ma_days = 1;
|
||||||
|
cfg.explicit_actions = vec![PlatformTradeAction::Order {
|
||||||
|
kind: PlatformExplicitOrderKind::Value,
|
||||||
|
symbol: "000001.SZ".to_string(),
|
||||||
|
amount_expr: "1000".to_string(),
|
||||||
|
limit_price_expr: None,
|
||||||
|
start_time_expr: None,
|
||||||
|
end_time_expr: None,
|
||||||
|
when_expr: Some(
|
||||||
|
concat!(
|
||||||
|
"ma(\"close\", 2) == 11.5",
|
||||||
|
" && vma(2) == 150.0",
|
||||||
|
" && rolling_sum(\"volume\", 2) == 300.0",
|
||||||
|
" && rolling_min(\"close\", 2) == 11.0",
|
||||||
|
" && rolling_max(\"close\", 2) == 12.0",
|
||||||
|
" && stddev(\"close\", 2) > 0.49",
|
||||||
|
" && rolling_zscore(\"close\", 2) > 0.9",
|
||||||
|
" && pct_change(\"close\", 1) > 0.09",
|
||||||
|
" && factor_value(\"mixed_factor\") == 7.0"
|
||||||
|
)
|
||||||
|
.to_string(),
|
||||||
|
),
|
||||||
|
reason: "rolling_stats_entry".to_string(),
|
||||||
|
}];
|
||||||
|
let mut strategy = PlatformExprStrategy::new(cfg);
|
||||||
|
|
||||||
|
let decision = strategy.on_day(&ctx).expect("platform decision");
|
||||||
|
|
||||||
|
assert_eq!(decision.order_intents.len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn platform_strategy_emits_target_shares_explicit_action() {
|
fn platform_strategy_emits_target_shares_explicit_action() {
|
||||||
let date = d(2025, 2, 3);
|
let date = d(2025, 2, 3);
|
||||||
|
|||||||
1036
crates/fidc-core/src/platform_strategy_spec.rs
Normal file
1036
crates/fidc-core/src/platform_strategy_spec.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1675,6 +1675,7 @@ impl OmniMicroCapStrategy {
|
|||||||
.max(1)
|
.max(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
fn projected_buy_quantity(&self, cash: f64, sizing_price: f64, execution_price: f64) -> u32 {
|
fn projected_buy_quantity(&self, cash: f64, sizing_price: f64, execution_price: f64) -> u32 {
|
||||||
if cash <= 0.0 || sizing_price <= 0.0 || execution_price <= 0.0 {
|
if cash <= 0.0 || sizing_price <= 0.0 || execution_price <= 0.0 {
|
||||||
return 0;
|
return 0;
|
||||||
@@ -1856,6 +1857,7 @@ impl OmniMicroCapStrategy {
|
|||||||
Some(fill.quantity)
|
Some(fill.quantity)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
fn projected_market_fillable_quantity(
|
fn projected_market_fillable_quantity(
|
||||||
&self,
|
&self,
|
||||||
ctx: &StrategyContext<'_>,
|
ctx: &StrategyContext<'_>,
|
||||||
|
|||||||
@@ -97,10 +97,10 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
|
|||||||
"平台策略脚本采用声明式 DSL + 表达式执行模型。".to_string(),
|
"平台策略脚本采用声明式 DSL + 表达式执行模型。".to_string(),
|
||||||
"支持 let 变量、fn 自定义函数、when/unless/else 条件块、可用指标/因子字段映射。".to_string(),
|
"支持 let 变量、fn 自定义函数、when/unless/else 条件块、可用指标/因子字段映射。".to_string(),
|
||||||
"支持数值型和字符串型因子,字符串字段可用于行业、概念、标签、板块等分类过滤。".to_string(),
|
"支持数值型和字符串型因子,字符串字段可用于行业、概念、标签、板块等分类过滤。".to_string(),
|
||||||
"当前默认回测数据已支持 OHLCV、市值、流通市值、换手率、有效换手率、上市天数、停牌/ST/板块、涨跌停价格、tick 触达涨跌停、常用价格/成交量均线;复杂技术指标和财务报表字段必须来自预计算因子或后续扩展函数。".to_string(),
|
"当前默认回测数据已支持 OHLCV、市值、流通市值、换手率、有效换手率、上市天数、停牌/ST/板块、涨跌停价格、tick 触达涨跌停、常用价格/成交量均线,以及 stock_indicator_factors_v1 中已入库的通用指标因子。".to_string(),
|
||||||
"AI 生成策略时只能输出完整 engine-script 代码,不输出 Markdown、解释、推理过程、JSON 包装或手册复述。".to_string(),
|
"AI 生成策略时只能输出完整 engine-script 代码,不输出 Markdown、解释、推理过程、JSON 包装或手册复述。".to_string(),
|
||||||
"表达式字段以运行时字段为准:市值使用 market_cap,流通市值使用 free_float_cap;不要在策略表达式中使用数据库原始字段 float_market_cap。".to_string(),
|
"表达式字段以运行时字段为准:市值使用 market_cap,流通市值使用 free_float_cap;不要在策略表达式中使用数据库原始字段 float_market_cap。".to_string(),
|
||||||
"60日价格均线使用 rolling_mean(\"close\", 60),不要使用 ma60、stock_ma60、signal_ma60 或 benchmark_ma60。".to_string(),
|
"任意窗口价格均线使用 rolling_mean(\"close\", n) 或 ma(\"close\", n),任意窗口均量使用 rolling_mean(\"volume\", n) 或 vma(n);不要使用未列出的 ma60、stock_ma60、signal_ma60 或 benchmark_ma60 变量。".to_string(),
|
||||||
"自定义 fn 必须通过参数传入运行时字段;不要用 fn score() 这类零参数函数直接引用 market_cap、close、ma5 等股票字段。".to_string(),
|
"自定义 fn 必须通过参数传入运行时字段;不要用 fn score() 这类零参数函数直接引用 market_cap、close、ma5 等股票字段。".to_string(),
|
||||||
"禁止自由 Python/JavaScript 命令式语句,最终必须输出平台 DSL。".to_string(),
|
"禁止自由 Python/JavaScript 命令式语句,最终必须输出平台 DSL。".to_string(),
|
||||||
],
|
],
|
||||||
@@ -323,9 +323,11 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
|
|||||||
ManualFunction { name: "order/order_status/order_avg_price/order_transaction_cost".to_string(), signature: "ctx.order(order_id)".to_string(), detail: "按订单 id 查询运行时订单对象,支持已结束订单和当前挂单。返回字段包括 status、filled_quantity、unfilled_quantity、avg_price、transaction_cost、symbol、side、reason;可用便捷函数读取状态、成交均价和费用,对齐 平台内核 Order 的核心属性。".to_string() },
|
ManualFunction { name: "order/order_status/order_avg_price/order_transaction_cost".to_string(), signature: "ctx.order(order_id)".to_string(), detail: "按订单 id 查询运行时订单对象,支持已结束订单和当前挂单。返回字段包括 status、filled_quantity、unfilled_quantity、avg_price、transaction_cost、symbol、side、reason;可用便捷函数读取状态、成交均价和费用,对齐 平台内核 Order 的核心属性。".to_string() },
|
||||||
ManualFunction { name: "account/portfolio_view/accounts".to_string(), signature: "ctx.account()".to_string(), detail: "返回当前股票账户/组合运行时视图,字段包括 account_type、cash、available_cash、frozen_cash、market_value、total_value、unit_net_value、daily_pnl、daily_returns、total_returns、transaction_cost、trading_pnl、position_pnl 等;DSL 中同名字段可直接使用。也可用 ctx.stock_account()、ctx.account_by_type(\"STOCK\")、ctx.accounts() 按账户类型读取;当前股票回测路径不会把 FUTURE 虚假映射成 STOCK。".to_string() },
|
ManualFunction { name: "account/portfolio_view/accounts".to_string(), signature: "ctx.account()".to_string(), detail: "返回当前股票账户/组合运行时视图,字段包括 account_type、cash、available_cash、frozen_cash、market_value、total_value、unit_net_value、daily_pnl、daily_returns、total_returns、transaction_cost、trading_pnl、position_pnl 等;DSL 中同名字段可直接使用。也可用 ctx.stock_account()、ctx.account_by_type(\"STOCK\")、ctx.accounts() 按账户类型读取;当前股票回测路径不会把 FUTURE 虚假映射成 STOCK。".to_string() },
|
||||||
ManualFunction { name: "deposit_withdraw/finance_repay/management_fee".to_string(), signature: "account.deposit_withdraw(amount, receiving_days=0)".to_string(), detail: "策略账户资金动作。deposit_withdraw 正数入金、负数出金;receiving_days 大于 0 时按交易日延迟到账,并保持净值口径不把外部资金流当成收益。finance_repay 正数融资、负数还款,会同步维护 cash_liabilities。set_management_fee_rate 设置结算管理费率;普通策略可覆盖 management_fee(ctx, rate) 自定义计算器,对齐 平台内核 管理费回调能力。".to_string() },
|
ManualFunction { name: "deposit_withdraw/finance_repay/management_fee".to_string(), signature: "account.deposit_withdraw(amount, receiving_days=0)".to_string(), detail: "策略账户资金动作。deposit_withdraw 正数入金、负数出金;receiving_days 大于 0 时按交易日延迟到账,并保持净值口径不把外部资金流当成收益。finance_repay 正数融资、负数还款,会同步维护 cash_liabilities。set_management_fee_rate 设置结算管理费率;普通策略可覆盖 management_fee(ctx, rate) 自定义计算器,对齐 平台内核 管理费回调能力。".to_string() },
|
||||||
ManualFunction { name: "rolling_mean".to_string(), signature: "rolling_mean(\"field\", lookback)".to_string(), detail: "任意字段滚动均值,支持 volume/amount/turnover_ratio、signal_open/signal_close、benchmark_open/benchmark_close 等。个股 volume 与 close 均按当前交易日前已完成交易日计算;单只股票历史窗口不足时,在选股过滤和买入仓位表达式中按不通过/0 仓处理,不会中断整次回测。任意成交量窗口推荐用它,比如 rolling_mean(\"volume\", 15)。".to_string() },
|
ManualFunction { name: "rolling_mean / sma / ma".to_string(), signature: "rolling_mean(\"field\", lookback) / ma(\"close\", 20)".to_string(), detail: "任意字段滚动均值,支持 close、volume、amount、turnover_ratio、effective_turnover_ratio、signal_open/signal_close、benchmark_open/benchmark_close 和所有数值型 extra_factors。个股 close 使用当前交易日前已完成收盘序列,volume 使用当前交易日前已完成成交量序列;历史窗口不足时在选股过滤和买入仓位表达式中按不通过/0 仓处理。".to_string() },
|
||||||
ManualFunction { name: "sma".to_string(), signature: "sma(\"field\", lookback)".to_string(), detail: "rolling_mean 的别名。任意价格均线窗口推荐用它,比如 sma(\"close\", 15)。".to_string() },
|
ManualFunction { name: "vma".to_string(), signature: "vma(60)".to_string(), detail: "rolling_mean(\"volume\", lookback) 的便捷别名,用于任意窗口成交量均线,例如 vma(5) < vma(60)。".to_string() },
|
||||||
ManualFunction { name: "复杂技术指标".to_string(), signature: "factor_value(\"macd\", 1) 或预计算字段".to_string(), detail: "BOLL、EMA、WMA、DEMA、TEMA、KAMA、SAR、ADX、CCI、MACD、RSI、KDJ、WILLR、ATR、ROC、TRIX、MFI、Aroon、OBV、ADL、Beta、相关系数、线性回归、标准差、方差、K 线形态等目前不是默认内建函数;可先预计算成数值因子,再用 factor_value/rolling_mean 读取。".to_string() },
|
ManualFunction { name: "rolling_sum / rolling_min / rolling_max".to_string(), signature: "rolling_sum(\"volume\", 20)".to_string(), detail: "任意数值字段滚动求和、最小值、最大值。可用于量能收缩、区间高低点、资金活跃度等过滤或排序。".to_string() },
|
||||||
|
ManualFunction { name: "rolling_stddev / stddev / rolling_zscore / pct_change".to_string(), signature: "stddev(\"close\", 20) / pct_change(\"close\", 10)".to_string(), detail: "滚动标准差、最新值 Z 分数和区间涨跌幅。pct_change(field, n) 会读取 n+1 个窗口点并计算 latest / first - 1。".to_string() },
|
||||||
|
ManualFunction { name: "数据库指标因子".to_string(), signature: "factor_value(\"ths_valid_turnover_stock\", 1)".to_string(), detail: "stock_indicator_factors_v1 中的指标会进入 extra_factors,可用 factor(\"字段\")、factors[\"字段\"]、factor_value(\"字段\", lookback) 或 rolling_mean(\"字段\", n) 读取。市值类指标统一提供亿元口径别名 ths_market_value_stock、ths_market_value_stock_bn、ths_current_mv_stock、ths_current_mv_stock_bn,同时保留 raw 后缀原始值。".to_string() },
|
||||||
ManualFunction { name: "round/floor/ceil/abs/min/max/clamp".to_string(), signature: "round(x)".to_string(), detail: "常用数值函数。".to_string() },
|
ManualFunction { name: "round/floor/ceil/abs/min/max/clamp".to_string(), signature: "round(x)".to_string(), detail: "常用数值函数。".to_string() },
|
||||||
ManualFunction { name: "safe_div".to_string(), signature: "safe_div(lhs, rhs, fallback)".to_string(), detail: "安全除法。".to_string() },
|
ManualFunction { name: "safe_div".to_string(), signature: "safe_div(lhs, rhs, fallback)".to_string(), detail: "安全除法。".to_string() },
|
||||||
ManualFunction { name: "contains/starts_with/ends_with/lower/upper/trim/strlen".to_string(), signature: "starts_with(symbol, \"60\")".to_string(), detail: "字符串辅助函数。".to_string() },
|
ManualFunction { name: "contains/starts_with/ends_with/lower/upper/trim/strlen".to_string(), signature: "starts_with(symbol, \"60\")".to_string(), detail: "字符串辅助函数。".to_string() },
|
||||||
@@ -343,7 +345,7 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
|
|||||||
},
|
},
|
||||||
ManualFactorSource {
|
ManualFactorSource {
|
||||||
table: "扩展指标因子".to_string(),
|
table: "扩展指标因子".to_string(),
|
||||||
detail: "当前可用扩展指标主要包括总市值、流通市值、换手率、有效换手率;其他财务、行业、概念、陆股通、技术指标等只有落地为可用因子后才可在策略中直接使用。".to_string(),
|
detail: "来自 stock_indicator_factors_v1 和运行时 extra_factors。已入库指标会自动进入策略运行时,字段名使用 dataset 小写下划线;市值类默认换算为亿元口径,raw 后缀保留原始 indicator_value。".to_string(),
|
||||||
fields: vec![],
|
fields: vec![],
|
||||||
},
|
},
|
||||||
ManualFactorSource {
|
ManualFactorSource {
|
||||||
@@ -428,7 +430,7 @@ pub fn render_manual_markdown(manual: &StrategyAiManual) -> String {
|
|||||||
out.push_str("- 只使用支持语句块:`market`、`benchmark`、`signal`、`rebalance.every_days(...).at([...])`、`selection.limit`、`selection.market_cap_band`、`filter.stock_ma`、`filter.stock_expr`、`ordering.rank_by`、`ordering.rank_expr`、`allocation.buy_scale`、`risk.stop_loss`、`risk.take_profit`、`risk.index_exposure`、`execution.matching_type`、`execution.slippage`、`universe.exclude`。\n");
|
out.push_str("- 只使用支持语句块:`market`、`benchmark`、`signal`、`rebalance.every_days(...).at([...])`、`selection.limit`、`selection.market_cap_band`、`filter.stock_ma`、`filter.stock_expr`、`ordering.rank_by`、`ordering.rank_expr`、`allocation.buy_scale`、`risk.stop_loss`、`risk.take_profit`、`risk.index_exposure`、`execution.matching_type`、`execution.slippage`、`universe.exclude`。\n");
|
||||||
out.push_str("- 禁止伪 DSL:`filter(...)`、`rank(...)`、`select.top(...)`、`weight.equal(...)`、`sell_rule(...)`、`backtest(...)`、`risk.max_position(...)`。\n");
|
out.push_str("- 禁止伪 DSL:`filter(...)`、`rank(...)`、`select.top(...)`、`weight.equal(...)`、`sell_rule(...)`、`backtest(...)`、`risk.max_position(...)`。\n");
|
||||||
out.push_str("- 市值表达式字段只能用 `market_cap` 或 `free_float_cap`;不要使用数据库原始字段 `float_market_cap`。\n");
|
out.push_str("- 市值表达式字段只能用 `market_cap` 或 `free_float_cap`;不要使用数据库原始字段 `float_market_cap`。\n");
|
||||||
out.push_str("- 60日价格均线使用 `rolling_mean(\"close\", 60)`;不要使用 `ma60`、`stock_ma60`、`signal_ma60` 或 `benchmark_ma60`。\n");
|
out.push_str("- 任意窗口价格均线使用 `rolling_mean(\"close\", n)` 或 `ma(\"close\", n)`;任意窗口均量使用 `rolling_mean(\"volume\", n)` 或 `vma(n)`;不要使用未列出的 `ma60`、`stock_ma60`、`signal_ma60` 或 `benchmark_ma60` 变量。\n");
|
||||||
out.push_str("- 自定义 `fn` 必须通过参数传入运行时字段;不要用 `fn score()` 这类零参数函数直接引用 `market_cap`、`close`、`ma5` 等股票字段。\n");
|
out.push_str("- 自定义 `fn` 必须通过参数传入运行时字段;不要用 `fn score()` 这类零参数函数直接引用 `market_cap`、`close`、`ma5` 等股票字段。\n");
|
||||||
out.push_str("- `selection.market_cap_band` 必须写命名参数:`field=\"market_cap\"` 或 `field=\"free_float_cap\"`,并包含 `lower=...` 与 `upper=...`。\n");
|
out.push_str("- `selection.market_cap_band` 必须写命名参数:`field=\"market_cap\"` 或 `field=\"free_float_cap\"`,并包含 `lower=...` 与 `upper=...`。\n");
|
||||||
out.push_str("- `risk.index_exposure(...)` 只能传一个表达式;`execution.matching_type(...)` 和 `execution.slippage(...)` 必须使用手册列出的合法取值。\n\n");
|
out.push_str("- `risk.index_exposure(...)` 只能传一个表达式;`execution.matching_type(...)` 和 `execution.slippage(...)` 必须使用手册列出的合法取值。\n\n");
|
||||||
@@ -506,7 +508,7 @@ pub fn build_generation_prompt(
|
|||||||
prompt.push_str("- 生成的代码必须能转换为 strategy_spec 并提交 POST /v1/backtests。\n");
|
prompt.push_str("- 生成的代码必须能转换为 strategy_spec 并提交 POST /v1/backtests。\n");
|
||||||
prompt.push_str("- 不要使用手册未列出的字段、函数或外部平台 API 名称。\n\n");
|
prompt.push_str("- 不要使用手册未列出的字段、函数或外部平台 API 名称。\n\n");
|
||||||
prompt.push_str("只允许使用这些可编译语句:market、benchmark、signal、rebalance.every_days(...).at([...])、selection.limit、selection.market_cap_band、filter.stock_ma、filter.stock_expr、ordering.rank_by、ordering.rank_expr、allocation.buy_scale、risk.stop_loss、risk.take_profit、risk.index_exposure、execution.matching_type、execution.slippage、universe.exclude。禁止输出 filter(...)、rank(...)、select.top(...)、weight.equal()、sell_rule(...)、backtest(...)、risk.max_position(...) 这类未支持伪语法。\n");
|
prompt.push_str("只允许使用这些可编译语句:market、benchmark、signal、rebalance.every_days(...).at([...])、selection.limit、selection.market_cap_band、filter.stock_ma、filter.stock_expr、ordering.rank_by、ordering.rank_expr、allocation.buy_scale、risk.stop_loss、risk.take_profit、risk.index_exposure、execution.matching_type、execution.slippage、universe.exclude。禁止输出 filter(...)、rank(...)、select.top(...)、weight.equal()、sell_rule(...)、backtest(...)、risk.max_position(...) 这类未支持伪语法。\n");
|
||||||
prompt.push_str("参数形态必须严格:selection.market_cap_band 必须写 field=\"market_cap\" 或 field=\"free_float_cap\", lower=..., upper=...;禁止使用 float_market_cap;禁止使用 ma60、stock_ma60、signal_ma60、benchmark_ma60,60日价格均线写 rolling_mean(\"close\", 60);不要生成 fn score() 这类零参数函数,股票字段排序直接写在 ordering.rank_expr 内或用带参数函数;布尔字段按布尔使用,写 !is_st、!paused、!at_upper_limit、!at_lower_limit,不要写 is_st == 0;risk.index_exposure 只能传一个数值表达式,例如 ((signal_close < signal_ma20) ? 0.35 : 1.0);execution.matching_type 只能取 next_tick_last、next_tick_best_own、next_tick_best_counterparty、counterparty_offer、vwap、current_bar_close、next_bar_open、open_auction;execution.slippage 必须写 execution.slippage(\"none\") 或 execution.slippage(\"price_ratio\", 0.001)。\n");
|
prompt.push_str("参数形态必须严格:selection.market_cap_band 必须写 field=\"market_cap\" 或 field=\"free_float_cap\", lower=..., upper=...;禁止使用 float_market_cap;禁止使用 ma60、stock_ma60、signal_ma60、benchmark_ma60,60日价格均线写 rolling_mean(\"close\", 60) 或 ma(\"close\", 60),任意窗口均量写 rolling_mean(\"volume\", n) 或 vma(n);不要生成 fn score() 这类零参数函数,股票字段排序直接写在 ordering.rank_expr 内或用带参数函数;布尔字段按布尔使用,写 !is_st、!paused、!at_upper_limit、!at_lower_limit,不要写 is_st == 0;risk.index_exposure 只能传一个数值表达式,例如 ((signal_close < signal_ma20) ? 0.35 : 1.0);execution.matching_type 只能取 next_tick_last、next_tick_best_own、next_tick_best_counterparty、counterparty_offer、vwap、current_bar_close、next_bar_open、open_auction;execution.slippage 必须写 execution.slippage(\"none\") 或 execution.slippage(\"price_ratio\", 0.001)。\n");
|
||||||
prompt.push_str("回测成功但 tradeCount=0 或 holdingCount=0 是无效策略;第一版必须保持稳定买入覆盖率,复杂因子只能在后续优化中逐步加严。\n");
|
prompt.push_str("回测成功但 tradeCount=0 或 holdingCount=0 是无效策略;第一版必须保持稳定买入覆盖率,复杂因子只能在后续优化中逐步加严。\n");
|
||||||
prompt.push_str("可参考但不要照抄的最小模板,回复时不要包含 ``` 代码围栏:\nstrategy(\"cn_a_smallcap_factor_rotation\") {\nmarket(\"CN_A\")\nbenchmark(\"000852.SH\")\nsignal(\"000001.SH\")\nrebalance.every_days(5).at([\"10:18\"])\nselection.limit(40)\nselection.market_cap_band(field=\"market_cap\", lower=0, upper=1000)\nfilter.stock_expr(listed_days >= 60 && !is_st && !paused && close > 2 && !at_upper_limit && !at_lower_limit)\nordering.rank_by(\"market_cap\", \"asc\")\nallocation.buy_scale(1.0)\nrisk.index_exposure((signal_close < signal_ma20) ? 0.35 : 1.0)\nrisk.stop_loss(holding_return < -0.08)\nexecution.slippage(\"price_ratio\", 0.001)\n}\n\n");
|
prompt.push_str("可参考但不要照抄的最小模板,回复时不要包含 ``` 代码围栏:\nstrategy(\"cn_a_smallcap_factor_rotation\") {\nmarket(\"CN_A\")\nbenchmark(\"000852.SH\")\nsignal(\"000001.SH\")\nrebalance.every_days(5).at([\"10:18\"])\nselection.limit(40)\nselection.market_cap_band(field=\"market_cap\", lower=0, upper=1000)\nfilter.stock_expr(listed_days >= 60 && !is_st && !paused && close > 2 && !at_upper_limit && !at_lower_limit)\nordering.rank_by(\"market_cap\", \"asc\")\nallocation.buy_scale(1.0)\nrisk.index_exposure((signal_close < signal_ma20) ? 0.35 : 1.0)\nrisk.stop_loss(holding_return < -0.08)\nexecution.slippage(\"price_ratio\", 0.001)\n}\n\n");
|
||||||
prompt.push_str("用户目标:\n");
|
prompt.push_str("用户目标:\n");
|
||||||
@@ -535,6 +537,7 @@ pub fn build_optimization_prompt(
|
|||||||
prompt.push_str("输出格式硬约束:回复第一行必须是 strategy(\"...\")、let、fn、const 或 //;回复中不得包含 Markdown、解释、思考过程、手册复述、JSON 包装或自然语言总结。\n");
|
prompt.push_str("输出格式硬约束:回复第一行必须是 strategy(\"...\")、let、fn、const 或 //;回复中不得包含 Markdown、解释、思考过程、手册复述、JSON 包装或自然语言总结。\n");
|
||||||
prompt.push_str("长度硬约束:策略代码目标 80 行以内,只保留必要 let/fn/strategy 块;不要复制下面的手册片段、历史策略全文或字段清单。\n");
|
prompt.push_str("长度硬约束:策略代码目标 80 行以内,只保留必要 let/fn/strategy 块;不要复制下面的手册片段、历史策略全文或字段清单。\n");
|
||||||
prompt.push_str("只修改与优化目标相关的少量参数或过滤条件,保留原策略的市场、基准、信号指数和核心风控;不要引入手册未列出的字段或外部平台 API 名称。\n");
|
prompt.push_str("只修改与优化目标相关的少量参数或过滤条件,保留原策略的市场、基准、信号指数和核心风控;不要引入手册未列出的字段或外部平台 API 名称。\n");
|
||||||
|
prompt.push_str("优化可以调整调仓周期、持仓数、市值带、filter.stock_expr、ordering.rank_expr、allocation.buy_scale、止盈止损;如上一轮无交易或质量分过低,必须先放宽过滤条件并优先使用已入库指标因子、rolling_mean/ma/vma/rolling_stddev/pct_change 等支持函数。\n");
|
||||||
prompt.push_str("优化目标:\n");
|
prompt.push_str("优化目标:\n");
|
||||||
prompt.push_str(&format!("- {}\n\n", request.objective));
|
prompt.push_str(&format!("- {}\n\n", request.objective));
|
||||||
prompt.push_str("当前策略代码如下,仅作为输入参考;回复时不要包含 Markdown 代码围栏:\n");
|
prompt.push_str("当前策略代码如下,仅作为输入参考;回复时不要包含 Markdown 代码围栏:\n");
|
||||||
|
|||||||
Reference in New Issue
Block a user