Factor research

Factor data preparation, PIT alignment, forward returns, costs, research evaluation, detailed research, tears and serialization.

See the usage guide for task-oriented examples. Signatures below are generated from the public headers at the same commit as the rest of this site.

class dataframe_snapshot

Owned native dataframe snapshot (replacing the pandas pickle snapshot).

Public Functions

dataframe_snapshot() = default

Constructs an empty snapshot with an empty digest.

explicit dataframe_snapshot(dataframe value)

Snapshots value and computes its content digest.

Parameters:

value – Dataframe to take ownership of.

Throws:

fincore_error – If a column type cannot be encoded in the canonical content representation.

inline const dataframe &data() const noexcept

Returns the owned dataframe.

inline dataframe copy() const

Returns a copy of the owned dataframe.

inline const std::string &content_sha256() const noexcept

Returns the lowercase hexadecimal content digest; empty for a default-constructed snapshot.

class enhanced_non_matching_timezone_error : public fincore::factor_data_error

Enhanced-kernel timezone validation error (Python subclasses ValueError).

Public Functions

inline explicit enhanced_non_matching_timezone_error(const std::string &message = "factor and prices have different timezones")

Constructs the enhanced error with the supplied message.

Parameters:

message – Failure description; defaults to the pinned mismatch text.

class factor_data_error : public std::invalid_argument

Reports invalid factor data or operation input.

Subclassed by fincore::enhanced_non_matching_timezone_error, fincore::factor_loss_exceeded

class factor_loss_exceeded : public fincore::factor_data_error

Reports factor cleaning loss that exceeds the configured budget.

Public Functions

inline factor_loss_exceeded(const std::string &message, factor_loss_report report)

Constructs the error with a message and loss report.

Parameters:
  • message – Failure description.

  • report – Cleaning-loss breakdown that exceeded the budget.

Public Members

factor_loss_report loss_report

Cleaning-loss breakdown.

class factor_value

Deterministic native value model used by factor serialization.

Objects are ordered maps, so both JSON output and fingerprints are stable regardless of insertion order. Doubles keep their IEEE-754 bit pattern in the canonical encoding; NaN payloads are canonicalized to one quiet NaN.

Public Types

using array_type = std::vector<factor_value>

Ordered array of values.

using object_type = std::map<std::string, factor_value>

Ordered map from string key to value.

Public Functions

factor_value() = default

Constructs a null value.

inline factor_value(std::nullptr_t)

Constructs a null value from nullptr.

inline factor_value(bool value)

Constructs a boolean value.

inline factor_value(int value)

Constructs a 64-bit integer value from int.

inline factor_value(std::int64_t value)

Constructs a 64-bit integer value.

inline factor_value(double value)

Constructs a floating-point number value.

inline factor_value(std::string value)

Constructs a string value, taking ownership of value.

inline factor_value(const char *value)

Constructs a string value by copying value.

inline factor_value(array_type value)

Constructs an array value, taking ownership of value.

inline factor_value(object_type value)

Constructs an object value, taking ownership of value.

inline bool is_null() const noexcept

Returns whether the value is null.

inline bool is_bool() const noexcept

Returns whether the value holds a boolean.

inline bool is_integer() const noexcept

Returns whether the value holds a 64-bit integer.

inline bool is_number() const noexcept

Returns whether the value holds a floating-point number; integers are a separate alternative.

inline bool is_string() const noexcept

Returns whether the value holds a string.

inline bool is_array() const noexcept

Returns whether the value holds an array.

inline bool is_object() const noexcept

Returns whether the value holds an object.

inline bool as_bool() const

Returns the stored boolean.

Throws:

std::bad_variant_access – If the value holds another type.

inline std::int64_t as_integer() const

Returns the stored 64-bit integer.

Throws:

std::bad_variant_access – If the value holds another type.

inline double as_number() const

Returns the stored floating-point number.

Throws:

std::bad_variant_access – If the value holds another type.

inline const std::string &as_string() const

Returns the stored string.

Throws:

std::bad_variant_access – If the value holds another type.

inline const array_type &as_array() const

Returns the stored array.

Throws:

std::bad_variant_access – If the value holds another type.

inline const object_type &as_object() const

Returns the stored object.

Throws:

std::bad_variant_access – If the value holds another type.

inline array_type &as_array()

Returns the stored array for mutation.

Throws:

std::bad_variant_access – If the value holds another type.

inline object_type &as_object()

Returns the stored object for mutation.

Throws:

std::bad_variant_access – If the value holds another type.

const factor_value &at(std::string_view key) const

Returns the value stored under key.

Parameters:

key – Object key to look up.

Throws:

input_error – If the value is not an object or key is absent.

Returns:

Reference to the stored value.

const factor_value *find(std::string_view key) const noexcept

Finds the value stored under key.

Parameters:

key – Object key to look up.

Returns:

Pointer to the stored value, or nullptr when the value is not an object or key is absent.

Friends

friend bool operator==(const factor_value&, const factor_value&) = default
template<typename Value>
class frozen_mapping

Immutable ordered map.

Construction snapshots the supplied map; callers cannot mutate the stored entries and mutation of the source has no effect.

Public Types

using storage_type = std::map<std::string, Value>

Ordered map type used to store the entries.

using const_iterator = typename storage_type::const_iterator

Read-only iterator over the stored entries.

Public Functions

frozen_mapping() = default

Constructs an empty mapping.

inline explicit frozen_mapping(storage_type values)

Constructs a mapping that takes ownership of values.

Parameters:

values – Entries to store; the map is moved into the snapshot.

inline frozen_mapping(std::initializer_list<typename storage_type::value_type> values)

Constructs a mapping from an initializer list.

Parameters:

values – Entries to copy into the mapping.

inline const Value &at(const std::string &key) const

Returns the value stored under key.

Parameters:

key – Entry key to look up.

Throws:

std::out_of_range – If key is absent.

Returns:

Reference to the stored value.

inline const Value *find(const std::string &key) const noexcept

Finds the value stored under key.

Parameters:

key – Entry key to look up.

Returns:

Pointer to the stored value, or nullptr when key is absent.

inline bool contains(const std::string &key) const noexcept

Returns whether key is present.

Parameters:

key – Entry key to look up.

inline std::size_t size() const noexcept

Returns the number of entries.

inline bool empty() const noexcept

Returns whether the mapping has no entries.

inline const_iterator begin() const noexcept

Returns an iterator to the first entry in key order.

inline const_iterator end() const noexcept

Returns the past-the-end iterator.

inline storage_type snapshot() const

Returns a mutable copy of the stored map.

Friends

friend bool operator==(const frozen_mapping&, const frozen_mapping&) = default
class grid_figure

Native layout model replacing the Matplotlib-backed GridFigure.

It owns only geometry (figure size, spacing and allocated cells); Python figure object identity is not claimed. close is idempotent and any later allocation fails, matching the source lifecycle.

Public Functions

grid_figure(std::size_t rows, std::size_t cols)

Creates a grid with rows rows and cols columns.

Parameters:
  • rows – Row count; must be positive.

  • cols – Column count; must be positive.

Throws:

factor_data_error – If rows or cols is zero.

inline std::size_t rows() const noexcept

Returns the configured row count.

inline std::size_t cols() const noexcept

Returns the configured column count.

inline std::size_t current_row() const noexcept

Returns the current cursor row.

inline std::size_t current_col() const noexcept

Returns the current cursor column.

inline bool closed() const noexcept

Returns whether close() has been called.

inline double width() const noexcept

Returns the fixed figure width of 14.

inline double height() const noexcept

Returns the figure height, seven units per row.

inline double wspace() const noexcept

Returns the fixed horizontal spacing of 0.4.

inline double hspace() const noexcept

Returns the fixed vertical spacing of 0.3.

inline const std::vector<grid_cell> &cells() const noexcept

Returns the allocated cells in allocation order; empty after close().

std::uint64_t create_new_figure() const

Returns the owned figure identifier (1 for every native grid).

Throws:

std::runtime_error – If the grid is closed.

Returns:

Figure identifier, always 1.

grid_cell next_row()

Allocates the next full-width row.

Throws:
  • std::runtime_error – If the grid is closed.

  • std::out_of_range – If the next row lies beyond the grid.

Returns:

Allocated full-row cell.

grid_cell next_cell()

Allocates the next cell, advancing to a new row when necessary.

Throws:
  • std::runtime_error – If the grid is closed.

  • std::out_of_range – If the next cell lies beyond the grid.

Returns:

Allocated cell.

void close() noexcept

Closes this grid’s figure and releases layout state.

The call is idempotent.

class max_loss_exceeded_error : public std::runtime_error

Pinned strict identity for a rejected cleaning-loss budget.

Public Functions

inline explicit max_loss_exceeded_error(std::string message = "", factor_loss_report report = {})

Constructs the error with an optional message and loss report.

Parameters:
  • message – Failure description.

  • report – Cleaning-loss breakdown associated with the failure.

Public Members

factor_loss_report loss_report

Cleaning-loss breakdown for the error.

class non_matching_timezone_error : public std::runtime_error

Pinned strict identity for a factor/prices timezone mismatch.

Public Functions

inline explicit non_matching_timezone_error(const std::string &message = "factor and prices have different timezones")

Constructs the error with the supplied message.

Parameters:

message – Failure description; defaults to the pinned mismatch text.

class research_config_error : public fincore::research_error

Research error with the ConfigError category.

Public Functions

inline explicit research_config_error(const std::string &message, std::string code = default_code, std::map<std::string, std::string> report = {})

Constructs a configuration error.

Parameters:
  • message – Human-readable failure description.

  • code – Machine-readable identifier; defaults to invalid_config.

  • report – Optional structured diagnostic fields.

Public Static Attributes

static constexpr const char *default_category = "ConfigError"

Category name reported for configuration failures.

static constexpr const char *default_code = "invalid_config"

Default machine-readable code for invalid configuration.

class research_data_quality_error : public fincore::research_error

Research error with the DataQualityError category.

Public Functions

inline explicit research_data_quality_error(const std::string &message, std::string code = default_code, std::map<std::string, std::string> report = {})

Constructs a data-quality error.

Parameters:
  • message – Human-readable failure description.

  • code – Machine-readable identifier; defaults to data_quality.

  • report – Optional structured diagnostic fields.

Public Static Attributes

static constexpr const char *default_category = "DataQualityError"

Category name reported for data-quality failures.

static constexpr const char *default_code = "data_quality"

Default machine-readable code for data-quality failures.

class research_dataset_error : public fincore::research_error

Research error with the DatasetError category.

Public Functions

inline explicit research_dataset_error(const std::string &message, std::string code = default_code, std::map<std::string, std::string> report = {})

Constructs a dataset error.

Parameters:
  • message – Human-readable failure description.

  • code – Machine-readable identifier; defaults to invalid_dataset.

  • report – Optional structured diagnostic fields.

Public Static Attributes

static constexpr const char *default_category = "DatasetError"

Category name reported for dataset failures.

static constexpr const char *default_code = "invalid_dataset"

Default machine-readable code for invalid datasets.

class research_dependency_error : public fincore::research_error

Research error with the DependencyError category.

Public Functions

inline explicit research_dependency_error(const std::string &message, std::string code = default_code, std::map<std::string, std::string> report = {})

Constructs a dependency error.

Parameters:
  • message – Human-readable failure description.

  • code – Machine-readable identifier; defaults to missing_dependency.

  • report – Optional structured diagnostic fields.

Public Static Attributes

static constexpr const char *default_category = "DependencyError"

Category name reported for missing dependencies.

static constexpr const char *default_code = "missing_dependency"

Default machine-readable code for a missing dependency.

class research_error : public fincore::fincore_error

Native structured research errors.

Python exception inheritance is not reproduced; category preserves the source class name and code carries the stable machine-readable identifier.

Subclassed by fincore::research_config_error, fincore::research_data_quality_error, fincore::research_dataset_error, fincore::research_dependency_error, fincore::research_factor_computation_error

Public Functions

inline research_error(std::string category, std::string code, const std::string &message, std::map<std::string, std::string> report = {})

Constructs a structured research error.

Parameters:
  • category – Source exception class name preserved for callers.

  • code – Stable machine-readable error identifier.

  • message – Human-readable failure description.

  • report – Optional structured diagnostic fields.

class research_factor_computation_error : public fincore::research_error

Research error with the FactorComputationError category.

Public Functions

inline explicit research_factor_computation_error(const std::string &message, std::string code = default_code, std::map<std::string, std::string> report = {})

Constructs a factor-computation error.

Parameters:
  • message – Human-readable failure description.

  • code – Machine-readable identifier; defaults to factor_computation_failed.

  • report – Optional structured diagnostic fields.

Public Static Attributes

static constexpr const char *default_category = "FactorComputationError"

Category name reported for factor-computation failures.

static constexpr const char *default_code = "factor_computation_failed"

Default machine-readable code for a computation failure.

struct cumulative_quantile_series

Cumulative growth of one quantile across a chart’s dates.

Public Members

int quantile = 0

Quantile bucket label.

std::vector<timestamp> dates

Dates aligned with values; sorted and unique in builder output.

std::vector<double> values

Cumulative growth from 1.0; a date without a finite mean keeps the previous value.

struct event_window_cell

One finite event-window value for an offset, event date and asset.

Public Members

int offset = 0

Row offset from the event date; negative is before.

timestamp event_date = 0

Event date.

std::string asset

Asset label; empty for date-mean output.

double value = 0.0

Window value, compounded or raw as requested.

struct event_window_result

Event-aligned window extraction.

Public Members

int before = 0

Requested rows before each event date.

int after = 0

Requested rows after each event date.

std::vector<int> offsets

Observed offsets, ascending and clipped.

std::vector<timestamp> event_dates

Event dates found in the ledger.

std::vector<std::string> asset_labels

Assets seen at event dates, sorted.

std::vector<event_window_cell> cells

Cells; non-finite ledger values skipped.

struct events_distribution_chart

Event counts per equal-width time bucket.

Public Functions

std::string to_svg() const

Renders the bucket counts as a deterministic native SVG bar chart.

A chart without counts still carries the title and axis labels.

Public Members

bool valid = true

Whether the chart is drawable; the builders leave it true.

std::string title = "Distribution of events in time"

Chart title.

std::string x_label = "Date"

X-axis label.

std::string y_label = "Number of events"

Y-axis label.

std::size_t requested_bars = 50U

Requested number of equal-width buckets, stored as supplied.

std::vector<timestamp> bucket_starts

Bucket start timestamps, aligned with counts.

std::vector<double> counts

Event counts aligned with bucket_starts.

struct factor_alpha_beta_row

Annualized alpha and market beta for one forward-return label.

Public Members

std::string label

Forward-return label.

double annual_alpha

Annualized intercept; NaN when undefined.

double beta

Slope on the universe mean; NaN when undefined.

struct factor_analysis_config

Options that select the labels and result views of one analysis run.

periods narrows the analysed forward-return labels; the remaining flags choose the weight construction and which per-group or portfolio members are populated.

Public Members

bool long_short = true

Demeans weights and returns; false keeps raw values.

bool group_neutral = false

Demeans within date and group; needs groups.

bool equal_weight = false

Equal-weights the positive and negative sides.

bool by_group = false

Adds per-group views; needs a group column.

std::vector<std::string> periods

Empty selects every forward-return label.

std::vector<int> turnover_periods = {1}

Positive, unique lag values.

std::vector<std::string> time_aggregation = {"M"}

Only monthly "M"/"ME" aggregation is implemented natively.

bool include_portfolio_inputs = true

Builds inputs for the first selected period.

std::string portfolio_benchmark_period = "1D"

Non-empty label recorded in the fingerprint.

struct factor_analysis_model

Complete result of one analyze_factor run.

Aggregate members are built for every run; per-group members appear only when config.by_group is true, and the event members only for the overload that receives an event-return ledger.

Public Functions

std::string to_serializable() const

Returns the deterministic JSON serialization envelope.

Implemented in factor/serialization.cpp; declared here so the model keeps the source’s to_serializable member route.

Returns:

JSON text of the serialization envelope.

Public Members

prepared_factor_data factor_data

Owning copy of the analysed input.

std::vector<std::string> forward_periods

Selected labels, in request order.

std::vector<factor_quantile_statistics> quantile_statistics

Per-quantile factor distribution.

factor_ic_table information_coefficient

Aggregate rank IC per date and label; never filled with group rows.

factor_ic_summary mean_information_coefficient

Mean of the finite aggregate IC values per label.

factor_return_table factor_returns

Portfolio returns per date and label.

std::vector<factor_weight_row> factor_weights

Per-observation weights.

quantile_return_table mean_returns_by_quantile

Aggregate quantile means.

quantile_date_return_table mean_returns_by_date

Per-date quantile means.

std::vector<factor_spread_row> mean_return_spread

Spreads per label; empty below two observed quantiles.

std::vector<factor_alpha_beta_row> alpha_beta

Annualized alpha and beta per label.

std::vector<factor_turnover_series> quantile_turnover

Turnover per requested lag and observed quantile.

std::vector<factor_rank_autocorrelation_series> rank_autocorrelation

Rank autocorrelation per requested lag.

std::vector<factor_cumulative_curve> factor_cumulative_returns

Compounded factor return curve per selected period.

std::vector<factor_quantile_curve> quantile_cumulative_returns

Compounded quantile growth curves per selected period.

std::vector<factor_position_series> factor_positions

Overlapping positions per selected period.

std::vector<factor_time_information_table> time_aggregated_information

Monthly mean IC, one table per requested frequency.

std::vector<factor_group_analysis> grouped_results

Independent subgroup reruns when by_group is true.

std::optional<factor_event_model> event_analysis

Present only for a call that supplies an event-return ledger.

std::optional<dataframe> event_input_snapshot

Owning copy of the event ledger that was analysed.

std::optional<factor_portfolio_inputs> portfolio_inputs

Daily inputs from the first selected period when requested.

std::string result_fingerprint

SHA-256 hex digest of the options, input and event ledger.

std::optional<factor_ic_table> summary_information_coefficient

Present only when group_neutral makes the legacy summary IC differ from information_coefficient; otherwise that field is the same view.

std::vector<factor_group_snapshot> group_snapshots

Per-group primary views, filled only when config.by_group is true.

factor_analysis_config config

Owning copy of the requested options, including the original periods.

std::uint32_t result_fingerprint_version = factor_analysis_fingerprint_version

Fingerprint encoding version recorded with this result.

struct factor_capacity_result

Capacity estimate for a weight panel against dollar volume.

Public Members

double maximum_portfolio_value = 0.0

Smallest finite per-date capacity.

std::vector<timestamp> dates

Panel dates in ascending order.

std::vector<double> maximum_portfolio_value_by_date

Capacity per date; infinity when the date has no trade.

std::vector<std::string> assets

Panel assets in ascending order.

std::vector<double> trade_weights

Dates x assets absolute traded weights.

double max_participation = 1.0

Participation cap used by the estimate.

timestamp binding_date = 0

First date attaining the smallest capacity.

std::string binding_asset

Asset limiting capacity on the binding date.

struct factor_cost_model

Spread, market-impact and participation settings for trading costs.

Public Members

double half_spread_bps = 0.0

Half-spread in basis points per traded weight.

double impact_coefficient = 0.0

Scale of the impact term.

double max_participation = 1.0

Participation cap in (0, 1].

double impact_exponent = 0.5

Participation exponent; must be positive.

struct factor_cost_result

Per-date cost ledger produced by applying a cost model to gross returns.

Public Members

factor_cost_model model

Cost model used for the ledger.

double portfolio_value = 0.0

Portfolio value the ledger was computed for.

std::vector<timestamp> dates

Panel dates in ascending order.

std::vector<std::string> assets

Panel assets in ascending order.

std::vector<double> gross_returns

Gross return per date, copied from the input.

std::vector<double> net_returns

Gross return less total cost per date.

std::vector<double> turnover

One-way turnover per date.

std::vector<double> spread_cost

Spread cost per date as a return fraction.

std::vector<double> impact_cost

Market-impact cost per date as a return fraction.

std::vector<double> borrow_cost

Borrow cost per date as a return fraction.

std::vector<double> total_cost

Sum of spread, impact and borrow costs per date.

std::vector<double> trade_weights

Dates x assets absolute traded weights.

std::vector<double> participation

Dates x assets traded value over dollar volume.

factor_capacity_result capacity

Capacity estimate at the model participation cap.

struct factor_cumulative_curve

Compounded factor return curve for one forward-return label.

Public Members

std::string period

Forward-return label.

factor_series_result values

Dated growth compounded from one.

struct factor_event_model

Event-window summary built from the optional event-return ledger.

Public Members

std::vector<int> offsets

Window offsets, ascending.

std::vector<timestamp> event_dates

Event dates found in both inputs.

std::vector<double> mean_returns

Mean per offset; NaN when empty.

std::vector<double> return_distribution

Window cells, ordered by offset and then event date.

std::vector<quantile_event_statistics> quantile_average_returns

Per-quantile event averages, ascending by quantile.

struct factor_event_tear_charts

Chart data for an optional event study.

Public Members

std::vector<int> offsets

Event offsets in observations.

series_chart mean_returns

Mean return over the offsets.

histogram_bins return_distribution

Histogram of event-window returns.

series_chart quantile_average_returns

Mean return by quantile over the offsets.

struct factor_group_analysis

Rerun of the analysis on one subgroup’s rows.

Public Members

std::string group

Group label that selected the rows.

std::vector<factor_quantile_statistics> quantile_statistics

Factor-value distribution inside the subgroup.

std::vector<factor_weight_row> factor_weights

Subgroup weights; group adjustment is off for this rerun.

factor_return_table factor_returns

Portfolio returns of the subgroup.

quantile_return_table mean_returns_by_quantile

Subgroup quantile means and standard errors.

factor_ic_table information_coefficient

Subgroup rank IC per date.

factor_ic_summary mean_information_coefficient

Subgroup mean IC per forward-return label.

std::vector<factor_turnover_series> quantile_turnover

Subgroup turnover per requested lag and quantile.

std::vector<factor_rank_autocorrelation_series> rank_autocorrelation

Subgroup rank autocorrelation per requested lag.

struct factor_group_snapshot

Python’s primary by_group result views, kept separate from grouped_results.

These tables were computed from the full analysis universe before their group rows were selected, so long_short demeaning can span groups.

Public Members

std::string group

Group label that selected the rows.

quantile_return_table mean_returns_by_quantile

Group rows of the aggregate quantile means.

quantile_date_return_table mean_returns_by_date

Group rows of the per-date quantile means.

std::vector<factor_spread_row> mean_return_spread

Spread rows for this group.

factor_ic_table information_coefficient

Group rows of the rank IC table.

factor_ic_summary mean_information_coefficient

This group’s mean IC row.

std::vector<factor_time_information_table> time_aggregated_information

Monthly IC tables restricted to this group.

struct factor_group_tear_charts

Chart data for one factor group.

Public Members

std::string group

Group label.

series_chart information_coefficient

Information coefficient by forward label.

bar_chart quantile_returns

Mean return by quantile per forward label.

series_chart turnover

Quantile turnover at the primary lag.

bar_chart spread

Top-minus-bottom quantile spread by period.

series_chart rank_autocorrelation

Rank autocorrelation by lag.

struct factor_grouping

Asset-to-group mapping used for grouped quantization and preparation.

An empty group_by_asset map disables grouping.

Public Members

std::map<std::string, std::string> group_by_asset

Asset to group name.

std::map<std::string, std::string> group_labels

Optional group label remapping.

struct factor_hypothesis

Inference outcome for one information-coefficient label.

Public Members

std::string label

Forward-return label.

std::size_t n_observations = 0U

Finite IC observations used.

double mean_ic = 0.0

Mean of those observations.

double t_stat = 0.0

t statistic; NaN for an untestable label.

double p_value = 0.0

Two-sided p value; NaN when untestable.

double adjusted_p_value = 0.0

Benjamini-Hochberg value; NaN when untestable.

bool rejected = false

True when the adjusted test rejects at alpha.

bool testable = false

True with at least two finite observations.

struct factor_ic_summary

Mean information coefficient per label or per group.

Public Members

std::vector<std::string> labels

Forward-return labels.

std::vector<double> means

Labels or groups x labels.

std::vector<std::string> groups

Empty for aggregate output; otherwise one entry per group row in means.

struct factor_ic_table

Spearman rank information coefficient per date and forward-return label.

values is a rectangular cube: one row per entry of dates and one column per entry of labels; a cell with fewer than two usable observations stays NaN.

Public Members

std::vector<timestamp> dates

Row dates; repeats per observed group.

std::vector<std::string> labels

Forward-return labels.

std::vector<double> values

(date[, group]) rows x labels, NaN missing.

std::vector<std::string> groups

Empty for aggregate output; otherwise parallel to dates, where dates repeats once per observed (date, group) row in date/group order.

struct factor_loss_report

Cleaning-loss accounting for one factor preparation.

Each loss member is the share of input_count dropped at that stage, so the three stage losses sum to total_loss.

Public Members

std::size_t input_count = 0U

Rows in the input factor panel.

std::size_t finite_factor_count = 0U

Rows with a finite factor value.

std::size_t forward_returns_count = 0U

Rows with all forward labels finite.

std::size_t binning_count = 0U

Rows retained after quantization.

double factor_input_loss = 0.0

Share lost to a non-finite factor.

double forward_returns_loss = 0.0

Share lost to missing forward returns.

double binning_loss = 0.0

Share dropped when assigning quantiles.

double total_loss = 0.0

Sum of the three staged losses.

struct factor_model_envelope

The subset of a serialized model that the native envelope can restore.

Public Members

std::string schema

Serialization schema identifier; the value written and accepted by this library is fincore-factor-analysis-native-v1.

std::uint32_t fingerprint_version = 0U

Result-fingerprint format version stored in the envelope.

std::string result_fingerprint

Result fingerprint restored from the envelope.

factor_analysis_config config

Factor-analysis configuration restored from the envelope.

std::vector<std::string> forward_periods

Forward-return period labels restored from the envelope.

factor_loss_report loss_report

Data loss report restored from the envelope.

struct factor_operation_descriptor

Stable operation descriptors for the factor runtime catalog.

Public Members

std::string operation_id

Stable operation identifier.

std::string capability_id

Equals operation_id when generated.

std::string domain

Equals "factor_analysis" when generated.

std::map<std::string, std::string> provenance

Owner and kernel keys.

struct factor_portfolio_inputs

Daily portfolio inputs built from one factor period.

Public Members

factor_series_result returns

Daily simple returns generated from the compounded period curve.

std::vector<factor_weight_row> positions

Daily gross-normalized asset weights plus one explicit cash row per timestamp.

Cash makes every row’s signed total exactly one.

std::optional<factor_series_result> benchmark_returns

Daily long-only equal-weight benchmark returns when the requested period labels a forward-return column; absent otherwise.

struct factor_position_series

Overlapping portfolio positions for one forward-return label.

Public Members

std::string period

Forward-return label.

std::vector<factor_weight_row> positions

Positions for this label.

struct factor_quantile_curve

Compounded quantile growth curves for one forward-return label.

Public Members

std::string period

Forward-return label.

std::vector<timestamp> dates

Curve dates, ascending.

std::vector<int> quantiles

Descending, matching the source renderer.

std::vector<double> values

Dates x quantiles, compounded growth.

struct factor_quantile_statistics

Factor-value distribution inside one quantile bucket.

Only finite factor values are counted, so the moments describe the values that survive preparation.

Public Members

int quantile = 0

Quantile label.

double minimum = 0.0

Smallest finite factor value.

double maximum = 0.0

Largest finite factor value.

double mean = 0.0

Arithmetic mean of the finite values.

double stddev = 0.0

Sample standard deviation, NaN below two values.

std::size_t count = 0U

Finite factor observations in the bucket.

double count_percent = 0.0

Share of all finite values, in percent.

struct factor_rank_autocorrelation_series

Rank-autocorrelation series for one lag.

Public Members

int lag = 1

Date lag in observations.

factor_series_result values

Rank correlation per date; NaN in warm-up.

struct factor_return_table

Portfolio returns per date and forward-return label.

Public Members

std::vector<timestamp> dates

Sorted unique dates.

std::vector<std::string> labels

Forward-return labels.

std::vector<double> values

Dates x labels; zero when no pair is usable.

struct factor_row

One prepared factor observation.

Public Members

timestamp date = 0

Observation date.

std::string asset

Asset identifier.

double factor = 0.0

Finite factor value.

int quantile = 0

One-based quantile label.

bool has_group = false

Whether a group label was resolved.

std::string group

Group label, empty when ungrouped.

std::vector<double> forward_returns

Returns aligned with forward_labels.

struct factor_series

Long-form factor panel with row-aligned dates, assets and values.

Each index is one observation. Preparation and quantization require the three vectors to have equal lengths and (date, asset) pairs to be unique.

Public Members

std::vector<timestamp> dates

Observation dates.

std::vector<std::string> assets

Asset identifiers.

std::vector<double> values

Factor values, one per row.

struct factor_series_result

Dated scalar series.

Public Members

std::vector<timestamp> dates

Series dates, parallel to values.

std::vector<double> values

Values; NaN marks a missing point.

struct factor_spread_row

Top-minus-bottom quantile return spread for one label.

Public Members

std::string period

Forward-return label.

double spread = 0.0

Upper quantile mean minus lower quantile mean.

double standard_error = 0.0

Combined error; NaN when either leg is.

std::string group

Empty for aggregate rows; set for a by-group spread row.

struct factor_tear_charts

Chart bundle for one factor analysis.

grouped entries carry every panel, while group_snapshots entries carry only their information coefficient, quantile returns and spread panels.

Public Members

series_chart information_coefficient

Information coefficient by forward label.

bar_chart quantile_returns

Mean return by quantile per forward label.

series_chart turnover

Quantile turnover at the primary lag.

bar_chart spread

Top-minus-bottom spread per forward period.

series_chart rank_autocorrelation

Rank autocorrelation by lag.

std::vector<factor_group_tear_charts> grouped

Per-group charts with every panel.

std::vector<factor_group_tear_charts> group_snapshots

Per-group snapshot charts.

std::optional<factor_event_tear_charts> event_analysis

Event-study charts when present.

struct factor_time_information_table

Monthly aggregation of the information coefficient.

Public Members

std::string frequency

Requested aggregation label.

std::vector<timestamp> dates

Month rows; repeats once per group.

std::vector<std::string> labels

Forward-return labels.

std::vector<double> means

(date[, group]) rows x labels; NaN if empty.

std::vector<std::string> groups

Empty for aggregate output; otherwise parallel to dates.

struct factor_turnover_series

Turnover series for one quantile and lag.

Public Members

int quantile = 0

Quantile label.

int lag = 1

Date lag in observations.

factor_series_result values

Turnover per date; NaN during warm-up.

struct factor_weight_row

One asset weight on one date.

Public Members

timestamp date

Observation date.

std::string asset

Asset identifier.

double weight

Gross-normalized weight; NaN for a zero gross bucket.

struct factor_workflow

One named, renderer-independent factor workflow.

build is the canonical analysis builder; it never re-runs a workflow specific kernel. renderer stays empty because native workflows return prepared models and chart data rather than Matplotlib figures.

Public Members

std::string workflow_id

Workflow identifier such as "summary".

std::string model_operation_id

Analysis-kernel operation identifier.

std::vector<std::string> sections

Ordered analysis section names.

std::optional<std::string> renderer

Optional renderer ID; empty here.

factor_analysis_model (*build)(const prepared_factor_data&, const factor_analysis_config&) = &analyze_factor

Builds the analysis model from prepared data and configuration.

struct fama_macbeth_estimate

One estimated Fama-MacBeth coefficient series.

Public Members

double mean = 0.0

Mean of the per-date estimates.

double std_error = 0.0

Standard error of that mean.

double t_stat = 0.0

Ratio of the mean to the standard error.

struct fama_macbeth_result

Fama-MacBeth cross-sectional regression result.

Public Members

fama_macbeth_estimate intercept

Intercept across cross-sections.

fama_macbeth_estimate exposure

Exposure slope across cross-sections.

std::size_t n_cross_sections = 0U

Fitted cross-sections.

fama_macbeth_covariance covariance = fama_macbeth_covariance::iid

Requested estimator.

std::size_t newey_west_lags = 1U

Requested lags; recorded even for i.i.d.

struct fdr_result

Benjamini-Hochberg step-up adjustment output.

Public Members

std::vector<double> p_values

Input p values, in input order.

std::vector<double> adjusted_p_values

Adjusted values, in input order.

std::vector<bool> rejected

Rejection flag per input, in input order.

double alpha = 0.05

Requested false-discovery rate.

struct forward_return_table

Forward returns for factor observations, stored label by label.

dates and assets form the row keys; values holds one vector per entry of labels, each aligned with those rows.

Public Members

std::vector<std::string> labels

Horizon labels such as "1D".

std::vector<timestamp> dates

Row dates, parallel to assets.

std::vector<std::string> assets

Row assets, parallel to dates.

std::vector<std::vector<double>> values

Labels x rows, NaN missing.

struct grid_cell

Zero-based position of one allocated grid cell.

Public Members

std::size_t row = 0U

Zero-based row.

std::size_t col = 0U

Zero-based column; 0 for a full-row cell.

bool full_row = false

Whether the cell spans the full row.

std::size_t index = 0U

Allocation order within cells().

struct ic_inference_result

Per-label IC inference with a false-discovery-rate adjustment.

Public Members

double alpha = 0.05

Requested false-discovery rate.

std::vector<factor_hypothesis> hypotheses

One entry per label.

struct ic_interval

Symmetric confidence interval for a mean IC.

Public Members

double lower

Lower bound; NaN when undefined.

double upper

Upper bound; NaN when undefined.

struct monthly_ic_heatmap_chart

Monthly information-coefficient heatmap for one period and group.

Public Functions

std::string to_svg() const

Renders one rectangle per present heatmap cell as native SVG.

Cell colors use a red/blue diverging scale normalized by the largest absolute value. Year and month labels are not drawn.

Public Members

std::string period

Forward-return period label.

std::string group

Group label; empty for aggregate output.

std::string title

Chart title.

std::vector<int> years

Row year labels, ascending.

std::vector<std::string> month_columns

Twelve month labels, January first.

std::vector<double> values

Years x 12 values in row-major order; NaN for an absent month.

std::vector<bool> present

Cell presence flags aligned with values.

struct multi_horizon_prepared_factor_data

Prepared factor panels, one per forward-return horizon.

Public Members

std::vector<std::pair<std::string, prepared_factor_data>> by_horizon

Label and panel pairs in the order of the requested periods.

struct named_factor_panel

Named factor panel accepted by the multi-factor evaluator.

Public Members

std::string name

Factor name; must be non-empty and unique.

factor_series values

Factor values by (date, asset).

struct named_research_result

Named single-factor result used by comparison diagnostics.

Public Members

std::string name

Factor or combination name; must be non-empty and unique.

research_result result

Stored evaluation result.

struct owned_figures

Caller-owned figure identifiers returned by a tear-sheet workflow.

Public Members

std::vector<std::uint64_t> figures

Figure identifiers in display order.

std::vector<bool> closed

Closed flags aligned with figures; filled by close_owned_figures.

struct pit_observation

Asset-scoped point-in-time observation used to materialize a panel.

Public Members

std::string asset

Non-empty asset identifier.

pit_point point

Revision of the asset’s factor value.

bool in_universe = true

Whether the asset enters the materialized panel.

struct pit_point

One point-in-time revision of an asset’s factor value.

The dates must satisfy as_of <= known_at <= effective_from.

Public Members

timestamp as_of = 0

Date the value describes.

timestamp known_at = 0

Date the value became known; at least as_of.

timestamp effective_from = 0

First effective date; at least known_at.

double value = 0.0

Factor value; must be finite.

struct prepare_factor_config

Full configuration for factor preparation.

Public Members

int quantiles = 5

Quantile bucket count.

bool use_bins = false

Uses equal-width bins instead of quantiles.

std::vector<double> bins

Explicit bin edges; empty derives them.

std::vector<int> periods = {1, 5, 10}

Forward horizons in observations.

double max_loss = 0.35

Maximum tolerated total cleaning loss in [0, 1].

bool binning_by_group = false

Quantizes within each (date, group) cross-section.

std::optional<double> filter_zscore

Per-asset forward-return z-score cutoff.

bool zero_aware = false

Separates negative and non-negative values.

bool cumulative_returns = true

Compounds returns over the horizon when true.

factor_grouping grouping

Asset-to-group mapping; empty disables grouping.

struct prepared_factor_data

Prepared factor rows with their labels and cleaning-loss report.

Public Members

std::vector<factor_row> rows

Retained observations.

std::vector<std::string> forward_labels

Labels aligned with row returns.

factor_loss_report loss_report

Cleaning-loss accounting.

struct qq_chart

Q-Q chart data for one or more periods.

Public Functions

std::string to_svg() const

Renders the Q-Q scatter and a diagonal reference line as native SVG.

reference_slope and reference_intercept are not used by this renderer.

Public Members

std::vector<qq_series> series

Series in draw order.

std::string x_label = "Normal Distribution Quantile"

X-axis label.

std::string y_label = "Observed Quantile"

Y-axis label.

struct qq_series

Normal Q-Q series for the information coefficient of one period.

Public Members

std::string period

Forward-return period label.

std::vector<double> theoretical_quantiles

Standard-normal quantiles at (i + 1) / (n + 1).

std::vector<double> observed_quantiles

Sorted IC observations aligned with theoretical_quantiles; values are standardized only when mean is nonzero and scale is positive and not 1.

double mean = 0.0

Mean of the observations; non-finite IC values count as zero.

double scale = 1.0

Population standard deviation of the observations.

double reference_slope = 1.0

Slope of the reference line drawn by the interactive backend.

double reference_intercept = 0.0

Intercept of the reference line drawn by the interactive backend.

struct quantile_cumulative_chart

Cumulative-return chart data for every quantile of one forward period.

Public Functions

std::string to_svg() const

Renders the chart as a deterministic native SVG document.

Public Members

std::string period

Forward-return period label used in the title.

std::string title

Chart title.

std::string y_label = "Log Cumulative Returns"

Y-axis label.

std::vector<cumulative_quantile_series> series

Quantiles descending.

double y_min = 0.0

Lower bound of the cumulative-growth axis.

double y_max = 1.0

Upper bound of the cumulative-growth axis.

bool log_scale = true

Log-scale flag; the native SVG renderer maps cumulative values linearly.

double reference = 1.0

Horizontal reference value, drawn by to_svg() when inside the bounds.

struct quantile_date_return_table

Per-date quantile mean returns and standard errors.

Public Members

std::vector<timestamp> dates

Row keys; repeats for each observed group.

std::vector<int> quantiles

Quantile keys.

std::vector<std::string> labels

Forward-return labels.

std::vector<double> means

(date[, group]) x quantiles x labels.

std::vector<double> standard_errors

(date[, group]) x quantiles x labels.

std::vector<std::string> groups

Empty for aggregate output; otherwise parallel to dates.

struct quantile_event_statistics

Event-window averages for one quantile.

Public Members

int quantile = 0

Quantile label.

std::vector<int> offsets

Contiguous offsets, first through last.

std::vector<double> means

Mean value per offset; NaN when empty.

std::vector<double> standard_deviations

Sample deviation; NaN below two values.

struct quantile_return_table

Quantile mean returns and standard errors.

Public Members

std::vector<int> quantiles

Row keys; repeats when multiple groups exist.

std::vector<std::string> labels

Forward-return labels.

std::vector<double> means

(quantile[, group]) rows x labels.

std::vector<double> standard_errors

(quantile[, group]) rows x labels.

std::vector<std::string> groups

Empty for aggregate output; otherwise parallel to quantiles.

struct quantile_spread_result

Top-minus-bottom quantile spreads.

Public Members

std::vector<std::string> labels

Periods; repeats for each group.

std::vector<double> spreads

Upper mean minus lower mean.

std::vector<double> standard_errors

Combined error; NaN when either leg is.

std::vector<std::string> groups

Empty for aggregate output; otherwise parallel to labels.

struct quantization_config

Bucket assignment settings for a factor cross-section.

Public Members

int quantiles = 5

Bucket count when use_bins is false.

bool use_bins = false

Uses equal-width bins instead of quantiles.

std::vector<double> bins

Explicit bin edges; empty derives them.

bool by_group = false

Buckets within each (date, group) cross-section.

bool no_raise = false

Labels failed buckets empty instead of throwing.

bool zero_aware = false

Separates negative and non-negative values.

struct render_customization

Native replacement for the customize decorator: the context a renderer applies around a chart call.

It carries no callable identity.

Public Members

bool set_context = true

Whether context is applied around the call.

bool colorblind_palette = true

Whether a colorblind palette is used.

bool despine_left = true

Whether the left spine is removed.

style_context context = {"notebook", 1.5, {{"lines.linewidth", "1.5"}}}

Context applied around the chart call when set_context is true.

style_context axes = {"darkgrid", 1.5, {}}

Axes style applied around the chart call.

std::vector<std::string> palette{"#0173B2", "#DE8F05", "#029E73", "#D55E00", "#CC78BC", "#CA9161", "#FBAFE4", "#949494"}

Colorblind-safe color cycle used when colorblind_palette is true.

struct research_capabilities

Pinned capability declaration for the native research surface.

Public Members

std::string api_version = research_api_version

Research API version string.

int result_schema_version = research_result_schema_version

Result schema version.

std::vector<std::string> labels{"close_to_close", "next_open_to_open", "precomputed"}

Supported label bases.

std::vector<std::string> preprocess{"cross_section_rank", "cross_section_zscore", "none"}

Preprocessing methods.

std::vector<std::string> metrics{"pearson_ic", "spearman_ic", "icir", "quantile_returns", "spread", "rank_autocorrelation", "quantile_turnover", "factor_correlation", "paired_comparison"}

Advertised metric identifiers.

std::vector<std::string> result_tables{"signals", "labels", "ic", "ic_summary", "quantile_returns", "turnover", "spreads", "stability", "correlation", "comparisons", "coverage", "diagnostics"}

Names accepted by research_result::table().

std::vector<std::string> export_formats = {"json", "csv"}

Advertised export formats.

std::vector<std::string> statuses = {"OK", "PARTIAL", "UNEVALUABLE"}

Evaluation statuses.

struct research_comparison_row

Mean-IC and ICIR comparison for one factor pair and period.

Public Members

std::string comparison

Comparison name from the requested map.

std::string left

Left factor name.

std::string right

Right factor name.

std::string period

Forward-return period label.

double mean_ic = 0.0

Left-minus-right mean IC; NaN when either side is unavailable.

double icir = 0.0

Left-minus-right ICIR; NaN when either side is unavailable.

double mean_ic_left = 0.0

Mean IC of the left factor; NaN when unavailable.

double mean_ic_right = 0.0

Mean IC of the right factor; NaN when unavailable.

double icir_left = 0.0

Left ICIR; NaN with too few dates or zero deviation.

double icir_right = 0.0

Right ICIR; NaN with too few dates or zero deviation.

std::size_t n_dates_left = 0U

Finite IC dates used for the left factor.

std::size_t n_dates_right = 0U

Finite IC dates used for the right factor.

struct research_correlation_row

Correlation summary for one ordered factor pair.

Public Members

std::string left

Left factor name.

std::string right

Right factor name.

double mean_correlation = 0.0

Mean Pearson correlation; NaN if none.

double std_correlation = 0.0

Sample standard deviation; NaN with fewer than two dates.

std::size_t n_dates = 0U

Number of dates with a finite correlation.

struct research_detailed_coverage_row

Coverage counts for the single factor evaluated by this API.

Public Members

std::string factor

Factor name.

std::string kind = "factor"

Coverage row kind; "factor" here.

int direction = 1

Applied direction, +1 or -1.

std::size_t input_cells = 0U

Cells after window/target selection.

std::size_t finite_cells = 0U

Cells with a finite processed factor.

std::size_t label_cells = 0U

Cells with at least one finite label.

std::size_t evaluable_cells = 0U

Cells with finite factor and label.

std::string status

"OK", "PARTIAL" or "UNEVALUABLE".

struct research_detailed_diagnostic

Structured, source-compatible diagnostic row.

factor is empty when the Python table’s nullable factor value is absent.

Public Members

std::optional<std::string> factor

Factor name; empty when absent.

std::string stage

Evaluation stage that emitted the diagnostic.

std::string severity

Severity such as "warning" or "error".

std::string code

Stable machine-readable diagnostic code.

std::string message

Human-readable diagnostic text.

struct research_detailed_export_outcome

Owning metadata returned by the combined detailed evaluation and export.

Signal and label rows are streamed to the CSV files and are not retained in this outcome; their row counts remain available here and in the manifest.

Public Members

std::string status

Evaluation status copied from the result.

std::map<std::string, std::string> manifest

Evaluation manifest.

std::vector<research_detailed_diagnostic> diagnostics

Evaluation diagnostics.

std::size_t signal_rows = 0U

Signal rows written to signals.csv.

std::size_t label_rows = 0U

Label rows written to labels.csv.

research_export_result exported

Directory and exported file names.

struct research_detailed_ic_row

One date/factor/period observation from the Python research ic table.

Public Members

timestamp time = 0

Observation date in UTC nanoseconds.

std::string factor

Factor name.

std::string period

Forward-return period label.

double ic = 0.0

Pearson IC for the date; NaN when undefined.

double rank_ic = 0.0

Spearman rank IC; NaN when undefined.

std::size_t n_assets = 0U

Paired assets contributing to the IC.

struct research_detailed_ic_summary_row

Finite-observation summaries for Pearson and Spearman (rank) IC.

Public Members

std::string factor

Factor name.

std::string period

Forward-return period label.

double mean_ic = 0.0

Mean of finite Pearson IC values.

double std_ic = 0.0

Sample standard deviation of Pearson ICs.

double icir = 0.0

Mean IC divided by its sample deviation.

double mean_rank_ic = 0.0

Mean of finite rank IC values.

double std_rank_ic = 0.0

Sample standard deviation of rank ICs.

double rank_icir = 0.0

Mean rank IC divided by its sample deviation.

std::size_t n_dates = 0U

Number of finite Pearson IC observations.

struct research_detailed_quantile_return_row

One date/factor/period/quantile raw-return mean and its contributing count.

Public Members

timestamp time = 0

Observation date in UTC nanoseconds.

std::string factor

Factor name.

std::string period

Forward-return period label.

int quantile = 0

One-based quantile label.

double mean_return = 0.0

Mean raw forward return in the quantile.

std::size_t n_assets = 0U

Label cells contributing to the mean.

struct research_detailed_result

Version 2 owns typed rows for the factor-local detailed research tables.

Rows follow the pinned Python 1.0 evaluator’s append order; all numeric missing values are quiet NaNs. The single-factor entry represents the Python correlation and comparisons tables as empty vectors.

Public Members

std::string status

Overall status: "OK" or "UNEVALUABLE".

std::vector<research_signal_row> signals

Signal rows per panel cell.

std::vector<research_label_row> labels

Complete panel × period grid, including NaN values for missing labels.

std::vector<research_detailed_ic_row> ic

Per-date Pearson/rank IC.

std::vector<research_detailed_ic_summary_row> ic_summary

One per period.

std::vector<research_detailed_quantile_return_row> quantile_returns

Quantile means.

std::vector<research_detailed_turnover_row> turnover

Quantile turnover.

std::vector<research_detailed_spread_row> spreads

Daily spreads.

std::vector<research_detailed_stability_row> stability

Rank stability.

std::vector<research_correlation_row> correlation

Empty for this API.

std::vector<research_comparison_row> comparisons

Empty for this API.

std::vector<research_detailed_coverage_row> coverage

Factor coverage.

std::vector<research_detailed_diagnostic> diagnostics

Warnings and errors.

std::map<std::string, std::string> manifest

Metadata and row counts.

int schema_version = research_detailed_result_schema_version

Schema version.

struct research_detailed_spread_row

Daily top-minus-bottom quantile spread and the quantiles used.

Public Members

timestamp time = 0

Observation date in UTC nanoseconds.

std::string factor

Factor name.

std::string period

Forward-return period label.

double spread = 0.0

Top-quantile mean minus bottom-quantile mean.

int top_quantile = 0

Highest populated quantile label.

int bottom_quantile = 0

Lowest populated quantile label.

struct research_detailed_stability_row

Whole processed-panel stability summary for one requested lag.

Public Members

std::string factor

Factor name.

int lag = 0

Lag in observation dates.

double mean_rank_autocorrelation = 0.0

Mean rank autocorrelation.

double std_rank_autocorrelation = 0.0

Sample standard deviation.

std::size_t n_dates = 0U

Number of finite autocorrelation values.

struct research_detailed_turnover_row

Quantile turnover with the period-specific lag used by the Python API.

Public Members

timestamp time = 0

Observation date in UTC nanoseconds.

std::string factor

Factor name.

std::string period

Forward-return period label.

int quantile = 0

One-based quantile label.

double turnover = 0.0

Share of members absent at the lagged date.

struct research_evaluation_input

Caller-supplied values before defaulting.

Unset optionals take the pinned defaults; unknown_fields mirrors the source’s unknown-key rejection.

Public Members

std::optional<std::vector<std::string>> targets

Optional target list; normalization requires it.

std::optional<timestamp> start

Optional window start; normalization requires it.

std::optional<timestamp> end

Optional window end; normalization requires it.

std::optional<std::string> snapshot_id

Optional snapshot id; unset uses unspecified.

std::optional<std::string> price_basis

Optional price basis; unset uses unspecified.

std::optional<std::string> calendar_id

Optional calendar id; unset uses unspecified.

std::optional<std::string> frequency

Optional frequency; unset uses unspecified.

std::optional<std::string> source_timezone

Optional timezone metadata; unset uses UTC.

std::optional<std::string> feed_time_kind

Optional feed kind; unset uses close_time.

std::optional<std::vector<int>> periods

Optional horizons; unset uses {1, 5, 20}.

std::optional<std::string> label

Optional label basis; unset uses next_open_to_open.

std::optional<std::string> precomputed_entry

Optional entry convention; unset uses next_open.

std::optional<int> quantiles

Optional quantile count; unset uses 5.

std::optional<int> min_assets

Optional minimum assets; unset uses 10.

std::optional<int> min_quantile_assets

Optional minimum quantile observations; unset uses 1.

std::optional<std::string> preprocess

Optional method; unset uses cross_section_rank.

std::optional<double> max_loss

Optional loss fraction; unset uses 1.0.

std::optional<std::vector<int>> stability_lags

Optional lags; unset uses {1, 5, 20}.

std::optional<std::map<std::string, int>> direction_overrides

Optional per-asset signs (+1 or -1).

std::optional<std::map<std::string, std::map<std::string, double>>> combinations

Optional weighted blends; unset leaves the map empty.

std::optional<std::map<std::string, std::pair<std::string, std::string>>> comparisons

Optional factor pairs; unset leaves the map empty.

std::optional<std::map<std::string, std::pair<std::string, std::string>>> segments

Optional provenance ranges; unset leaves the map empty.

std::vector<std::string> unknown_fields

Unknown keys rejected by normalization.

struct research_evaluation_spec

Validated, default-filled research evaluation specification.

Mirrors the pinned Python ResearchEvaluationSpec field set, including the native UTC-nanosecond window endpoints.

Public Members

std::vector<std::string> targets

Target assets; non-empty and duplicate-free.

timestamp start = 0

Inclusive window start; must not exceed end.

timestamp end = 0

Inclusive window end.

std::string snapshot_id = "unspecified"

Provenance snapshot identifier.

std::string price_basis = "unspecified"

Provenance price basis.

std::string calendar_id = "unspecified"

Provenance calendar identifier.

std::string frequency = "unspecified"

Provenance data frequency.

std::string source_timezone = "UTC"

Descriptive source timezone; timestamps remain UTC.

std::string feed_time_kind = "close_time"

Descriptive feed timestamp convention.

std::vector<int> periods = {1, 5, 20}

Non-empty, positive, unique price-row horizons.

std::string label = "next_open_to_open"

Forward-return basis.

std::string precomputed_entry = "next_open"

Precomputed-label entry convention.

int quantiles = 5

Quantile bucket count; normalization requires at least one.

int min_assets = 10

Minimum asset count threshold.

int min_quantile_assets = 1

Minimum observations per quantile.

std::string preprocess = "cross_section_rank"

Cross-sectional preprocessing method.

double max_loss = 1.0

Tolerated data-loss fraction in [0, 1].

std::vector<int> stability_lags = {1, 5, 20}

Positive rank-autocorrelation lags.

std::map<std::string, int> direction_overrides

Per-asset signs; values must be +1 or -1.

std::map<std::string, std::map<std::string, double>> combinations

Weighted factor blends.

std::map<std::string, std::pair<std::string, std::string>> comparisons

Named factor pairs; sides distinct.

std::map<std::string, std::pair<std::string, std::string>> segments

Named provenance ranges.

struct research_export_result

Files written by export_factor_research().

Public Members

std::string directory

Requested output directory as supplied.

std::vector<std::string> files

Relative names of written files, in write order.

struct research_factor_panel

Named factor panel used as correlation input.

Public Members

std::string name

Factor name; must be non-empty and unique.

factor_series values

Factor values by (date, asset).

struct research_label_row

One forward-return label row.

Public Members

timestamp date = 0

Observation date in UTC nanoseconds.

std::string asset

Asset identifier.

std::string period

Forward-return period label, such as 1D.

double value = 0.0

Forward return for the period; NaN when missing.

struct research_panel_result

Aggregated multi-factor evaluation result.

status is OK when every named result is OK, UNEVALUABLE when all are, and PARTIAL otherwise.

Public Members

std::string status

Aggregated evaluation status.

std::vector<named_research_result> factors

Input factors first, then combinations.

std::vector<research_correlation_row> correlations

Pairwise processed-panel correlations.

std::vector<research_comparison_row> comparisons

Comparison rows; empty if not requested.

std::vector<research_signal_row> signals

Concatenated signals tagged with factor names.

std::map<std::string, std::string> manifest

Counts and API/schema version metadata.

struct research_result

Aggregated single-factor research result.

status is OK when every requested horizon has prepared rows, PARTIAL when at least one horizon has none, and UNEVALUABLE when no horizon was prepared at all.

Public Functions

research_table table(std::string_view name) const

Returns one named result table.

Unknown names raise a structured DatasetError (unknown_result_table). The correlation and comparisons tables expose canonical columns with no rows in this single-factor result.

Parameters:

name – Table name; one of research_capabilities::result_tables.

Throws:

research_dataset_error – When name is not a known table, with code unknown_result_table.

Returns:

Table with canonical columns and row-major cells.

std::string to_serializable() const

Returns the JSON-compatible status/manifest/tables/columns payload.

Returns:

JSON text whose tables and columns objects contain all canonical result tables.

Public Members

std::string status

OK, PARTIAL or UNEVALUABLE.

std::vector<research_label_row> labels

Forward-return rows for prepared cells.

std::vector<research_signal_row> signals

Signal rows for evaluated cells.

factor_ic_table information_coefficient

Per-date Spearman rank IC by period; NaN missing.

factor_ic_summary information_coefficient_summary

Mean rank IC per period.

quantile_return_table quantile_returns

Raw quantile return means and standard errors.

std::vector<factor_series_result> turnover

Turnover series per quantile, first horizon.

std::vector<factor_series_result> stability

Rank autocorrelation per lag, first horizon.

std::vector<int> stability_lags

Lags used for the stability series.

std::vector<double> spread

Top-minus-bottom quantile return per period; NaN if absent.

std::vector<std::size_t> coverage

Prepared observation count per period.

std::vector<std::string> diagnostics

Human-readable status notes.

std::map<std::string, std::string> manifest

Provenance key/value metadata.

int schema_version = research_result_schema_version

Result schema version.

struct research_signal_row

One signal row: a factor observation for a date and asset.

Public Members

timestamp date = 0

Observation date in UTC nanoseconds.

std::string asset

Asset identifier.

std::string factor

Factor name; factor for single-factor evaluations.

int direction = 1

Direction sign applied to the factor value.

double value = 0.0

Direction-adjusted raw factor value.

double processed_value = 0.0

Value after direction adjustment and preprocessing.

std::string preprocess

Preprocessing method used for the panel.

std::string group

Configured group name, or default when groups are unset.

struct research_spec

Execution specification consumed by the research evaluators.

Public Members

std::vector<std::string> targets

Requested targets; empty selects all observed assets.

timestamp start = 0

Inclusive UTC-nanosecond window start.

timestamp end = 0

Inclusive UTC-nanosecond window end.

std::vector<int> periods = {1, 5, 20}

Forward price-row horizons; non-empty, positive.

int quantiles = 5

Quantile bucket count; must be at least two.

int min_assets = 1

Minimum asset count for correlation and detailed thresholds.

int min_quantile_assets = 1

Minimum observations per quantile for detailed thresholds.

std::string label = "close_to_close"

Forward-return basis.

std::string preprocess = "cross_section_rank"

Cross-sectional preprocessing method.

double max_loss = 1.0

Tolerated binning data-loss fraction in [0, 1].

std::vector<int> stability_lags = {1, 5, 20}

Positive rank-autocorrelation lags.

std::map<std::string, int> direction_overrides

Optional per-asset signs (+1 or -1).

std::map<std::string, std::pair<std::string, std::string>> segments

Named provenance ranges.

std::map<std::string, std::pair<std::string, std::string>> comparisons

Panel-evaluator factor pairs.

std::map<std::string, std::map<std::string, double>> combinations

Weighted factor blends.

std::map<std::string, std::string> groups

Asset-to-group map covering evaluated assets.

std::string snapshot_id = "unspecified"

Provenance snapshot identifier.

std::string price_basis = "unspecified"

Provenance price basis.

std::string calendar_id = "unspecified"

Provenance calendar identifier.

std::string frequency = "unspecified"

Provenance data frequency.

struct research_table

One named research result table in native column form.

Public Members

std::string name

Table name.

std::vector<std::string> columns

Column names in row-cell order.

std::vector<std::vector<factor_value>> rows

Row-major cells aligned with columns.

struct spread_time_series_chart

Spread chart data for one forward period.

Public Functions

std::string to_svg() const

Renders spreads, the rolling mean and the optional band as native SVG.

A zero line is added when dates are present; the band polygon is skipped when band_lower is empty.

Public Members

std::string period

Forward-return period label used in the title.

std::string title

Chart title.

std::string y_label = "Difference In Quantile Mean Return (bps)"

Y-axis label.

std::vector<timestamp> dates

Observation timestamps.

std::vector<double> spreads

Spreads in basis points; non-finite inputs become NaN.

std::vector<double> rolling_mean

Trailing 22-observation mean in basis points; NaN until 22 consecutive finite spreads are available.

std::vector<double> band_lower

Lower band in basis points; empty when no standard errors are supplied and NaN where an input is non-finite.

std::vector<double> band_upper

Upper band in basis points, aligned with band_lower.

double y_limit = 1.0

Symmetric y-axis limit: the 95th percentile of finite absolute spreads, falling back to 1.0 when no positive value exists.

double bandwidth = 1.0

Standard-error multiplier used to build the band.

struct style_context

Renderer style contexts (seaborn plotting_context / axes_style).

Public Members

std::string name

Context or style name, such as “notebook”.

double font_scale = 1.5

Font scaling factor carried by the context.

std::map<std::string, std::string> rc

rc parameter overrides by name.

struct trading_calendar

Deterministic trading-day set used by the factor calendar helpers.

A calendar is defined by local wall dates: seven weekday flags plus a set of holiday day numbers (days since 1970-01-01 in UTC). It intentionally has no timezone object; timestamps are UTC nanoseconds.

Public Functions

bool is_trading_day(std::int64_t day_number) const noexcept

Checks whether a day number is a trading day.

Parameters:

day_number – Days since 1970-01-01 in UTC.

Returns:

true when the weekday is enabled and the day is not a holiday.

bool is_session(timestamp value) const noexcept

Checks whether a timestamp falls on a trading day.

Parameters:

value – Timestamp in UTC nanoseconds.

Returns:

true when the timestamp’s UTC day is a trading day.

std::int64_t busday_count(std::int64_t start_day, std::int64_t end_day) const noexcept

Counts trading sessions in [start_day, end_day) when start_day <= end_day; otherwise returns the negation of the count in (end_day, start_day] (NumPy busday_count half-open semantics).

Parameters:
  • start_day – First day number.

  • end_day – Exclusive end day number for forward counts.

Returns:

Signed number of trading sessions.

Public Members

bool weekdays[7] = {true, true, true, true, true, false, false}

Monday-first weekday mask. true marks a trading weekday.

std::vector<std::int64_t> holidays

Sorted, unique holiday day numbers. Never contains a non-weekday.

struct violin_chart

Quantile-return violin chart data for one forward period.

Public Functions

std::string to_svg() const

Renders one violin polygon per group as native SVG.

Groups without density points or with zero density are skipped.

Public Members

std::string title = "Period Wise Return By Factor Quantile"

Chart title.

std::string y_label = "Return (bps)"

Y-axis label.

std::vector<violin_group> groups

Groups, ascending by quantile.

struct violin_group

Violin samples and quartiles for one quantile of a forward period.

Public Members

int quantile = 0

Quantile bucket label.

std::string period

Forward-return period label.

std::vector<double> samples

Finite period returns in basis points.

double first_quartile = 0.0

First quartile of samples in bps.

double median = 0.0

Median of samples in bps.

double third_quartile = 0.0

Third quartile of samples in bps.

std::vector<double> density_x

Support points for the kernel-density estimate.

std::vector<double> density_y

Density values aligned with density_x; empty when no density was computed.

enum class fincore::fama_macbeth_covariance

Covariance estimator for the Fama-MacBeth standard errors.

Values:

enumerator iid

I.i.d. sample standard errors.

enumerator newey_west

Bartlett-kernel HAC standard errors at newey_west_lags.

timestamp fincore::add_custom_calendar_timedelta(timestamp input, std::int64_t delta, const trading_calendar &calendar)

Adds delta nanoseconds, counting whole days through calendar.

The timedelta is normalized to a floor whole-day component plus a non-negative remainder; the day component is rolled by the calendar and the remainder is added afterwards. This matches pandas’ Timestamp + CalendarOffset(days) + remainder behaviour.

Parameters:
  • input – Starting timestamp or timestamps in UTC nanoseconds.

  • delta – Signed duration in nanoseconds.

  • calendar – Calendar used to roll whole-day components.

Throws:

factor_data_error – When the shifted timestamp overflows.

Returns:

The shifted timestamp, or one shifted timestamp per input value.

std::vector<timestamp> fincore::add_custom_calendar_timedelta(const std::vector<timestamp> &input, std::int64_t delta, const trading_calendar &calendar)

Adds delta nanoseconds to each timestamp using calendar.

Applies the same normalization and whole-day roll rules as the scalar overload and preserves the input order.

Parameters:
  • input – Starting timestamps in UTC nanoseconds.

  • delta – Signed duration in nanoseconds.

  • calendar – Calendar used to roll whole-day components.

Throws:

factor_data_error – When a shifted timestamp overflows.

Returns:

One shifted timestamp per input value.

trading_calendar fincore::all_days_calendar()

Returns a calendar with every day marked as a trading day, matching pandas’ default Day offset.

Returns:

The all-days calendar.

factor_analysis_model fincore::analyze_factor(const prepared_factor_data &factor_data, const factor_analysis_config &config = {})

Computes the complete factor analysis model for one prepared panel.

Runs the information-coefficient, weight, return, quantile, spread, turnover, rank-autocorrelation, cumulative, position and monthly aggregation kernels over the selected labels. The returned model owns copies of the input and of the requested options.

Parameters:
  • factor_data – Prepared rows, forward-return labels and cleaning losses.

  • config – Labels and views to build; the defaults analyse every label with long-short aggregate output.

Throws:

factor_data_error – If factor_data has no rows or labels, a row does not match the label count, turnover_periods or time_aggregation is empty, duplicated or invalid, portfolio_benchmark_period is empty, a selected period is not a prepared label or not a whole-day label, or by_group is set without a group column.

Returns:

Aggregate views, optional per-group views and the input fingerprint.

factor_analysis_model fincore::analyze_factor(const prepared_factor_data &factor_data, const factor_analysis_config &config, const dataframe &event_returns, int event_before, int event_after)

Computes the analysis model together with an event-return study.

Event dates are the factor dates present in event_returns. Each window spans event_before ledger rows before the event through event_after rows after it, clipped to the ledger bounds; ledger values are used as given and are demeaned across the universe when config.long_short is true.

Parameters:
  • factor_data – Prepared rows, forward-return labels and cleaning losses.

  • config – Labels and views to build; group_neutral must be false.

  • event_returns – Rectangular ledger of double columns indexed by date.

  • event_before – Non-negative ledger rows before each event date.

  • event_after – Non-negative ledger rows after each event date.

Throws:

factor_data_error – If the common validations fail, the ledger is not a rectangular double table, its index repeats, a factor asset is missing from it, an offset is negative, or group-neutral event analysis is requested.

Returns:

Model with event_analysis and event_input_snapshot set.

factor_cost_result fincore::apply_factor_costs(std::span<const double> gross_returns, const std::vector<factor_weight_row> &weights, const dataframe &dollar_volume, double portfolio_value, const factor_cost_model &model, const dataframe *borrow_rates = nullptr, const dataframe *borrow_available = nullptr)

Applies spread, market-impact and borrow costs to gross returns.

Turnover is half the summed absolute weight change on each date. Spread cost charges half_spread_bps on traded weight, impact cost charges impact_coefficient * participation^impact_exponent per asset, and borrow cost accrues on short positions from the supplied borrow panels.

Parameters:
  • gross_returns – One gross return per weight date.

  • weights – Gross-normalized weights, one row per (date, asset).

  • dollar_volume – Tradable dollar volume on a sorted, unique index spanning every weight date and asset, strictly positive.

  • portfolio_value – Positive portfolio value, no larger than the estimated capacity.

  • model – Cost parameters applied to every date.

  • borrow_rates – Short-rate panel on the weight grid; required when any weight is negative and rejected otherwise.

  • borrow_available – Availability panel on the weight grid, where 1.0 marks a lendable short; required alongside borrow_rates.

Throws:

factor_data_error – When inputs are malformed, a short lacks borrow data or availability, the portfolio exceeds capacity, or a cost or participation value is non-finite.

Returns:

Cost ledger with gross, net, turnover, cost components, trades, participation and capacity.

std::vector<quantile_event_statistics> fincore::average_cumulative_return_by_quantile(const prepared_factor_data &factor_data, const dataframe &returns, int before = 10, int after = 15, bool demeaned = true)

Averages cumulative event-window returns per quantile.

Builds one event panel per observed quantile and calls common_start_returns with cumulative and date-mean output; each offset reports the mean and the sample standard deviation of its cells, an offset with no cell has NaN mean and deviation, and an offset with a single cell has a NaN deviation.

Parameters:
  • factor_data – Prepared rows; their quantiles define the groups.

  • returns – Ledger indexed by date with one double column per asset.

  • before – Non-negative ledger rows before each event date.

  • after – Non-negative ledger rows after each event date.

  • demeaned – Subtract the full-universe date mean from each cell.

Throws:

factor_data_error – If an offset is negative or the ledger is invalid for common_start_returns.

Returns:

One statistics block per quantile, in ascending quantile order.

style_context fincore::axes_style(std::string style = "darkgrid", std::map<std::string, std::string> rc = {})

Creates a renderer axes style with a fixed font scale of 1.5.

Parameters:
  • style – Style name.

  • rc – rc parameter overrides keyed by parameter name.

Returns:

Style context named style; font_scale is always 1.5.

factor_series fincore::backshift_returns_series(const factor_series &series, const std::vector<timestamp> &date_levels, int N)

Move a backward-looking return series N date-level positions earlier.

date_levels is the complete, sorted, unique date level from the source MultiIndex, including unused dates. Rows with level positions below N are discarded. Remaining rows retain their order, assets and values (including NaNs) while their dates move to the level N positions earlier. A result is empty when date_levels.size() <= N.

fdr_result fincore::benjamini_hochberg(std::span<const double> p_values, double alpha = 0.05)

Applies the Benjamini-Hochberg step-up correction.

Adjusted values are the monotone running minimum of n * p / rank, clamped to [0, 1]. A hypothesis is rejected when its sorted p value is at or below alpha * rank / n, which rejects the leading block up to the largest passing rank. Empty input yields empty output.

Parameters:
  • p_values – Finite probabilities in [0, 1].

  • alpha – Target false-discovery rate in (0, 1].

Throws:

factor_data_error – If alpha is outside (0, 1] or a p value is not a finite probability in [0, 1].

Returns:

Copies of the inputs plus adjusted values and rejection flags.

quantile_cumulative_chart fincore::build_cumulative_returns_by_quantile(const quantile_date_return_table &returns, std::string period)

Builds cumulative-growth chart data for each quantile of one period.

Means are averaged per date for the requested quantile and label, then compounded from 1.0 in date order. Dates without a finite mean keep the previous growth value. Quantiles are emitted in descending order, and the y bounds cover every emitted growth value.

Parameters:
  • returns – Mean returns by date, quantile and label.

  • period – Forward-return label; must be present in returns.labels.

Throws:

factor_data_error – If period is not present in returns.labels.

Returns:

Chart data with one series per distinct quantile.

events_distribution_chart fincore::build_events_distribution(const std::vector<timestamp> &dates, const std::vector<double> &values = {}, std::size_t num_bars = 50U)

Builds event counts per equal-width time bucket.

values follows dates; non-finite values are skipped, and an empty values counts every event. Buckets are half-open except the final bucket, which also covers the latest date. A single distinct date produces one bucket.

Parameters:
  • dates – Event timestamps.

  • values – Optional event values aligned with dates.

  • num_bars – Number of equal-width buckets; must be positive.

Throws:

factor_data_error – If num_bars is zero, values is non-empty with a different length than dates, or the date span cannot form positive-width buckets.

Returns:

Bucket starts and counts; no buckets are produced for empty dates.

factor_portfolio_inputs fincore::build_factor_portfolio_inputs(const prepared_factor_data &factor_data, std::string_view period_label, bool long_short = true, bool group_neutral = false, bool equal_weight = false, const std::vector<int> &quantiles = {}, const std::vector<std::string> &groups = {})

Resamples the compounded period curve and overlapping positions to a daily grid, adds an explicit cash overlay, and derives the optional benchmark.

Intraday holding remainders, capital-scaled dollar positions, and custom trading calendars are not represented by this kernel.

Parameters:
  • factor_data – Prepared factor panel with forward-return labels.

  • period_label – Forward-return label whose day count sets the holding.

  • long_short – Enables long-short weighting when true.

  • group_neutral – Applies group-neutral weighting when true.

  • equal_weight – Uses equal weights within each bucket when true.

  • quantiles – Optional quantile filter; empty keeps all quantiles.

  • groups – Optional group filter; empty keeps all groups.

Throws:

factor_data_error – When the period label is absent, the selection is empty, or grouped weights lack group labels.

Returns:

Daily strategy returns, cash-overlaid positions, and benchmark returns for the period.

report_document fincore::build_factor_report(const factor_analysis_model &model, std::string title = "Factor Analysis Report")

Builds a renderer-independent factor analysis report from a computed model.

The document carries summary, information-coefficient, returns and turnover sections in that order.

Parameters:
  • model – Computed factor analysis model.

  • title – Document title.

Returns:

Report document with domain "factor" and derived metadata.

factor_tear_charts fincore::build_factor_tear_charts(const factor_analysis_model &model)

Builds owning chart data for a factor tear sheet.

Time-series charts omit non-finite points, bar charts keep the panel ordering of model, and the event histogram is rebuilt from the model’s finite return distribution.

Parameters:

model – Analyzed factor model supplying every panel.

Throws:

input_error – When event analysis is present without a finite return-distribution value.

Returns:

Chart bundle that owns copies and outlives model.

std::vector<qq_chart> fincore::build_ic_qq(const factor_ic_table &ic)

Builds normal Q-Q chart data from information coefficients.

One chart is returned per label, each holding one series whose observations are the IC values for that label; non-finite values are treated as zero. Theoretical quantiles use the standard-normal inverse CDF.

Parameters:

ic – Information-coefficient table with values in date-major order.

Returns:

One chart per label, in ic.labels order; empty when ic.dates or ic.labels is empty or no observations are available.

spread_time_series_chart fincore::build_mean_quantile_returns_spread_time_series(const std::vector<timestamp> &dates, const std::vector<double> &spreads, std::string period, const std::vector<double> &standard_errors = {}, double bandwidth = 1.0)

Builds spread time-series chart data for one forward period.

Spreads and standard errors are converted from decimal returns to basis points. The rolling mean is a trailing 22-observation mean and stays NaN until 22 consecutive finite spreads exist. Bands are built as spread +/- standard_error * 10000 * bandwidth when standard errors are supplied.

Parameters:
  • dates – Observation timestamps.

  • spreads – Spreads in decimal return units, aligned with dates.

  • period – Forward-return period label used in the title.

  • standard_errors – Optional standard errors in decimal return units, aligned with spreads.

  • bandwidth – Standard-error multiplier used for the band.

Throws:

factor_data_error – If dates and spreads differ in length, or standard_errors is non-empty with a different length.

Returns:

Chart data with bps spreads, rolling mean and optional band.

std::vector<monthly_ic_heatmap_chart> fincore::build_monthly_ic_heatmap(const factor_time_information_table &monthly)

Builds one heatmap per forward period (and per group when the table is grouped).

Years are the distinct calendar years observed for the selected group and are emitted in ascending order. Months without a finite mean stay NaN with present == false. No charts are returned when monthly.labels or monthly.dates is empty.

Parameters:

monthly – Monthly information-coefficient table with means in date-major order and optional groups parallel to dates.

Returns:

One chart per group and label; groups are emitted in sorted order.

violin_chart fincore::build_quantile_returns_violin(const quantile_date_return_table &returns, std::string period)

Builds quantile-return violin data for one forward period.

Each group collects finite mean returns for one quantile, converted from decimal returns to basis points. Quartiles use linear interpolation over the sorted samples, and the density is a Gaussian kernel estimate on 64 support points when there are at least two samples and their deviation is positive. Quantiles are emitted in ascending order, and quantiles without finite samples are omitted.

Parameters:
  • returns – Mean returns by date, quantile and label.

  • period – Forward-return label; must be present in returns.labels.

Throws:

factor_data_error – If period is not present in returns.labels.

Returns:

Violin chart data with one group per quantile that has samples.

trading_calendar fincore::business_day_calendar()

Returns a Monday-Friday calendar with no holidays.

Returns:

The business-day calendar.

void fincore::close_owned_figures(owned_figures &figures)

Marks every owned figure as closed.

The identifier list is left unchanged, so the call is idempotent.

Parameters:

figures – Figure list whose closed flags are set to true.

event_window_result fincore::common_start_returns(const factor_series &factor, const dataframe &returns, int before, int after, bool cumulative = false, bool mean_by_date = false, const factor_series *demean_by = nullptr)

Extracts event-aligned return windows for a factor panel.

Event dates are the factor dates present in the returns index. Each window spans before ledger rows before the event through after rows after it, clipped to the ledger bounds, so offsets near the edges are absent. Non-finite ledger values are skipped. With cumulative the ledger is read as already cumulative, otherwise each column is compounded into a wealth index from one. demean_by subtracts the same-date cross-sectional mean of its assets, and mean_by_date emits one averaged cell per offset and date.

Parameters:
  • factor – Event panel; its dates and assets select the windows.

  • returns – Ledger indexed by date with one double column per asset.

  • before – Non-negative ledger rows before each event date.

  • after – Non-negative ledger rows after each event date.

  • cumulative – Read the ledger as cumulative rather than simple returns.

  • mean_by_date – Emit date means with an empty asset label.

  • demean_by – Optional panel supplying the assets to demean against.

Throws:

factor_data_error – If an offset is negative, the returns index has duplicates, a factor asset is missing from the ledger, or a demean asset is missing at an event date.

Returns:

Observed offsets, event dates, asset labels and window cells.

forward_return_table fincore::compute_forward_returns(const factor_series &factor, const dataframe &prices, const std::vector<int> &periods = {1, 5, 10}, std::optional<double> filter_zscore = std::nullopt, bool cumulative_returns = true)

Computes forward returns for every factor observation from a price panel.

Labels are the requested periods rendered as "<period>D". A value is NaN when the factor date is absent from prices, the horizon runs past the panel, or the base price is zero. When filter_zscore is set, forward returns further than that many standard deviations from the per-asset mean are removed independently for each label.

Parameters:
  • factor – Row-aligned factor panel supplying dates and assets.

  • prices – Price panel indexed by date with one column per factor asset.

  • periods – Positive horizons in price observations.

  • filter_zscore – Optional per-asset z-score cutoff; nullopt keeps all.

  • cumulative_returns – Compounded window return when true, otherwise a one-observation return.

Throws:

factor_data_error – When the factor index is invalid, a period is not positive, an asset is missing from prices, no date is shared, or filter_zscore is non-finite.

Returns:

Label-major forward returns aligned with the factor rows.

render_customization fincore::customize(bool set_context = true)

Creates the native render customization used around chart calls.

The returned value uses the default plotting_context() and axes_style() values and keeps the built-in eight-color palette.

Parameters:

set_context – Whether the context is applied around the chart call.

Returns:

Customization carrying the default context, axes style and palette.

factor_model_envelope fincore::deserialize_factor_model(std::string_view text)

Restores the supported model envelope from serialized JSON text.

The root must be an object carrying schema, fingerprint_version, result_fingerprint, config, forward_periods and loss_report. The schema must equal the supported version, and the fingerprint version must fit in 32 bits. Additional keys are ignored.

Parameters:

text – Serialized JSON text.

Throws:

input_error – If the text is not valid JSON, the root is not an object, a required field is missing, the schema is unsupported, or the fingerprint version is out of range.

Returns:

Envelope with the schema, fingerprint fields, configuration, forward periods and loss report.

factor_value fincore::deserialize_serializable_value(std::string_view text)

Parses serialized model text into a native value.

The text is parsed without checking the envelope schema; use deserialize_factor_model to validate and restore the supported subset.

Parameters:

text – Serialized JSON text.

Throws:

input_error – If the text is not valid strict JSON.

Returns:

Parsed native value.

std::int64_t fincore::diff_custom_calendar_timedeltas(timestamp start, timestamp end, const trading_calendar &calendar)

Returns end - start with whole-day components measured by calendar.

The wall-clock remainder is preserved; only the whole-day part is replaced by the busday count. Both endpoints use local wall dates, as in the pinned source.

Parameters:
  • start – Start timestamp in UTC nanoseconds.

  • end – End timestamp in UTC nanoseconds.

  • calendar – Calendar used for the whole-day count.

Returns:

Signed duration in nanoseconds with the wall-clock remainder.

factor_capacity_result fincore::estimate_factor_capacity(const std::vector<factor_weight_row> &weights, const dataframe &dollar_volume, double max_participation)

Estimates the largest portfolio value a weight panel can trade.

Each date is limited by the tightest asset-level max_participation * dollar_volume / |trade|; the panel capacity is the smallest finite date limit. The first date that attains the limit and the asset limiting it are reported as the binding pair.

Parameters:
  • weights – Gross-normalized weights, one row per (date, asset).

  • dollar_volume – Tradable dollar volume on a sorted, unique index spanning every weight date and asset, strictly positive.

  • max_participation – Fraction of dollar volume allowed per asset, in (0, 1].

Throws:

factor_data_error – When the weights are duplicated, non-finite or not gross-normalized, when dollar volume is missing, unsorted, non-finite or non-positive, or when no trade occurs.

Returns:

Capacity summary carrying the trade panel and binding pair.

research_detailed_export_outcome fincore::evaluate_and_export_factor_research_detailed(std::string_view factor_name, const factor_series &factors, const dataframe &prices, const research_spec &spec, const std::string &directory)

Evaluates one factor and exports its detailed result without materializing owning signal and label row vectors.

Large tables are synchronously written from the evaluator’s live columns; no borrowed view escapes the call. If evaluation or export fails, files created by the call are removed, and a newly created destination is removed only when it is empty. Existing empty destinations are retained and non-empty destinations are rejected. Evaluation and writing may interleave: the first encountered failure is propagated, rather than imposing the error order of two separate calls.

Parameters:
  • factor_name – Factor name used for output rows and direction overrides.

  • factors – Factor panel with row-aligned dates, assets and values.

  • prices – Price panel indexed by date with one column per asset.

  • spec – Evaluation window, label, preprocessing and table settings.

  • directory – Destination directory for the CSV files and manifest.

Throws:

factor_data_error – When evaluation input is invalid or export validation or writing fails.

Returns:

Owning outcome with status, manifest, diagnostics, row counts and export metadata.

research_result fincore::evaluate_factor_research(const factor_series &factors, const dataframe &prices, const research_spec &spec)

Evaluates one factor against forward returns derived from prices.

spec.label must be close_to_close or next_open_to_open; the precomputed basis is served by the forward-return-table overload. Period labels are derived from the price grid. close_to_close labels span period price rows from each factor date; next_open_to_open labels enter one row later and span period rows from that entry.

Parameters:
  • factors – Factor values by (date, asset).

  • prices – Price dataframe with asset columns and a UTC timestamp index.

  • spec – Execution spec; its inclusive window and target guards are applied before evaluation.

Throws:

factor_data_error – When the spec, factor panel or price grid violates the evaluated contract, including unsupported labels, missing targets, an empty window, duplicates or malformed prices.

Returns:

Aggregated result with OK, PARTIAL or UNEVALUABLE status.

research_result fincore::evaluate_factor_research(const factor_series &factors, const dataframe &prices, const research_spec &spec, const dataframe &universe)

Evaluates one factor against price-derived returns under a wide mask.

The boolean mask keeps only cells whose (date, asset) entry is true, and the returned result records universe=applied in its manifest.

Parameters:
  • factors – Factor values by (date, asset).

  • prices – Price dataframe with asset columns and a UTC timestamp index.

  • spec – Execution spec; the precomputed label basis is rejected.

  • universe – Wide boolean eligibility mask (dates x assets).

Throws:

factor_data_error – When the mask contains non-boolean columns, duplicate dates or removes every cell, or the underlying evaluation fails.

Returns:

Aggregated result for the masked panel.

research_result fincore::evaluate_factor_research(const factor_series &factors, const forward_return_table &precomputed_returns, const research_spec &spec)

Evaluates one factor against caller-supplied forward returns.

spec.label must not be next_open_to_open; the result manifest records the precomputed label.

Parameters:
  • factors – Factor values by (date, asset).

  • precomputed_returns – Label-major forward-return table covering the requested periods.

  • spec – Execution spec selecting the periods and quantiles.

Throws:

factor_data_error – When the table is empty, malformed, has duplicate keys, misses a requested period or yields no prepared rows, or the factor panel violates its contract.

Returns:

Aggregated result for the supplied labels.

research_detailed_result fincore::evaluate_factor_research_detailed(std::string_view factor_name, const factor_series &factors, const dataframe &prices, const research_spec &spec)

Evaluates one named factor against price-derived forward labels.

factor_name supplies the Python DataFrame column name used for direction overrides and output rows. spec.start/end and all input timestamps are UTC nanoseconds. Only close_to_close and next_open_to_open are supported by this price-based overload; precomputed labels and multi-factor combinations are rejected explicitly.

Parameters:
  • factor_name – Factor name used for output rows and direction overrides.

  • factors – Factor panel with row-aligned dates, assets and values.

  • prices – Price panel indexed by date with one column per asset.

  • spec – Evaluation window, label, preprocessing and table settings.

Throws:

factor_data_error – When the factor, price or specification input is invalid, including unsupported labels or missing price columns.

Returns:

Detailed result with signal, label, IC, quantile, stability, coverage and diagnostic tables.

research_panel_result fincore::evaluate_factor_research_panel(std::span<const named_factor_panel> factors, const dataframe &prices, const research_spec &spec)

Evaluates multiple named factor panels and derives correlations/comparisons.

Each panel is evaluated independently; spec.combinations are then blended from the processed panels with preprocessing disabled and direction overrides cleared, and the named comparisons are appended.

Parameters:
  • factors – Named factor panels; names must be non-empty and unique.

  • prices – Price grid used for forward returns.

  • spec – Execution spec including combinations and comparisons.

Throws:

factor_data_error – When names are empty or duplicated, a combination or comparison references an unknown factor, weights are invalid, or a panel evaluation fails.

Returns:

Named results, correlations, comparisons, concatenated signals and manifest counts.

research_export_result fincore::export_factor_research(const research_result &result, const std::string &directory, bool charts = false)

Writes deterministic CSV tables and a JSON manifest without overwriting.

A preexisting destination is rejected and left untouched. A directory created by this call is removed if a later write fails. charts=true requests raster chart export, which the native library does not provide; it fails closed instead of silently skipping charts.

Parameters:
  • result – Result tables to export.

  • directory – Fresh destination directory.

  • charts – Whether to request charts; the native library rejects true.

Throws:

factor_data_error – When charts are requested, the result tables are malformed, the manifest uses reserved keys status or exports, the directory is empty, contains a null byte or already exists, or a file cannot be written.

Returns:

The requested directory and the relative names of the files written.

research_export_result fincore::export_factor_research_detailed(const research_detailed_result &result, const std::string &directory)

Exports the ten factor-local detailed research tables as UTF-8/LF CSV files with a versioned JSON manifest.

Rows retain the order in result. The single-factor result must have empty correlation and comparison tables; their omission is identified in the manifest’s engine metadata.

A non-empty destination is never overwritten. If an export fails, only files created by this call are removed; a newly created destination is removed only when it is empty. An existing empty destination is retained.

Parameters:
  • result – Detailed result whose tables are written.

  • directory – Destination directory for the CSV files and manifest.

Throws:

factor_data_error – When the directory is invalid or non-empty, the result schema is unsupported, correlation or comparison tables are non-empty, or writing fails.

Returns:

Created directory and exported file names.

std::vector<factor_alpha_beta_row> fincore::factor_alpha_beta(const prepared_factor_data &factor_data, bool demeaned = true, bool group_adjust = false, bool equal_weight = false)

Regresses portfolio returns on the same-date universe mean return.

The slope is the OLS beta against the equal-weighted universe mean of each label; the intercept is annualized with 252 / N periods, where N is the leading whole-day count of the label. Fewer than two usable dates or a zero market variance leaves the estimates NaN, and a label without a leading day count leaves only annual_alpha NaN.

Parameters:
  • factor_data – Prepared rows and forward-return labels.

  • demeaned – Center the bucket values before weighting.

  • group_adjust – Form weights per (date, group) and renormalize per date.

  • equal_weight – Give each side of zero an equal share.

Throws:

factor_data_error – If group_adjust is true and a row has no group.

Returns:

One row per forward-return label, in label order.

factor_series_result fincore::factor_cumulative_returns(const prepared_factor_data &factor_data, std::string_view period_label, bool long_short = true, bool group_neutral = false, bool equal_weight = false, const std::vector<int> &quantiles = {}, const std::vector<std::string> &groups = {})

Compounds the selected period returns from one.

Parameters:
  • factor_data – Prepared factor panel with forward-return labels.

  • period_label – Forward-return label to compound.

  • long_short – Enables long-short weighting when true.

  • group_neutral – Applies group-neutral weighting when true.

  • equal_weight – Uses equal weights within each bucket when true.

  • quantiles – Optional quantile filter; empty keeps all quantiles.

  • groups – Optional group filter; empty keeps all groups.

Throws:

factor_data_error – When the period label is absent, the selection is empty, or grouped weights lack group labels.

Returns:

Compounded cumulative return series indexed by date.

factor_ic_table fincore::factor_information_coefficient(const prepared_factor_data &factor_data, bool group_adjust = false, bool by_group = false)

Computes the Spearman rank information coefficient per date and label.

Each cell correlates the finite factor values with the matching forward returns across the assets of one date bucket; fewer than two usable pairs leave the cell as NaN. group_adjust demeans forward returns within each (date, group) bucket first and therefore requires groups, while by_group emits one row per (date, group) pair instead of one row per date.

Parameters:
  • factor_data – Prepared rows and forward-return labels.

  • group_adjust – Demean forward returns per date and group before ranking.

  • by_group – Emit one row per (date, group) instead of one row per date.

Throws:

factor_data_error – If group data is required or requested and a row has no group column.

Returns:

IC table whose groups member stays empty unless grouped.

ic_inference_result fincore::factor_model_inference(const factor_analysis_model &model, double alpha = 0.05)

Runs IC inference and false-discovery-rate correction on the model.

Forwards model.information_coefficient to information_coefficient_inference; per-group tables are not consulted.

Parameters:
  • model – Analysed model whose aggregate IC table is read.

  • alpha – Target false-discovery rate in (0, 1].

Throws:

factor_data_error – If alpha is not a finite probability in (0, 1].

Returns:

One hypothesis per IC label with the Benjamini-Hochberg adjustment.

const std::vector<factor_operation_descriptor> &fincore::factor_operation_descriptors()

Returns stable operation descriptors for the factor runtime catalog.

Returns:

Reference to the immutable descriptor list.

std::string fincore::factor_operations_digest()

Computes SHA-256 over the canonical descriptor listing (identifier order).

Returns:

Lowercase hexadecimal SHA-256 digest.

std::vector<factor_weight_row> fincore::factor_positions(const prepared_factor_data &factor_data, std::string_view period_label, bool long_short = true, bool group_neutral = false, bool equal_weight = false, const std::vector<int> &quantiles = {}, const std::vector<std::string> &groups = {}, std::optional<std::vector<factor_weight_row>> weights = std::nullopt)

Builds overlapping gross-normalized trade positions for one factor period.

period_label counts whole business days (for example "3D" or "1D2D"); a holding expires on the corresponding Monday-Friday weekday calendar without exchange-holiday knowledge, matching pandas’ default BusinessDay offset. The result spans every trade and expiry timestamp, including a zero row after the final holding expires.

Parameters:
  • factor_data – Prepared factor panel with forward-return labels.

  • period_label – Forward-return label whose day count sets the holding.

  • long_short – Enables long-short weighting when true.

  • group_neutral – Applies group-neutral weighting when true.

  • equal_weight – Uses equal weights within each bucket when true.

  • quantiles – Optional quantile filter; empty keeps all quantiles.

  • groups – Optional group filter; empty keeps all groups.

  • weights – Optional precomputed weights replacing derived weights.

Throws:

factor_data_error – When the period label is absent or malformed, the selection is empty, or grouped weights lack group labels.

Returns:

Gross-normalized position rows in date/asset order.

factor_series_result fincore::factor_rank_autocorrelation(const prepared_factor_data &factor_data, int period = 1)

Computes the rank autocorrelation of the factor at a fixed lag.

Factor values are average-ranked within each date and then correlated with the lagged ranks over the assets present on both dates. Non-finite factor values are excluded; the first period dates, fewer than two shared assets and a constant rank vector yield NaN.

Parameters:
  • factor_data – Prepared rows and forward-return labels.

  • period – Positive lag in dates.

Throws:

factor_data_error – If period is not positive.

Returns:

Series over every unique date, sorted ascending.

factor_return_table fincore::factor_returns(const prepared_factor_data &factor_data, bool demeaned = true, bool group_adjust = false, bool equal_weight = false)

Computes portfolio returns from factor weights.

Calls factor_weights with the same options and accumulates weight times forward return per date and label, skipping any pair with a non-finite value.

Parameters:
  • factor_data – Prepared rows and forward-return labels.

  • demeaned – Center the bucket values before weighting.

  • group_adjust – Form weights per (date, group) and renormalize per date.

  • equal_weight – Give each side of zero an equal share.

Throws:

factor_data_error – If group_adjust is true and a row has no group.

Returns:

Returns per date and label; a cell with no usable pair stays zero.

std::vector<factor_weight_row> fincore::factor_weights(const prepared_factor_data &factor_data, bool demeaned = true, bool group_adjust = false, bool equal_weight = false)

Computes per-observation factor weights.

Weights form inside each (date[, group]) bucket: demeaned centers the bucket values, equal_weight gives each side of zero an equal share, and the bucket is divided by its gross absolute exposure. group_adjust then renormalizes across the groups of each date. A bucket whose gross exposure is zero or non-finite yields NaN weights.

Parameters:
  • factor_data – Prepared rows and forward-return labels.

  • demeaned – Center the bucket values before weighting.

  • group_adjust – Form weights per (date, group) and renormalize per date.

  • equal_weight – Give each side of zero an equal share.

Throws:

factor_data_error – If group_adjust is true and a row has no group.

Returns:

One row per prepared row, in input order.

const std::vector<factor_workflow> &fincore::factor_workflows()

Returns the built-in named factor workflows.

The list covers the summary, returns, information, turnover, full, event_returns and event_study workflows.

Returns:

Reference to the immutable workflow list.

fama_macbeth_result fincore::fama_macbeth(const dataframe &returns, const dataframe &exposures, fama_macbeth_covariance covariance = fama_macbeth_covariance::iid, std::size_t newey_west_lags = 1U)

Runs Fama-MacBeth cross-sectional regressions.

Each return date with a matching exposure row, or the single exposure row that is broadcast across dates, is regressed cross-sectionally across the shared asset columns. A cross-section is skipped when fewer than two assets are finite or the exposures do not vary. The coefficient series are then summarized with i.i.d. or Bartlett Newey-West standard errors; a standard error at or below 1e-15 yields an infinite t statistic, or zero when the mean is zero.

Parameters:
  • returns – Returns with at least two double asset columns.

  • exposures – Per-date exposures for the same assets, or one row broadcast across every return date.

  • covariance – Standard-error estimator for the coefficient series.

  • newey_west_lags – Bartlett lags; must be smaller than the fitted cross-section count when covariance is newey_west.

Throws:

factor_data_error – If an input is empty, has duplicate index values, lacks two double asset columns, misses return assets, is unsorted for Newey-West, or requests too many lags.

Returns:

Slope and intercept estimates plus the fitted cross-section count.

const factor_workflow *fincore::find_factor_workflow(std::string_view workflow_id)

Looks up a workflow by identifier and returns nullptr when absent.

Parameters:

workflow_id – Workflow identifier to find.

Returns:

Pointer to the matching workflow, or nullptr when absent.

std::string fincore::fingerprint_value(const factor_value &value)

Returns a stable SHA-256 digest over the canonical native encoding.

The digest covers detail::canonical_factor_value(value), is 64 lowercase hexadecimal characters, and is independent of object insertion order and NaN payloads.

Parameters:

value – Value to fingerprint.

Returns:

Lowercase hexadecimal SHA-256 digest.

std::string fincore::fingerprint_value(const factor_analysis_model &model)

Returns the fingerprint of serializable_value(model).

Parameters:

model – Model to fingerprint.

Returns:

Lowercase hexadecimal SHA-256 digest.

std::string fincore::fingerprint_value(const factor_loss_report &report)

Returns the fingerprint of serializable_value(report).

Parameters:

report – Loss report to fingerprint.

Returns:

Lowercase hexadecimal SHA-256 digest.

std::string fincore::fingerprint_value(const research_result &result)

Returns the fingerprint of the serialized research result.

Parameters:

result – Research result to fingerprint.

Returns:

Lowercase hexadecimal SHA-256 digest.

std::vector<std::string> fincore::get_forward_returns_columns(const std::vector<std::string> &columns, bool require_exact_day_multiple = false)

Select labels matching the pinned factor forward-return grammar.

Results keep the input order and duplicates. Invalid labels are skipped. With require_exact_day_multiple, only repeated day components are kept; unlike the Python implementation, the native helper skips silently instead of emitting a warning.

ic_interval fincore::ic_confidence_interval(std::span<const double> values, double z = 1.96)

Computes a normal confidence interval for the mean IC.

The half-width is z times the sample standard error of the non-NaN values. Fewer than two usable values yield NaN bounds.

Parameters:
  • values – IC observations.

  • z – Positive finite multiplier, conventionally 1.96 for 95%.

Throws:

factor_data_error – If z is not finite and positive, or a value is infinite.

Returns:

Interval bounds; both NaN below two usable values.

double fincore::ic_mean(std::span<const double> values)

Computes the mean of a sample of IC values.

NaN entries are skipped; an empty or all-NaN sample yields NaN.

Parameters:

values – IC observations.

Throws:

factor_data_error – If a value is infinite.

Returns:

Arithmetic mean of the non-NaN values.

double fincore::ic_t_stat(std::span<const double> values)

Computes the t statistic of a sample of IC values.

The statistic is the mean divided by the sample standard error computed from the one-degree-of-freedom deviation. NaN entries are skipped; fewer than two usable values yield NaN, and a standard error below 1e-15 yields an infinity or zero that follows the sign of the mean.

Parameters:

values – IC observations.

Throws:

factor_data_error – If a value is infinite.

Returns:

t statistic of the sample.

trading_calendar fincore::infer_trading_calendar(const std::vector<timestamp> &factor_dates, const std::vector<timestamp> &price_dates)

Infers trading weekdays and missing-session holidays from factor and price dates.

The union is normalized to days; an empty union is rejected.

Parameters:
  • factor_dates – Factor observation timestamps in UTC nanoseconds.

  • price_dates – Price observation timestamps in UTC nanoseconds.

Throws:

factor_data_error – When both input date lists are empty.

Returns:

Calendar whose enabled weekdays and holidays cover the union.

ic_inference_result fincore::information_coefficient_inference(const factor_ic_table &information, double alpha = 0.05)

Tests each IC label for a zero mean with an FDR adjustment.

Per label, the finite entries of the IC table are pooled and tested with a two-sided Student-t test on n - 1 degrees of freedom. Labels with fewer than two finite entries are reported as untestable, with NaN t and p values. Only the testable labels enter the Benjamini-Hochberg correction, which sets rejected and adjusted_p_value.

Parameters:
  • information – IC table whose rows are pooled per label.

  • alpha – Target false-discovery rate in (0, 1].

Throws:

factor_data_error – If alpha is outside (0, 1].

Returns:

One hypothesis per label, in the table’s label order.

double fincore::legacy_forward_returns_loss(const factor_loss_report &report)

Loss wording used by the pinned strict facade’s stdout projection.

Returns (input_count - forward_returns_count) / input_count and 0 for an empty input.

factor_series fincore::materialize_pit_factor(const std::vector<pit_observation> &observations, const std::vector<timestamp> &evaluation_dates)

Materializes a factor panel from point-in-time observations.

For each evaluation date, an asset contributes the revision with the largest (effective_from, known_at, as_of) among revisions that are already known and effective on that date. Assets flagged outside the universe are skipped, and assets without an eligible revision are absent from that date.

Parameters:
  • observations – Point-in-time observations with non-empty assets.

  • evaluation_dates – Strictly increasing dates to evaluate.

Throws:

factor_data_error – When dates are unsorted, an asset is empty, a point is invalid, or a revision is duplicated.

Returns:

Long-form panel ordered by date and asset.

factor_ic_summary fincore::mean_information_coefficient(const prepared_factor_data &factor_data, bool group_adjust = false, bool by_group = false)

Computes the mean information coefficient per label or per group.

Averages the finite IC values across dates for aggregate output, or across the rows of each group when by_group is true. A label or group with no finite value yields NaN.

Parameters:
  • factor_data – Prepared rows and forward-return labels.

  • group_adjust – Demean forward returns per date and group before ranking.

  • by_group – Summarize one row per group instead of per label.

Throws:

factor_data_error – If group data is required or requested and a row has no group column.

Returns:

Summary with one mean per label or per group row.

quantile_return_table fincore::mean_return_by_quantile(const prepared_factor_data &factor_data, bool by_date = false, bool by_group = false, bool demeaned = true, bool group_adjust = false)

Computes mean forward returns per quantile.

Each date’s quantile mean is the equal-weighted mean of its finite forward returns; the reported mean averages those date means, and the standard error is their sample deviation divided by the square root of the usable date count. A quantile with no usable date keeps NaN.

Parameters:
  • factor_data – Prepared rows and forward-return labels.

  • by_date – Must be false; the by-date view has its own function.

  • by_group – Emit one row per (quantile, group) pair.

  • demeaned – Demean forward returns per date before averaging.

  • group_adjust – Demean per date and group instead; implies groups.

Throws:

factor_data_error – If by_date is true or group data is missing.

Returns:

Quantile table with means and standard errors.

quantile_date_return_table fincore::mean_return_by_quantile_by_date(const prepared_factor_data &factor_data, bool demeaned = true, bool group_adjust = false, bool by_group = false)

Computes per-date quantile mean forward returns.

Each (date, quantile, label) cell averages the finite forward returns of the assets in that bucket; the standard error is their sample deviation divided by the square root of their count and stays NaN below two values.

Parameters:
  • factor_data – Prepared rows and forward-return labels.

  • demeaned – Demean forward returns per date before averaging.

  • group_adjust – Demean per date and group instead; implies groups.

  • by_group – Emit one row per (date, group) pair.

Throws:

factor_data_error – If group data is missing while required.

Returns:

Cube over (date[, group]) rows x quantiles x labels.

quantile_spread_result fincore::mean_return_spread(const quantile_return_table &table, int upper_quantile, int lower_quantile)

Computes the upper-minus-lower quantile return spread.

The spread subtracts the lower quantile mean from the upper quantile mean and combines their standard errors in quadrature when both are finite.

Parameters:
  • table – Quantile means and standard errors to read.

  • upper_quantile – Quantile used as the long leg.

  • lower_quantile – Quantile used as the short leg.

Throws:

factor_data_error – If an aggregate table lacks either quantile, or a grouped table’s groups are not parallel to its quantile rows.

Returns:

Spread per label, or per group and label when the table is grouped.

research_evaluation_spec fincore::normalize_research_evaluation_spec(const research_evaluation_input &values)

Validates caller values and fills every documented default.

Parameters:

values – Caller-supplied optional fields and unknown keys.

Throws:

research_config_error – When unknown fields are present or a supplied value violates its field contract; code() identifies the kind of failure.

Returns:

Normalized evaluation spec with defaults applied.

factor_value fincore::parse_json_value(std::string_view text)

Parses strict JSON into a native value.

Integers are returned as 64-bit integer values where they fit, and other numbers as doubles. Object keys must be strings.

Parameters:

text – JSON text to parse.

Throws:

input_error – If the text is malformed, has trailing content, uses an unsupported escape, or contains a number outside the finite double range.

Returns:

Parsed native value.

std::int64_t fincore::parse_timedelta_nanoseconds(const std::string &label)

Parses a forward-return duration label into nanoseconds.

Accepts an optional leading sign followed by one or more <digits><unit> components, where unit is one of D, h, m, s, ms, us, ns (case-insensitive). Malformed labels are rejected.

Parameters:

label – Duration label such as "1D" or "2h30m".

Throws:

factor_data_error – When the label is empty, malformed or names an unsupported unit.

Returns:

Parsed duration in nanoseconds, negative when the label starts with -.

inline quantile_cumulative_chart fincore::plot_cumulative_returns_by_quantile(const quantile_date_return_table &returns, std::string period)

Builds cumulative-growth chart data via build_cumulative_returns_by_quantile.

Arguments and validation are forwarded unchanged.

Parameters:
  • returns – Mean returns by date, quantile and label.

  • period – Forward-return label; must be present in returns.labels.

Returns:

Chart data identical to the canonical builder’s result.

inline events_distribution_chart fincore::plot_events_distribution(const std::vector<timestamp> &dates, const std::vector<double> &values = {}, std::size_t num_bars = 50U)

Builds event-bucket chart data via build_events_distribution.

Parameters:
  • dates – Event timestamps.

  • values – Optional event values aligned with dates.

  • num_bars – Number of equal-width buckets; must be positive.

Returns:

Chart data identical to the canonical builder’s result.

inline std::vector<qq_chart> fincore::plot_ic_qq(const factor_ic_table &ic)

Builds Q-Q chart data via build_ic_qq.

Parameters:

ic – Information-coefficient table with values in date-major order.

Returns:

One chart per label, in ic.labels order.

inline spread_time_series_chart fincore::plot_mean_quantile_returns_spread_time_series(const std::vector<timestamp> &dates, const std::vector<double> &spreads, std::string period, const std::vector<double> &standard_errors = {}, double bandwidth = 1.0)

Builds spread chart data via build_mean_quantile_returns_spread_time_series.

Parameters:
  • dates – Observation timestamps.

  • spreads – Spreads in decimal return units, aligned with dates.

  • period – Forward-return period label.

  • standard_errors – Optional standard errors in decimal return units.

  • bandwidth – Standard-error multiplier used for the band.

Returns:

Chart data identical to the canonical builder’s result.

inline std::vector<monthly_ic_heatmap_chart> fincore::plot_monthly_ic_heatmap(const factor_time_information_table &monthly)

Builds monthly IC heatmap data via build_monthly_ic_heatmap.

Parameters:

monthly – Monthly information-coefficient table.

Returns:

One chart per group and label.

inline violin_chart fincore::plot_quantile_returns_violin(const quantile_date_return_table &returns, std::string period)

Builds quantile-return violin data via build_quantile_returns_violin.

Parameters:
  • returns – Mean returns by date, quantile and label.

  • period – Forward-return label; must be present in returns.labels.

Returns:

Violin chart data with one group per quantile that has samples.

style_context fincore::plotting_context(std::string context = "notebook", double font_scale = 1.5, std::map<std::string, std::string> rc = {})

Creates a renderer style context with an explicit font scale.

The returned context uses context as its name and keeps rc unchanged except for adding lines.linewidth=1.5 when that key is absent.

Parameters:
  • context – Context name.

  • font_scale – Font scaling factor stored on the context.

  • rc – rc parameter overrides keyed by parameter name.

Returns:

Style context carrying the name, font scale and overrides.

prepared_factor_data fincore::prepare_factor_data(const factor_series &factor, const dataframe &prices, const prepare_factor_config &config = {})

Prepares a quantified factor panel from raw factor values and prices.

Forward returns are computed with config.periods, observations without a finite value for every label are dropped, and the remainder is quantified within the configured cross-sections.

Parameters:
  • factor – Row-aligned factor panel to prepare.

  • prices – Price panel used for forward returns.

  • config – Horizons, bucket settings, grouping and loss budget.

Throws:
Returns:

Retained rows, forward labels and the cleaning-loss report.

multi_horizon_prepared_factor_data fincore::prepare_factor_data_by_horizon(const factor_series &factor, const dataframe &prices, const prepare_factor_config &config = {})

Prepares one quantified panel per forward-return horizon.

Each horizon is bucketed against the cross-section with a finite return for that horizon and checked against config.max_loss separately.

Parameters:
  • factor – Row-aligned factor panel to prepare.

  • prices – Price panel used for forward returns.

  • config – Horizons, bucket settings, grouping and loss budget.

Throws:
  • factor_data_error – When an input is invalid or config.filter_zscore is set, since per-horizon preparation has no full-sample filter.

  • factor_loss_exceeded – When a horizon exceeds config.max_loss.

Returns:

Per-horizon prepared panels in the order of config.periods.

prepared_factor_data fincore::prepare_factor_data_from_forward_returns(const factor_series &factor, const forward_return_table &forward_returns, const prepare_factor_config &config = {})

Prepares a quantified factor panel from a supplied forward-return table.

The table must carry unique labels and unique (date, asset) rows, with one value per row for every label. Observations whose pair is absent or whose value is not finite are dropped and charged to the loss report.

Parameters:
  • factor – Row-aligned factor panel to prepare.

  • forward_returns – Precomputed forward returns to align by date/asset.

  • config – Bucket settings, grouping and loss budget.

Throws:
Returns:

Retained rows, forward labels and the cleaning-loss report.

prepared_factor_data fincore::prepare_pit_factor_data(const std::vector<pit_observation> &observations, const dataframe &prices, const std::vector<timestamp> &evaluation_dates, const prepare_factor_config &config = {})

Prepares a quantified factor panel from point-in-time observations.

The observations are first materialized into a factor panel and then prepared against prices, so only information known and effective on each evaluation date reaches the output.

Parameters:
  • observations – Point-in-time observations with non-empty assets.

  • prices – Price panel used for forward returns.

  • evaluation_dates – Strictly increasing dates to evaluate.

  • config – Horizons, bucket settings, grouping and loss budget.

Throws:
  • factor_data_error – When config.filter_zscore is set, no eligible value materializes, or preparation inputs are invalid.

  • factor_loss_exceeded – When total cleaning loss exceeds config.max_loss.

Returns:

Retained rows, forward labels and the cleaning-loss report.

factor_series_result fincore::quantile_turnover(const prepared_factor_data &factor_data, int quantile, int period = 1)

Computes quantile turnover at a fixed lag.

Turnover on a date is the share of the quantile’s assets that were absent period dates earlier; membership follows the supplied rows even when a factor value is non-finite. The first period dates and dates whose quantile is empty are NaN.

Parameters:
  • factor_data – Prepared rows and forward-return labels.

  • quantile – Quantile whose membership is tracked.

  • period – Positive lag in dates.

Throws:

factor_data_error – If period is not positive.

Returns:

Series over every unique date, sorted ascending.

std::vector<std::optional<int>> fincore::quantize_factor(const factor_series &factor, const quantization_config &config = {}, const factor_grouping &grouping = {})

Assigns one-based bucket labels to factor observations.

Buckets are built per date, or per (date, group) pair when config.by_group is true. Non-finite factor values receive no label.

Parameters:
  • factor – Row-aligned factor panel to label.

  • config – Bucket count, explicit bins and failure handling.

  • grouping – Asset-to-group mapping required when binning by group.

Throws:

factor_data_error – When no usable quantiles or bins are configured, a group is missing, or bucket edges are not unique.

Returns:

One optional label per factor row; empty when no label applies.

research_capabilities fincore::research_capabilities_report()

Returns the pinned native research capability declaration.

Returns:

Capability record listing the supported labels, preprocessing methods, metrics, result tables, export formats and statuses.

std::vector<research_comparison_row> fincore::research_factor_comparisons(std::span<const named_research_result> results, const std::map<std::string, std::pair<std::string, std::string>> &comparisons)

Computes mean-IC and ICIR differences for named factor pairs, per period.

Period labels are the union of both stored IC label sets. Statistics use finite IC values only; a difference is NaN when either side is unavailable.

Parameters:
  • results – Named single-factor results; names must be non-empty and unique.

  • comparisons – Comparison name to (left, right) factor names.

Throws:

factor_data_error – When a result name is empty or duplicated, or a comparison references an unknown factor.

Returns:

One row per comparison and union period label.

std::vector<research_correlation_row> fincore::research_factor_correlations(std::span<const research_factor_panel> factors, int min_assets = 1)

Computes per-date Pearson correlations across common assets for every factor pair.

Dates with fewer than min_assets common finite assets and dates with zero dispersion on either side are skipped. Pairs follow input order, and each row summarizes the contributing dates.

Parameters:
  • factors – Named factor panels; names must be non-empty and unique.

  • min_assets – Minimum common assets per date; must be positive.

Throws:

factor_data_error – When min_assets is not positive or a panel name is empty or duplicated.

Returns:

One row per factor pair in input order, empty when factors is empty.

factor_value fincore::serializable_value(const research_result &result)

Returns the native value form used by fingerprints and JSON envelopes.

Parameters:

result – Research result to serialize.

Returns:

Object with status, schema_version, manifest, tables and columns; non-finite numbers become null.

factor_value fincore::serializable_value(const factor_analysis_model &model)

Converts a factor-analysis model into its native envelope value.

The envelope carries the schema identifier, fingerprint version, result fingerprint, configuration, forward periods, loss report, quantile statistics and tables, IC tables, mean-return spread, turnover and rank-autocorrelation series, and optional event analysis. Non-finite entries in the IC, quantile, turnover, rank-autocorrelation and event arrays are encoded as null.

Parameters:

model – Model to serialize.

Returns:

Native object value for the model.

factor_value fincore::serializable_value(const factor_loss_report &report)

Converts a loss report into a native object value.

Parameters:

report – Loss report to serialize.

Returns:

Native object with the report counters and loss values.

std::vector<std::uint64_t> fincore::show_owned_figures(const owned_figures &figures)

Returns the figure identifiers in display order without opening a window.

Parameters:

figures – Figure list to display.

Returns:

Copy of figures.figures.

dataframe_snapshot fincore::snapshot_pandas(const dataframe &value)

Snapshots a native dataframe and computes its deterministic content digest.

Parameters:

value – Dataframe to copy.

Throws:

fincore_error – If a column type cannot be encoded in the canonical content representation.

Returns:

Snapshot owning an independent copy of value.

dataframe_snapshot fincore::snapshot_pandas(dataframe &&value)

Snapshots a native dataframe by taking ownership of its storage.

Parameters:

value – Dataframe to move.

Throws:

fincore_error – If a column type cannot be encoded in the canonical content representation.

Returns:

Snapshot owning value.

double fincore::student_t_two_sided_p(double statistic, double df)

Returns the two-sided Student-t tail probability.

Uses the regularized incomplete beta function for df degrees of freedom. A NaN statistic or a non-positive or NaN df yields NaN; an infinite statistic yields zero.

Parameters:
  • statistic – t statistic.

  • df – Degrees of freedom; must be positive.

Returns:

Two-sided p value, or NaN when it is undefined.

std::vector<int> fincore::timedelta_strings_to_integers(const std::vector<std::string> &sequence)

Returns the whole-day component of each pandas-style duration string.

Parameters:

sequence – Duration labels to parse.

Throws:

factor_data_error – When a label is malformed or a day component does not fit in int.

Returns:

One whole-day component per label, in input order.

std::string fincore::timedelta_to_string(std::int64_t delta)

Formats a duration using the pinned forward-return label grammar.

Components follow pandas’ normalized representation (floor days and a non-negative remainder), for example -1h becomes "-1D23h" and a zero duration becomes "".

Parameters:

delta – Duration in nanoseconds.

Returns:

Pinned duration label; empty for a zero duration.

std::string fincore::to_json_string(const factor_value &value)

Serializes a native value as deterministic, standards-compliant JSON text.

Object keys are emitted in sorted order, so the text is stable for a given value.

Parameters:

value – Value to serialize.

Throws:

input_error – If the value contains a non-finite floating-point number or a string that is not valid UTF-8.

Returns:

Deterministic JSON text.

research_spec fincore::to_research_spec(const research_evaluation_spec &values)

Projects a normalized evaluation spec onto the execution spec.

Parameters:

values – Normalized evaluation spec.

Returns:

Execution spec carrying the shared fields; analysis-only metadata has no execution-spec counterpart.

std::string fincore::to_serializable(const factor_analysis_model &model)

Returns the JSON text form of serializable_value(model).

This is the native equivalent of the Python to_serializable method.

Parameters:

model – Model to serialize.

Throws:

input_error – If a value cannot be represented as JSON, such as a non-finite loss-report number.

Returns:

Deterministic JSON text for the model envelope.

void fincore::validate_pit_alignment(const std::vector<pit_point> &points)

Validates point-in-time ordering and finiteness.

Each point must carry a finite value, with known_at not before as_of and effective_from not before known_at.

Parameters:

points – Points to check; an empty batch is valid.

Throws:

factor_data_error – When a point violates finiteness or ordering.

using fincore::factor_data_error_alias = factor_data_error

Source-name alias for factor_data_error.

using fincore::factor_loss_exceeded_error = factor_loss_exceeded

Source-name aliases preserving the enhanced/strict split.

constexpr double fincore::DECIMAL_TO_BPS = 10'000.0

Alphalens-compatible decimal-to-basis-points scale.

constexpr int fincore::EVALUATION_CONFIG_SCHEMA_VERSION = 1

Schema version of the normalized research evaluation configuration.

constexpr double fincore::decimal_to_bps = DECIMAL_TO_BPS

Alias for DECIMAL_TO_BPS.

constexpr int fincore::evaluation_config_schema_version = EVALUATION_CONFIG_SCHEMA_VERSION

Lower-case alias of EVALUATION_CONFIG_SCHEMA_VERSION.

constexpr std::uint32_t fincore::factor_analysis_fingerprint_version = 2U

Version of the native result-fingerprint encoding.

Mixed into every result fingerprint and echoed by factor_analysis_model::result_fingerprint_version.

constexpr const char *fincore::factor_analyze_operation_id = "factor_analysis.analysis.analyze_factor"

Operation identifier of the shared factor analysis kernel.

constexpr std::int64_t fincore::nanoseconds_per_day = 86'400'000'000'000LL

Nanoseconds in one calendar day.

constexpr const char *fincore::research_api_version = "1.0"

Research API version reported by capability and result manifests.

constexpr const char *fincore::research_detailed_api_version = "2.0"

Detailed research API version recorded in result and export manifests.

constexpr const char *fincore::research_detailed_export_schema_id = "fincore.factor_research_detailed.v2"

Schema identifier written to the detailed export manifest.

constexpr int fincore::research_detailed_export_schema_version = 2

Schema version written to the detailed export manifest.

constexpr int fincore::research_detailed_result_schema_version = 2

Schema version of research_detailed_result.

constexpr int fincore::research_result_schema_version = 1

Schema version of research result envelopes and their manifests.