alphawinnow 0.1.2

Typed, deterministic formulaic alpha-mining, factor-evaluation, and quantitative expression-search engine with a local CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::{
    Expr, ExprKind,
    operators::{self, Arity},
};

/// One immutable step from an expression root to an argument or keyword slot.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(tag = "slot", rename_all = "snake_case")]
pub enum PathSegment {
    UnaryArg,
    BinaryLeft,
    BinaryRight,
    VariadicArg { index: usize },
    Keyword { name: String },
}

/// Stable path to an AST subtree. The empty path identifies the root.
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ExprPath {
    pub segments: Vec<PathSegment>,
}

impl std::fmt::Display for ExprPath {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("$")?;
        for segment in &self.segments {
            match segment {
                PathSegment::UnaryArg => formatter.write_str(".arg")?,
                PathSegment::BinaryLeft => formatter.write_str(".left")?,
                PathSegment::BinaryRight => formatter.write_str(".right")?,
                PathSegment::VariadicArg { index } => write!(formatter, ".args[{index}]")?,
                PathSegment::Keyword { name } => write!(formatter, ".kwargs.{name}")?,
            }
        }
        Ok(())
    }
}

/// Compact set of expression kinds accepted by a typed tree slot.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct KindSet(u8);

impl KindSet {
    pub const SIGNAL_OR_SCALAR: Self = Self(0b0011);

    #[must_use]
    pub const fn singleton(kind: ExprKind) -> Self {
        Self(match kind {
            ExprKind::Signal => 0b0001,
            ExprKind::Scalar => 0b0010,
            ExprKind::Boolean => 0b0100,
            ExprKind::Group => 0b1000,
        })
    }

    #[must_use]
    pub const fn contains(self, kind: ExprKind) -> bool {
        self.0 & Self::singleton(kind).0 != 0
    }

    #[must_use]
    pub fn from_kinds(kinds: impl IntoIterator<Item = ExprKind>) -> Self {
        kinds
            .into_iter()
            .fold(Self(0), |set, kind| Self(set.0 | Self::singleton(kind).0))
    }

    pub fn iter(self) -> impl Iterator<Item = ExprKind> {
        [
            ExprKind::Signal,
            ExprKind::Scalar,
            ExprKind::Boolean,
            ExprKind::Group,
        ]
        .into_iter()
        .filter(move |kind| self.contains(*kind))
    }
}

/// A reachable subtree and the kinds accepted by its containing slot.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PathEntry {
    pub path: ExprPath,
    pub subtree_kind: ExprKind,
    pub allowed_kinds: KindSet,
}

#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum PathError {
    #[error("expression path does not exist: {0}")]
    Missing(ExprPath),
    #[error("path {path} accepts {allowed:?}, got {actual:?}")]
    WrongKind {
        path: ExprPath,
        allowed: KindSet,
        actual: ExprKind,
    },
    #[error("replacement at {path} violates its containing operator: {message}")]
    InvalidContext { path: ExprPath, message: String },
}

/// Enumerate the root, every positional argument, and every keyword slot.
#[must_use]
pub fn enumerate_paths(expression: &Expr) -> Vec<PathEntry> {
    let mut entries = Vec::new();
    let root = ExprPath::default();
    enumerate(
        expression,
        &root,
        KindSet::singleton(expression.kind()),
        &mut entries,
    );
    entries
}

fn enumerate(
    expression: &Expr,
    path: &ExprPath,
    allowed_kinds: KindSet,
    entries: &mut Vec<PathEntry>,
) {
    entries.push(PathEntry {
        path: path.clone(),
        subtree_kind: expression.kind(),
        allowed_kinds,
    });
    match expression {
        Expr::UnaryCall {
            op, arg, kwargs, ..
        } => {
            let allowed = positional_kinds(op, 0, arg);
            enumerate(
                arg,
                &extended(path, PathSegment::UnaryArg),
                allowed,
                entries,
            );
            enumerate_keywords(kwargs, path, entries);
        }
        Expr::BinaryCall {
            op,
            left,
            right,
            kwargs,
            ..
        } => {
            enumerate(
                left,
                &extended(path, PathSegment::BinaryLeft),
                positional_kinds(op, 0, left),
                entries,
            );
            enumerate(
                right,
                &extended(path, PathSegment::BinaryRight),
                positional_kinds(op, 1, right),
                entries,
            );
            enumerate_keywords(kwargs, path, entries);
        }
        Expr::VariadicCall {
            op, args, kwargs, ..
        } => {
            for (index, arg) in args.iter().enumerate() {
                enumerate(
                    arg,
                    &extended(path, PathSegment::VariadicArg { index }),
                    positional_kinds(op, index, arg),
                    entries,
                );
            }
            enumerate_keywords(kwargs, path, entries);
        }
        Expr::Field { .. } | Expr::Scalar { .. } | Expr::Group { .. } | Expr::Bool { .. } => {}
    }
}

fn enumerate_keywords(
    kwargs: &std::collections::BTreeMap<String, Expr>,
    path: &ExprPath,
    entries: &mut Vec<PathEntry>,
) {
    for (name, value) in kwargs {
        enumerate(
            value,
            &extended(path, PathSegment::Keyword { name: name.clone() }),
            KindSet::singleton(ExprKind::Scalar),
            entries,
        );
    }
}

fn positional_kinds(op: &str, index: usize, actual: &Expr) -> KindSet {
    let Some(spec) = operators::lookup(op) else {
        return KindSet::singleton(actual.kind());
    };
    let input = match spec.arity {
        Arity::Variadic { .. } => spec.inputs.first(),
        Arity::Exact { .. } | Arity::Unary | Arity::Binary => spec.inputs.get(index),
    };
    input.map_or_else(
        || KindSet::singleton(actual.kind()),
        |input| KindSet::from_kinds(input.kinds.iter().copied()),
    )
}

fn extended(path: &ExprPath, segment: PathSegment) -> ExprPath {
    let mut segments = path.segments.clone();
    segments.push(segment);
    ExprPath { segments }
}

/// Look up a subtree without modifying its owner.
#[must_use]
pub fn subtree_at<'a>(expression: &'a Expr, path: &ExprPath) -> Option<&'a Expr> {
    let mut current = expression;
    for segment in &path.segments {
        current = match (current, segment) {
            (Expr::UnaryCall { arg, .. }, PathSegment::UnaryArg) => arg,
            (Expr::BinaryCall { left, .. }, PathSegment::BinaryLeft) => left,
            (Expr::BinaryCall { right, .. }, PathSegment::BinaryRight) => right,
            (Expr::VariadicCall { args, .. }, PathSegment::VariadicArg { index }) => {
                args.get(*index)?
            }
            (
                Expr::UnaryCall { kwargs, .. }
                | Expr::BinaryCall { kwargs, .. }
                | Expr::VariadicCall { kwargs, .. },
                PathSegment::Keyword { name },
            ) => kwargs.get(name)?,
            _ => return None,
        };
    }
    Some(current)
}

/// Return all kinds accepted by a path in the current typed tree.
#[must_use]
pub fn allowed_kinds(expression: &Expr, path: &ExprPath) -> Option<KindSet> {
    enumerate_paths(expression)
        .into_iter()
        .find(|entry| entry.path == *path)
        .map(|entry| entry.allowed_kinds)
}

/// Clone a tree with exactly one typed subtree replaced.
///
/// # Errors
/// Returns an error for a missing path or a replacement of the wrong kind.
pub fn replace_subtree(
    expression: &Expr,
    path: &ExprPath,
    replacement: Expr,
) -> Result<Expr, PathError> {
    let allowed =
        allowed_kinds(expression, path).ok_or_else(|| PathError::Missing(path.clone()))?;
    if !allowed.contains(replacement.kind()) {
        return Err(PathError::WrongKind {
            path: path.clone(),
            allowed,
            actual: replacement.kind(),
        });
    }
    let candidate = replace_at(expression, &path.segments, replacement)
        .ok_or_else(|| PathError::Missing(path.clone()))?;
    validate_structure(&candidate).map_err(|message| PathError::InvalidContext {
        path: path.clone(),
        message,
    })?;
    Ok(candidate)
}

fn validate_structure(expression: &Expr) -> Result<(), String> {
    for child in expression.children() {
        validate_structure(child)?;
    }
    let rebuilt = match expression {
        Expr::UnaryCall {
            op, arg, kwargs, ..
        } => operators::build_call(op, vec![arg.as_ref().clone()], kwargs.clone())?,
        Expr::BinaryCall {
            op,
            left,
            right,
            kwargs,
            ..
        } => operators::build_call(
            op,
            vec![left.as_ref().clone(), right.as_ref().clone()],
            kwargs.clone(),
        )?,
        Expr::VariadicCall {
            op, args, kwargs, ..
        } => operators::build_call(op, args.clone(), kwargs.clone())?,
        Expr::Field { .. } | Expr::Scalar { .. } | Expr::Group { .. } | Expr::Bool { .. } => {
            return Ok(());
        }
    };
    if rebuilt.kind() == expression.kind() {
        Ok(())
    } else {
        Err(format!(
            "operator output kind is {:?}, stored node kind is {:?}",
            rebuilt.kind(),
            expression.kind()
        ))
    }
}

fn replace_at(expression: &Expr, segments: &[PathSegment], replacement: Expr) -> Option<Expr> {
    let Some((head, tail)) = segments.split_first() else {
        return Some(replacement);
    };
    let mut result = expression.clone();
    match (&mut result, head) {
        (Expr::UnaryCall { arg, .. }, PathSegment::UnaryArg) => {
            **arg = replace_at(arg, tail, replacement)?;
        }
        (Expr::BinaryCall { left, .. }, PathSegment::BinaryLeft) => {
            **left = replace_at(left, tail, replacement)?;
        }
        (Expr::BinaryCall { right, .. }, PathSegment::BinaryRight) => {
            **right = replace_at(right, tail, replacement)?;
        }
        (Expr::VariadicCall { args, .. }, PathSegment::VariadicArg { index }) => {
            args[*index] = replace_at(args.get(*index)?, tail, replacement)?;
        }
        (
            Expr::UnaryCall { kwargs, .. }
            | Expr::BinaryCall { kwargs, .. }
            | Expr::VariadicCall { kwargs, .. },
            PathSegment::Keyword { name },
        ) => {
            let current = kwargs.get(name)?;
            let value = replace_at(current, tail, replacement)?;
            kwargs.insert(name.clone(), value);
        }
        _ => return None,
    }
    Some(result)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{canonical, parse_expression};

    #[test]
    fn enumerates_arguments_keywords_and_allowed_kinds() {
        let expression = parse_expression("winsorize(ts_mean(close, 20), std=2)").unwrap();
        let entries = enumerate_paths(&expression);
        assert_eq!(entries.len(), 5);
        assert!(entries.iter().any(|entry| {
            entry.path.to_string() == "$.arg.right"
                && entry.allowed_kinds == KindSet::singleton(ExprKind::Scalar)
        }));
        assert!(entries.iter().any(|entry| {
            entry.path.to_string() == "$.kwargs.std"
                && entry.allowed_kinds == KindSet::singleton(ExprKind::Scalar)
        }));
    }

    #[test]
    fn replaces_only_a_kind_compatible_slot() {
        let expression = parse_expression("ts_mean(close, 20)").unwrap();
        let path = ExprPath {
            segments: vec![PathSegment::BinaryLeft],
        };
        let replaced = replace_subtree(
            &expression,
            &path,
            Expr::Field {
                name: "open".to_owned(),
            },
        )
        .unwrap();
        assert_eq!(canonical(&replaced), "ts_mean(open, 20)");
        assert!(matches!(
            replace_subtree(&expression, &path, Expr::Scalar { value: 2.0 }),
            Err(PathError::WrongKind { .. })
        ));
    }

    #[test]
    fn multiply_slots_accept_signal_or_scalar_while_preserving_a_signal() {
        let expression = parse_expression("multiply(close, open)").unwrap();
        let first = ExprPath {
            segments: vec![PathSegment::VariadicArg { index: 0 }],
        };
        let first_entry = enumerate_paths(&expression)
            .into_iter()
            .find(|entry| entry.path == first)
            .unwrap();
        assert_eq!(first_entry.allowed_kinds, KindSet::SIGNAL_OR_SCALAR);

        let replaced = replace_subtree(&expression, &first, Expr::Scalar { value: 2.0 }).unwrap();
        assert_eq!(canonical(&replaced), "multiply(2, open)");

        let last_signal = parse_expression("multiply(close, 2)").unwrap();
        assert!(matches!(
            replace_subtree(&last_signal, &first, Expr::Scalar { value: 3.0 }),
            Err(PathError::InvalidContext { .. })
        ));
    }
}