OptionalstackStaticstackStaticcaptureCreates a .stack property on targetObject, which when accessed returns
-a string representing the location in the code at which
-Error.captureStackTrace() was called.
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Similar to `new Error().stack`
-
-
-The first line of the trace will be prefixed with
-${myObject.name}: ${myObject.message}.
The optional constructorOpt argument accepts a function. If given, all frames
-above constructorOpt, including constructorOpt, will be omitted from the
-generated stack trace.
The constructorOpt argument is useful for hiding implementation
-details of error generation from the user. For instance:
function a() {
b();
}
function b() {
c();
}
function c() {
// Create an error without stack trace to avoid calculating the stack trace twice.
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;
// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}
a();
-
-
-OptionalconstructorOpt: FunctionStaticprepareOptionalstackStaticstackThe Error.stackTraceLimit property specifies the number of stack frames
-collected by a stack trace (whether generated by new Error().stack or
-Error.captureStackTrace(obj)).
The default value is 10 but may be set to any valid JavaScript number. Changes
-will affect any stack trace captured after the value has been changed.
If set to a non-number value, or set to a negative number, stack traces will -not capture any frames.
-StaticcaptureCreates a .stack property on targetObject, which when accessed returns
-a string representing the location in the code at which
-Error.captureStackTrace() was called.
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Similar to `new Error().stack`
-
-
-The first line of the trace will be prefixed with
-${myObject.name}: ${myObject.message}.
The optional constructorOpt argument accepts a function. If given, all frames
-above constructorOpt, including constructorOpt, will be omitted from the
-generated stack trace.
The constructorOpt argument is useful for hiding implementation
-details of error generation from the user. For instance:
function a() {
b();
}
function b() {
c();
}
function c() {
// Create an error without stack trace to avoid calculating the stack trace twice.
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;
// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}
a();
-
-
-OptionalconstructorOpt: FunctionStaticprepareOptionalstackStaticstackThe Error.stackTraceLimit property specifies the number of stack frames
-collected by a stack trace (whether generated by new Error().stack or
-Error.captureStackTrace(obj)).
The default value is 10 but may be set to any valid JavaScript number. Changes
-will affect any stack trace captured after the value has been changed.
If set to a non-number value, or set to a negative number, stack traces will -not capture any frames.
-StaticcaptureCreates a .stack property on targetObject, which when accessed returns
-a string representing the location in the code at which
-Error.captureStackTrace() was called.
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Similar to `new Error().stack`
-
-
-The first line of the trace will be prefixed with
-${myObject.name}: ${myObject.message}.
The optional constructorOpt argument accepts a function. If given, all frames
-above constructorOpt, including constructorOpt, will be omitted from the
-generated stack trace.
The constructorOpt argument is useful for hiding implementation
-details of error generation from the user. For instance:
function a() {
b();
}
function b() {
c();
}
function c() {
// Create an error without stack trace to avoid calculating the stack trace twice.
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;
// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}
a();
-
-
-OptionalconstructorOpt: FunctionStaticprepareOptionalstackStaticstackThe Error.stackTraceLimit property specifies the number of stack frames
-collected by a stack trace (whether generated by new Error().stack or
-Error.captureStackTrace(obj)).
The default value is 10 but may be set to any valid JavaScript number. Changes
-will affect any stack trace captured after the value has been changed.
If set to a non-number value, or set to a negative number, stack traces will -not capture any frames.
-StaticcaptureCreates a .stack property on targetObject, which when accessed returns
-a string representing the location in the code at which
-Error.captureStackTrace() was called.
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Similar to `new Error().stack`
-
-
-The first line of the trace will be prefixed with
-${myObject.name}: ${myObject.message}.
The optional constructorOpt argument accepts a function. If given, all frames
-above constructorOpt, including constructorOpt, will be omitted from the
-generated stack trace.
The constructorOpt argument is useful for hiding implementation
-details of error generation from the user. For instance:
function a() {
b();
}
function b() {
c();
}
function c() {
// Create an error without stack trace to avoid calculating the stack trace twice.
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;
// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}
a();
-
-
-OptionalconstructorOpt: FunctionStaticprepareOptionalstackStaticstackThe Error.stackTraceLimit property specifies the number of stack frames
-collected by a stack trace (whether generated by new Error().stack or
-Error.captureStackTrace(obj)).
The default value is 10 but may be set to any valid JavaScript number. Changes
-will affect any stack trace captured after the value has been changed.
If set to a non-number value, or set to a negative number, stack traces will -not capture any frames.
-StaticcaptureCreates a .stack property on targetObject, which when accessed returns
-a string representing the location in the code at which
-Error.captureStackTrace() was called.
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Similar to `new Error().stack`
-
-
-The first line of the trace will be prefixed with
-${myObject.name}: ${myObject.message}.
The optional constructorOpt argument accepts a function. If given, all frames
-above constructorOpt, including constructorOpt, will be omitted from the
-generated stack trace.
The constructorOpt argument is useful for hiding implementation
-details of error generation from the user. For instance:
function a() {
b();
}
function b() {
c();
}
function c() {
// Create an error without stack trace to avoid calculating the stack trace twice.
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;
// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}
a();
-
-
-OptionalconstructorOpt: FunctionStaticprepareCollection of aligned timeseries with portfolio and correlation methods.
-Optionaloptions: { countries?: string | string[] }Country code(s) for business calendar (holidays, resampling). Used when adapting data to business days.
-Lag-k autocorrelation per constituent. Matches Python OpenFrame.autocorr_func.
-CAGR-based capture ratio vs benchmark column. -Matches Python openseries capture_ratio_func behavior: uses frame data as-is (no resample) -with dynamic time_factor = observations / (span_days/365.25).
-"up" | "down" | "both" (up/down or both = up/down)
-Benchmark column index (-1 = last)
-Optionalopts: { freq?: ResampleFreq }Optionalfreq?: ResampleFreqIf set, resample to period-end before computing (e.g. "ME" for monthly). -When omitted, uses frame data as-is to match Python default.
-Filters tsdf to retain only business days. Mutates in place.
-OptionalweightStrat: LiteralPortfolioWeightingsMax drawdown per column (price series). Returns array of max drawdowns.
-Date when max drawdown bottom occurs per column. -Returns array of date strings (or undefined when no drawdown).
-Ordinary Least Squares fit of y on x. -Regresses tsdf column yColumn (dependent) on xColumn (explanatory). -Matches Python openseries ord_least_squares_fit.
-Column index of dependent variable y
-Column index of exogenous variable x
-Optionalopts: { fittedSeries?: boolean }OptionalfittedSeries?: booleanIf true, add fitted values as new column (default true)
-Object with coefficient (slope), intercept, and rsquared
-Resamples all constituents to business period-end frequency, then re-merges. -Throws if any constituent is a return series.
-Returns return columns (first element 0). Throws if mixed PRICE/RTRN.
-Converts each column to drawdown series (value / running peak - 1). -Operates on the frame's aligned tsdf. Call after mergeSeries and truncate -so drawdown is computed on the truncated date range.
-Optional_opts: { fromDate?: string; toDate?: string }Truncates frame and constituents to a common date range.
-Truncation options
-OptionalendCut?: stringNew last date (default: earliest last date if where includes 'after')
-OptionalstartCut?: stringNew first date (default: latest first date of all constituents if where includes 'before')
-Optionalwhere?: "before" | "after" | "both"Which end(s) to truncate when cuts not provided
-Timeseries of dates and values with methods for risk metrics.
-Country code(s) for business calendar (holidays, resampling). Default "SE".
-ReadonlydatesReadonlyinstrumentReadonlynameReadonlytimeseriesReadonlyvaluesAutocorrelation function for specified lags. -If lags is an int, compute ACF from lag 0 through that value (inclusive).
-Lag-k autocorrelation of demeaned returns. -For price series, returns are derived via pct_change; for return series, -values are demeaned. Matches Python openseries autocorr_func.
-Filters tsdf to retain only business days. Mutates in place.
-Ljung-Box test for autocorrelation at the given lags.
-Returns the date when the max drawdown bottom occurs (the date of the lowest point -relative to the preceding peak). Returns undefined if no drawdown occurs.
-Partial autocorrelation function for specified lags. -If lags is an int, compute PACF from lag 0 through that value (inclusive).
-Partial autocorrelation at a given lag.
-Resamples to business period-end frequency (week, month, quarter, year). -Mutates tsdf. Throws on return series (use price series).
-OptionallvlZero: stringOptionallvlOne: ValueTypeWorst single calendar month return (business-month-end based). -Uses filterToBusinessDays + resampleToPeriodEnd(ME) + min of monthly returns.
-StaticfromCreates an OpenTimeSeries from a name, dates array, and values array.
-Optionaloptions: {StaticfromCreates an OpenTimeSeries from simulation dateColumns by column index.
-Optionaloptions: { columnIndex?: number; countries?: string | string[]; valuetype?: ValueType }StaticfromCreates an OpenTimeSeries from a record or array of {date, value}.
-OptionalstackStaticstackThe Error.stackTraceLimit property specifies the number of stack frames
-collected by a stack trace (whether generated by new Error().stack or
-Error.captureStackTrace(obj)).
The default value is 10 but may be set to any valid JavaScript number. Changes
-will affect any stack trace captured after the value has been changed.
If set to a non-number value, or set to a negative number, stack traces will -not capture any frames.
-StaticcaptureCreates a .stack property on targetObject, which when accessed returns
-a string representing the location in the code at which
-Error.captureStackTrace() was called.
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Similar to `new Error().stack`
-
-
-The first line of the trace will be prefixed with
-${myObject.name}: ${myObject.message}.
The optional constructorOpt argument accepts a function. If given, all frames
-above constructorOpt, including constructorOpt, will be omitted from the
-generated stack trace.
The constructorOpt argument is useful for hiding implementation
-details of error generation from the user. For instance:
function a() {
b();
}
function b() {
c();
}
function c() {
// Create an error without stack trace to avoid calculating the stack trace twice.
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;
// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}
a();
-
-
-OptionalconstructorOpt: FunctionStaticprepareMonte Carlo return simulation with optional seed for reproducibility.
-ReadonlydframeReadonlyjumpsReadonlyjumpsReadonlyjumpsReadonlymeanReadonlymeanReadonlynumberOptional ReadonlyseedReadonlytradingReadonlytradingOptionaloptions: { asReturns?: boolean; end?: string; start?: string }StaticfromOptionalseed: numberStaticfromOptionalseed: numberStaticfromOptionalseed: numberStaticfromOptionalseed: numberComputes the mean-variance efficient frontier using analytic QP.
-Fetches a single timeseries from the Captor Open API.
-The timeseries ID (e.g. "638f681e0c2f4c8d28a13392")
-The timeseries data with dates and values arrays
-Fetches multiple timeseries from the Captor Open API.
-Array of timeseries IDs
-Array of timeseries data
-Filters an array of date strings to keep only business days. -Business day = not weekend (Sat/Sun) and not a holiday in any of the specified countries.
-Array of date strings (YYYY-MM-DD)
-Country code(s) for holiday calendar, e.g. "SE", "US", ["SE", "NO"]
-Array of business-day date strings (subsequence of input, preserving order)
-Filters (dates, columns) to retain only rows where the date is a business day. -Preserves alignment across all columns.
-Returns the most recent business day strictly before today. -Uses the given country code(s) for holiday calendar (e.g. "SE" for XSTO/Stockholm).
-Generate full-page series plot HTML, write to file, and optionally open in browser. -Analogous to Python plot_series with auto_open.
-OpenTimeSeries or OpenFrame (use mergeSeries("inner") for frame)
-Title, filename, autoOpen
-Path to the written HTML file
-Generate full-page HTML with a line chart of the series (or multiple series). -Plots cumulative returns (base 1). Percent display is formatting only. -Works with OpenTimeSeries or OpenFrame. For OpenFrame, use mergeSeries("inner") first.
-OpenTimeSeries or OpenFrame
-Optional title
-HTML string
-Prepares labeled points for the efficient-frontier chart: individual assets, -current (e.g. eq-weight) portfolio, and the max-Sharpe optimum.
-Generate HTML report from an OpenFrame. -Analogous to Python openseries report_html(data: OpenFrame, ...). -The frame should have mergeSeries("inner") already applied.
-Requires at least 2 constituents: the first N-1 are compared against the last -(benchmark). Benchmark-relative metrics (Capture Ratio, Information Ratio, etc.) -are empty for the benchmark series.
-OpenFrame with aligned series (mergeSeries("inner"))
-Report options (title, logo). Countries come from frame.countries.
-HTML string
-Resamples dates and columns to end-of-business period frequency. -Each period takes the last observation that falls on a business day within that period.
-Sorted array of date strings
-Value columns (same length as dates)
-WE (week-end), ME (month-end), QE (quarter-end), YE (year-end)
-Country code(s) for holiday filtering
-Writes efficient-frontier HTML to file and optionally opens in browser.
-Generates full-page HTML with efficient frontier scatter plot. -Simulated portfolios colored by Sharpe ratio, frontier as line, labeled points.
-Simulates random long-only portfolios from frame returns and covariance.
-Chains two timeseries at their overlap. Scales back by front's level at the overlap date.
-Tools for analyzing financial timeseries of a single asset or a group of assets. -Designed for daily or less frequent data. -TypeScript port of the -Python openseries package.
-npm install @captor/openseries-ts
-
-
-The published package requires Node.js 22 or later.
-To develop this repository you need npm 12+ and Node.js 22, 24, or 26
-(^22.22.2 || ^24.15.0 || >=26.0.0). Those versions are enforced via
-package.json engines, devEngines, and packageManager (npm@12.0.2).
-CI runs the test suite on Node 22, 24, and 26.
import { OpenTimeSeries } from "@captor/openseries-ts";
const dates = ["2020-01-02", "2020-01-03", "2020-01-06", "2020-01-07"];
const values = [100, 101, 102, 99];
const series = OpenTimeSeries.fromArrays("My Series", dates, values);
console.log(series.geoRet()); // CAGR
console.log(series.vol()); // Annualized volatility
console.log(series.maxDrawdown()); // Max drawdown
console.log(series.autocorr()); // lag-1 autocorrelation of demeaned returns
-
-
-fetchCaptorSeries, fetchCaptorSeriesBatch)reportHtml(frame, options) — programmatic HTML report;
-CLI via npm run reportplotSeriesHtml(), plotSeries() — full-page series line chart
-(like Python plot_series)fromArrays(), fromObject(), fromDateColumns() — create from dates/values
-or simulation outputvalueToRet(), toCumret() - Convert price ↔ returnsgeoRet(), arithmeticRet(), vol(), varDown(), cvarDown()sortinoRatio(), retVolRatio(), maxDrawdown(), maxDrawdownBottomDate(), downsideDeviation()autocorr(lag?, opts?, squared?) — lag-k autocorrelation of demeaned returnsacf(lags, opts?, squared?), pacf(lags, opts?, squared?), partialAutocorr(lag?, opts?, squared?)ljungBox(lags, opts?, squared?) — Ljung–Box test (statistic, pvalue, lags)ewmaVolFunc(), ewmaVarFunc() - EWMA risk measuresmergeSeries(), truncFrame() - Align multiple seriestoDrawdownSeries() - Convert aligned columns to drawdown (value/peak - 1)makePortfolio() - Weighted portfolio (eq_weights, inv_vol, max_div, min_vol_overweight)correlMatrix(), trackingError(), infoRatio(), beta(), jensenAlpha()autocorr(lag?, squared?) — per-constituent lag-k autocorrelation (number[])maxDrawdown(), maxDrawdownBottomDate() - Per-column drawdown metricscaptureRatio(ratio, baseColumn?, opts?) - CAGR-based capture vs benchmark
-(opts.freq optional; when omitted, uses frame data as-is)ordLeastSquaresFit(), filterToBusinessDays(), resampleToPeriodEnd()fromNormal(), fromLognormal(), fromGbm(), fromMertonJumpGbm() — all accept
-optional seed for reproducibilitytoDateColumns(name, options?) — returns dates and columns
-(as returns or cumulative prices)randomGenerator(seed?) — seeded RNG for custom usefetchCaptorSeries(id) — fetch a single series from Captor Open APIfetchCaptorSeriesBatch(ids) — fetch multiple seriesreportHtml(frame, options?) — generate HTML report (cumulative performance,
-annual returns, stats) from an OpenFrame.
-Options: title, logoUrl, addLogo.
-Countries for business-day metrics come from frame.countries.plotSeriesHtml(seriesOrFrame, options?) — generate full-page HTML with a line
-chart of cumulative returns (base 1).
-Works with OpenTimeSeries or OpenFrame (use mergeSeries("inner") first).
-Options: title, logoUrl, addLogo, asDrawdown (plot drawdown series).plotSeries(seriesOrFrame, options?) — async: writes HTML to file and optionally
-opens in browser.
-Options: title, logoUrl, addLogo, filename (default: ~/Documents/plot.html),
-autoOpen (default: true).API reference: https://captorab.github.io/openseries-ts/
-To regenerate docs locally:
-npm run docs
-
-
-This writes static HTML to docs/. To serve them via GitHub Pages:
npm run docs and commit the docs/ foldermain (or your default branch), folder: /docsDocs will be available at https://<username>.github.io/<repo>/.
| Command | -Description | -
|---|---|
npm run build |
-Build dist/ (ESM + CJS + declarations) |
-
npm run test |
-Run Vitest test suite | -
npm run test:coverage |
-Run tests with Istanbul coverage report | -
npm run lint |
-Run ESLint on src/ |
-
npm run lint:fix |
-ESLint with auto-fix | -
npm run typecheck |
-TypeScript check (tsc --noEmit) |
-
npm run check |
-Run lint + typecheck | -
npm run docs |
-Generate API docs to docs/ (TypeDoc) |
-
npm publish |
-publish to npm | -
Generates an HTML portfolio report from Captor API timeseries -(cumulative performance, annual returns, statistics).
-| Command | -Description | -
|---|---|
npm run report |
-Report with custom or default Captor series IDs | -
npm run report:iris |
-Preset: Captor Iris Bond + Benchmark Index | -
npm run report:captor |
-Same as report (default Captor IDs) |
-
Default output (in ~/Documents): iris_report.html (Iris preset), captor_report.html
-(default Captor preset), or report.html (custom --ids).
Options (pass after --): --ids id1 id2 ..., --iris, --title "Title",
---countries "SE,US", --from-date YYYY-MM-DD, --to-date YYYY-MM-DD,
---filename path, --no-open, --no-logo.
Examples:
-npm run report -- --ids 638f681e 5b72a10c 5c1115fb
npm run report:iris -- --from-date 2023-01-01 --to-date 2024-12-31 --no-open
-
-
-Generates a full-page HTML line chart of cumulative returns (base 1)
-from Captor API timeseries.
-With the default Captor preset (no --ids), an equal-weight portfolio series is included.
| Command | -Description | -
|---|---|
npm run plot |
-Plot with custom or default Captor series IDs | -
npm run plot:iris |
-Preset: Captor Iris Bond + Benchmark Index | -
npm run plot:captor |
-Same as plot |
-
npm run plot:drawdown |
-DEFAULT_SERIES as drawdown series | -
Default output (in ~/Documents): iris_plot.html (Iris preset), captor_plot.html
-(default Captor preset), drawdown_plot.html (drawdown preset), or plot.html (custom --ids).
Options (pass after --): same as Report (--ids, --iris, --drawdown, --title,
---countries, --from-date, --to-date, --filename, --no-open, --no-logo).
Examples:
-npm run plot:iris
npm run plot -- --ids id1 id2 --no-open --filename my-plot.html
-
-
-Simulates asset returns (lognormal), builds portfolio frame, computes efficient -frontier and max-Sharpe portfolio, and plots simulated portfolios, frontier, -and labeled points (assets, current, optimum). -Mirrors the Python openseries Jupyter notebook workflow.
-| Command | -Description | -
|---|---|
npm run efficient-frontier |
-Run efficient frontier demo | -
Options (pass after --): --simulations N (default: 5000), --points N
-(default: 30), --seed N (default: 71), --countries "SE", --title "Title",
---filename path, --no-open, --no-logo.
Example:
-npm run efficient-frontier -- --simulations 3000 --points 25 --no-open
-
-
-Compares TypeScript openseries-ts metrics against Python openseries metrics.
-Loads timeseries data from iris.json, computes metrics with the TS
-implementation, and displays them side-by-side with Python metrics from
-data.json.
Prerequisites: Run the Python script first to create the reference data in ~/Documents/:
python scripts/load_py_openseries_data.py
-
-
-This fetches the Captor Iris Bond timeseries from the API, saves it to
-~/Documents/iris.json, and exports Python-calculated metrics to
-~/Documents/data.json.
| Command | -Description | -
|---|---|
npm run compare-metrics |
-Compare TS vs Python metrics (default: 4 decimal places) | -
Options: --decimals=N (pass after --).
Examples:
-npm run compare-metrics
npm run compare-metrics -- --decimals=6
-
-
-Result of Ordinary Least Squares regression (ord_least_squares_fit).
-OptionaladdIf true, show logo in upper left. Default: true.
-OptionalasIf true, data is drawdown series (0 to negative decimals). Plot raw values * 100 as %, skip cumulative conversion.
-OptionalautoIf true, open the HTML file in the default browser. Default: true.
-OptionalfilenameOutput file path. Default: ~/Documents/plot.html (or ~/ if Documents missing).
-OptionallogoLogo URL (e.g. company logo). Shown in upper left when addLogo is true.
-OptionaltitleOptional title above the chart.
-Options to slice a series by date range.
-Result of the Ljung-Box test.
-
The
-Error.stackTraceLimitproperty specifies the number of stack frames -collected by a stack trace (whether generated bynew Error().stackor -Error.captureStackTrace(obj)).The default value is
-10but may be set to any valid JavaScript number. Changes -will affect any stack trace captured after the value has been changed.If set to a non-number value, or set to a negative number, stack traces will -not capture any frames.
-