Collapse
kaya-collapseCoreVariants
One module per value type. They behave identically; pick the one matching the type you are wiring.
| Name | Type |
|---|---|
| Collapse Boolean | True/false |
| Collapse Double | Number |
| Collapse Float | Number |
| Collapse Integer | Whole number |
| Collapse String | Text |
Cost
1 credits for n bars, rounded up. The marks are each plan's limit of bars.
A sweep asks a question many times at once. Collapse answers it once.
Fan a strategy out over a basket of assets, or a range of indicator settings, and you get many parallel candidates. But a signal needs one answer. Collapse applies your rules and forwards exactly one, so the rest of the strategy works on a single branch.
If Filter says "give me the best few", Collapse says "give me the one". It is the normal way to end a sweep.
The fan-out is described on the For Each page; forwarding several ranked survivors on the Filter page. This page is about choosing the winner, and it is mostly worked examples.
Where Collapse Sits
flowchart LR
S["Sweep<br/>5 combinations"]
subgraph FAN["Fanned-out branch"]
direction TB
C0["Candidate 0"]
C1["Candidate 1"]
C2["Candidate 2"]
C3["Candidate 3"]
C4["Candidate 4"]
end
CO["Collapse<br/>Take = 1"]
SEL["Selection"]
IDX["Selection index"]
D["Rest of the strategy<br/>one branch"]
S --> C0 & C1 & C2 & C3 & C4
C0 & C1 & C2 & C3 & C4 --> CO
CO --> SEL --> D
CO --> IDX
style CO fill:#1565c0,color:#fff
style SEL fill:#c8e6c9,stroke:#2e7d32
style IDX fill:#c8e6c9,stroke:#2e7d32
style D fill:#fff3e0,stroke:#ef6c00
Everything downstream of Selection sees one ordinary series, as if the sweep had never happened.
The Selection Rule
Let be the candidates in sweep order. Three stages follow.
Stage 1 — Eligibility. A candidate survives if it has data and its Condition ends true, meaning its last non-empty value is true, 1 or any non-zero number:
Without Condition wired the second clause drops, and every non-empty candidate survives.
Stage 2 — Ranking. Survivors are ordered by the last non-empty value of their Sort series, :
Without Sort wired no reordering happens at all: survivors keep input order, and Order is irrelevant.
Stage 3 — Take. Take is fixed at : the first ranked candidate becomes the Selection, the rest are discarded. That fixed is the whole difference from Filter.
Ranking is stable: survivors with the same Sort value keep their input order, so the earlier one wins.
flowchart TB
A["All candidates<br/>in input order"] --> B{"Condition wired?"}
B -- "no" --> C["Every non-empty<br/>candidate survives"]
B -- "yes" --> D["Keep candidates whose<br/>Condition ends true"]
C --> E{"Any survivor?"}
D --> E
E -- "no" --> F["Selection empty<br/>branch dies"]
E -- "yes" --> G{"Sort wired?"}
G -- "no" --> H["Keep input order"]
G -- "yes" --> I["Rank by last Sort value<br/>Order = asc or desc<br/>ties keep input order"]
H --> J["Take the first<br/>Take = 1"]
I --> J
J --> K["Selection + Selection index"]
style F fill:#ffcdd2,stroke:#c62828
style K fill:#c8e6c9,stroke:#2e7d32
style D fill:#e3f2fd,stroke:#1565c0
style I fill:#e3f2fd,stroke:#1565c0
Inputs and Outputs at a Glance
| Wiring | Role |
|---|---|
| Items | The candidates, one per sweep combination, in sweep order. |
| Condition (optional) | One boolean series per candidate. Only its last value is read. |
| Sort (optional) | One numeric series per candidate. Only its last value is read. |
| Order | desc — highest Sort value wins. asc — lowest wins. Absent, it behaves as desc. |
| Take | Fixed at 1. |
| Selection | The winning candidate's series. |
| Selection index | Which candidate won, counting from 0 in input order. You can read it, but only Selection can be wired. |
Condition and Sort are verdicts on a candidate, not bar-by-bar signals.
Worked Example 1: One Sector Out of Five
The idea. Rather than spread capital across every sector, hold the one with the strongest risk-adjusted momentum, and hold nothing that is falling.
The setup. Daily closes for five SPDR sector ETFs over the 63 trading days from 2026-06-05 to 2026-09-04 (64 closes, 63 daily returns, roughly one quarter). One combination per symbol, in this order: XLE (energy), XLK (technology), XLF (financials), XLV (health care), XLU (utilities).
The Sort statistic. Quarterly return over annualised volatility — a simple risk-adjusted momentum score:
where is the sample standard deviation of the 63 daily log returns and annualises it. Order is desc; Condition requires a positive quarterly return — a gate, not a ranking. It sets who reaches the podium, not who tops it.
The Candidate Table
| Index | Sector | Start (06-05) | End (09-04) | Return | Ann. volatility | Sort value | Condition |
|---|---|---|---|---|---|---|---|
| 0 | XLE | 57.67 | 64.06 | +11.08% | 22.18% | 0.500 | ✅ true |
| 1 | XLK | 180.30 | 187.28 | +3.87% | 31.92% | 0.121 | ✅ true |
| 2 | XLF | 52.30 | 58.10 | +11.09% | 12.75% | 0.870 | ✅ true |
| 3 | XLV | 153.01 | 171.45 | +12.05% | 18.62% | 0.647 | ✅ true |
| 4 | XLU | 44.35 | 43.08 | −2.86% | 14.63% | −0.196 | ❌ false |
Check the arithmetic: , and .
What happens. XLU falls at Stage 1: it declined, so its Condition ends false. The four survivors rank descending — XLF (0.870), XLV (0.647), XLE (0.500), XLK (0.121). Take is 1, so:
- Selection = the XLF price series
- Selection index = 2
Why This Example Is Worth Studying
The sector with the highest return did not win. XLV rose 12.05% against XLF's 11.09%, but was 46% more volatile, and the score reversed the ordering. XLE is starker: XLF's return earned at 22.18% volatility instead of 12.75% lands two places lower.
The lesson: the module does not know what "best" means — your Sort input defines it. Wire raw return and XLV wins; wire risk-adjusted return and XLF does. That choice is the real work.
Notice how the optional inputs divide the labour. Condition is a hard veto — is this acceptable at all? Sort is a soft preference — among those, which is better?
Worked Example 2: When Nothing Deserves Your Money
The idea. Sweep an indicator setting instead of an asset. Hold XLK only while its close sits above its -day simple moving average, letting the sweep choose — but give no signal unless the winner made money.
The setup. XLK daily closes. Five lookbacks, , in that order. Averages warm up over earlier bars; the rule runs across the 49 trading days from 2026-06-26 to 2026-09-04. Sort is the rule's realised return, Order desc, Condition demands it be positive.
The Candidate Table
| Index | Lookback | Days invested | Winning days | Rule return | Condition |
|---|---|---|---|---|---|
| 0 | 10 | 19 / 49 | 42.1% | −2.80% | ❌ false |
| 1 | 20 | 21 / 49 | 38.1% | −9.99% | ❌ false |
| 2 | 30 | 24 / 49 | 45.8% | −0.62% | ❌ false |
| 3 | 40 | 28 / 49 | 42.9% | −6.07% | ❌ false |
| 4 | 50 | 31 / 49 | 45.2% | −3.53% | ❌ false |
Simply holding XLK over the same window returned +3.41%. Every swept rule lost money, and every one lost to doing nothing clever.
What happens. All five fail the Condition. No candidate survives, Selection is empty, and nothing downstream of it runs: the strategy gives no signal. That is the module working, not failing: the honest answer to "which lookback?" was none of them.
The Same Sweep Without a Condition
Unwire Condition and re-run the same numbers. Nothing is eliminated, all five rank by Sort descending, and wins at −0.62% — Selection index 2. The strategy picks the least-bad loser.
Sort ranks; it never rejects. If your strategy must be able to stand aside, only Condition lets it.
Ties, and Values That Are Not Numbers
A Real Tie
Ties are rare with a statistic whose decimals never coincide, and the norm with counting statistics. Split the same five sectors over the same window into thirteen blocks of five trading days (the last runs three) and count the blocks that closed up:
| Index | Sector | Positive blocks (of 13) |
|---|---|---|
| 0 | XLE | 7 |
| 1 | XLK | 6 |
| 2 | XLF | 10 |
| 3 | XLV | 8 |
| 4 | XLU | 6 |
Wire this count to Sort with Order = asc — a contrarian sweep hunting the weakest sector — and XLK and XLU tie at 6. Ranking is stable, so input order decides: XLK wins, Selection index 1, being combination 1 against XLU's 4.
With coarse statistics, the order of your sweep is a silent tie-breaker. Use a finer statistic if that bothers you.
Unreadable Sort Values
A Sort value that cannot be read as a number — an empty series, or something non-numeric — is not an error and does not stop the strategy. The candidate is ranked last in both directions: under desc and asc alike, every readable candidate is placed ahead of it.
Two unreadable candidates keep their input order. An unreadable candidate wins only when no readable one is left.
The Trap: Choosing the Winner Is Not Free
Selecting the best-performing candidate from a sweep and trading it is the classic overfitting mistake. The more combinations you sweep, the likelier the winner won by luck — and luck does not repeat.
The mechanism is multiple comparisons: search enough variants against one history and something looks excellent by chance. Bailey, Borwein, López de Prado and Zhu show in Pseudo-Mathematics and Financial Charlatanism that a few trials manufacture an impressive backtest from noise.
Defences that fit naturally around a Collapse:
- Sweep across assets, not parameters. Cross-sectional momentum is widely replicated; the parameter that best fit last quarter is not.
- Keep the sweep small. Five candidates is a choice; twenty is a search.
- Make the Sort statistic robust, measured over a longer window than you intend to trade.
- Insist the winner clears an absolute bar through Condition. Best of five bad options is no reason to invest.
Collapse answers "which one?" precisely. Whether the question was worth asking of this data is a judgement it cannot make for you.
Missing Data
A branch can produce nothing upstream: a data source with no history, a Filter that rejected everything, a calculation with no result.
- A candidate whose branch produced nothing arrives empty. It keeps its place, so Selection index stays meaningful, but it can never win.
- A missing or empty Condition series eliminates that candidate. No verdict is not a pass.
- Candidates with different periods or lengths are aligned. A series with a longer period repeats its last known value, a series that ends early repeats its final value forward, and a series that starts late is empty before its first bar, so a late starter that wins brings those empty bars into Selection.
- If every candidate is eliminated, Selection is empty and nothing downstream of it runs. This is the intended way to say "no acceptable choice, so no signal".
Edge Cases
| Situation | What Collapse does |
|---|---|
| Neither Condition nor Sort wired | The first non-empty candidate wins. |
| One candidate, Condition true | It wins. Selection index 0. |
| Sweep at its cap | A sweep produces at most 20 combinations, so there are never more candidates. |
Further Reading
- Sharpe Ratio — the risk-adjusted return idea behind Example 1's Sort statistic
- Momentum in finance — why "hold the strongest" is a strategy family, not a hunch
- Jegadeesh & Titman (1993), Returns to Buying Winners and Selling Losers — the foundational momentum study
- Bailey, Borwein, López de Prado & Zhu, Pseudo-Mathematics and Financial Charlatanism — how fast sweeping makes false winners
- The multiple comparisons problem and overfitting — the statistics under that warning
- Sector rotation — the family Example 1 belongs to