@tradecanvas/analytics 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 TradeCanvas Contributors
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 TradeCanvas Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,146 +1,146 @@
1
- # @tradecanvas/analytics
2
-
3
- Backtesting, portfolio tracking, and risk analytics for [TradeCanvas](https://github.com/bonguynvan/tradecanvas).
4
-
5
- > **Preview release.** API is stable but the engine has only been validated
6
- > against synthetic test fixtures. Treat results as indicative until you've
7
- > cross-checked them against your own reference implementation.
8
-
9
- ## Install
10
-
11
- ```bash
12
- npm install @tradecanvas/analytics @tradecanvas/commons
13
- ```
14
-
15
- ## Backtester
16
-
17
- Bar-by-bar engine. Strategy fn runs at close of each bar; orders fill on the **next** bar (market → next-bar open, limit/stop → when the next bar trades through the trigger price).
18
-
19
- ```ts
20
- import { Backtester, FixedCommission, PercentSlippage } from '@tradecanvas/analytics'
21
-
22
- const bt = new Backtester({
23
- initialCash: 10_000,
24
- commission: new FixedCommission(2),
25
- slippage: new PercentSlippage(0.0005),
26
- allowShort: true,
27
- })
28
-
29
- const result = bt.run(historicalBars, (ctx) => {
30
- if (!ctx.position) {
31
- ctx.placeOrder({ side: 'long', type: 'market', quantity: 1 })
32
- } else if (ctx.bar.close > ctx.position.averagePrice * 1.02) {
33
- ctx.close()
34
- }
35
- })
36
-
37
- console.log(result.metrics.sharpe, result.metrics.maxDrawdownPct)
38
- ```
39
-
40
- ## StrategyContext
41
-
42
- Field / method | Description
43
- ---|---
44
- `bar` | Current bar
45
- `index` | Index of `bar` in the input series
46
- `history` | Bars up to and including `bar`
47
- `position` | Current position or `null`
48
- `cash` | Available cash
49
- `equity` | Cash + mark-to-market position value
50
- `placeOrder(order)` | Queue order for next bar
51
- `close(tag?)` | Market-close current position
52
- `cancel(orderId)` | Cancel a pending order
53
-
54
- ## Commission & slippage models
55
-
56
- - `FixedCommission(perTrade)`
57
- - `PercentCommission(rate)` — fraction of notional, e.g. `0.001` = 10 bps
58
- - `PerShareCommission(perShare, minimum?)`
59
- - `PercentSlippage(rate)` — adverse fraction of price
60
- - `RangeBasedSlippage(factor)` — proportional to bar range
61
-
62
- ## Portfolio
63
-
64
- Tracks cash, one net position, realized P&L, and the equity curve.
65
-
66
- ```ts
67
- import { Portfolio } from '@tradecanvas/analytics'
68
-
69
- const portfolio = new Portfolio({ initialCash: 10_000 })
70
- portfolio.applyFill({ ... })
71
- portfolio.mark(time, price)
72
-
73
- portfolio.getPosition() // → { side, quantity, averagePrice, ... } | null
74
- portfolio.getTrades() // → closed trades
75
- portfolio.getEquityCurve() // → equity points
76
- portfolio.equity(price) // mark-to-market
77
- ```
78
-
79
- > Currently single-position. Multi-symbol portfolios are on the roadmap.
80
-
81
- ## Risk metrics
82
-
83
- ```ts
84
- import { computeRiskMetrics } from '@tradecanvas/analytics'
85
-
86
- const m = computeRiskMetrics(initialCash, equityCurve, trades, {
87
- periodsPerYear: 252, // optional; auto-detected from timestamps
88
- riskFreeRate: 0.03,
89
- })
90
-
91
- m.totalReturnPct
92
- m.cagr
93
- m.sharpe
94
- m.sortino
95
- m.calmar
96
- m.maxDrawdownPct
97
- m.winRate
98
- m.profitFactor
99
- m.expectancy
100
- ```
101
-
102
- ## Strategy library
103
-
104
- Reference strategies live under `@tradecanvas/analytics` — drop in, tune
105
- parameters, run. All four implement the same `StrategyFn` shape and respect
106
- the backtester's `allowShort` flag.
107
-
108
- ```ts
109
- import {
110
- Backtester,
111
- smaCrossStrategy,
112
- rsiReversionStrategy,
113
- donchianBreakoutStrategy,
114
- bollingerReversionStrategy,
115
- } from '@tradecanvas/analytics';
116
-
117
- const bt = new Backtester({ initialCash: 10_000 });
118
-
119
- const result = bt.run(bars, smaCrossStrategy({
120
- fastPeriod: 10,
121
- slowPeriod: 30,
122
- size: 1,
123
- }));
124
- ```
125
-
126
- | Strategy | Style | Tuning |
127
- |---|---|---|
128
- | `smaCrossStrategy` | Trend-following | `fastPeriod`, `slowPeriod`, `size` |
129
- | `rsiReversionStrategy` | Mean-reversion (long-only) | `period`, `oversold`, `overbought`, `size` |
130
- | `donchianBreakoutStrategy` | Trend breakout (Turtle-style) | `entryPeriod`, `exitPeriod`, `size` |
131
- | `bollingerReversionStrategy` | Mean-reversion to SMA | `period`, `stdDev`, `size` |
132
-
133
- Each is a one-line function call returning a `StrategyFn` — easy to wrap,
134
- combine, or compare side-by-side in a backtest harness.
135
-
136
- ## Edge cases (current behavior)
137
-
138
- - **Gaps past a limit price**: if the bar opens already through the limit, the order fills at the better of `open` and the limit price.
139
- - **Stop orders inside a gap**: fill at the worse of `open` and the stop price.
140
- - **Bar that touches both stop and limit on the same bar**: order resolves to the more pessimistic price for the current side (no intra-bar tick simulation).
141
-
142
- These choices are conservative. A future release will offer a configurable intra-bar fill model.
143
-
144
- ## License
145
-
146
- MIT
1
+ # @tradecanvas/analytics
2
+
3
+ Backtesting, portfolio tracking, and risk analytics for [TradeCanvas](https://github.com/bonguynvan/tradecanvas).
4
+
5
+ > **Preview release.** API is stable but the engine has only been validated
6
+ > against synthetic test fixtures. Treat results as indicative until you've
7
+ > cross-checked them against your own reference implementation.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install @tradecanvas/analytics @tradecanvas/commons
13
+ ```
14
+
15
+ ## Backtester
16
+
17
+ Bar-by-bar engine. Strategy fn runs at close of each bar; orders fill on the **next** bar (market → next-bar open, limit/stop → when the next bar trades through the trigger price).
18
+
19
+ ```ts
20
+ import { Backtester, FixedCommission, PercentSlippage } from '@tradecanvas/analytics'
21
+
22
+ const bt = new Backtester({
23
+ initialCash: 10_000,
24
+ commission: new FixedCommission(2),
25
+ slippage: new PercentSlippage(0.0005),
26
+ allowShort: true,
27
+ })
28
+
29
+ const result = bt.run(historicalBars, (ctx) => {
30
+ if (!ctx.position) {
31
+ ctx.placeOrder({ side: 'long', type: 'market', quantity: 1 })
32
+ } else if (ctx.bar.close > ctx.position.averagePrice * 1.02) {
33
+ ctx.close()
34
+ }
35
+ })
36
+
37
+ console.log(result.metrics.sharpe, result.metrics.maxDrawdownPct)
38
+ ```
39
+
40
+ ## StrategyContext
41
+
42
+ Field / method | Description
43
+ ---|---
44
+ `bar` | Current bar
45
+ `index` | Index of `bar` in the input series
46
+ `history` | Bars up to and including `bar`
47
+ `position` | Current position or `null`
48
+ `cash` | Available cash
49
+ `equity` | Cash + mark-to-market position value
50
+ `placeOrder(order)` | Queue order for next bar
51
+ `close(tag?)` | Market-close current position
52
+ `cancel(orderId)` | Cancel a pending order
53
+
54
+ ## Commission & slippage models
55
+
56
+ - `FixedCommission(perTrade)`
57
+ - `PercentCommission(rate)` — fraction of notional, e.g. `0.001` = 10 bps
58
+ - `PerShareCommission(perShare, minimum?)`
59
+ - `PercentSlippage(rate)` — adverse fraction of price
60
+ - `RangeBasedSlippage(factor)` — proportional to bar range
61
+
62
+ ## Portfolio
63
+
64
+ Tracks cash, one net position, realized P&L, and the equity curve.
65
+
66
+ ```ts
67
+ import { Portfolio } from '@tradecanvas/analytics'
68
+
69
+ const portfolio = new Portfolio({ initialCash: 10_000 })
70
+ portfolio.applyFill({ ... })
71
+ portfolio.mark(time, price)
72
+
73
+ portfolio.getPosition() // → { side, quantity, averagePrice, ... } | null
74
+ portfolio.getTrades() // → closed trades
75
+ portfolio.getEquityCurve() // → equity points
76
+ portfolio.equity(price) // mark-to-market
77
+ ```
78
+
79
+ > Currently single-position. Multi-symbol portfolios are on the roadmap.
80
+
81
+ ## Risk metrics
82
+
83
+ ```ts
84
+ import { computeRiskMetrics } from '@tradecanvas/analytics'
85
+
86
+ const m = computeRiskMetrics(initialCash, equityCurve, trades, {
87
+ periodsPerYear: 252, // optional; auto-detected from timestamps
88
+ riskFreeRate: 0.03,
89
+ })
90
+
91
+ m.totalReturnPct
92
+ m.cagr
93
+ m.sharpe
94
+ m.sortino
95
+ m.calmar
96
+ m.maxDrawdownPct
97
+ m.winRate
98
+ m.profitFactor
99
+ m.expectancy
100
+ ```
101
+
102
+ ## Strategy library
103
+
104
+ Reference strategies live under `@tradecanvas/analytics` — drop in, tune
105
+ parameters, run. All four implement the same `StrategyFn` shape and respect
106
+ the backtester's `allowShort` flag.
107
+
108
+ ```ts
109
+ import {
110
+ Backtester,
111
+ smaCrossStrategy,
112
+ rsiReversionStrategy,
113
+ donchianBreakoutStrategy,
114
+ bollingerReversionStrategy,
115
+ } from '@tradecanvas/analytics';
116
+
117
+ const bt = new Backtester({ initialCash: 10_000 });
118
+
119
+ const result = bt.run(bars, smaCrossStrategy({
120
+ fastPeriod: 10,
121
+ slowPeriod: 30,
122
+ size: 1,
123
+ }));
124
+ ```
125
+
126
+ | Strategy | Style | Tuning |
127
+ |---|---|---|
128
+ | `smaCrossStrategy` | Trend-following | `fastPeriod`, `slowPeriod`, `size` |
129
+ | `rsiReversionStrategy` | Mean-reversion (long-only) | `period`, `oversold`, `overbought`, `size` |
130
+ | `donchianBreakoutStrategy` | Trend breakout (Turtle-style) | `entryPeriod`, `exitPeriod`, `size` |
131
+ | `bollingerReversionStrategy` | Mean-reversion to SMA | `period`, `stdDev`, `size` |
132
+
133
+ Each is a one-line function call returning a `StrategyFn` — easy to wrap,
134
+ combine, or compare side-by-side in a backtest harness.
135
+
136
+ ## Edge cases (current behavior)
137
+
138
+ - **Gaps past a limit price**: if the bar opens already through the limit, the order fills at the better of `open` and the limit price.
139
+ - **Stop orders inside a gap**: fill at the worse of `open` and the stop price.
140
+ - **Bar that touches both stop and limit on the same bar**: order resolves to the more pessimistic price for the current side (no intra-bar tick simulation).
141
+
142
+ These choices are conservative. A future release will offer a configurable intra-bar fill model.
143
+
144
+ ## License
145
+
146
+ MIT
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=class{constructor(e){this.perTrade=e}calculate(){return this.perTrade}},t=class{constructor(e){this.rate=e}calculate(e,t){return Math.abs(e)*t*this.rate}},n=class{constructor(e,t=0){this.perShare=e,this.minimum=t}calculate(e){return Math.max(this.minimum,Math.abs(e)*this.perShare)}},r={calculate:()=>0},i={apply:e=>e},a=class{constructor(e){this.rate=e}apply(e,t){return e*(t===`long`?1+this.rate:1-this.rate)}},o=class{constructor(e){this.factor=e}apply(e,t,n){let r=(n.high-n.low)*this.factor;return t===`long`?e+r:e-r}},s=class{cash;initialCash;position=null;fills=[];trades=[];equityCurve=[];realizedPnl=0;constructor(e){if(e.initialCash<=0)throw Error(`initialCash must be > 0`);this.cash=e.initialCash,this.initialCash=e.initialCash}getCash(){return this.cash}getPosition(){return this.position}getFills(){return this.fills}getTrades(){return this.trades}getEquityCurve(){return this.equityCurve}getInitialCash(){return this.initialCash}getRealizedPnl(){return this.realizedPnl}unrealizedPnl(e){if(!this.position)return 0;let t=this.position.side===`long`?1:-1;return(e-this.position.averagePrice)*this.position.quantity*t}equity(e){return this.cash+this.positionValue(e)}positionValue(e){if(!this.position)return 0;let t=this.position.side===`long`?1:-1;return this.position.quantity*e*t}applyFill(e){this.fills.push(e);let t=e.side===`long`?e.quantity:-e.quantity;if(this.cash-=t*e.price,this.cash-=e.commission,!this.position){this.position={side:e.side,quantity:e.quantity,averagePrice:e.price,openedAt:e.time,tag:e.tag};return}if(this.position.side===e.side){let t=this.position.quantity+e.quantity;this.position={...this.position,quantity:t,averagePrice:(this.position.averagePrice*this.position.quantity+e.price*e.quantity)/t};return}let n=Math.min(this.position.quantity,e.quantity),r=this.position.side===`long`?1:-1,i=(e.price-this.position.averagePrice)*n*r;this.realizedPnl+=i,this.trades.push({entryTime:this.position.openedAt,exitTime:e.time,side:this.position.side,quantity:n,entryPrice:this.position.averagePrice,exitPrice:e.price,pnl:i,pnlPct:(e.price/this.position.averagePrice-1)*r,commission:e.commission,tag:e.tag??this.position.tag});let a=this.position.quantity-e.quantity;a>0?this.position={...this.position,quantity:a}:a<0?this.position={side:e.side,quantity:-a,averagePrice:e.price,openedAt:e.time,tag:e.tag}:this.position=null}mark(e,t){let n=this.positionValue(t),r=this.unrealizedPnl(t);this.equityCurve.push({time:e,equity:this.cash+n,cash:this.cash,positionValue:n,unrealizedPnl:r,realizedPnl:this.realizedPnl})}reverseSide(e){return e===`long`?`short`:`long`}},c=365*24*60*60*1e3;function l(e,t,n,r={}){if(t.length<2)return u(e,t,n);let i=t[t.length-1].equity,a=i-e,o=a/e,s=r.periodsPerYear??_(t),l=(r.riskFreeRate??0)/s,v=d(t),y=f(v),b=p(v,y),x=m(v,l),S=b===0?0:(y-l)/b*Math.sqrt(s),C=x===0?0:(y-l)/x*Math.sqrt(s),w=t[t.length-1].time-t[0].time,T=w>0?w/c:0,E=T>0?(i/e)**(1/T)-1:0,{maxDrawdown:D,maxDrawdownPct:O}=h(t);return{totalReturn:a,totalReturnPct:o,cagr:E,sharpe:S,sortino:C,calmar:O>0?E/O:0,maxDrawdown:D,maxDrawdownPct:O,...g(n)}}function u(e,t,n){let r=t.length>0?t[t.length-1].equity:e;return{totalReturn:r-e,totalReturnPct:(r-e)/e,cagr:0,sharpe:0,sortino:0,calmar:0,maxDrawdown:0,maxDrawdownPct:0,...g(n)}}function d(e){let t=[];for(let n=1;n<e.length;n++){let r=e[n-1].equity;if(r<=0){t.push(0);continue}t.push(e[n].equity/r-1)}return t}function f(e){if(e.length===0)return 0;let t=0;for(let n of e)t+=n;return t/e.length}function p(e,t){if(e.length<2)return 0;let n=0;for(let r of e)n+=(r-t)**2;return Math.sqrt(n/(e.length-1))}function m(e,t){if(e.length<2)return 0;let n=0,r=0;for(let i of e){let e=i-t;e<0&&(n+=e**2,r++)}return r===0?0:Math.sqrt(n/r)}function h(e){let t=e[0].equity,n=0,r=0;for(let i of e){i.equity>t&&(t=i.equity);let e=t-i.equity;e>n&&(n=e,r=t>0?e/t:0)}return{maxDrawdown:n,maxDrawdownPct:r}}function g(e){if(e.length===0)return{winRate:0,profitFactor:0,expectancy:0,averageWin:0,averageLoss:0,trades:0};let t=0,n=0,r=0,i=0;for(let a of e)a.pnl>0?(t++,r+=a.pnl):a.pnl<0&&(n++,i+=-a.pnl);let a=t/e.length,o=t>0?r/t:0,s=n>0?i/n:0;return{winRate:a,profitFactor:i>0?r/i:r>0?1/0:0,expectancy:a*o-(1-a)*s,averageWin:o,averageLoss:s,trades:e.length}}function _(e){if(e.length<2)return 252;let t=[];for(let n=1;n<e.length&&n<50;n++)t.push(e[n].time-e[n-1].time);let n=f(t);if(n<=0)return 252;let r=c/n;return r>2e5?365*24*60:r>5e4?365*24*4:r>5e3?365*24:r>200?252:r>40?52:12}var v=class{commission;slippage;allowShort;portfolio;pendingOrders=[];orderSeq=0;constructor(e){this.commission=e.commission??r,this.slippage=e.slippage??i,this.allowShort=e.allowShort??!0,this.portfolio=new s({initialCash:e.initialCash})}run(e,t){if(e.length<2)throw Error(`Backtester requires at least 2 bars`);for(let n=0;n<e.length;n++){let r=e[n];this.fillPendingOrders(r),this.portfolio.mark(r.time,r.close),n<e.length-1&&t(this.makeContext(r,n,e.slice(0,n+1)))}for(let e of this.pendingOrders)e.status===`pending`&&(e.status=`cancelled`);let n=this.portfolio.getEquityCurve(),r=this.portfolio.getInitialCash(),i=this.portfolio.getTrades(),a=n.length>0?n[n.length-1].equity:r;return{fills:this.portfolio.getFills(),trades:i,equityCurve:n,initialCash:r,finalEquity:a,metrics:l(r,n,i)}}fillPendingOrders(e){for(let t of this.pendingOrders){if(t.status!==`pending`)continue;let n=this.resolveFillPrice(t,e);if(n===null){(t.timeInForce===`day`||t.timeInForce===`ioc`)&&(t.status=`cancelled`);continue}let r=this.slippage.apply(n,t.side,e),i=this.commission.calculate(t.quantity,r),a={orderId:t.id,time:e.time,price:r,quantity:t.quantity,side:t.side,commission:i,slippage:Math.abs(r-n),tag:t.tag};this.portfolio.applyFill(a),t.status=`filled`}this.pendingOrders=this.pendingOrders.filter(e=>e.status===`pending`)}resolveFillPrice(e,t){switch(e.type){case`market`:return t.open;case`limit`:return e.price===void 0?null:e.side===`long`&&t.low<=e.price?Math.min(e.price,t.open):e.side===`short`&&t.high>=e.price?Math.max(e.price,t.open):null;case`stop`:return e.price===void 0?null:e.side===`long`&&t.high>=e.price?Math.max(e.price,t.open):e.side===`short`&&t.low<=e.price?Math.min(e.price,t.open):null}}makeContext(e,t,n){let r=this.portfolio;return{bar:e,index:t,history:n,position:r.getPosition(),cash:r.getCash(),equity:r.equity(e.close),placeOrder:t=>this.placeOrder(t,e.time),close:t=>this.closePosition(e.time,t),cancel:e=>this.cancelOrder(e)}}placeOrder(e,t){if(e.quantity<=0)throw Error(`order quantity must be > 0`);if(!this.allowShort&&e.side===`short`){let t=this.portfolio.getPosition();if(!(t!==null&&t.side===`long`&&e.quantity<=t.quantity))throw Error(`shorting is disabled`)}let n=e.id??`o-${++this.orderSeq}`;return this.pendingOrders.push({id:n,side:e.side,type:e.type,quantity:e.quantity,price:e.price,tag:e.tag,timeInForce:e.timeInForce??`gtc`,status:`pending`,placedAt:t}),n}closePosition(e,t){let n=this.portfolio.getPosition();if(!n)return null;let r=n.side===`long`?`short`:`long`;return this.placeOrder({side:r,type:`market`,quantity:n.quantity,tag:t},e)}cancelOrder(e){let t=this.pendingOrders.find(t=>t.id===e);return!t||t.status!==`pending`?!1:(t.status=`cancelled`,!0)}};function y(e,t,n={}){let r=n.simulations??1e3,i=(n.percentiles??[5,25,50,75,95]).slice().sort((e,t)=>e-t),a=S(n.seed??Date.now()^23100);if(t.length===0||r<=0)return{simulations:r,initialCash:e,equityBands:[{step:0,p5:e,p25:e,p50:e,p75:e,p95:e}],finalEquityPercentiles:Object.fromEntries(i.map(t=>[`p${t}`,e])),probabilityProfitable:0,worstMaxDrawdownPct:0};let o=t.map(e=>e.pnl),s=t.length+1,c=o.slice(),l=new Float64Array(r),u=new Float64Array(r*s),d=0,f=0;for(let t=0;t<r;t++){b(c,a);let n=e,r=e,i=0,o=t*s;u[o]=n;for(let e=0;e<c.length;e++){n+=c[e],u[o+e+1]=n,n>r&&(r=n);let t=r>0?(r-n)/r:0;t>i&&(i=t)}l[t]=n,n>e&&f++,i>d&&(d=i)}let p=[],m=new Float64Array(r);for(let e=0;e<s;e++){for(let t=0;t<r;t++)m[t]=u[t*s+e];m.sort(),p.push({step:e,p5:x(m,5),p25:x(m,25),p50:x(m,50),p75:x(m,75),p95:x(m,95)})}let h=new Float64Array(l);h.sort();let g={};for(let e of i)g[`p${e}`]=x(h,e);return{simulations:r,initialCash:e,equityBands:p,finalEquityPercentiles:g,probabilityProfitable:f/r,worstMaxDrawdownPct:d*100}}function b(e,t){for(let n=e.length-1;n>0;n--){let r=Math.floor(t()*(n+1)),i=e[n];e[n]=e[r],e[r]=i}}function x(e,t){if(e.length===0)return 0;if(e.length===1)return e[0];let n=t/100*(e.length-1),r=Math.floor(n),i=Math.ceil(n);return r===i?e[r]:e[r]*(i-n)+e[i]*(n-r)}function S(e){let t=e>>>0;return()=>{t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}function C(e={}){let t=e.fastPeriod??10,n=e.slowPeriod??30,r=e.size??1,i=e.tag??`sma-cross`;if(t>=n)throw Error(`smaCrossStrategy: fastPeriod must be less than slowPeriod`);return e=>{if(e.index<n)return;let a=e.history,o=w(a,e.index,t),s=w(a,e.index,n),c=w(a,e.index-1,t),l=w(a,e.index-1,n);c<=l&&o>s?(e.position?.side===`short`&&e.close(i),(!e.position||e.position.side===`short`)&&e.placeOrder({side:`long`,type:`market`,quantity:r,tag:i})):c>=l&&o<s&&e.position?.side===`long`&&e.close(i)}}function w(e,t,n){let r=0;for(let i=t-n+1;i<=t;i++)r+=e[i].close;return r/n}function T(e={}){let t=e.period??14,n=e.oversold??30,r=e.overbought??70,i=e.size??1,a=e.tag??`rsi-reversion`;return e=>{if(e.index<t+1)return;let o=E(e.history,e.index,t),s=E(e.history,e.index-1,t),c=s<n&&o>=n,l=s<r&&o>=r;c&&!e.position?e.placeOrder({side:`long`,type:`market`,quantity:i,tag:a}):l&&e.position?.side===`long`&&e.close(a)}}function E(e,t,n){let r=0,i=0;for(let a=t-n+1;a<=t;a++){let t=e[a].close-e[a-1].close;t>=0?r+=t:i-=t}return i===0?100:100-100/(1+r/n/(i/n))}function D(e={}){let t=e.entryPeriod??20,n=e.exitPeriod??10,r=e.size??1,i=e.tag??`donchian-breakout`;return e=>{if(e.index<t)return;let a=e.bar.close,o=O(e.history,e.index-t,e.index-1),s=k(e.history,e.index-t,e.index-1),c=O(e.history,e.index-n,e.index-1),l=k(e.history,e.index-n,e.index-1);e.position?(e.position.side===`long`&&a<l||e.position.side===`short`&&a>c)&&e.close(i):a>o?e.placeOrder({side:`long`,type:`market`,quantity:r,tag:i}):a<s&&e.placeOrder({side:`short`,type:`market`,quantity:r,tag:i})}}function O(e,t,n){let r=-1/0;for(let i=Math.max(0,t);i<=n;i++)e[i].high>r&&(r=e[i].high);return r}function k(e,t,n){let r=1/0;for(let i=Math.max(0,t);i<=n;i++)e[i].low<r&&(r=e[i].low);return r}function A(e={}){let t=e.period??20,n=e.stdDev??2,r=e.size??1,i=e.tag??`bollinger-reversion`;return e=>{if(e.index<t)return;let{mid:a,lower:o}=j(e.history,e.index,t,n),s=e.bar.close;!e.position&&s<=o?e.placeOrder({side:`long`,type:`market`,quantity:r,tag:i}):e.position?.side===`long`&&s>=a&&e.close(i)}}function j(e,t,n,r){let i=0;for(let r=t-n+1;r<=t;r++)i+=e[r].close;let a=i/n,o=0;for(let r=t-n+1;r<=t;r++){let t=e[r].close-a;o+=t*t}let s=Math.sqrt(o/n);return{mid:a,upper:a+r*s,lower:a-r*s}}exports.Backtester=v,exports.FixedCommission=e,exports.NO_SLIPPAGE=i,exports.PerShareCommission=n,exports.PercentCommission=t,exports.PercentSlippage=a,exports.Portfolio=s,exports.RangeBasedSlippage=o,exports.ZERO_COMMISSION=r,exports.bollingerReversionStrategy=A,exports.computeRiskMetrics=l,exports.donchianBreakoutStrategy=D,exports.rsiReversionStrategy=T,exports.runMonteCarlo=y,exports.smaCrossStrategy=C;
2
- //# sourceMappingURL=index.cjs.map
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class B{constructor(t){this.perTrade=t}calculate(){return this.perTrade}}class T{constructor(t){this.rate=t}calculate(t,e){return Math.abs(t)*e*this.rate}}class N{constructor(t,e=0){this.perShare=t,this.minimum=e}calculate(t){return Math.max(this.minimum,Math.abs(t)*this.perShare)}}const D={calculate:()=>0},z={apply:i=>i};class Y{constructor(t){this.rate=t}apply(t,e){const n=e==="long"?1+this.rate:1-this.rate;return t*n}}class _{constructor(t){this.factor=t}apply(t,e,n){const o=(n.high-n.low)*this.factor;return e==="long"?t+o:t-o}}class b{cash;initialCash;position=null;fills=[];trades=[];equityCurve=[];realizedPnl=0;constructor(t){if(t.initialCash<=0)throw new Error("initialCash must be > 0");this.cash=t.initialCash,this.initialCash=t.initialCash}getCash(){return this.cash}getPosition(){return this.position}getFills(){return this.fills}getTrades(){return this.trades}getEquityCurve(){return this.equityCurve}getInitialCash(){return this.initialCash}getRealizedPnl(){return this.realizedPnl}unrealizedPnl(t){if(!this.position)return 0;const e=this.position.side==="long"?1:-1;return(t-this.position.averagePrice)*this.position.quantity*e}equity(t){return this.cash+this.positionValue(t)}positionValue(t){if(!this.position)return 0;const e=this.position.side==="long"?1:-1;return this.position.quantity*t*e}applyFill(t){this.fills.push(t);const e=t.side==="long"?t.quantity:-t.quantity;if(this.cash-=e*t.price,this.cash-=t.commission,!this.position){this.position={side:t.side,quantity:t.quantity,averagePrice:t.price,openedAt:t.time,tag:t.tag};return}if(this.position.side===t.side){const a=this.position.quantity+t.quantity;this.position={...this.position,quantity:a,averagePrice:(this.position.averagePrice*this.position.quantity+t.price*t.quantity)/a};return}const n=Math.min(this.position.quantity,t.quantity),s=this.position.side==="long"?1:-1,o=(t.price-this.position.averagePrice)*n*s;this.realizedPnl+=o,this.trades.push({entryTime:this.position.openedAt,exitTime:t.time,side:this.position.side,quantity:n,entryPrice:this.position.averagePrice,exitPrice:t.price,pnl:o,pnlPct:(t.price/this.position.averagePrice-1)*s,commission:t.commission,tag:t.tag??this.position.tag});const r=this.position.quantity-t.quantity;r>0?this.position={...this.position,quantity:r}:r<0?this.position={side:t.side,quantity:-r,averagePrice:t.price,openedAt:t.time,tag:t.tag}:this.position=null}mark(t,e){const n=this.positionValue(e),s=this.unrealizedPnl(e);this.equityCurve.push({time:t,equity:this.cash+n,cash:this.cash,positionValue:n,unrealizedPnl:s,realizedPnl:this.realizedPnl})}reverseSide(t){return t==="long"?"short":"long"}}const I=365*24*60*60*1e3;function A(i,t,e,n={}){if(t.length<2)return j(i,t,e);const s=t[t.length-1].equity,o=s-i,r=o/i,a=n.periodsPerYear??G(t),u=(n.riskFreeRate??0)/a,h=V(t),d=C(h),m=H(h,d),q=W(h,u),g=m===0?0:(d-u)/m*Math.sqrt(a),S=q===0?0:(d-u)/q*Math.sqrt(a),M=t[t.length-1].time-t[0].time,l=M>0?M/I:0,p=l>0?Math.pow(s/i,1/l)-1:0,{maxDrawdown:y,maxDrawdownPct:f}=$(t),O=f>0?p/f:0,P=L(e);return{totalReturn:o,totalReturnPct:r,cagr:p,sharpe:g,sortino:S,calmar:O,maxDrawdown:y,maxDrawdownPct:f,...P}}function j(i,t,e){const n=t.length>0?t[t.length-1].equity:i;return{totalReturn:n-i,totalReturnPct:(n-i)/i,cagr:0,sharpe:0,sortino:0,calmar:0,maxDrawdown:0,maxDrawdownPct:0,...L(e)}}function V(i){const t=[];for(let e=1;e<i.length;e++){const n=i[e-1].equity;if(n<=0){t.push(0);continue}t.push(i[e].equity/n-1)}return t}function C(i){if(i.length===0)return 0;let t=0;for(const e of i)t+=e;return t/i.length}function H(i,t){if(i.length<2)return 0;let e=0;for(const n of i)e+=(n-t)**2;return Math.sqrt(e/(i.length-1))}function W(i,t){if(i.length<2)return 0;let e=0,n=0;for(const s of i){const o=s-t;o<0&&(e+=o**2,n++)}return n===0?0:Math.sqrt(e/n)}function $(i){let t=i[0].equity,e=0,n=0;for(const s of i){s.equity>t&&(t=s.equity);const o=t-s.equity;o>e&&(e=o,n=t>0?o/t:0)}return{maxDrawdown:e,maxDrawdownPct:n}}function L(i){if(i.length===0)return{winRate:0,profitFactor:0,expectancy:0,averageWin:0,averageLoss:0,trades:0};let t=0,e=0,n=0,s=0;for(const h of i)h.pnl>0?(t++,n+=h.pnl):h.pnl<0&&(e++,s+=-h.pnl);const o=t/i.length,r=t>0?n/t:0,a=e>0?s/e:0,c=s>0?n/s:n>0?1/0:0,u=o*r-(1-o)*a;return{winRate:o,profitFactor:c,expectancy:u,averageWin:r,averageLoss:a,trades:i.length}}function G(i){if(i.length<2)return 252;const t=[];for(let s=1;s<i.length&&s<50;s++)t.push(i[s].time-i[s-1].time);const e=C(t);if(e<=0)return 252;const n=I/e;return n>2e5?365*24*60:n>5e4?365*24*4:n>5e3?365*24:n>200?252:n>40?52:12}class Z{commission;slippage;allowShort;portfolio;pendingOrders=[];orderSeq=0;constructor(t){this.commission=t.commission??D,this.slippage=t.slippage??z,this.allowShort=t.allowShort??!0,this.portfolio=new b({initialCash:t.initialCash})}run(t,e){if(t.length<2)throw new Error("Backtester requires at least 2 bars");for(let a=0;a<t.length;a++){const c=t[a];if(this.fillPendingOrders(c),this.portfolio.mark(c.time,c.close),a<t.length-1){const u=this.makeContext(c,a,t.slice(0,a+1));e(u)}}for(const a of this.pendingOrders)a.status==="pending"&&(a.status="cancelled");const n=this.portfolio.getEquityCurve(),s=this.portfolio.getInitialCash(),o=this.portfolio.getTrades(),r=n.length>0?n[n.length-1].equity:s;return{fills:this.portfolio.getFills(),trades:o,equityCurve:n,initialCash:s,finalEquity:r,metrics:A(s,n,o)}}fillPendingOrders(t){for(const e of this.pendingOrders){if(e.status!=="pending")continue;const n=this.resolveFillPrice(e,t);if(n===null){(e.timeInForce==="day"||e.timeInForce==="ioc")&&(e.status="cancelled");continue}const s=this.slippage.apply(n,e.side,t),o=this.commission.calculate(e.quantity,s),r={orderId:e.id,time:t.time,price:s,quantity:e.quantity,side:e.side,commission:o,slippage:Math.abs(s-n),tag:e.tag};this.portfolio.applyFill(r),e.status="filled"}this.pendingOrders=this.pendingOrders.filter(e=>e.status==="pending")}resolveFillPrice(t,e){switch(t.type){case"market":return e.open;case"limit":return t.price===void 0?null:t.side==="long"&&e.low<=t.price?Math.min(t.price,e.open):t.side==="short"&&e.high>=t.price?Math.max(t.price,e.open):null;case"stop":return t.price===void 0?null:t.side==="long"&&e.high>=t.price?Math.max(t.price,e.open):t.side==="short"&&e.low<=t.price?Math.min(t.price,e.open):null}}makeContext(t,e,n){const s=this.portfolio;return{bar:t,index:e,history:n,position:s.getPosition(),cash:s.getCash(),equity:s.equity(t.close),placeOrder:o=>this.placeOrder(o,t.time),close:o=>this.closePosition(t.time,o),cancel:o=>this.cancelOrder(o)}}placeOrder(t,e){if(t.quantity<=0)throw new Error("order quantity must be > 0");if(!this.allowShort&&t.side==="short"){const s=this.portfolio.getPosition();if(!(s!==null&&s.side==="long"&&t.quantity<=s.quantity))throw new Error("shorting is disabled")}const n=t.id??`o-${++this.orderSeq}`;return this.pendingOrders.push({id:n,side:t.side,type:t.type,quantity:t.quantity,price:t.price,tag:t.tag,timeInForce:t.timeInForce??"gtc",status:"pending",placedAt:e}),n}closePosition(t,e){const n=this.portfolio.getPosition();if(!n)return null;const s=n.side==="long"?"short":"long";return this.placeOrder({side:s,type:"market",quantity:n.quantity,tag:e},t)}cancelOrder(t){const e=this.pendingOrders.find(n=>n.id===t);return!e||e.status!=="pending"?!1:(e.status="cancelled",!0)}}function Q(i,t,e={}){const n=e.simulations??1e3,s=(e.percentiles??[5,25,50,75,95]).slice().sort((l,p)=>l-p),o=x(e.seed??Date.now()^23100);if(t.length===0||n<=0)return{simulations:n,initialCash:i,equityBands:[{step:0,p5:i,p25:i,p50:i,p75:i,p95:i}],finalEquityPercentiles:Object.fromEntries(s.map(l=>[`p${l}`,i])),probabilityProfitable:0,worstMaxDrawdownPct:0};const r=t.map(l=>l.pnl),a=t.length+1,c=r.slice(),u=new Float64Array(n),h=new Float64Array(n*a);let d=0,m=0;for(let l=0;l<n;l++){U(c,o);let p=i,y=i,f=0;const O=l*a;h[O]=p;for(let P=0;P<c.length;P++){p+=c[P],h[O+P+1]=p,p>y&&(y=p);const F=y>0?(y-p)/y:0;F>f&&(f=F)}u[l]=p,p>i&&m++,f>d&&(d=f)}const q=[],g=new Float64Array(n);for(let l=0;l<a;l++){for(let p=0;p<n;p++)g[p]=h[p*a+l];g.sort(),q.push({step:l,p5:w(g,5),p25:w(g,25),p50:w(g,50),p75:w(g,75),p95:w(g,95)})}const S=new Float64Array(u);S.sort();const M={};for(const l of s)M[`p${l}`]=w(S,l);return{simulations:n,initialCash:i,equityBands:q,finalEquityPercentiles:M,probabilityProfitable:m/n,worstMaxDrawdownPct:d*100}}function U(i,t){for(let e=i.length-1;e>0;e--){const n=Math.floor(t()*(e+1)),s=i[e];i[e]=i[n],i[n]=s}}function w(i,t){if(i.length===0)return 0;if(i.length===1)return i[0];const e=t/100*(i.length-1),n=Math.floor(e),s=Math.ceil(e);return n===s?i[n]:i[n]*(s-e)+i[s]*(e-n)}function x(i){let t=i>>>0;return()=>{t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}function J(i={}){const t=i.fastPeriod??10,e=i.slowPeriod??30,n=i.size??1,s=i.tag??"sma-cross";if(t>=e)throw new Error("smaCrossStrategy: fastPeriod must be less than slowPeriod");return o=>{if(o.index<e)return;const r=o.history,a=v(r,o.index,t),c=v(r,o.index,e),u=v(r,o.index-1,t),h=v(r,o.index-1,e),d=u<=h&&a>c,m=u>=h&&a<c;d?(o.position?.side==="short"&&o.close(s),(!o.position||o.position.side==="short")&&o.placeOrder({side:"long",type:"market",quantity:n,tag:s})):m&&o.position?.side==="long"&&o.close(s)}}function v(i,t,e){let n=0;for(let s=t-e+1;s<=t;s++)n+=i[s].close;return n/e}function K(i={}){const t=i.period??14,e=i.oversold??30,n=i.overbought??70,s=i.size??1,o=i.tag??"rsi-reversion";return r=>{if(r.index<t+1)return;const a=k(r.history,r.index,t),c=k(r.history,r.index-1,t),u=c<e&&a>=e,h=c<n&&a>=n;u&&!r.position?r.placeOrder({side:"long",type:"market",quantity:s,tag:o}):h&&r.position?.side==="long"&&r.close(o)}}function k(i,t,e){let n=0,s=0;for(let r=t-e+1;r<=t;r++){const a=i[r].close-i[r-1].close;a>=0?n+=a:s-=a}return s===0?100:100-100/(1+n/e/(s/e))}function X(i={}){const t=i.entryPeriod??20,e=i.exitPeriod??10,n=i.size??1,s=i.tag??"donchian-breakout";return o=>{if(o.index<t)return;const r=o.bar.close,a=R(o.history,o.index-t,o.index-1),c=E(o.history,o.index-t,o.index-1),u=R(o.history,o.index-e,o.index-1),h=E(o.history,o.index-e,o.index-1);o.position?(o.position.side==="long"&&r<h||o.position.side==="short"&&r>u)&&o.close(s):r>a?o.placeOrder({side:"long",type:"market",quantity:n,tag:s}):r<c&&o.placeOrder({side:"short",type:"market",quantity:n,tag:s})}}function R(i,t,e){let n=-1/0;for(let s=Math.max(0,t);s<=e;s++)i[s].high>n&&(n=i[s].high);return n}function E(i,t,e){let n=1/0;for(let s=Math.max(0,t);s<=e;s++)i[s].low<n&&(n=i[s].low);return n}function tt(i={}){const t=i.period??20,e=i.stdDev??2,n=i.size??1,s=i.tag??"bollinger-reversion";return o=>{if(o.index<t)return;const{mid:r,lower:a}=et(o.history,o.index,t,e),c=o.bar.close;!o.position&&c<=a?o.placeOrder({side:"long",type:"market",quantity:n,tag:s}):o.position?.side==="long"&&c>=r&&o.close(s)}}function et(i,t,e,n){let s=0;for(let c=t-e+1;c<=t;c++)s+=i[c].close;const o=s/e;let r=0;for(let c=t-e+1;c<=t;c++){const u=i[c].close-o;r+=u*u}const a=Math.sqrt(r/e);return{mid:o,upper:o+n*a,lower:o-n*a}}exports.Backtester=Z;exports.FixedCommission=B;exports.NO_SLIPPAGE=z;exports.PerShareCommission=N;exports.PercentCommission=T;exports.PercentSlippage=Y;exports.Portfolio=b;exports.RangeBasedSlippage=_;exports.ZERO_COMMISSION=D;exports.bollingerReversionStrategy=tt;exports.computeRiskMetrics=A;exports.donchianBreakoutStrategy=X;exports.rsiReversionStrategy=K;exports.runMonteCarlo=Q;exports.smaCrossStrategy=J;
2
+ //# sourceMappingURL=index.cjs.map