V0 Changelog#
0.7.0 (2026-11-02)#
Changed#
The library ships only as compiled wheels. Nuitka compiles the package into one extension module (
.github/workflows/compiled.yml) for Windows (x86-64), macOS (Apple silicon, macOS 11 or later) and Linux (manylinux_2_28, x86-64), on Python 3.12, 3.13 and 3.14; there is no wheel for Intel Macs or for 64-bit ARM Linux. The wheel carries none of the package’s source. Every release wheel trusts none of the tests’ keys (vendor.py --check) and, installed, refuses one. It needskaxanuk-license-client1.4 (1.4.1 on Python 3.14) and licence server 3.8, both in production since 2026-11-02; the production seal key,kxs-1, is the public half of the licence server’s RSA-3072 key (LICENSE_SEAL_KEY).The licence is checked inside the library (docs/plan/30 of the KaxaNuk Research Lab, phase 3).
validate_license()no longer takes the licence client’s word: it makes the one heavy check of the process inkaxanuk.attribution_analysis._guard, whichvendor.pyof the licence repository writes into the package. The guard identifies this computer itself (itsMachineGuid, the hardware UUID thatgethostuuid()gives on macOS, or/etc/machine-idon Linux, with a secret only this computer can open, kept in%ProgramData%\KaxaNuk\device-key, or under%LOCALAPPDATA%when ProgramData cannot be written, in~/Library/Application Support/KaxaNukon macOS and in~/.local/share/KaxaNukon Linux), has the client fetch the server’s signed acceptance for it, checks the Ed25519 signature and the claims itself, then the licence server’s seal: an RSA-3072 signature of the product, the device, the SHA-256 of the machine id and the times, which only the server’s private key makes. It keeps that sealed grant. Nothing compiled into the library can make a seal. It needs kaxanuk-license-client 1.4 (LicenseClient.acceptance): with an older client,validate_license()raisesLicenseConfigurationErrorsaying so. It needs licence server 3.8, which signsvalid_until: an acceptance without it is refused withLicenseValidationError.validate_license()still returns aValidationResult(ok=True,message="Validated", and the licence’sexpires_at,Nonefor one that never expires) and raises the same four licence errors. The seat the computer held under the client’s own device id moves to the guard’s, so updating takes no second seat.KAXANUK_DEVICE_FINGERPRINT_OVERRIDEno longer names the device (only the Research Lab cloud’s build,vendor.py --build cloud, reads it), and a Linux container without a machine id is refused.The attribution classes check the licence themselves, not only the entry points: the constructors of
BrinsonFachlerArrowAttributionandFactorModelArrowAttribution, the methods that compute the attribution (brinson_fachler_model,time_series_calculationandcompute_cumulative_indexes;multifactor_attribution,time_series_calculation,calc_pct_area,cumulative_pct_decompandcumulative_totals), andperformance_attribution._align_and_attribute. Each check verifies the grant’s seal against this computer’s machine id (theMachineGuid; the hardware UUID on macOS;/etc/machine-idon Linux), with the originalhashlib.sha256, and that the names a module calls pandas, numpy and pyarrow by are modules, not stand-ins that record every call. It takes about 0.35 ms, once per call, never per date or segment, and callsvalidate_license()when the grant does not stand; an object made withobject.__new__or unpickled is checked too. Code that uses these classes directly now needs a valid licence, asmain()andrun_attribution()always did.``reset_validation_state()`` only clears. It forgets the grant of the process (and the client’s own flag), so the next
validate_license()makes the heavy check again; the acceptance the client saved stays in its cache. The Research Lab calls it between users.Development.
_guard.pyand the# kx-guardblocks are written bypackages/license-guard/vendor.pyof the licence repository: never edit them by hand; to check another method, add the marker lines and runvendor.py --library <this repository>again..kx-guard.jsonat the root holds the product, the masks of the signing key, the seal’s public keys and the libraries checked to be modules; nothing in it is secret. This copy is a development build, which also trusts the tests’ keys (kx-test,kxs-test). The tests hold a grant sealed bytests/kx_guard_testing.py, whichvendor.pywrites too; those that go through the real guard and client are skipped with a client older than 1.4.``kaxanuk-license-client~=1.4``, which is on KaxaNuk’s index since 2026-11-02 (it was
~=1.0): the guard asks the client foracceptance(), which 1.4 added.Python 3.14.
requires-pythonis>=3.12,<3.15, the tests run on 3.12, 3.13 and 3.14, and the compiled wheels are built for the three. It needskaxanuk-license-client1.4.1, the first that admits 3.14. Python 3.15 waits for the libraries’ dependencies (cvxpy has no wheels for it yet).The CLI’s help is its commands’ ``help=``, not their docstrings. Each text moved word for word into its
@cli.command(help=...)or@click.group(help=...), so the compiled library, built without docstrings, still describes its commands;--helpreads exactly as before.Compiled wheels for Windows, macOS and Linux (docs/plan/30, phase 4).
.github/workflows/compiled.ymlcompiles the library with Nuitka on Windows, macOS (Apple silicon, from macOS 11) and Linux (manylinux_2_28, built in its container), for Python 3.12, 3.13 and 3.14. It runs the tests against the compiled code, then builds the release wheels, checks that they ship none of the tests’ keys and that, installed, they refuse one, and keeps them as the run’s artifacts; nothing reaches the bucket from it. It runs when it or the guard’s tools change ondev, and for a tag namedcompiled-*. The tools are in.github/kx_guard, copied there byvendor.pyfrom the licence repository like the guard: never edit them here..gitignoreignoresdist-dev/anddist-compiled/, where they leave the wheels. The test that reads the exceptions’ hierarchy from the module’s docstring skips against a compiled build, which keeps no docstrings; the pure run keeps it.
Removed#
``services.license_validator._state``. Setting
_state["validated"]toTrueskipped the check; no flag stands in for the licence now. Code that cleared it to validate again callsreset_validation_state(); a test that set it to skip the check holds a grant instead.
0.6.0 (2026-10-24)#
Added#
Benchmark and relative statistics on the result.
AttributionResult.benchmark_statsholds thesummary_statskeys for the benchmark the attribution compared the portfolio with (Brinson-Fachler’s, else the active factor model’s holdings benchmark), andAttributionResult.relative_statsholdsActive Return,Annualized Active Return,Tracking Error,Information Ratio,BetaandHit Rate, on the dates both have a return. Professional attribution reports put active risk next to active return; the definitions are the Backtest Engine’s (sample deviations, annualized over 252 days), so a backtest and its attribution report the same tracking error and information ratio. Both are empty when no benchmark was attributed.Attribution by calendar year.
BrinsonFachlerResult.by_yearandFactorModelResult.by_yearhold one row per year, linked within the year exactly as the cumulative tables link the whole window, so a year’s effects add up to its own return difference. Cumulative effects over many years read as counterintuitive without them. Years compound into the window; they do not add up to it.A clearer Excel report, laid out the way professional attribution reports are (vendor reports from FactSet, MSCI, Morningstar and Bloomberg, and the CFA Institute’s draft guide on attribution reporting):
- headline figures across the top of
summary(portfolio, benchmark and active return, tracking error, information ratio, maximum drawdown), and key findings led by a bottom-line sentence, with the active risk, selection counted with interaction, and the best and worst calendar year;
- headline figures across the top of
- the portfolio’s and the benchmark’s statistics side by side, then the relative ones, as in the
Backtest Engine’s report;
- Brinson-Fachler and the factor model by calendar year, on
summaryand in the newbf_by_year and
factor_by_yearsheets;
- Brinson-Fachler and the factor model by calendar year, on
- a bridge chart from the benchmark’s return to the portfolio’s through allocation, selection and
interaction, and a chart of the cumulative portfolio and benchmark return;
- factors under their display names (
Energy, notf_Energy), grouped into style and industry factors with subtotals, and ranked in a chart that colours gains and losses apart and labels each bar;
- factors under their display names (
- shares read
n/m(not meaningful) when the cumulative return is under 1% in size or a share would exceed 200%, where they mislead;
- shares read
- a methodology block on
checks(holdings-based or hypothetical, gross of costs, how the periods are linked, arithmetic active return, where interaction and residual go, the benchmark, the factor model, annualization), backtests labelled hypothetical on
summary, and the note every run logs (its first date has no return) marked Expected instead of counted as a warning;
- a methodology block on
- signed number formats for effects and contributions, light blue and vermilion fills for gains
and losses (a palette that reads with any colour vision), lines told apart by dash as well as colour;
- a linked table of contents and a link back to
summaryon every sheet, data sheets as Excel tables with filters, landscape one-page-wide printing with the report name and page number, and the workbook’s properties set.
- a linked table of contents and a link back to
Changed#
The factor model’s diagnostic for dates without a portfolio return names the first such date (
first_date), so the expected case, the window’s first price date, can be told from a real gap. The log line is unchanged.
0.5.0 (2026-10-21)#
Added#
An Excel report of every run.
main(), and sokaxanuk.attribution_analysis run, now writes{portfolio_file_name}_{UTC %Y%m%d%H%M%S}_attribution_results.xlsxto the newoutput_directory(Outputby default) before it plots or starts the dashboard. Until now a run only drew charts or served the dashboard and left nothing a reader could open later. The workbook follows the look of the KaxaNuk Backtest Engine’s report, so a backtest and its attribution read alike.summarycomes first: the window and the methods, key findings in plain English generated from the numbers (portfolio against benchmark and the active return; how allocation, selection and interaction split it and which is largest; the factor share against the idiosyncratic share; the largest positive factor and the largest drag; the active factor split; the costs of a Backtest-Engine run; how many warnings the run logged), the headline tables and two native Excel charts (cumulative effects over time, contribution per factor). Thenchecks(the run’s parameters and every warning it logged),how_to_read(what each effect and term means) and one sheet per result table: Brinson-Fachlerper_periodandcumulative, the factor model’s five tables, the active factor model’s and theimplementationtable when present. The per-date Brinson-Fachlerdetailsare not written: they can exceed Excel’s 1,048,576 rows. The report recomputes no attribution number: the summary shows values of the result, and only the implementation block compounds the engine and holdings returns and sums the costs, saying so in its labels. Number formats are declared per value (the Sharpe ratio is a ratio, not a percentage) and dates are real Excel dates. It writes nothing but the workbook (no chart images), never overwrites an earlier report (a second one in the same second gets_2) and removes a workbook that fails while being saved. The report is in English; every word of it lives inoutput_handlers/excel_report_text.py, so another language is a translation of that module. openpyxl writes it cell by cell, throughlxml(a new dependency, see below): about 4 seconds for a ten-year daily run with 17 factors.Output handlers, which write a run’s results apart from the attribution, as input handlers read its inputs.
main()passes its result tooutput_handlers(new keyword): by default[ExcelOutputHandler.from_configuration(configuration)], which writes the report above;output_handlers=()writes nothing. A handler of your own subclassesoutput_handlers.OutputHandlerInterfaceand implementsoutput_result(*, result).ExcelOutputHandler(output_directory, *, name="Portfolio", benchmark_name=None)and the functionwrite_excel_report(result, output_directory, *, name, benchmark_name), exported from the package root next torun_attribution, write the report of anyAttributionResult(including arun_attribution_from_backtest()one, which adds the implementation sheet) and return its path.run_attribution()still writes no file.``AttributionResult.diagnostics``: the warnings a run logs, kept on the result. Dates or rows left out, returns substituted, the holdings benchmark differing from the reported one by more than 1 bp, a skipped cross-check, an ignored cash price file and the other warnings the pipeline logs were only log lines, so whoever read the results never saw them. Each is now also a
Diagnosticwith a stablecode(e.g.benchmark_returns_differ,factor_dates_without_factor_attribution), itslevel(warning, orinfofor the notes on a skipped benchmark cross-check, ignored benchmark weights and legacy Brinson-Fachler not being linked), the log line asmessage, andcount,total,first_dateanddetailswhen the line gives them. They are recorded where each line is logged, from the values it is built from; the log lines are unchanged and no number changes. The tuple is empty by default, survivespickle,copy.deepcopyanddataclasses.asdict, and is filled by file-based runs (loading included) and byrun_attribution_from_backtest();repr(result)shows only its count. Collection is per thread and task, so concurrent runs never mix their diagnostics.Optional ``output_directory`` row in the Excel parameters file (
Configuration.output_directory): wheremain()writes the report, relative to the folder the run starts from and created when missing. When the row is missing or blank the report goes toOutput, the folderinitcreates. Existing parameter files keep working without it, andparameters_format_versionstays0.1.0.
Changed#
``main()`` writes a file. It writes the Excel report to
output_directorybefore plotting or serving the dashboard, and raisesOSErrorif it cannot. Code that callsmain()and must not write anything passesoutput_handlers=(), or callsrun_attribution(), which returns the same result.``lxml`` is a dependency. The package does not import it: openpyxl writes with it whenever it is installed, about five times faster than with its pure-Python writer (a ten-year daily report with 17 factors saves in about 4 seconds instead of 20).
Removed#
The names renamed in 0.4.0. They warned since 0.4.0 and now fail: the modules
interfaces.brinston_fachler_arrow_methodandinterfaces.brinston_fachler_arrow_interface(ImportError); the classesBrinstonFachlerArrowAttributionandBrinstonFachlerArrowInterface, frominterfaces, fromperformance_attributionor from their modules, thebrinston_fach_indexesattribute,FactorModelArrowAttribution.cummulative_pct_decomp()and the interface’sreturns_investible_assetsattribute (AttributeError); and thereturns_investible_assetskeyword (TypeError). UseBrinsonFachlerArrowAttribution,BrinsonFachlerArrowInterface,brinson_fachler_indexes,cumulative_pct_decomp()andreturns_investable_assets. Objects pickled by 0.3.x name the removed module and no longer load, as 0.4.0 announced: load them under 0.4.x and pickle them again. Objects pickled by 0.4.x load unchanged. No number changes.
0.4.1 (2026-10-19)#
Fixed#
``BrinsonFachlerArrowAttribution.time_series_calculation()`` with date columns of different types. It returned an empty table, without an error, when the input tables stored their dates in different types (for example weights in
timestamp[ns]and returns indate32), althoughbrinson_fachler_model(date)matched them. Each portfolio-weights date is now converted to every table’s own date type with the single-date rules (exact conversion; a time zone on both sides or neither), andDateConversionErrornames the table when a conversion is not exact or the date columns cannot match. Date columns that are not dates but hold the same kind of value (two string types, such as thelarge_stringof a pandas 3 table andstring, or two integer types) still match by value. Tables with a single date type give the same results as before; null dates are ignored.A factor-model-only ``run_attribution_from_backtest()`` no longer needs an engine benchmark. A Backtest-Engine result whose
benchmarkisNonefailed with “The backtest has no benchmark”, although the factor model never uses the benchmark return. It now runs and gives the numbers of the same run with a benchmark; when there is one, its dates still bound the window. Brinson-Fachler and the active factor model still raiseDataValidationErrorwithout one, and now say why.AttributionInputs.benchmark_returnsis optional (Noneby default): without it the window is not bounded by it and the holdings-benchmark cross-check is skipped (logged at INFO). The file pipeline is unchanged.The factor model attributes dates in ascending order whatever the input order.
FactorModelArrowAttributionattributed and linked the dates in the row order of the weights, so weights passed out of date order gave different linked contributions and shares (Carino/GRAP) and running series that did not end on the last date. The weights are now sorted by date (a stable sort) when the model is built, anddaily_portfolio_weightsholds the sorted table. Weight rows without a date are dropped, with a warning. File runs, whose dates were already sorted, are unchanged.The factor model warns when dates with a portfolio return have no factor attribution (no factor file has a row for them, or nothing has a non-zero weight on them). They were silently left out of the cumulative contributions, shares and totals, whose compounded portfolio return then differed from the portfolio’s own. One warning per model gives the count and the first date; dates whose return is 0 are not counted. No number changes.
Changed#
Brinson-Fachler reads only the rows it needs.
brinson_fachler_model(date)takes that date’s rows from each table before converting them, instead of converting every full table: 11.5 ms instead of 78.8 ms a call at 3,000 dates x 400 groups, back to the speed of the per-date loop of 0.3.x.time_series_calculation()attributes the dates in blocks of 256, so its working memory above the per-date detail tables stays bounded:main()peaks at 121.6 MiB of Python allocations instead of 154.2 MiB (tracemalloc; ticker-level textbook, 600 assets + 120 benchmark-only x 1,500 dates, of which the detail tables are 84.5 MiB), in the same run time. Outputs are bit-identical. Rows of dates that are not attributed are no longer read, so a malformed cell there no longer raises.The attribution core has public names.
performance_attribution.attribute,require_a_methodandweighted_columnswere_attribute,_require_a_methodand_weighted_columns. They are what file-based runs andrun_attribution_from_backtest()share, so a refactor of the file pipeline can no longer break the adapter through a private name. Being public,attribute()now validates the licence first, like every other entry point (once per process). No numbers change;_load_inputsand_runstay private.
0.4.0 (2026-10-14)#
Added#
Multi-period linking.
linking_method(carinodefault,grap,none; optional Excel row 25, case-insensitive; existing parameter files keep working) makes cumulative effects add up to the compounded return. Brinson-Fachler: cumulative allocation + selection + interaction equal the cumulative alpha at every date, and alpha equals the compoundedR_p - R_bup to the per-period reconciliation residuals. Factor model: cumulative factor contributions plus the residual add up to the compounded portfolio return (b = 0). The Carino coefficient is computed in a numerically stable form; linking raises on returns of -100% or below, non-finite values, or cumulative growth that overflows or underflows. Legacy Brinson-Fachler is never linked (an INFO note sayslinking_methodis ignored for it).Textbook Brinson-Fachler by segment.
brinson_fachler_formula = textbook(the new default) applies Brinson-Fachler (1985): allocation(w_p - w_b)(R_b,i - R_b), selectionw_b (R_p,i - R_b,i), interaction(w_p - w_b)(R_p,i - R_b,i). Segments are tickers by default or come from aticker,segmentCSV named bysegment_map_file_name. Effects reconcile toR_p - R_bon every date (tolerance1e-10 + 2e-6 * |R_b|) or the run stops. It also stops when a side’s weights do not sum to 1, a return is not finite, or a segment’s long and short legs net to ~0 weight while its P&L is not ~0 (its return is undefined; split the legs into separate segments).Cash. With the textbook formula, net weights that sum below 1 are topped up with
cash_ticker(defaultCASH), which needs no price file and returns 0; a price file for it is ignored, with a warning. Net weights above 1 are rejected. Legacy and factor-model-only runs are unchanged: therecash_tickeris an ordinary ticker priced from its file.``factor_return_type = log`` restates log factor files as simple returns, proportionally per stock and day, so the log/simple gap no longer lands in the idiosyncratic residual. Infinite values, duplicate dates or mismatched date types in the factor files raise an error.
A warning when the holdings-based benchmark return differs from the benchmark returns file by more than 1 bp on any date.
BrinsonFachlerArrowAttribution.compute_cumulative_indexes(): the cumulative indexes without drawing a plot. Separateportfolio_returns/benchmark_returnsper group.The dashboard launches whenever any method produced results, not only the factor model.
``run_attribution(configuration)`` returns the results as data. It validates the licence, runs the enabled methods and returns a frozen
AttributionResult(start_date,end_date,brinson_fachler,factor_model,portfolio_returns,summary_stats), exported from the package root. Each method’s result holds its PyArrow tables (Brinson-Fachler:per_period,cumulative,details; factor model:portfolio_returns,contributions,cumulative_contributions,cumulative_totals,daily_shares,cumulative_shares) and itslinking. It never plots and never starts the dashboard, and raisesConfigurationErrorwhen both methods are off.summary_statsis read-only and empty, with a warning, when no date has a portfolio return. The mappings (summary_stats,cumulative_shares,details) areReadOnlyMapping``s, so a result survives ``pickle,copy.deepcopyanddataclasses.asdict;repr(result)is a one-line summary (date window, methods run, row count, headline statistics) instead of a dump of every table. The factor model’s residual isidio_returnsincumulative_sharesandf_idio_returnsindaily_shares.FactorModelArrowAttribution.cumulative_totals(): cumulative portfolio, factor and idiosyncratic return (date,portfolio_returns,factor_returns,idiosyncratic_returns) over the dates with a portfolio return. With linking it reconciles to the compounded return and tocumulative_contributions; withlinking_method = noneit is an arithmetic running sum, so it differs fromTotal Returnand from the per-factor cumulative columns (which also cover dates without a return).A
Total Returnentry (compounded), first in the summary statistics.main(..., dashboard_host="127.0.0.1", dashboard_debug=False): the host and Dash debug mode of the dashboard can be set from Python. Debug mode (the Werkzeug debugger shows source code in tracebacks and has a PIN-guarded console that runs code) with a host that is not a loopback address logs a warning.Four optional rows in the Excel parameters file; existing 0.1.0 files keep working without them and
parameters_format_versionis not bumped.``run_attribution_from_backtest(backtest_result, market_data_bundle, *, settings, …)`` attributes a finished KaxaNuk Backtest-Engine 0.67.0 run from its in-memory result and market data bundle, exported from the package root. Attribution runs on the holdings: the start-of-day book (the previous date’s end-of-day
Daily_Weights) at the engine’s mark-to-market prices, before costs; the dashboard shows this holdings return as the portfolio return. Day 0 (initial capital to the first NAV) is excluded with its initial-build costs and its return. The engine’sCASH_RESERVEbecomescash_tickerand earns 0. The factor model takesfactor_returns_directoryand uses the engine benchmark’s return. Brinson-Fachler requiresbenchmark_weights, the start-of-day constituent weights (naive dates, no nulls, every weighted ticker priced in the run); without them it raisesConfigurationError. With the textbook formula a warning is logged when those weights do not reproduce the engine benchmark’s return (legacy skips the check), and, as in the file pipeline, only the textbook formula andactive_factor_modelprice benchmark-only constituents.segment_mapapplies to textbook Brinson-Fachler.DataValidationErroris raised whenRegister_dforDaily_Weightshas repeated or unsorted dates, when the bundle’s dates inside the run window are not the engine’s, or when a non-emptyFinancing_dflacksFinancing_Cost. Prices convert to float64 as the file pipeline’s price files do, and decimalbenchmark_weightsexactly (float(Decimal)). The engine is never imported: the result is read by duck typing, and its layout is pinned by a fixture generated from the real engine plus a live test that runs only where the engine is installed.``AttributionResult.implementation`` (
Nonefor file-based runs): per date,engine_returns,holdings_returns,commissions,slippage,financingandexecution, withengine = holdings + commissions + slippage + financing + execution. Costs are negative fractions of the previous NAV (a cash-interest credit is positive).executionis the trade-execution price (before slippage, which has its own column) versus the close on traded shares, plus any other NAV movement the holdings and the costs do not explain (e.g. forced exits) and rounding. Day 0 has no row, so the cost columns do not sum to the engine’sTotal_commissions/Total_slippage_costs/Total_financing_costs, and compoundedengine_returnsgiveNAV_last / NAV_day0 - 1, not the return from the initial capital. The table keeps the dates ofportfolio_returns(the KPI dates), so itsholdings_returnscompound toTotal Return;implementation_breakdown()gives the whole run. The dashboard does not show it yet.``AttributionSettings``: the validated method options (method flags, Brinson-Fachler formula, factor return type, linking method, cash ticker), exported from the package root.
Configurationvalidates through it, and in-memory runs take it directly.Carry and dividends components.
f_carry.csvandf_dividends.csvin the factor folder are reserved for simple-return components that are not factors. They are never restated from log returns and stay out of the log factor total. They are reported as their own contributions and shares, and ascarry_returns/dividends_returnsincumulative_totals(only when supplied). They are taken out of the idiosyncratic residual (r_p - factors - carry - dividends). At load time they are ordinary factor files, so one that covers fewer dates narrows the common window; the factor-coverage log ignores them. The charts draw them with the totals (“Carry”, “Dividends”), never among the factors. Use total-return prices when supplyingf_dividends; otherwise the residual is understated by the dividends. The reserved names (these two and the aggregate vendor files) are matched whatever the case of the file name:F_Dividends.csvis the dividends component, reported asf_dividends. Two files for one component (f_carry.csvandF_Carry.csvin a case-sensitive folder) raiseDataValidationErrornaming both.Active factor attribution (
active_factor_model, default off, set from Python). The factor model also runs on the benchmark’s constituent weights. The active contribution of each factor and component is portfolio minus benchmark, the active residual isr_p - r_bminus all of them, and the cumulative active effects are linked withb= the holdings benchmark return, so with Carino/GRAP they add up to the compoundedR_p - R_b(none: running sums).Results are in
FactorModelResult.active(ActiveFactorResult:returns,contributions,cumulative_contributions,cumulative_totals,linking). Weighted benchmark constituents are priced and their factor columns read; a constituent without a column has no exposure to that factor (the factor-coverage INFO line is logged for each side). A weighted constituent without a return on a date counts as 0, with one warning. Turning the option on never changes the portfolio’s own numbers, in file runs and in Backtest-Engine runs. In file runs without textbook Brinson-Fachler the constituents the portfolio does not hold are priced on their own and their prices taken on the portfolio’s price dates (a move across a date only they have lands on the next portfolio date). In Backtest-Engine runsbenchmark_weightsbound the attribution window only when Brinson-Fachler runs; for the active model alone, the dates they do not cover are left out of the active results only. Dates without a benchmark return or benchmark weights are dropped with one warning, so the active window can be shorter than the portfolio’s. The holdings benchmark is cross-checked once against the reported one. Without textbook Brinson-Fachler the benchmark weights are not topped up with implied cash (acash_tickercolumn in them needs a price file in file runs). They are used as given, and one warning gives the number of active dates whose net benchmark weights differ from 1 by more than 1e-6, the first such date and its sum: below 1 the remainder is cash earning 0, above 1 the over-allocation is kept, and nothing is raised. Needsfactor_model_method; the dashboard does not show the active results yet.``risk_free_rate`` (
AttributionSettings/Configuration, annual decimal, default 0.0, set from Python) feeds the Sharpe ratio insummary_stats. It must be finite and above -1.FactorModelArrowAttribution.decompose(): the daily contributions and portfolio returns, without cumulative linking (run()=decompose()+time_series_calculation()).Methodology docs: beta or market timing is not split out by the factor model, since it needs factor return series and exposures that the factor files (exposure x return) do not carry. Timing is measured by textbook Brinson-Fachler through the cash segment.
Changed#
Loading and computing are separate internal stages (
_load_inputsreads the files,_attributealigns and computes), so file-based and in-memory runs share one computation. The numbers of the file pipeline are unchanged.``main()`` returns the ``AttributionResult`` (it returned
None). Static plots are drawn only withlaunch_dashboard=False; the dashboard is fed from the same result.The dashboard runs with Dash debug mode off by default (it was on), and binds to
127.0.0.1unlessdashboard_hostsays otherwise.The dashboard’s Total Return card shows the compounded total return (it showed the annualized return), and its header dates are the first and last date with a valid (non-null, non-NaN) return.
Every factor is drawn. The factor tab shows each non-aggregate factor: style factors first,
f_marketincluded, then custom factor names alphabetically; industries with any non-zero value. The aggregate vendor files (f_total_factor_returns,f_total_excess_returns,f_idyo_returns) are never drawn. The residual is labelled “Idiosyncratic” in every chart, and the stacked chart’s smoothing uses a partial window at the start, so it begins at the first date; both hold for the dashboard and for the matplotlibplot_stacked_weights_normalized.Missing statistics show “N/A”. When
summary_statsis empty (no date has a portfolio return) the dashboard’s metric cards show “N/A” instead of 0. The cards use the statistics table’s formatting (Sharpe ratio and skewness to 4 decimals), and the table showsAnnualized Volas a percentage (it printed the raw fraction).The dashboard’s headline chart is the model’s Portfolio / Factors / Idiosyncratic cumulative totals (
cumulative_totals).create_dashboard_from_attributioncallers that pass the earlier keys (simulated_rets,portfolio_returns) withoutcumulative_totalsget it derived from them (linkingkey, defaultcarino);create_dashboard_from_result(result)builds the dashboard from anAttributionResultand, likeAttributionDashboardandcreate_dashboard_from_attribution, can be imported fromkaxanuk.attribution_analysis.dashboard(Dash loads on that first access, not with the package).Both methods off now raises ``ConfigurationError`` instead of running with nothing to do.
Factor names keep inner dots. The factor name is the file name without the final
.csv(f_value.v2.csvisf_value.v2); it used to be cut at the first dot, sof_value.v1.csvandf_value.v2.csvcollided. The factor folder reads only regular*.csvfiles, skipping anything else and names starting with.or~$; an unreadable file raisesDataLoadingErrornaming it.Parquet market data accepts native types. Date columns may be
date,date64ortimestamp(a time-zone-aware timestamp keeps its local calendar date) and price columns integer, float or decimal; nulls, NaN and infinite prices raiseDataLoadingErrornaming the column and ticker. The text path is unchanged.Vertical weights files accept ``date`` or ``m_date`` as the first header besides
date_column(case-insensitive).Much faster on large portfolios. Factor-model contributions, portfolio returns, Brinson-Fachler and input loading are vectorized. Measured wall time of
main()(both methods, textbook by segment, 17 factors; before and after back to back, faster of two runs): 1,500 assets x 3,600 dates takes 24.2 s instead of 390 s (16.1x), 500 x 1,500 takes 3.8 s instead of 39.9 s (10.6x), 200 x 750 takes 1.4 s instead of 7.9 s (5.6x); ticker-level 500 x 1,500 is 13.3x faster and legacy Brinson-Fachler alone 7.3x. Outputs are unchanged within relative 1e-11 (summation-order noise), protected by a golden test. Afactor_return_type = logfactor-model run peaks at 6.2 MiB of Python allocations instead of 24.9 MiB (tracemalloc, 200 x 750 x 17); the process working set barely changes (304 vs 322 MiB).Market data with a null date now raises
DataLoadingErrornaming the ticker instead of producing a null-dated row.Decimal-typed inputs to the factor model and Brinson-Fachler are converted exactly instead of raising.
BrinsonFachlerArrowAttribution.brinson_fachler_model(date)convertsdateto the date type of each input table separately (portfolio weights, benchmark weights, portfolio returns, benchmark returns) before the lookup. The tables may therefore store their dates in different types (date32,date64,timestampin any unit), and adatetime.date,datetime.datetime,pd.Timestamp,np.datetime64,pa.Scalaror ISO-8601 string names the same row in all of them (a date without a time means midnight). A value with no exact equivalent in a table’s date type raisesDateConversionError(aValueError) naming the table, instead of an Arrow error or a silent row of zero weights: a number (anintsuch as20240102, afloat, abool),NoneorNaT, a string that is not ISO-8601, a time of day for a date column (or more precision than the column’s unit), and a time-zone-aware value for a column without a time zone or the reverse (0.3.x matched a UTC-midnight value against adate32column). Only date and timestamp columns are converted: with any other date column type (strings, integers)datemust equal the column’s values, as before, and a date absent from a table still gives zero weights or missing returns there.time_series_calculation()takes its dates from the tables and converts nothing.Cumulative effects are linked by default. The cumulative Brinson-Fachler indexes (portfolio and benchmark returns are compounded) and the factor model’s cumulative contributions and shares are linked to compounded returns; set
linking_method = nonefor the previous arithmetic sums. The dashboard’s cumulative charts and shares therefore change. With linking, the factor model’ssimulated_retscovers only dates with a portfolio return (the first price date is excluded), a warning counts the dropped dates once per model, and a portfolio return of -100% or below or non-finite (e.g. a zero price) or a non-finite factor contribution raises an error naming the date. The dashboard’s daily decomposition view still covers every attribution date.Stricter validation of the cumulative Brinson-Fachler indexes. Legacy Brinson-Fachler and
linking_method = nonenow raisePerformanceAttributionErroron non-finite per-period values or returns of -100% or below, where 0.3.x carried NaN or infinity into the charts. Valid inputs give the same numbers as before, bitwise.Brinson-Fachler numbers change by default. The previous asset-level formula is available as
brinson_fachler_formula = legacy(aliascustomin the Python API) and is deprecated.Direct Python callers of ``BrinsonFachlerArrowAttribution`` get the textbook formula by default. Each side’s weights must then sum to 1 on every date: implied cash is added only by
main(), not by the class. Passformula="legacy"to keep the numbers of 0.3.x and earlier.Textbook Brinson-Fachler starts at the second price date: the first price date has no return, so it is excluded. Weights dates with no price row (e.g. a market holiday) are skipped with a warning instead of counting as a flat period. Legacy keeps both.
Textbook Brinson-Fachler prices every benchmark holding with a non-zero weight on some loaded date, not only the ones the portfolio owns; before, benchmark-only names were dropped and the benchmark return was only the held slice. Constituents whose weight is 0 throughout need no price file. Legacy still prices only the portfolio’s tickers.
Factor model shares. The cumulative decomposition divides by the portfolio’s own total return, over the dates that have both factor data and a portfolio return (a warning counts the excluded dates), like the daily view. The first price date has no asset return, so its portfolio return is null (it was 0) and it is left out of the shares and the dashboard’s summary statistics. Previously, without an
f_total_excess_returnsfile, the cumulative idiosyncratic share was always 0.f_marketis now an ordinary factor, and the aggregate filesf_total_factor_returns,f_total_excess_returnsandf_idyo_returnsare never factors. If you suppliedf_total_excess_returns, shares used to be relative to that excess total withf_marketexcluded; now cash and excess differences land in the idiosyncratic residual.Aggregate vendor files are no longer loaded.
f_total_factor_returns,f_total_excess_returnsandf_idyo_returnsin the factor folder are skipped (one INFO line names them): they no longer appear incontributions/cumulative_contributionsand no longer narrow the common date window. Every other number is unchanged.``run_attribution_from_backtest`` uses ``benchmark_weights`` when Brinson-Fachler or the active factor model is on (it was Brinson-Fachler only); the INFO line that says they are ignored now names both.
active_factor_modelwithoutbenchmark_weightsraisesConfigurationError.The factor chart’s totals panel title names the components drawn (“Total / Factor / Idiosyncratic / Carry / Dividends”), in the dashboard as in the matplotlib plots.
More specific exceptions. Invalid arguments and misaligned series raise the package’s own errors, each also a subclass of the builtin it replaces, so
except ValueError/except TypeErrorcode keeps working:AttributionArgumentError(aConfigurationErrorand aValueError: unknown formula or linking method, missing weights or returns, conflicting return arguments),SeriesAlignmentError(aDataAlignmentErrorand aValueError: linking inputs of different shapes),DateConversionError(aDateParsingErrorand aValueError: a datebrinson_fachler_model()cannot convert) andReturnsTypeError(aReturnsTimeSeriesErrorand aTypeError: risk statistics given something other than a pandas Series or DataFrame).exceptions.exceptionsalso re-exportsDateRangeErrorand the new classes.``BrinsonFachlerArrowInterface`` matches its implementation. Its constructor takes
returns_investable_assets,complete_portfolio_weightsandcomplete_benchmark_weights, the namesBrinsonFachlerArrowAttributionuses (which now calls it), and raisesAttributionArgumentErrorwhen a weights table is missing. The attributes it set asportfolio_weights/benchmark_weightsare nowcomplete_portfolio_weights/complete_benchmark_weights. Only custom subclasses of the interface are affected.Type checking.
mypy(thetypingdevelopment group, which now includestypes-openpyxl) reports no errors onsrc.Documentation. New methodology pages on multi-period linking and on conventions and limitations (weight timing, cash, holdings return versus NAV, the residual’s names); API pages for the results, linking, the exceptions and the pipeline modules; the docs build without warnings.
Deprecated#
Typos in public names. The old names keep working until 0.5.0, each with a
DeprecationWarning: modulesinterfaces.brinston_fachler_arrow_methodandinterfaces.brinston_fachler_arrow_interfaceareinterfaces.brinson_fachler_arrow_methodandinterfaces.brinson_fachler_arrow_interface; classesBrinstonFachlerArrowAttributionandBrinstonFachlerArrowInterfaceareBrinsonFachlerArrowAttributionandBrinsonFachlerArrowInterface; the attributebrinston_fach_indexesisbrinson_fachler_indexes;FactorModelArrowAttribution.cummulative_pct_decomp()iscumulative_pct_decomp(); and the interface’sreturns_investible_assetskeyword and attribute arereturns_investable_assets. The old attribute names can still be read and assigned (a 0.3.x subclass that setsself.returns_investible_assetskeeps working), and the warning points at the calling line, so Python’s default filters show it in scripts.performance_attribution.BrinstonFachlerArrowAttribution, which 0.3.x exposed through that module’s import, also resolves to the new class with the warning (once per process). The pipeline buildsBrinsonFachlerArrowAttribution: replacing the old name on that module (for instance withmonkeypatch.setattr) still runs but no longer changes what the pipeline uses, so patch the new name.Objects pickled before 0.4.0 still load. Unpickling stores
brinston_fach_indexesandreturns_investible_assetsunder their current names, without a warning of its own, so both the old and the new attribute names read the pickled values. ABrinstonFachlerArrowAttributionpickled by 0.3.x loads as aformula="legacy",linking="none"model, so recomputing it gives the numbers it was pickled with. Such a pickle names the class by its old module, which warns on load and goes away in 0.5.0: pickle the object again under 0.4.x to keep it loadable.
Removed#
Legacy pandas attribution classes. No pipeline used them and their numbers disagreed with the PyArrow classes:
BrinstonFachlerAttributionandBrinstonFachlerInterface(legacy formula only;BrinsonFachlerArrowAttributionwithformula="legacy"gives the same per-date numbers), andFactorModelAttributionandFactorModelAttributionInterface(they left outf_market, divided byf_total_excess_returnsand read a risk-free rate from FRED; useFactorModelArrowAttribution, andrisk_free_ratefor the Sharpe ratio), with the helpersresample_rate,weighted_stdandwexpof their module.fredapiis no longer a dependency.Modules no code of the package imported: the pandas Plotly charts
modules.attribution_visualizers(usemodules.attribution_visualizers_arrow),modules.table_conversion(usemodules.table_conversion_arrow),modules.synthetic_exposures_creator(generate_synthetic_exposure_dict,stock_factor_returns_loader); the entitiesmarket_data(MarketData),market_data_daily_row(MarketDataDailyRow),ticker(Ticker),portfolio_daily_weights(PortfolioDailyWeights),portfolio_returns(PortfolioReturns),strategy_weights(DailyWeights) and the emptyfield_validation; the servicesentity_helperandvalidator; the input handlersasset_returns_input_handler(AssetInfoInputHandler, which could not be imported) andportfolio_returns_input_handler(PortfolioReturnsInputHandlerfailed on every call), andWeightsInputHandlerfrominput_handlers.portfolio_weights_input_handler(read_csv_intersectionstays). Weights files are read byCsvPortfolioInputHandlerandExcelPortfolioInputHandler.Duplicate interfaces
interfaces.configurator_interfaceandinterfaces.input_handler_interface(the latter made the API docs’InputHandlerInterfacelinks ambiguous): useconfig_handlers.configurator_interface.ConfiguratorInterfaceandinput_handlers.input_handler_interface.InputHandlerInterface.Dependencies
scikit-learn(unused) andimportlib(an obsolete backport of the standard library module).scipy, which the risk statistics import andscikit-learnused to bring in, is now declared.plotly-express(the old standalone package:plotly.expressships insideplotly) andpandas-market-calendarsare gone too: no version of this package ever imported them. They no longer bring instatsmodels,patsyorexchange-calendars: install those yourself if your own code got them through this package.httpxmoved from the runtime dependencies to the test group: this package does not import it. The licence client is what useshttpxat run time, and only the licence tests script its transport; if your environment relied on this package to installhttpx, install it yourself.Pillow>=12.1.1stays although the package does not import it: it is a security floor on matplotlib’s own dependency (CVE-2026-25990).
Fixed#
main()withportfolio_input_format = excelraisedUnboundLocalError(benchmark returns handlers were only built for CSV).Vertical
.xlsxweights or benchmark files whose date cells are real Excel dates failed with a rawArrowInvalid(Failed to parse string: '2026-05-20 00:00:00'). Date headers may now also be date-times (2026-05-20 00:00:00or ISO2026-05-20T00:00:00), truncated to the day; a header no format parses, or two headers on the same day, raiseDataLoadingErrornaming them.The benchmark cross-check warning no longer says the benchmark weights come from a file: in
run_attribution_from_backtestthey are passed in memory.FactorModelArrowAttribution.last_day_decomposition()labels the residual “Idiosyncratic” and the components “Carry” / “Dividends”, as the dashboard does (it showed the raw keys).Importing
modules.attribution_visualizers_arrowbefore the dashboard no longer fails with a circularImportError: thedashboardpackage loads its app on first use.
Known limitations#
Menchero linking and geometric attribution are not offered.
The dashboard’s decomposition tab (daily view) still covers all attribution dates, while the cumulative views skip dates without a portfolio return.
Weights files must be daily: one entry per trading day, not only rebalancing dates. A series that spans at least a year must hold 240 to 260 dates in its first and its last year, or it is rejected.
The licence client is still required to import the package.
Price files with mismatched dates leave gaps as null (no forward fill), which can null other tickers’ returns on those dates.
The segment map is static (not point-in-time), and cash earns 0 (no carry yet).
run_attribution_from_backtest: benchmark constituents of textbook Brinson-Fachler or the active factor model must be in the engine’s universe (priced in its mark-to-market table); the adapter reads no other prices.
0.3.0 (2026-09-27)#
Added#
One licence check for every KaxaNuk library. Attribution validates its licence through
kaxanuk-license-client1.0, the package the Backtest Engine, Attribution Analysis and Portfolio Construction share, instead of a validator of its own. It is a new dependency,kaxanuk-license-client~=1.0, which takes the client’s fixes without a new attribution release, and it comes from KaxaNuk’s private package index, the one thepip installcommand of the welcome email names, which serves it to any valid licence.services.license_validatorstays as a thin wrapper with the names attribution and the KaxaNuk Research Lab use:validate_license(),_state(now the client’s own dict, changed in place and never replaced), the licence errors as attributes of the module, and a newreset_validation_state(), which forgets that the process validated so the next call checks again. It also holdsPRODUCT, what attribution tells the client about itself: the productattribution-analysis, the key inKNAA_API_KEY_KAXANUK, another server inKNAA_LICENSE_SERVER_URL, the unified licence server by default, and the logger it has always used,kaxanuk.attribution_analysis.services.license_validator. The Research Lab, which puts each user’s key inKNAA_API_KEY_KAXANUK, clears_state["validated"]before validating and catches the errors by name, keeps working as it is.``LicenseConfigurationError``, raised when
KNAA_LICENSE_SERVER_URLorKAXANUK_LICENSE_SERVER_URLis not an http or https URL a request can be sent to, before anything is sent. The licence errors,LicenseErrorand its four subclasses, now inherit fromAttributionAnalysisErrorand from the client’s matching error at once, so bothexcept AttributionAnalysisErrorandexcept kaxanuk.license_client.LicenseErrorcatch them.``KNAA_LICENSE_SERVER_URL`` points attribution, and only attribution, at another licence server.
KAXANUK_LICENSE_SERVER_URLstill works, for every KaxaNuk library, and is read after it.
Changed#
The licence is checked on the unified KaxaNuk licence server, for this product. Without a server variable, attribution validates on the licence server that serves every KaxaNuk library instead of on a server of its own, and the request names the product,
attribution-analysis, and attribution’s version: a licence that does not include Attribution Analysis is refused with a message naming the products it does include.The analysis keeps running when the licence server cannot be reached, for 3 days. A successful check is saved, and inside 24 hours a run does not contact the server at all, as before. When the server cannot be reached, a check saved less than 3 days ago stands in, with a warning each run saying how much of the grace is left. “Cannot be reached” is now anything that is not a verdict on the licence: no connection, a timeout, a redirect, a 400, 408, 422, 425, 429 or 5xx, or a 200 that cannot be read. In 0.2 the grace was 7 days but covered only connection errors and timeouts, and any answer other than a 200, an outage on our side included, rejected the licence outright. The grace runs from the last successful check, never past the expiry the server reported, and ignores a check stamped more than an hour in the future, so neither repeated offline runs nor a rolled-back clock can stretch it.
A rejection is final. A 401, 402, 403 or 404, or a 200 whose
okis nottrue, raisesLicenseValidationErrorat once and deletes the saved check, so going offline cannot bring a revoked licence back. In 0.2 a rejection left the saved check in place, where it went on standing in offline for up to 7 days after the last success, and a 200 whoseokwas"yes"or1was accepted.Where the saved checks live. One file per licence key, named after the key’s SHA-256 digest, in the folder
%LOCALAPPDATA%\KaxaNuk\licence-cache\attribution-analysison Windows and$XDG_CACHE_HOME/kaxanuk/licence-cache/attribution-analysiselsewhere (~/.cachewithoutXDG_CACHE_HOME);KAXANUK_LICENSE_CACHE_DIRmoves them. Each holds the key’s digest, never the key, is signed, is tied to the device and to Attribution Analysis, and is written atomically, so a process that validates several users’ keys, like the Research Lab’s, never mixes them.~/.kaxanuk_attribution_cache, the single cache of 0.2 and earlier, is neither read nor removed:the first run after upgrading needs to reach the licence server*, and the old file can be deleted by hand.
``.kaxanuk_license`` is read as a ``.env`` file. The line
KNAA_API_KEY_KAXANUK=<key>is attribution’s, and a file holding a single key without a name serves every product; in 0.2 the first line counted, whatever product it named. AKNAA_API_KEY_KAXANUKholding only spaces now counts as unset instead of being sent as an empty key.validate_license()returns the client’sValidationResult: keyword-only, withok,messageand the licence’sexpires_at. Code that built attribution’s two-fieldValidationResultby position has to name its fields. Every licence message and log line is ASCII and never carries the licence key.Development.
kaxanuk-license-clientis the only package taken from KaxaNuk’s private index, and it is taken from nowhere else ([[tool.pdm.source]]withinclude_packagesandexclude_packages): installing the project with PDM needsKAXANUK_INDEX_KEYset to a licence key.Read the Docs no longer installs the package. Installing it would need the licence client, which only the private index serves: autodoc imports the package from
src/,kaxanuk.license_clientis mocked,docs/source/conf.pyreads the version from the source instead of importing it, and thedocsdependency group now also lists the package’s runtime dependencies.
Fixed#
The offline-grace warning reached nobody on a Spanish Windows console. Its em dash cannot be encoded in cp850, and the bare
StreamHandlerinservices.configuration_loggerturned that into aUnicodeEncodeErrorinsidelogging: the user saw--- Logging error ---and the warning itself was lost. The console is now moved to UTF-8 when it is not on it already, a console that refuses to be reconfigured gets the record with the offending characters replaced rather than no record at all, and the optional log file is written as UTF-8 instead of in the machine’s codepage.
0.2.0 (2026-07-12)#
Added#
Input handlers now slices the file right away with the actual start date.
Fixed#
Formating in the [attribution_analysis_parameters.xlsx](templates/attribution_analysis/Config/attribution_analysis_parameters.xlsx) configuration
0.1.0 (2026-07-03)#
Added#
Brinson-Fachler attribution, decomposing active return into allocation, selection and interaction effects per asset and date.
KN Five-Factor Model (KN5FM) attribution, decomposing portfolio return into per-factor contributions plus an idiosyncratic residual.
Excel-based configuration workbook (
attribution_analysis_parameters.xlsx) and CLI (init,run,update,autorun).CSV and Parquet market data input handlers, and CSV/Excel portfolio and benchmark weight handlers.
Interactive Dash dashboard for cumulative factor contributions and summary statistics.
License key validation against the KaxaNuk license server, with local caching and an offline grace period.
Added a data-integrity check to PortfolioWeights that rejects weight series without ~daily (240–260/year) observation density, catching backtest-granularity files passed in by mistake.
Auto date alignment across all input tables (asset returns, portfolio/benchmark weights, benchmark returns, factor returns) to their common date range before running any calculation.
User-defined column name mapping for market-data inputs, so CSV/Parquet files don’t need to match a fixed schema.
Performance statistics module (Sharpe ratio, annualized return/volatility, skewness, kurtosis, max drawdown, historic and Gaussian VaR/CVaR) surfaced in the dashboard’s summary panel.
Synthetic factor-exposure generator for prototyping the factor model pipeline without real factor data.
PyArrow-based columnar architecture used throughout for high-performance, vectorized computation.
Pandas-based reference implementations of both attribution methodologies, provided alongside the PyArrow implementations for validation and comparison.
Excel-workbook schema-version check that prompts
update excelwhen the configuration template is outdated.