return-scenario-engine 0.1.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 +201 -0
- package/NOTICE +5 -0
- package/README.md +68 -0
- package/lib/index.d.ts +24 -0
- package/lib/index.js +452 -0
- package/lib/methodology.d.ts +4 -0
- package/lib/methodology.js +4 -0
- package/lib/types.d.ts +111 -0
- package/lib/types.js +1 -0
- package/methodology/return-scenario-v1.json +42 -0
- package/package.json +16 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# return-scenario-engine
|
|
2
|
+
|
|
3
|
+
Dependency-free historical investment scenarios for caller-owned normalized index series. TypeScript and Python share a public contract and synthetic golden corpus.
|
|
4
|
+
|
|
5
|
+

|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install return-scenario-engine
|
|
9
|
+
# or: python -m pip install return-scenario-engine
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
```ts
|
|
13
|
+
import { calculateScenario } from 'return-scenario-engine';
|
|
14
|
+
|
|
15
|
+
const dates = ['2024-01-01', '2024-01-02', '2024-01-03'];
|
|
16
|
+
const result = calculateScenario({
|
|
17
|
+
amountCents: 100_000,
|
|
18
|
+
requestedStart: '2024-01-01',
|
|
19
|
+
requestedEnd: '2024-01-03',
|
|
20
|
+
assetA: { assetKey: 'sample-a', schemaVersion: 1, methodologyVersion: 'return-scenario-v1.0.0', seriesBasis: 'close_index', annualizationFactor: 365, dates, growthIndex: [100, 110, 121] },
|
|
21
|
+
assetB: { assetKey: 'sample-b', schemaVersion: 1, methodologyVersion: 'return-scenario-v1.0.0', seriesBasis: 'close_index', annualizationFactor: 365, dates, growthIndex: [100, 95, 100] },
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
console.log(result.status); // "ok"
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Each artifact provides its key, schema/methodology versions, series basis, annualization factor, ordered civil dates, and positive normalized index values. Results contain snapped dates, integer-cent ending values, display-rounded metrics, drawdown/recovery data, correlation, and a shared wealth path; invalid inputs return named errors.
|
|
28
|
+
|
|
29
|
+
`roundHalfAwayFromZero` / `round_half_away_from_zero` accept any positive safe
|
|
30
|
+
integer scale and reject nonfinite values, invalid scales, and unsafe results.
|
|
31
|
+
|
|
32
|
+
The visual is actual output from the synthetic `crypto_crypto_long_window` golden case: a $1,000 scenario ends at $2,309.81 for asset A and $845.66 for asset B. This is a headless library, not a chart UI.
|
|
33
|
+
|
|
34
|
+
## Contract and limits
|
|
35
|
+
|
|
36
|
+
Node.js 20+ and Python 3.11+ are supported. Both `0.1.0` artifacts share the methodology JSON, public SHA-256 hash, and synthetic fixtures. Read [`return-scenario-v1.json`](https://github.com/sidko/return-scenario-engine/blob/main/methodology/return-scenario-v1.json) before comparing outputs. The package does not fetch prices, select assets, retain provider data, or implement routes and UI. A partial paired registry upload must be completed or corrected before announcing the version.
|
|
37
|
+
|
|
38
|
+
## Development
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
npm ci
|
|
42
|
+
python -m pip install -e './python[test]'
|
|
43
|
+
PYTHON_BIN=python3 npm test
|
|
44
|
+
python -m build python
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
`npm test` builds a temporary Python wheel and checks every golden scenario against both implementations. Fixtures are synthetic and contain no provider history.
|
|
48
|
+
|
|
49
|
+
## First release
|
|
50
|
+
|
|
51
|
+
For the first npm release, publish the reviewed tarball interactively with 2FA
|
|
52
|
+
and configure npm trusted publishing for `.github/workflows/release.yml` and
|
|
53
|
+
its `npm` environment. Configure PyPI's pending trusted publisher, then run the
|
|
54
|
+
manual release workflow against the existing tag with target `pypi` to upload
|
|
55
|
+
the matching Python artifact. Verify both registries before creating the GitHub
|
|
56
|
+
Release. Later releases use the same manual workflow with target `both`; retry a
|
|
57
|
+
single failed side with `npm` or `pypi`. Never republish an immutable existing
|
|
58
|
+
version or treat a mismatched pair as successful.
|
|
59
|
+
|
|
60
|
+
## Origin
|
|
61
|
+
|
|
62
|
+
This package was extracted from [Gale Finance](https://gale.finance/) calculation work. Gale’s launch-bundle formats, UI, routes, analytics, market data, and asset policy stay private. Until migration, it is “extracted from Gale,” not evidence that Gale uses the published artifact.
|
|
63
|
+
|
|
64
|
+
Early commits reconstruct private-monorepo milestones. Author dates reflect original work; public content and hashes were rewritten to exclude private details. Some early development used Claude as a coding assistant; Sid Kalla selected, reviewed, and maintains this code.
|
|
65
|
+
|
|
66
|
+
Apache-2.0 covers this code and does not grant rights to Gale Finance branding. See [CONTRIBUTING](https://github.com/sidko/return-scenario-engine/blob/main/CONTRIBUTING.md), [SECURITY](https://github.com/sidko/return-scenario-engine/blob/main/SECURITY.md), and [AGENT_INTEGRATION](https://github.com/sidko/return-scenario-engine/blob/main/AGENT_INTEGRATION.md).
|
|
67
|
+
|
|
68
|
+
Maintenance is best effort; the latest release is supported unless its notes say otherwise.
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { AmountParseResult, HundredthsMetricValue, ScenarioInput, ScenarioResult } from './types.js';
|
|
2
|
+
export { ARTIFACT_SCHEMA_VERSION, METHODOLOGY_HASH, METHODOLOGY_VERSION } from './methodology.js';
|
|
3
|
+
export declare const SUPPORTED_SCHEMA_VERSION: 1;
|
|
4
|
+
export declare const SUPPORTED_METHODOLOGY_VERSION: "return-scenario-v1.0.0";
|
|
5
|
+
export declare const SUPPORTED_SERIES_BASES: readonly ["close_index", "adjusted_close_index"];
|
|
6
|
+
export declare const DEFAULT_FIXTURE_SERIES_BASIS = "close_index";
|
|
7
|
+
export declare const MIN_AMOUNT_CENTS = 100;
|
|
8
|
+
export declare const MAX_AMOUNT_CENTS = 1000000000;
|
|
9
|
+
export declare const CAGR_DAY_COUNT = 365.25;
|
|
10
|
+
export declare const CALMAR_MIN_ABS_DRAWDOWN = 0.0001;
|
|
11
|
+
export declare const ZERO_VARIANCE_SUMSQ_EPSILON = 1e-24;
|
|
12
|
+
export declare const CORRELATION_CLAMP_TOLERANCE = 1e-12;
|
|
13
|
+
export declare function roundHalfAwayFromZero(value: number, scale?: number): number;
|
|
14
|
+
export declare function displayCents(usdValue: number): number;
|
|
15
|
+
export declare function displayBasisPoints(decimalValue: number): number;
|
|
16
|
+
export declare function displayHundredths(ratioValue: number): number;
|
|
17
|
+
export declare function isValidCivilDate(value: unknown): value is string;
|
|
18
|
+
export declare function civilDay(value: string): number;
|
|
19
|
+
export declare function firstAnniversary(value: string): string;
|
|
20
|
+
export declare function shiftYearsBack(value: string, years: number): string;
|
|
21
|
+
export declare function parseUsdAmountToCents(value: unknown): AmountParseResult;
|
|
22
|
+
export declare const parseAmountToCents: typeof parseUsdAmountToCents;
|
|
23
|
+
export declare function pearsonCorrelation(valuesA: number[], valuesB: number[]): HundredthsMetricValue;
|
|
24
|
+
export declare function calculateScenario(input: ScenarioInput): ScenarioResult;
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
import { METHODOLOGY_HASH, ARTIFACT_SCHEMA_VERSION, METHODOLOGY_VERSION, } from './methodology.js';
|
|
2
|
+
export { ARTIFACT_SCHEMA_VERSION, METHODOLOGY_HASH, METHODOLOGY_VERSION } from './methodology.js';
|
|
3
|
+
export const SUPPORTED_SCHEMA_VERSION = ARTIFACT_SCHEMA_VERSION;
|
|
4
|
+
export const SUPPORTED_METHODOLOGY_VERSION = METHODOLOGY_VERSION;
|
|
5
|
+
export const SUPPORTED_SERIES_BASES = ['close_index', 'adjusted_close_index'];
|
|
6
|
+
export const DEFAULT_FIXTURE_SERIES_BASIS = 'close_index';
|
|
7
|
+
export const MIN_AMOUNT_CENTS = 100;
|
|
8
|
+
export const MAX_AMOUNT_CENTS = 1_000_000_000;
|
|
9
|
+
export const CAGR_DAY_COUNT = 365.25;
|
|
10
|
+
export const CALMAR_MIN_ABS_DRAWDOWN = 0.0001;
|
|
11
|
+
export const ZERO_VARIANCE_SUMSQ_EPSILON = 1e-24;
|
|
12
|
+
export const CORRELATION_CLAMP_TOLERANCE = 1e-12;
|
|
13
|
+
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
14
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
15
|
+
function normalizeZero(value) {
|
|
16
|
+
return value === 0 ? 0 : value;
|
|
17
|
+
}
|
|
18
|
+
function basisPointMetricUnavailable(reason) {
|
|
19
|
+
return { available: false, reason };
|
|
20
|
+
}
|
|
21
|
+
function hundredthsMetricUnavailable(reason) {
|
|
22
|
+
return { available: false, reason };
|
|
23
|
+
}
|
|
24
|
+
function basisPointMetricAvailable(value) {
|
|
25
|
+
if (!Number.isFinite(value))
|
|
26
|
+
return basisPointMetricUnavailable('nonfinite_result');
|
|
27
|
+
return { available: true, value: normalizeZero(value), displayBasisPoints: displayBasisPoints(value) };
|
|
28
|
+
}
|
|
29
|
+
function hundredthsMetricAvailable(value) {
|
|
30
|
+
if (!Number.isFinite(value))
|
|
31
|
+
return hundredthsMetricUnavailable('nonfinite_result');
|
|
32
|
+
return { available: true, value: normalizeZero(value), displayHundredths: displayHundredths(value) };
|
|
33
|
+
}
|
|
34
|
+
function decimalString(value) {
|
|
35
|
+
const raw = Math.abs(value).toString();
|
|
36
|
+
if (!raw.includes('e'))
|
|
37
|
+
return raw;
|
|
38
|
+
const [coefficient, exponentText] = raw.split('e');
|
|
39
|
+
const exponent = Number(exponentText);
|
|
40
|
+
const [integerPart, fractionPart = ''] = coefficient.split('.');
|
|
41
|
+
const digits = `${integerPart}${fractionPart}`;
|
|
42
|
+
const decimalIndex = integerPart.length + exponent;
|
|
43
|
+
if (decimalIndex <= 0)
|
|
44
|
+
return `0.${'0'.repeat(Math.abs(decimalIndex))}${digits}`;
|
|
45
|
+
if (decimalIndex >= digits.length)
|
|
46
|
+
return `${digits}${'0'.repeat(decimalIndex - digits.length)}`;
|
|
47
|
+
return `${digits.slice(0, decimalIndex)}.${digits.slice(decimalIndex)}`;
|
|
48
|
+
}
|
|
49
|
+
export function roundHalfAwayFromZero(value, scale = 1) {
|
|
50
|
+
if (!Number.isFinite(value))
|
|
51
|
+
throw new Error('cannot round nonfinite value');
|
|
52
|
+
if (!Number.isSafeInteger(scale) || scale <= 0)
|
|
53
|
+
throw new Error('scale must be a positive safe integer');
|
|
54
|
+
const sign = value < 0 ? -1 : 1;
|
|
55
|
+
const [integerPart, fractionPart = ''] = decimalString(value).split('.');
|
|
56
|
+
const numerator = BigInt(`${integerPart}${fractionPart}`.replace(/^0+(?=\d)/, '') || '0') * BigInt(scale);
|
|
57
|
+
const denominator = 10n ** BigInt(fractionPart.length);
|
|
58
|
+
let scaled = numerator / denominator;
|
|
59
|
+
if ((numerator % denominator) * 2n >= denominator)
|
|
60
|
+
scaled += 1n;
|
|
61
|
+
if (scaled > BigInt(Number.MAX_SAFE_INTEGER))
|
|
62
|
+
throw new Error('rounded result exceeds safe integer range');
|
|
63
|
+
const rounded = Number(scaled);
|
|
64
|
+
return rounded === 0 ? 0 : sign * rounded;
|
|
65
|
+
}
|
|
66
|
+
export function displayCents(usdValue) {
|
|
67
|
+
return roundHalfAwayFromZero(usdValue, 100);
|
|
68
|
+
}
|
|
69
|
+
export function displayBasisPoints(decimalValue) {
|
|
70
|
+
return roundHalfAwayFromZero(decimalValue, 10_000);
|
|
71
|
+
}
|
|
72
|
+
export function displayHundredths(ratioValue) {
|
|
73
|
+
return roundHalfAwayFromZero(ratioValue, 100);
|
|
74
|
+
}
|
|
75
|
+
export function isValidCivilDate(value) {
|
|
76
|
+
if (typeof value !== 'string' || !DATE_RE.test(value))
|
|
77
|
+
return false;
|
|
78
|
+
const [year, month, day] = value.split('-').map(Number);
|
|
79
|
+
const parsed = new Date(Date.UTC(year, month - 1, day));
|
|
80
|
+
return (parsed.getUTCFullYear() === year &&
|
|
81
|
+
parsed.getUTCMonth() === month - 1 &&
|
|
82
|
+
parsed.getUTCDate() === day);
|
|
83
|
+
}
|
|
84
|
+
export function civilDay(value) {
|
|
85
|
+
if (!isValidCivilDate(value))
|
|
86
|
+
throw new Error(`invalid civil date: ${value}`);
|
|
87
|
+
const [year, month, day] = value.split('-').map(Number);
|
|
88
|
+
return Math.floor(Date.UTC(year, month - 1, day) / DAY_MS);
|
|
89
|
+
}
|
|
90
|
+
export function firstAnniversary(value) {
|
|
91
|
+
if (!isValidCivilDate(value))
|
|
92
|
+
throw new Error(`invalid civil date: ${value}`);
|
|
93
|
+
const [year, month, day] = value.split('-').map(Number);
|
|
94
|
+
const shifted = new Date(Date.UTC(year + 1, month - 1, day));
|
|
95
|
+
if (shifted.getUTCMonth() !== month - 1) {
|
|
96
|
+
shifted.setUTCDate(0);
|
|
97
|
+
}
|
|
98
|
+
return shifted.toISOString().slice(0, 10);
|
|
99
|
+
}
|
|
100
|
+
export function shiftYearsBack(value, years) {
|
|
101
|
+
if (!isValidCivilDate(value))
|
|
102
|
+
return value;
|
|
103
|
+
const [year, month, day] = value.split('-').map(Number);
|
|
104
|
+
const shifted = new Date(Date.UTC(year - years, month - 1, day));
|
|
105
|
+
if (shifted.getUTCMonth() !== month - 1) {
|
|
106
|
+
shifted.setUTCDate(0);
|
|
107
|
+
}
|
|
108
|
+
return shifted.toISOString().slice(0, 10);
|
|
109
|
+
}
|
|
110
|
+
export function parseUsdAmountToCents(value) {
|
|
111
|
+
if (typeof value !== 'string')
|
|
112
|
+
return { ok: false, reason: 'invalid_amount' };
|
|
113
|
+
const raw = value.trim().replace(/^\$\s*/, '');
|
|
114
|
+
const plainAmount = /^(0|[1-9][0-9]*)(\.[0-9]{1,2})?$/;
|
|
115
|
+
const groupedAmount = /^(0|[1-9][0-9]{0,2}(,[0-9]{3})+)(\.[0-9]{1,2})?$/;
|
|
116
|
+
if (!plainAmount.test(raw) && !groupedAmount.test(raw)) {
|
|
117
|
+
return { ok: false, reason: 'invalid_amount' };
|
|
118
|
+
}
|
|
119
|
+
const [dollars, cents = ''] = raw.replaceAll(',', '').split('.');
|
|
120
|
+
const parsed = Number(dollars) * 100 + Number(cents.padEnd(2, '0') || '0');
|
|
121
|
+
if (!Number.isSafeInteger(parsed) || parsed < MIN_AMOUNT_CENTS || parsed > MAX_AMOUNT_CENTS) {
|
|
122
|
+
return { ok: false, reason: 'invalid_amount' };
|
|
123
|
+
}
|
|
124
|
+
return { ok: true, cents: parsed };
|
|
125
|
+
}
|
|
126
|
+
export const parseAmountToCents = parseUsdAmountToCents;
|
|
127
|
+
function orderedMean(values) {
|
|
128
|
+
return values.reduce((sum, value) => sum + value, 0) / values.length;
|
|
129
|
+
}
|
|
130
|
+
function sampleVariance(values) {
|
|
131
|
+
if (values.length < 2)
|
|
132
|
+
return null;
|
|
133
|
+
const mean = orderedMean(values);
|
|
134
|
+
return values.reduce((sum, value) => sum + (value - mean) ** 2, 0) / (values.length - 1);
|
|
135
|
+
}
|
|
136
|
+
function sampleStddev(values) {
|
|
137
|
+
const variance = sampleVariance(values);
|
|
138
|
+
return variance === null ? null : Math.sqrt(variance);
|
|
139
|
+
}
|
|
140
|
+
function simpleReturns(values) {
|
|
141
|
+
const returns = [];
|
|
142
|
+
for (let index = 1; index < values.length; index += 1) {
|
|
143
|
+
const previous = values[index - 1];
|
|
144
|
+
const current = values[index];
|
|
145
|
+
if (previous <= 0 || current <= 0)
|
|
146
|
+
throw new Error('normalized indexes must be positive');
|
|
147
|
+
returns.push(current / previous - 1);
|
|
148
|
+
}
|
|
149
|
+
return returns;
|
|
150
|
+
}
|
|
151
|
+
export function pearsonCorrelation(valuesA, valuesB) {
|
|
152
|
+
if (valuesA.length !== valuesB.length || valuesA.length < 2) {
|
|
153
|
+
return hundredthsMetricUnavailable('insufficient_data');
|
|
154
|
+
}
|
|
155
|
+
const meanA = orderedMean(valuesA);
|
|
156
|
+
const meanB = orderedMean(valuesB);
|
|
157
|
+
let covariance = 0;
|
|
158
|
+
let sumSqA = 0;
|
|
159
|
+
let sumSqB = 0;
|
|
160
|
+
for (let index = 0; index < valuesA.length; index += 1) {
|
|
161
|
+
const deltaA = valuesA[index] - meanA;
|
|
162
|
+
const deltaB = valuesB[index] - meanB;
|
|
163
|
+
covariance += deltaA * deltaB;
|
|
164
|
+
sumSqA += deltaA * deltaA;
|
|
165
|
+
sumSqB += deltaB * deltaB;
|
|
166
|
+
}
|
|
167
|
+
if (sumSqA <= ZERO_VARIANCE_SUMSQ_EPSILON || sumSqB <= ZERO_VARIANCE_SUMSQ_EPSILON) {
|
|
168
|
+
return hundredthsMetricUnavailable('zero_variance');
|
|
169
|
+
}
|
|
170
|
+
let correlation = covariance / Math.sqrt(sumSqA * sumSqB);
|
|
171
|
+
if (Math.abs(Math.abs(correlation) - 1) <= CORRELATION_CLAMP_TOLERANCE) {
|
|
172
|
+
correlation = correlation > 0 ? 1 : -1;
|
|
173
|
+
}
|
|
174
|
+
else if (correlation < -1 || correlation > 1) {
|
|
175
|
+
return hundredthsMetricUnavailable('nonfinite_result');
|
|
176
|
+
}
|
|
177
|
+
return hundredthsMetricAvailable(correlation);
|
|
178
|
+
}
|
|
179
|
+
function drawdownStats(values, dates) {
|
|
180
|
+
if (values.length < 2) {
|
|
181
|
+
return {
|
|
182
|
+
maxDrawdown: basisPointMetricUnavailable('insufficient_data'),
|
|
183
|
+
peakDate: null,
|
|
184
|
+
troughDate: null,
|
|
185
|
+
recoveryDate: null,
|
|
186
|
+
recoveryDays: null,
|
|
187
|
+
recoveryStatus: 'not_applicable',
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
let runningPeak = values[0];
|
|
191
|
+
let runningPeakAtTrough = values[0];
|
|
192
|
+
let troughIndex = 0;
|
|
193
|
+
let maxDrawdown = 0;
|
|
194
|
+
for (let index = 0; index < values.length; index += 1) {
|
|
195
|
+
const value = values[index];
|
|
196
|
+
if (value >= runningPeak)
|
|
197
|
+
runningPeak = value;
|
|
198
|
+
const drawdown = value / runningPeak - 1;
|
|
199
|
+
if (drawdown < maxDrawdown) {
|
|
200
|
+
maxDrawdown = drawdown;
|
|
201
|
+
troughIndex = index;
|
|
202
|
+
runningPeakAtTrough = runningPeak;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (maxDrawdown === 0) {
|
|
206
|
+
return {
|
|
207
|
+
maxDrawdown: { available: true, value: 0, displayBasisPoints: 0 },
|
|
208
|
+
peakDate: null,
|
|
209
|
+
troughDate: null,
|
|
210
|
+
recoveryDate: null,
|
|
211
|
+
recoveryDays: null,
|
|
212
|
+
recoveryStatus: 'not_applicable',
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
let peakIndex = 0;
|
|
216
|
+
for (let index = 0; index <= troughIndex; index += 1) {
|
|
217
|
+
if (values[index] === runningPeakAtTrough)
|
|
218
|
+
peakIndex = index;
|
|
219
|
+
}
|
|
220
|
+
let recoveryIndex = null;
|
|
221
|
+
for (let index = troughIndex; index < values.length; index += 1) {
|
|
222
|
+
if (values[index] >= runningPeakAtTrough) {
|
|
223
|
+
recoveryIndex = index;
|
|
224
|
+
break;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return {
|
|
228
|
+
maxDrawdown: basisPointMetricAvailable(maxDrawdown),
|
|
229
|
+
peakDate: dates[peakIndex],
|
|
230
|
+
troughDate: dates[troughIndex],
|
|
231
|
+
recoveryDate: recoveryIndex === null ? null : dates[recoveryIndex],
|
|
232
|
+
recoveryDays: recoveryIndex === null ? null : civilDay(dates[recoveryIndex]) - civilDay(dates[troughIndex]),
|
|
233
|
+
recoveryStatus: recoveryIndex === null ? 'not_recovered' : 'recovered',
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
function validateAsset(asset) {
|
|
237
|
+
if (typeof asset.assetKey !== 'string' || !asset.assetKey)
|
|
238
|
+
return false;
|
|
239
|
+
if (!SUPPORTED_SERIES_BASES.includes(asset.seriesBasis))
|
|
240
|
+
return false;
|
|
241
|
+
if (!Array.isArray(asset.dates) || !Array.isArray(asset.growthIndex) || asset.dates.length !== asset.growthIndex.length) {
|
|
242
|
+
return false;
|
|
243
|
+
}
|
|
244
|
+
if (asset.dates.length === 0)
|
|
245
|
+
return false;
|
|
246
|
+
if (typeof asset.annualizationFactor !== 'number' || !Number.isFinite(asset.annualizationFactor) || asset.annualizationFactor <= 0) {
|
|
247
|
+
return false;
|
|
248
|
+
}
|
|
249
|
+
let previous = null;
|
|
250
|
+
for (let index = 0; index < asset.dates.length; index += 1) {
|
|
251
|
+
const currentDate = asset.dates[index];
|
|
252
|
+
const value = asset.growthIndex[index];
|
|
253
|
+
if (!isValidCivilDate(currentDate))
|
|
254
|
+
return false;
|
|
255
|
+
if (previous !== null && currentDate <= previous)
|
|
256
|
+
return false;
|
|
257
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0)
|
|
258
|
+
return false;
|
|
259
|
+
previous = currentDate;
|
|
260
|
+
}
|
|
261
|
+
return true;
|
|
262
|
+
}
|
|
263
|
+
function checkMethodology(assetA, assetB) {
|
|
264
|
+
return (assetA.schemaVersion === SUPPORTED_SCHEMA_VERSION &&
|
|
265
|
+
assetB.schemaVersion === SUPPORTED_SCHEMA_VERSION &&
|
|
266
|
+
assetA.methodologyVersion === SUPPORTED_METHODOLOGY_VERSION &&
|
|
267
|
+
assetB.methodologyVersion === SUPPORTED_METHODOLOGY_VERSION &&
|
|
268
|
+
SUPPORTED_SERIES_BASES.includes(assetA.seriesBasis) &&
|
|
269
|
+
SUPPORTED_SERIES_BASES.includes(assetB.seriesBasis));
|
|
270
|
+
}
|
|
271
|
+
function dateToIndex(asset) {
|
|
272
|
+
return new Map(asset.dates.map((currentDate, index) => [currentDate, index]));
|
|
273
|
+
}
|
|
274
|
+
function nativeWindow(asset, effectiveStart, effectiveEnd) {
|
|
275
|
+
const dates = [];
|
|
276
|
+
const values = [];
|
|
277
|
+
for (let index = 0; index < asset.dates.length; index += 1) {
|
|
278
|
+
const currentDate = asset.dates[index];
|
|
279
|
+
if (effectiveStart <= currentDate && currentDate <= effectiveEnd) {
|
|
280
|
+
dates.push(currentDate);
|
|
281
|
+
values.push(asset.growthIndex[index]);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
return { dates, values };
|
|
285
|
+
}
|
|
286
|
+
function assetMetrics(asset, dates, values, amountCents, elapsedDays) {
|
|
287
|
+
const amountUsd = amountCents / 100;
|
|
288
|
+
const growth = values[values.length - 1] / values[0];
|
|
289
|
+
const endingValueUsd = amountUsd * growth;
|
|
290
|
+
const endingValueCents = displayCents(endingValueUsd);
|
|
291
|
+
const profitLossUsd = endingValueUsd - amountUsd;
|
|
292
|
+
const profitLossCents = endingValueCents - amountCents;
|
|
293
|
+
const totalReturnValue = growth - 1;
|
|
294
|
+
const returns = simpleReturns(values);
|
|
295
|
+
const drawdown = drawdownStats(values, dates);
|
|
296
|
+
let cagr = basisPointMetricUnavailable('period_too_short');
|
|
297
|
+
if (elapsedDays >= 30) {
|
|
298
|
+
const cagrValue = growth ** (CAGR_DAY_COUNT / elapsedDays) - 1;
|
|
299
|
+
cagr = basisPointMetricAvailable(cagrValue);
|
|
300
|
+
}
|
|
301
|
+
let volatility = basisPointMetricUnavailable('insufficient_data');
|
|
302
|
+
if (returns.length >= 30) {
|
|
303
|
+
const stddev = sampleStddev(returns);
|
|
304
|
+
if (stddev !== null) {
|
|
305
|
+
const volatilityValue = stddev * Math.sqrt(asset.annualizationFactor);
|
|
306
|
+
volatility = basisPointMetricAvailable(volatilityValue);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
let calmar = hundredthsMetricUnavailable('period_too_short');
|
|
310
|
+
const firstAnniversaryReached = dates[dates.length - 1] >= firstAnniversary(dates[0]);
|
|
311
|
+
const drawdownMetric = drawdown.maxDrawdown;
|
|
312
|
+
if (firstAnniversaryReached && cagr.available && drawdownMetric.available) {
|
|
313
|
+
const maxDrawdown = drawdownMetric.value;
|
|
314
|
+
if (Math.abs(maxDrawdown) >= CALMAR_MIN_ABS_DRAWDOWN) {
|
|
315
|
+
const calmarValue = cagr.value / Math.abs(maxDrawdown);
|
|
316
|
+
calmar = hundredthsMetricAvailable(calmarValue);
|
|
317
|
+
}
|
|
318
|
+
else {
|
|
319
|
+
calmar = hundredthsMetricUnavailable('zero_drawdown');
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
return {
|
|
323
|
+
endingValueUsd: normalizeZero(endingValueUsd),
|
|
324
|
+
endingValueCents,
|
|
325
|
+
profitLossUsd: normalizeZero(profitLossUsd),
|
|
326
|
+
profitLossCents,
|
|
327
|
+
totalReturn: basisPointMetricAvailable(totalReturnValue),
|
|
328
|
+
cagr,
|
|
329
|
+
volatility,
|
|
330
|
+
drawdown,
|
|
331
|
+
calmar,
|
|
332
|
+
nativeObservationCount: values.length,
|
|
333
|
+
nativeReturnCount: returns.length,
|
|
334
|
+
periodOutcome: profitLossCents > 0 ? 'gain' : profitLossCents < 0 ? 'loss' : 'unchanged',
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
function compareDisplayValues(metricA, metricB) {
|
|
338
|
+
if (!metricA.available || !metricB.available)
|
|
339
|
+
return 'unavailable';
|
|
340
|
+
const valueA = metricA.displayBasisPoints;
|
|
341
|
+
const valueB = metricB.displayBasisPoints;
|
|
342
|
+
if (valueA === valueB)
|
|
343
|
+
return 'tie';
|
|
344
|
+
return valueA > valueB ? 'asset_a' : 'asset_b';
|
|
345
|
+
}
|
|
346
|
+
function compareEndingValue(metricsA, metricsB) {
|
|
347
|
+
if (metricsA.endingValueCents === metricsB.endingValueCents)
|
|
348
|
+
return 'tie';
|
|
349
|
+
return metricsA.endingValueCents > metricsB.endingValueCents ? 'asset_a' : 'asset_b';
|
|
350
|
+
}
|
|
351
|
+
function compareDeeperDrawdown(metricsA, metricsB) {
|
|
352
|
+
const drawdownA = metricsA.drawdown.maxDrawdown;
|
|
353
|
+
const drawdownB = metricsB.drawdown.maxDrawdown;
|
|
354
|
+
if (!drawdownA.available || !drawdownB.available)
|
|
355
|
+
return 'unavailable';
|
|
356
|
+
const valueA = drawdownA.displayBasisPoints;
|
|
357
|
+
const valueB = drawdownB.displayBasisPoints;
|
|
358
|
+
if (typeof valueA !== 'number' || typeof valueB !== 'number')
|
|
359
|
+
return 'unavailable';
|
|
360
|
+
if (valueA === valueB)
|
|
361
|
+
return 'tie';
|
|
362
|
+
return valueA < valueB ? 'asset_a' : 'asset_b';
|
|
363
|
+
}
|
|
364
|
+
export function calculateScenario(input) {
|
|
365
|
+
if (!input || typeof input !== 'object')
|
|
366
|
+
throw new Error('invalid scenario input');
|
|
367
|
+
const { assetA, assetB, amountCents, requestedStart, requestedEnd } = input;
|
|
368
|
+
if (!assetA || typeof assetA !== 'object' || !assetB || typeof assetB !== 'object') {
|
|
369
|
+
throw new Error('invalid asset artifact');
|
|
370
|
+
}
|
|
371
|
+
if (typeof assetA.assetKey !== 'string' ||
|
|
372
|
+
!assetA.assetKey ||
|
|
373
|
+
typeof assetB.assetKey !== 'string' ||
|
|
374
|
+
!assetB.assetKey) {
|
|
375
|
+
throw new Error('invalid asset artifact');
|
|
376
|
+
}
|
|
377
|
+
if (assetA.assetKey === assetB.assetKey)
|
|
378
|
+
return { status: 'error', reason: 'same_asset' };
|
|
379
|
+
if (!Number.isSafeInteger(amountCents) || amountCents < MIN_AMOUNT_CENTS || amountCents > MAX_AMOUNT_CENTS) {
|
|
380
|
+
return { status: 'error', reason: 'invalid_amount' };
|
|
381
|
+
}
|
|
382
|
+
if (!isValidCivilDate(requestedStart) || !isValidCivilDate(requestedEnd)) {
|
|
383
|
+
return { status: 'error', reason: 'invalid_date' };
|
|
384
|
+
}
|
|
385
|
+
if (requestedStart > requestedEnd)
|
|
386
|
+
return { status: 'error', reason: 'start_after_end' };
|
|
387
|
+
if (!checkMethodology(assetA, assetB))
|
|
388
|
+
return { status: 'error', reason: 'methodology_mismatch' };
|
|
389
|
+
if (!validateAsset(assetA) || !validateAsset(assetB))
|
|
390
|
+
throw new Error('invalid asset artifact');
|
|
391
|
+
const indexA = dateToIndex(assetA);
|
|
392
|
+
const indexB = dateToIndex(assetB);
|
|
393
|
+
const sharedDates = assetA.dates.filter((currentDate) => indexB.has(currentDate));
|
|
394
|
+
if (!sharedDates.length)
|
|
395
|
+
return { status: 'error', reason: 'no_overlap' };
|
|
396
|
+
const requestedSharedDates = sharedDates.filter((currentDate) => requestedStart <= currentDate && currentDate <= requestedEnd);
|
|
397
|
+
if (!requestedSharedDates.length)
|
|
398
|
+
return { status: 'error', reason: 'no_overlap' };
|
|
399
|
+
const effectiveStart = sharedDates.find((currentDate) => currentDate >= requestedStart) || null;
|
|
400
|
+
const effectiveEnd = [...sharedDates].reverse().find((currentDate) => currentDate <= requestedEnd) || null;
|
|
401
|
+
if (effectiveStart === null || effectiveEnd === null || effectiveStart >= effectiveEnd) {
|
|
402
|
+
return { status: 'error', reason: 'insufficient_shared_observations' };
|
|
403
|
+
}
|
|
404
|
+
const selectedSharedDates = sharedDates.filter((currentDate) => effectiveStart <= currentDate && currentDate <= effectiveEnd);
|
|
405
|
+
if (selectedSharedDates.length < 2)
|
|
406
|
+
return { status: 'error', reason: 'insufficient_shared_observations' };
|
|
407
|
+
const elapsedDays = civilDay(effectiveEnd) - civilDay(effectiveStart);
|
|
408
|
+
if (elapsedDays <= 0)
|
|
409
|
+
return { status: 'error', reason: 'insufficient_shared_observations' };
|
|
410
|
+
const nativeA = nativeWindow(assetA, effectiveStart, effectiveEnd);
|
|
411
|
+
const nativeB = nativeWindow(assetB, effectiveStart, effectiveEnd);
|
|
412
|
+
const sharedValuesA = selectedSharedDates.map((currentDate) => assetA.growthIndex[indexA.get(currentDate)]);
|
|
413
|
+
const sharedValuesB = selectedSharedDates.map((currentDate) => assetB.growthIndex[indexB.get(currentDate)]);
|
|
414
|
+
const metricsA = assetMetrics(assetA, nativeA.dates, nativeA.values, amountCents, elapsedDays);
|
|
415
|
+
const metricsB = assetMetrics(assetB, nativeB.dates, nativeB.values, amountCents, elapsedDays);
|
|
416
|
+
const sharedReturnsA = simpleReturns(sharedValuesA);
|
|
417
|
+
const sharedReturnsB = simpleReturns(sharedValuesB);
|
|
418
|
+
const correlation = sharedReturnsA.length >= 30 && sharedReturnsB.length >= 30
|
|
419
|
+
? pearsonCorrelation(sharedReturnsA, sharedReturnsB)
|
|
420
|
+
: hundredthsMetricUnavailable('insufficient_data');
|
|
421
|
+
const amountUsd = amountCents / 100;
|
|
422
|
+
return {
|
|
423
|
+
status: 'ok',
|
|
424
|
+
scenario: {
|
|
425
|
+
methodologyVersion: SUPPORTED_METHODOLOGY_VERSION,
|
|
426
|
+
methodologyContractHash: METHODOLOGY_HASH,
|
|
427
|
+
amountCents,
|
|
428
|
+
requestedStart,
|
|
429
|
+
requestedEnd,
|
|
430
|
+
effectiveStart,
|
|
431
|
+
effectiveEnd,
|
|
432
|
+
startSnap: effectiveStart === requestedStart ? 'exact' : 'forward',
|
|
433
|
+
endSnap: effectiveEnd === requestedEnd ? 'exact' : 'backward',
|
|
434
|
+
elapsedDays,
|
|
435
|
+
sharedObservationCount: selectedSharedDates.length,
|
|
436
|
+
assetA: metricsA,
|
|
437
|
+
assetB: metricsB,
|
|
438
|
+
pair: {
|
|
439
|
+
correlation,
|
|
440
|
+
sharedReturnCount: sharedReturnsA.length,
|
|
441
|
+
},
|
|
442
|
+
wealthPath: selectedSharedDates.map((currentDate) => ({
|
|
443
|
+
date: currentDate,
|
|
444
|
+
assetAUsd: normalizeZero(amountUsd * assetA.growthIndex[indexA.get(currentDate)] / sharedValuesA[0]),
|
|
445
|
+
assetBUsd: normalizeZero(amountUsd * assetB.growthIndex[indexB.get(currentDate)] / sharedValuesB[0]),
|
|
446
|
+
})),
|
|
447
|
+
endingValueWinner: compareEndingValue(metricsA, metricsB),
|
|
448
|
+
totalReturnWinner: compareDisplayValues(metricsA.totalReturn, metricsB.totalReturn),
|
|
449
|
+
deeperDrawdownAsset: compareDeeperDrawdown(metricsA, metricsB),
|
|
450
|
+
},
|
|
451
|
+
};
|
|
452
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** Identifiers for the public, provider-free return-scenario contract. */
|
|
2
|
+
export declare const ARTIFACT_SCHEMA_VERSION: 1;
|
|
3
|
+
export declare const METHODOLOGY_VERSION: "return-scenario-v1.0.0";
|
|
4
|
+
export declare const METHODOLOGY_HASH: "55ef9001eb8795071cfff1e135430d41952aedd8708ba1d767c3453804fd49b0";
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** Identifiers for the public, provider-free return-scenario contract. */
|
|
2
|
+
export const ARTIFACT_SCHEMA_VERSION = 1;
|
|
3
|
+
export const METHODOLOGY_VERSION = 'return-scenario-v1.0.0';
|
|
4
|
+
export const METHODOLOGY_HASH = '55ef9001eb8795071cfff1e135430d41952aedd8708ba1d767c3453804fd49b0';
|
package/lib/types.d.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
export type MetricReason = 'insufficient_data' | 'period_too_short' | 'zero_drawdown' | 'zero_variance' | 'nonfinite_result';
|
|
2
|
+
export type ScenarioErrorReason = 'same_asset' | 'invalid_amount' | 'invalid_date' | 'start_after_end' | 'methodology_mismatch' | 'no_overlap' | 'insufficient_shared_observations';
|
|
3
|
+
export type SnapStatus = 'exact' | 'forward' | 'backward';
|
|
4
|
+
export type ComparisonWinner = 'asset_a' | 'asset_b' | 'tie' | 'unavailable';
|
|
5
|
+
export type PeriodOutcome = 'gain' | 'loss' | 'unchanged';
|
|
6
|
+
export type RecoveryStatus = 'recovered' | 'not_recovered' | 'not_applicable';
|
|
7
|
+
export type MetricValue = {
|
|
8
|
+
available: true;
|
|
9
|
+
value: number;
|
|
10
|
+
} | {
|
|
11
|
+
available: false;
|
|
12
|
+
reason: MetricReason;
|
|
13
|
+
};
|
|
14
|
+
export type BasisPointMetricValue = {
|
|
15
|
+
available: true;
|
|
16
|
+
value: number;
|
|
17
|
+
displayBasisPoints: number;
|
|
18
|
+
} | {
|
|
19
|
+
available: false;
|
|
20
|
+
reason: MetricReason;
|
|
21
|
+
};
|
|
22
|
+
export type HundredthsMetricValue = {
|
|
23
|
+
available: true;
|
|
24
|
+
value: number;
|
|
25
|
+
displayHundredths: number;
|
|
26
|
+
} | {
|
|
27
|
+
available: false;
|
|
28
|
+
reason: MetricReason;
|
|
29
|
+
};
|
|
30
|
+
/** Caller-owned normalized index data; it intentionally has no provider or product metadata. */
|
|
31
|
+
export type AssetSeriesArtifact = Readonly<{
|
|
32
|
+
assetKey: string;
|
|
33
|
+
schemaVersion: 1;
|
|
34
|
+
methodologyVersion: 'return-scenario-v1.0.0';
|
|
35
|
+
seriesBasis: 'close_index' | 'adjusted_close_index';
|
|
36
|
+
annualizationFactor: number;
|
|
37
|
+
dates: readonly string[];
|
|
38
|
+
growthIndex: readonly number[];
|
|
39
|
+
}>;
|
|
40
|
+
export type ScenarioInput = Readonly<{
|
|
41
|
+
assetA: AssetSeriesArtifact;
|
|
42
|
+
assetB: AssetSeriesArtifact;
|
|
43
|
+
amountCents: number;
|
|
44
|
+
requestedStart: string;
|
|
45
|
+
requestedEnd: string;
|
|
46
|
+
}>;
|
|
47
|
+
export type DrawdownResult = Readonly<{
|
|
48
|
+
maxDrawdown: BasisPointMetricValue;
|
|
49
|
+
peakDate: string | null;
|
|
50
|
+
troughDate: string | null;
|
|
51
|
+
recoveryDate: string | null;
|
|
52
|
+
recoveryDays: number | null;
|
|
53
|
+
recoveryStatus: RecoveryStatus;
|
|
54
|
+
}>;
|
|
55
|
+
export type AssetScenarioMetrics = Readonly<{
|
|
56
|
+
endingValueUsd: number;
|
|
57
|
+
endingValueCents: number;
|
|
58
|
+
profitLossUsd: number;
|
|
59
|
+
profitLossCents: number;
|
|
60
|
+
totalReturn: BasisPointMetricValue;
|
|
61
|
+
cagr: BasisPointMetricValue;
|
|
62
|
+
volatility: BasisPointMetricValue;
|
|
63
|
+
drawdown: DrawdownResult;
|
|
64
|
+
calmar: HundredthsMetricValue;
|
|
65
|
+
nativeObservationCount: number;
|
|
66
|
+
nativeReturnCount: number;
|
|
67
|
+
periodOutcome: PeriodOutcome;
|
|
68
|
+
}>;
|
|
69
|
+
export type WealthPathPoint = Readonly<{
|
|
70
|
+
date: string;
|
|
71
|
+
assetAUsd: number;
|
|
72
|
+
assetBUsd: number;
|
|
73
|
+
}>;
|
|
74
|
+
export type PairMetrics = Readonly<{
|
|
75
|
+
correlation: HundredthsMetricValue;
|
|
76
|
+
sharedReturnCount: number;
|
|
77
|
+
}>;
|
|
78
|
+
export type ScenarioSuccess = Readonly<{
|
|
79
|
+
methodologyVersion: 'return-scenario-v1.0.0';
|
|
80
|
+
methodologyContractHash: string;
|
|
81
|
+
amountCents: number;
|
|
82
|
+
requestedStart: string;
|
|
83
|
+
requestedEnd: string;
|
|
84
|
+
effectiveStart: string;
|
|
85
|
+
effectiveEnd: string;
|
|
86
|
+
startSnap: 'exact' | 'forward';
|
|
87
|
+
endSnap: 'exact' | 'backward';
|
|
88
|
+
elapsedDays: number;
|
|
89
|
+
sharedObservationCount: number;
|
|
90
|
+
assetA: AssetScenarioMetrics;
|
|
91
|
+
assetB: AssetScenarioMetrics;
|
|
92
|
+
pair: PairMetrics;
|
|
93
|
+
wealthPath: readonly WealthPathPoint[];
|
|
94
|
+
endingValueWinner: ComparisonWinner;
|
|
95
|
+
totalReturnWinner: ComparisonWinner;
|
|
96
|
+
deeperDrawdownAsset: ComparisonWinner;
|
|
97
|
+
}>;
|
|
98
|
+
export type ScenarioResult = {
|
|
99
|
+
status: 'error';
|
|
100
|
+
reason: ScenarioErrorReason;
|
|
101
|
+
} | {
|
|
102
|
+
status: 'ok';
|
|
103
|
+
scenario: ScenarioSuccess;
|
|
104
|
+
};
|
|
105
|
+
export type AmountParseResult = {
|
|
106
|
+
ok: true;
|
|
107
|
+
cents: number;
|
|
108
|
+
} | {
|
|
109
|
+
ok: false;
|
|
110
|
+
reason: 'invalid_amount';
|
|
111
|
+
};
|
package/lib/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schemaVersion": 1,
|
|
3
|
+
"methodologyVersion": "return-scenario-v1.0.0",
|
|
4
|
+
"constants": {
|
|
5
|
+
"amountCentsMin": 100,
|
|
6
|
+
"amountCentsMax": 1000000000,
|
|
7
|
+
"cagrDayCount": 365.25,
|
|
8
|
+
"calmarMinAbsDrawdown": 0.0001,
|
|
9
|
+
"defaultAnnualizationFactor": 252
|
|
10
|
+
},
|
|
11
|
+
"dateAlignment": {
|
|
12
|
+
"civilDatePattern": "YYYY-MM-DD",
|
|
13
|
+
"timezone": "utc_civil_day_ordinals",
|
|
14
|
+
"startSnap": "first_shared_on_or_after_request",
|
|
15
|
+
"endSnap": "last_shared_on_or_before_request",
|
|
16
|
+
"sharedMetrics": "shared_observation_dates_only",
|
|
17
|
+
"nativeMetrics": "per_asset_native_observations_between_shared_effective_boundaries"
|
|
18
|
+
},
|
|
19
|
+
"formulas": {
|
|
20
|
+
"totalReturn": "index_end/index_start-1",
|
|
21
|
+
"endingValueUsd": "amount_usd*index_end/index_start",
|
|
22
|
+
"cagr": "pow(index_end/index_start,365.25/elapsed_calendar_days)-1",
|
|
23
|
+
"realizedVolatility": "sample_stddev_native_simple_returns_ddof_1*sqrt(annualization_factor)",
|
|
24
|
+
"drawdown": "index_t/running_max(index_0_to_t)-1",
|
|
25
|
+
"calmar": "cagr/abs(max_drawdown)",
|
|
26
|
+
"correlation": "pearson_aligned_shared_simple_returns_ordered_centered_sums"
|
|
27
|
+
},
|
|
28
|
+
"minimumEvidence": {
|
|
29
|
+
"totalReturnSharedPrices": 2,
|
|
30
|
+
"cagrElapsedCalendarDays": 30,
|
|
31
|
+
"volatilityNativeReturns": 30,
|
|
32
|
+
"drawdownNativePrices": 2,
|
|
33
|
+
"correlationSharedReturns": 30,
|
|
34
|
+
"calmarFirstAnniversaryRequired": true
|
|
35
|
+
},
|
|
36
|
+
"rounding": {
|
|
37
|
+
"money": "integer_cents_half_away_from_zero",
|
|
38
|
+
"percent": "integer_basis_points_half_away_from_zero",
|
|
39
|
+
"ratio": "integer_hundredths_half_away_from_zero",
|
|
40
|
+
"negativeZero": "normalize_to_positive_zero"
|
|
41
|
+
}
|
|
42
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "return-scenario-engine",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Portable historical return scenario calculations for normalized indexes.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": { ".": { "types": "./lib/index.d.ts", "import": "./lib/index.js" } },
|
|
7
|
+
"types": "./lib/index.d.ts",
|
|
8
|
+
"files": ["lib", "methodology", "LICENSE", "NOTICE", "README.md"],
|
|
9
|
+
"engines": { "node": ">=20" },
|
|
10
|
+
"scripts": { "build": "tsc --project tsconfig.json", "test": "npm run build && bash test/run-conformance.sh", "prepack": "npm run build" },
|
|
11
|
+
"repository": { "type": "git", "url": "git+https://github.com/sidko/return-scenario-engine.git" },
|
|
12
|
+
"bugs": { "url": "https://github.com/sidko/return-scenario-engine/issues" },
|
|
13
|
+
"homepage": "https://github.com/sidko/return-scenario-engine#readme",
|
|
14
|
+
"license": "Apache-2.0",
|
|
15
|
+
"devDependencies": { "@types/node": "24.3.1", "typescript": "5.9.3" }
|
|
16
|
+
}
|