API Reference¶
The public API surface of jquantstats. All stable exports are importable directly from the top-level package:
| Export | What it is | Start here when… |
|---|---|---|
Portfolio |
Position-level analytics: NAV, turnover, costs, attribution, lag() |
you have prices and positions |
Data |
Returns-level analytics: 50+ stats, plots, HTML report | you have returns (or prices only) |
CostModel |
Declarative trading-cost specification (per-unit or turnover-bps) | you want cost-adjusted analytics |
Result |
Lightweight container returned by some report helpers | you consume report internals |
NativeFrame, NativeFrameOrScalar |
Type aliases for narwhals-compatible input frames | you type-annotate your own code |
Exceptions live in jquantstats.exceptions and all inherit
from JQuantStatsError, so except JQuantStatsError catches the whole family.
See API Stability for the versioning and deprecation policy, and the FAQ for common errors.
Portfolio¶
jquantstats.Portfolio
dataclass
¶
Bases: PortfolioNavMixin, PortfolioAttributionMixin, PortfolioTurnoverMixin, PortfolioCostMixin, PortfolioTransformMixin, PortfolioConstructorMixin
Portfolio analytics class for quant finance.
Stores the three raw inputs — cash positions, prices, and AUM — and exposes the standard derived data series, analytics facades, transforms, and attribution tools.
Derived data series:
profits— per-asset daily cash P&Lprofit— aggregate daily portfolio profitnav_accumulated— cumulative additive NAVnav_compounded— compounded NAVreturns— daily returns (profit / AUM)monthly— monthly compounded returnshighwater— running high-water markdrawdown— drawdown from high-water mark-
all— merged view of all derived series -
Lazy composition accessors:
stats,plots,report - Portfolio transforms:
truncate,lag,smoothed_holding - Attribution:
tilt,timing,tilt_timing_decomp - Turnover:
turnover,turnover_weekly,turnover_summary - Cost analysis:
cost_adjusted_returns,trading_cost_impact - Utility:
correlation
Attributes:
| Name | Type | Description |
|---|---|---|
cashposition |
DataFrame
|
Polars DataFrame of positions per asset over time (includes date column if present). |
prices |
DataFrame
|
Polars DataFrame of prices per asset over time (includes date column if present). |
aum |
float
|
Assets under management used as base NAV offset. |
Analytics facades¶
.stats: delegates to the legacyStatspipeline via.data; all 50+ metrics available..plots: portfolio-specificPlots; NAV overlays, lead-lag IR, rolling Sharpe/vol, heatmaps..report: HTMLReport; self-contained portfolio performance report..data: bridge to the legacyData/Stats/DataPlotspipeline.
.plots and .report are intentionally not delegated to the legacy path: the legacy
path operates on a bare returns series, while the analytics path has access to raw prices,
positions, and AUM for richer portfolio-specific visualisations.
Cost models¶
Two independent cost models are provided. They are not interchangeable:
Model A — position-delta (stateful, set at construction):
cost_per_unit: float — one-way cost per unit of position change (e.g. 0.01 per share).
Used by .position_delta_costs and .net_cost_nav.
Best for: equity portfolios where cost scales with shares traded.
Model B — turnover-bps (stateless, passed at call time):
cost_bps: float — one-way cost in basis points of AUM turnover (e.g. 5 bps).
Used by .cost_adjusted_returns(cost_bps) and .trading_cost_impact(max_bps).
Best for: macro / fund-of-funds portfolios where cost scales with notional traded.
To sweep a range of cost assumptions use trading_cost_impact(max_bps=20) (Model B).
To compute a net-NAV curve set cost_per_unit at construction and read .net_cost_nav (Model A).
Date column requirement¶
Most analytics work with or without a date column. The following features require a
temporal date column (pl.Date or pl.Datetime):
portfolio.plots.correlation_heatmap()portfolio.plots.lead_lag_ir_plot()stats.monthly_win_rate()— returns NaN per column when no date is presentstats.annual_breakdown()— raisesValueErrorwhen no date is presentstats.max_drawdown_duration()— returns period count (int) instead of days
Portfolios without a date column (integer-indexed) are fully supported for
NAV, returns, Sharpe, drawdown, cost analytics, and most rolling metrics.
Examples:
>>> import polars as pl
>>> from datetime import date
>>> prices = pl.DataFrame({"date": [date(2020, 1, 1), date(2020, 1, 2)], "A": [100.0, 110.0]})
>>> pos = pl.DataFrame({"date": [date(2020, 1, 1), date(2020, 1, 2)], "A": [1000.0, 1000.0]})
>>> pf = Portfolio(prices=prices, cashposition=pos, aum=1e6)
>>> pf.assets
['A']
Source code in src/jquantstats/portfolio.py
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 | |
assets
property
¶
List the asset column names from prices (numeric columns).
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: Names of numeric columns in prices; typically excludes |
list[str]
|
|
cost_model
property
¶
data
property
¶
Build a legacy Data object from this portfolio's returns.
This bridges the two entry points: Portfolio compiles the NAV curve from
prices and positions; the returned Data object
gives access to the full legacy analytics pipeline (data.stats,
data.plots, data.reports).
Returns:
| Type | Description |
|---|---|
Data
|
|
Data
|
is the portfolio's daily return series and whose |
Data
|
column (or a synthetic integer index for date-free portfolios). |
Examples:
>>> import polars as pl
>>> from datetime import date
>>> prices = pl.DataFrame({"date": [date(2020, 1, 1), date(2020, 1, 2)], "A": [100.0, 110.0]})
>>> pos = pl.DataFrame({"date": [date(2020, 1, 1), date(2020, 1, 2)], "A": [1000.0, 1000.0]})
>>> pf = Portfolio(prices=prices, cashposition=pos, aum=1e6)
>>> d = pf.data
>>> "returns" in d.returns.columns
True
plots
property
¶
Convenience accessor returning a PortfolioPlots facade for this portfolio.
Use this to create Plotly visualizations such as snapshots, lagged performance curves, and lead/lag IR charts.
Returns:
| Type | Description |
|---|---|
PortfolioPlots
|
|
PortfolioPlots
|
plotting methods. |
The result is cached after first access so repeated calls are O(1).
report
property
¶
Convenience accessor returning a Report facade for this portfolio.
Use this to generate a self-contained HTML performance report containing statistics tables and interactive charts.
Returns:
| Type | Description |
|---|---|
Report
|
|
Report
|
report methods. |
The result is cached after first access so repeated calls are O(1).
stats
property
¶
Return a Stats object built from the portfolio's daily returns.
Delegates to the legacy Stats pipeline via
data, so all analytics (Sharpe, drawdown, summary, etc.) are
available through the shared implementation.
The result is cached after first access so repeated calls are O(1).
utils
property
¶
Convenience accessor returning a PortfolioUtils facade for this portfolio.
Use this for common data transformations such as converting returns to prices, computing log returns, rebasing, aggregating by period, and computing exponential standard deviation.
Returns:
| Type | Description |
|---|---|
PortfolioUtils
|
|
PortfolioUtils
|
utility transform methods. |
The result is cached after first access so repeated calls are O(1).
__post_init__()
¶
Validate input types, shapes, and parameters post-initialization.
Source code in src/jquantstats/portfolio.py
__repr__()
¶
Return a string representation of the Portfolio object.
Source code in src/jquantstats/portfolio.py
describe()
¶
Return a tidy summary of shape, date range and asset names.
Returns:¶
pl.DataFrame One row per asset with columns: asset, start, end, rows.
Examples:
>>> import polars as pl
>>> from datetime import date
>>> prices = pl.DataFrame({"date": [date(2020, 1, 1), date(2020, 1, 2)], "A": [100.0, 110.0]})
>>> pos = pl.DataFrame({"date": [date(2020, 1, 1), date(2020, 1, 2)], "A": [1000.0, 1000.0]})
>>> pf = Portfolio(prices=prices, cashposition=pos, aum=1e6)
>>> df = pf.describe()
>>> list(df.columns)
['asset', 'start', 'end', 'rows']
Source code in src/jquantstats/portfolio.py
from_cash_position(prices, cash_position, aum, cost_per_unit=0.0, cost_bps=0.0, cost_model=None)
classmethod
¶
Create a Portfolio directly from cash positions aligned with prices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prices
|
DataFrame
|
Price levels per asset over time (may include a date column). |
required |
cash_position
|
DataFrame | Expr
|
Cash exposure per asset over time, either as a DataFrame or as a Polars expression evaluated against prices. |
required |
aum
|
float
|
Assets under management used as the base NAV offset. |
required |
cost_per_unit
|
float
|
One-way trading cost per unit of position change. Defaults to 0.0 (no cost). Ignored when cost_model is given. |
0.0
|
cost_bps
|
float
|
One-way trading cost in basis points of AUM turnover. Defaults to 0.0 (no cost). Ignored when cost_model is given. |
0.0
|
cost_model
|
CostModel | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
A Portfolio instance with the provided cash positions. |
Raises:
| Type | Description |
|---|---|
PositionExprColumnError
|
If cash_position is an expression that
creates columns not present in prices (e.g. via |
Source code in src/jquantstats/portfolio.py
Data¶
jquantstats.Data
dataclass
¶
A container for financial returns data and an optional benchmark.
Provides methods for analyzing and manipulating financial returns data,
including resampling, truncation, and access to statistical metrics and
visualizations via the stats and plots properties.
Attributes:
| Name | Type | Description |
|---|---|---|
returns |
DataFrame
|
DataFrame containing returns data with assets as columns. |
benchmark |
DataFrame | None
|
Optional benchmark returns DataFrame. Defaults to None. |
index |
DataFrame
|
DataFrame containing the date index for the returns data. |
Source code in src/jquantstats/data.py
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 | |
all
property
¶
Combine index, returns, and benchmark data into a single DataFrame.
This property provides a convenient way to access all data in a single DataFrame, which is useful for analysis and visualization.
Returns:
| Type | Description |
|---|---|
DataFrame
|
pl.DataFrame: A DataFrame containing the index, all returns data, and benchmark data (if available) combined horizontally. |
assets
property
¶
Return the combined list of asset column names from returns and benchmark.
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: List of all asset column names from both returns and benchmark (if available). |
date_col
property
¶
Return the column names of the index DataFrame.
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: List of column names in the index DataFrame, typically containing the date column name. |
plots
property
¶
Provides access to visualization methods for the financial data.
Returns:
| Name | Type | Description |
|---|---|---|
DataPlots |
DataPlots
|
An instance of the DataPlots class initialized with this data. |
reports
property
¶
Provides access to reporting methods for the financial data.
Returns:
| Name | Type | Description |
|---|---|---|
Reports |
Reports
|
An instance of the Reports class initialized with this data. |
stats
property
¶
Provides access to statistical analysis methods for the financial data.
Returns:
| Name | Type | Description |
|---|---|---|
Stats |
Stats
|
An instance of the Stats class initialized with this data. |
utils
property
¶
Provides access to utility transforms and conversions for the financial data.
Returns:
| Name | Type | Description |
|---|---|---|
DataUtils |
DataUtils
|
An instance of the DataUtils class initialized with this data. |
__post_init__()
¶
Validate the Data object after initialization.
Source code in src/jquantstats/data.py
__repr__()
¶
Return a string representation of the Data object.
Source code in src/jquantstats/data.py
copy()
¶
Create a deep copy of the Data object.
Returns:
| Name | Type | Description |
|---|---|---|
Data |
Data
|
A new Data object with copies of the returns and benchmark. |
Source code in src/jquantstats/data.py
describe()
¶
Return a tidy summary of shape, date range and asset names.
Returns:
| Type | Description |
|---|---|
DataFrame
|
pl.DataFrame: One row per asset with columns: asset, start, end, |
DataFrame
|
rows, has_benchmark. |
Source code in src/jquantstats/data.py
from_prices(prices, rf=0.0, benchmark=None, date_col='Date', null_strategy=None)
classmethod
¶
Create a Data object from prices and optional benchmark.
Converts price levels to returns via percentage change and delegates
to from_returns. The first row of each asset is dropped because no
prior price is available to compute a return.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prices
|
NativeFrame
|
Price-level data. First column should be the date column; remaining columns are asset prices. |
required |
rf
|
float | NativeFrame
|
Risk-free rate. Forwarded unchanged to
|
0.0
|
benchmark
|
NativeFrame | None
|
Benchmark prices. Converted to
returns in the same way as |
None
|
date_col
|
str
|
Name of the date column in the DataFrames.
Defaults to |
'Date'
|
null_strategy
|
{'raise', 'drop', 'forward_fill'} | None
|
How to
handle
Note: Prices that contain nulls will produce null returns via
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Data |
Data
|
Object containing excess returns derived from the supplied |
Data
|
prices, with methods for analysis and visualization through the |
|
Data
|
|
Raises:
| Type | Description |
|---|---|
MissingDateColumnError
|
If date_col is not a column of prices or benchmark. Raised before returns are derived so the offending frame is named explicitly. |
Examples:
from jquantstats import Data
import polars as pl
prices = pl.DataFrame({
"Date": ["2023-01-01", "2023-01-02", "2023-01-03"],
"Asset1": [100.0, 101.0, 99.0]
}).with_columns(pl.col("Date").str.to_date())
data = Data.from_prices(prices=prices)
Source code in src/jquantstats/data.py
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 | |
from_returns(returns, rf=0.0, benchmark=None, date_col='Date', null_strategy=None)
classmethod
¶
Create a Data object from returns and optional benchmark.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
returns
|
NativeFrame
|
Financial returns data. First column should be the date column, remaining columns are asset returns. |
required |
rf
|
float | NativeFrame
|
Risk-free rate. Defaults to 0.0 (no risk-free rate adjustment).
|
0.0
|
benchmark
|
NativeFrame | None
|
Benchmark returns. Defaults to
None (no benchmark). First column should be the date column,
remaining columns are benchmark returns. Returns and
benchmark are aligned on their common dates; if either frame
contains dates the other lacks, those rows are dropped and a
|
None
|
date_col
|
str
|
Name of the date column in the DataFrames.
Defaults to |
'Date'
|
null_strategy
|
{'raise', 'drop', 'forward_fill'} | None
|
How to
handle
Note: Affects only Polars |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Data |
Data
|
Object containing excess returns and benchmark (if any), |
Data
|
with methods for analysis and visualization through the |
|
Data
|
and |
Raises:
| Type | Description |
|---|---|
MissingDateColumnError
|
If date_col is not a column of returns, benchmark, or a DataFrame-valued rf. Raised before any joins so the offending frame is named explicitly. |
NullsInReturnsError
|
If null_strategy is |
ValueError
|
If there are no overlapping dates between returns and benchmark. |
Warns:
| Type | Description |
|---|---|
BenchmarkAlignmentWarning
|
If aligning returns and benchmark on their common dates drops rows from either frame. |
Examples:
Basic usage:
from jquantstats import Data
import polars as pl
returns = pl.DataFrame({
"Date": ["2023-01-01", "2023-01-02", "2023-01-03"],
"Asset1": [0.01, -0.02, 0.03]
}).with_columns(pl.col("Date").str.to_date())
data = Data.from_returns(returns=returns)
With benchmark and risk-free rate:
benchmark = pl.DataFrame({
"Date": ["2023-01-01", "2023-01-02", "2023-01-03"],
"Market": [0.005, -0.01, 0.02]
}).with_columns(pl.col("Date").str.to_date())
data = Data.from_returns(returns=returns, benchmark=benchmark, rf=0.0002)
Handling nulls automatically:
returns_with_nulls = pl.DataFrame({
"Date": ["2023-01-01", "2023-01-02", "2023-01-03"],
"Asset1": [0.01, None, 0.03]
}).with_columns(pl.col("Date").str.to_date())
# Drop rows with nulls (mirrors pandas/QuantStats behaviour)
data = Data.from_returns(returns=returns_with_nulls, null_strategy="drop")
# Or forward-fill nulls
data = Data.from_returns(returns=returns_with_nulls, null_strategy="forward_fill")
Source code in src/jquantstats/data.py
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 | |
head(n=5)
¶
Return the first n rows of the combined returns and benchmark data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of rows to return. Defaults to 5. |
5
|
Returns:
| Name | Type | Description |
|---|---|---|
Data |
Data
|
A new Data object containing the first n rows of the combined data. |
Source code in src/jquantstats/data.py
items()
¶
Iterate over all assets and their corresponding data series.
This method provides a convenient way to iterate over all assets in the data, yielding each asset name and its corresponding data series.
Yields:
| Type | Description |
|---|---|
tuple[str, Series]
|
tuple[str, pl.Series]: A tuple containing the asset name and its data series. |
Source code in src/jquantstats/data.py
resample(every='1mo')
¶
Resample returns and benchmark to a different frequency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
every
|
str
|
Resampling frequency (e.g., |
'1mo'
|
Returns:
| Name | Type | Description |
|---|---|---|
Data |
Data
|
Resampled data at the requested frequency. |
Source code in src/jquantstats/data.py
tail(n=5)
¶
Return the last n rows of the combined returns and benchmark data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of rows to return. Defaults to 5. |
5
|
Returns:
| Name | Type | Description |
|---|---|---|
Data |
Data
|
A new Data object containing the last n rows of the combined data. |
Source code in src/jquantstats/data.py
truncate(start=None, end=None)
¶
Return a new Data object truncated to the inclusive [start, end] range.
When the index is temporal (Date/Datetime), truncation is performed by
comparing the date column against start and end values.
When the index is integer-based, row slicing is used instead, and
start and end must be non-negative integers. Passing
non-integer bounds to an integer-indexed Data raises TypeError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
date | datetime | str | int | None
|
Optional lower bound (inclusive). A date/datetime value
when the index is temporal; a non-negative |
None
|
end
|
date | datetime | str | int | None
|
Optional upper bound (inclusive). Same type rules as
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Data |
Data
|
A new Data object filtered to the specified range. |
Raises:
| Type | Description |
|---|---|
TypeError
|
When the index is not temporal and a non-integer bound is supplied. |
Source code in src/jquantstats/data.py
CostModel¶
jquantstats.CostModel
dataclass
¶
Unified representation of a portfolio transaction-cost model.
Eliminates the implicit "pick one" contract between the two independent
cost parameters (cost_per_unit and cost_bps) on
Portfolio. A CostModel
instance encapsulates one model at a time and can be passed to any
Portfolio factory method instead of specifying the raw float parameters.
Attributes:
| Name | Type | Description |
|---|---|---|
cost_per_unit |
float
|
One-way cost per unit of position change (Model A). Defaults to 0.0. |
cost_bps |
float
|
One-way cost in basis points of AUM turnover (Model B). Defaults to 0.0. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> CostModel.per_unit(0.01)
CostModel(cost_per_unit=0.01, cost_bps=0.0)
>>> CostModel.turnover_bps(5.0)
CostModel(cost_per_unit=0.0, cost_bps=5.0)
>>> CostModel.zero()
CostModel(cost_per_unit=0.0, cost_bps=0.0)
Source code in src/jquantstats/_cost_model.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | |
per_unit(cost)
classmethod
¶
Create a Model A (position-delta) cost model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cost
|
float
|
One-way cost per unit of position change. Must be non-negative. |
required |
Returns:
| Type | Description |
|---|---|
CostModel
|
A |
CostModel
|
|
Examples:
Source code in src/jquantstats/_cost_model.py
turnover_bps(bps)
classmethod
¶
Create a Model B (turnover-bps) cost model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bps
|
float
|
One-way cost in basis points of AUM turnover. Must be non-negative. |
required |
Returns:
| Type | Description |
|---|---|
CostModel
|
A |
CostModel
|
|
Examples:
Source code in src/jquantstats/_cost_model.py
Result¶
Result bundles a Portfolio with an optional per-asset expected-returns
frame (mu) and exports a standard artifact set in one call:
create_reports(output_dir) writes CSVs (prices, profit, returns, positions,
tilt/timing decomposition, and the mu signal when present) plus interactive
HTML plots. Use it when you want a reproducible on-disk report bundle from a
backtest or experiment; call portfolio.plots / portfolio.report directly
when you just want figures in a notebook. mu (when given) must be a Polars
DataFrame with one column per portfolio asset — anything else raises at
construction time.
jquantstats.Result
dataclass
¶
Lightweight container for system outputs.
Attributes:
| Name | Type | Description |
|---|---|---|
portfolio |
Portfolio
|
The portfolio constructed by a system/experiment. |
mu |
DataFrame | None
|
Optional per-asset expected-returns surface used by some systems. |
Source code in src/jquantstats/result.py
__post_init__()
¶
Validate that mu (when given) is a DataFrame covering every portfolio asset.
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
MuSchemaError
|
If |
Source code in src/jquantstats/result.py
create_reports(output_dir)
¶
Generate CSV exports and interactive HTML plots for this result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
|
Path
|
Destination directory where two subfolders will be created: - data/: CSV exports of prices, profit, returns, positions, and signal (if mu present). - plots/: Plotly HTML reports (snapshot, lead/lag IR, lagged performance, smoothed holdings performance). |
required |
Source code in src/jquantstats/result.py
Exceptions¶
jquantstats.exceptions
¶
Domain-specific exception types for the jquantstats package.
This module defines a hierarchy of exceptions that provide meaningful context when data-validation errors occur within the package.
All exceptions inherit from JQuantStatsError so callers can catch the
entire family with a single except JQuantStatsError clause if they prefer.
Examples:
>>> raise MissingDateColumnError("prices")
Traceback (most recent call last):
...
jquantstats.exceptions.MissingDateColumnError: ...
BenchmarkAlignmentWarning
¶
Bases: UserWarning
Emitted when aligning returns and benchmark drops rows from either side.
Returns and benchmark are aligned on their common dates with an inner join. Rows whose date appears in only one of the two frames are silently discarded by that join; this warning surfaces how many rows were lost so a partially overlapping benchmark cannot truncate the analysis unnoticed.
Suppress it once the overlap is understood::
import warnings
from jquantstats.exceptions import BenchmarkAlignmentWarning
warnings.filterwarnings("ignore", category=BenchmarkAlignmentWarning)
Source code in src/jquantstats/exceptions.py
IntegerIndexBoundError
¶
Bases: JQuantStatsError, TypeError
Raised when a row-index bound is not an integer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
param
|
str
|
Name of the offending parameter (e.g. |
required |
actual_type
|
str
|
The |
required |
Examples:
>>> raise IntegerIndexBoundError("start", "str")
Traceback (most recent call last):
...
jquantstats.exceptions.IntegerIndexBoundError: start must be an integer, got str.
Source code in src/jquantstats/exceptions.py
__init__(param, actual_type)
¶
Initialize with the parameter name and the offending type.
Source code in src/jquantstats/exceptions.py
InvalidCashPositionTypeError
¶
Bases: JQuantStatsError, TypeError
Raised when cashposition is not a polars.DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
actual_type
|
str
|
The |
required |
Examples:
>>> raise InvalidCashPositionTypeError("dict")
Traceback (most recent call last):
...
jquantstats.exceptions.InvalidCashPositionTypeError: cashposition must be pl.DataFrame, got dict.
Source code in src/jquantstats/exceptions.py
__init__(actual_type)
¶
InvalidMaxBpsError
¶
Bases: JQuantStatsError, ValueError
Raised when max_bps is not a positive integer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_bps
|
object
|
The invalid value that was supplied. |
required |
Examples:
>>> raise InvalidMaxBpsError(0)
Traceback (most recent call last):
...
jquantstats.exceptions.InvalidMaxBpsError: max_bps must be a positive integer, got 0.
Source code in src/jquantstats/exceptions.py
__init__(max_bps)
¶
InvalidPricesTypeError
¶
Bases: JQuantStatsError, TypeError
Raised when prices is not a polars.DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
actual_type
|
str
|
The |
required |
Examples:
>>> raise InvalidPricesTypeError("list")
Traceback (most recent call last):
...
jquantstats.exceptions.InvalidPricesTypeError: prices must be pl.DataFrame, got list.
Source code in src/jquantstats/exceptions.py
__init__(actual_type)
¶
JQuantStatsError
¶
MissingDateColumnError
¶
Bases: JQuantStatsError, ValueError
Raised when a required date column is absent from a DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame_name
|
str
|
Descriptive name of the frame missing the column (e.g. |
required |
column
|
str | None
|
Name of the date column that was looked up (e.g. the
|
None
|
available
|
list[str] | None
|
Column names actually present in the frame, included in the error message to help diagnose the mismatch. |
None
|
Examples:
>>> raise MissingDateColumnError("prices")
Traceback (most recent call last):
...
jquantstats.exceptions.MissingDateColumnError: ...
Source code in src/jquantstats/exceptions.py
__init__(frame_name, column=None, available=None)
¶
Initialize with the frame name and, optionally, the missing column and available columns.
Source code in src/jquantstats/exceptions.py
MuSchemaError
¶
Bases: JQuantStatsError, ValueError
Raised when a mu (expected-returns) frame doesn't match the portfolio's assets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
missing
|
list[str]
|
Portfolio asset columns absent from the mu frame. |
required |
Examples:
>>> raise MuSchemaError(["AAPL"])
Traceback (most recent call last):
...
jquantstats.exceptions.MuSchemaError: ...
Source code in src/jquantstats/exceptions.py
__init__(missing)
¶
Initialize with the asset columns missing from the mu frame.
Source code in src/jquantstats/exceptions.py
NegativeCostBpsError
¶
Bases: JQuantStatsError, ValueError
Raised when a trading cost in basis points is negative.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cost_bps
|
float
|
The negative cost value that was supplied. |
required |
Examples:
>>> raise NegativeCostBpsError(-1.0)
Traceback (most recent call last):
...
jquantstats.exceptions.NegativeCostBpsError: cost_bps must be non-negative, got -1.0.
Source code in src/jquantstats/exceptions.py
__init__(cost_bps)
¶
NoAssetColumnsError
¶
Bases: JQuantStatsError, ValueError
Raised when a DataFrame contains no numeric asset columns to aggregate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame_name
|
str
|
Descriptive name of the frame without asset columns (e.g. |
required |
Examples:
>>> raise NoAssetColumnsError("profits")
Traceback (most recent call last):
...
jquantstats.exceptions.NoAssetColumnsError: ...
Source code in src/jquantstats/exceptions.py
__init__(frame_name)
¶
Initialize with the name of the frame lacking asset columns.
Source code in src/jquantstats/exceptions.py
NoBenchmarkError
¶
Bases: JQuantStatsError, AttributeError
Raised when a benchmark-dependent statistic is requested without a benchmark.
Subclasses AttributeError so existing callers that catch
AttributeError for the no-benchmark path keep working unchanged.
Examples:
>>> raise NoBenchmarkError()
Traceback (most recent call last):
...
jquantstats.exceptions.NoBenchmarkError: No benchmark data available
Source code in src/jquantstats/exceptions.py
NonPositiveAumError
¶
Bases: JQuantStatsError, ValueError
Raised when aum is not strictly positive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
aum
|
float
|
The non-positive value that was supplied. |
required |
Examples:
>>> raise NonPositiveAumError(0.0)
Traceback (most recent call last):
...
jquantstats.exceptions.NonPositiveAumError: aum must be strictly positive, got 0.0.
Source code in src/jquantstats/exceptions.py
NonPositivePeriodsPerYearError
¶
Bases: JQuantStatsError, ValueError
Raised when periods_per_year is not strictly positive.
Examples:
>>> raise NonPositivePeriodsPerYearError()
Traceback (most recent call last):
...
jquantstats.exceptions.NonPositivePeriodsPerYearError: periods_per_year must be positive
Source code in src/jquantstats/exceptions.py
NonPositiveWindowError
¶
Bases: JQuantStatsError, ValueError
Raised when a rolling-window size is not a positive integer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
param
|
str
|
Name of the offending parameter (e.g. |
required |
Examples:
>>> raise NonPositiveWindowError("window")
Traceback (most recent call last):
...
jquantstats.exceptions.NonPositiveWindowError: window must be a positive integer
Source code in src/jquantstats/exceptions.py
__init__(param)
¶
Initialize with the name of the offending window parameter.
NullsInReturnsError
¶
Bases: JQuantStatsError, ValueError
Raised when null values are detected in returns (or benchmark) data.
Polars propagates null through calculations whereas pandas silently
drops NaN. Leaving nulls in place will cause most statistics to
return null instead of a numeric result.
Use the null_strategy parameter on from_returns
or from_prices to handle nulls automatically, or
clean the data before construction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame_name
|
str
|
Descriptive name of the frame that contains nulls
(e.g. |
required |
columns
|
list[str]
|
Names of the columns that contain at least one null. |
required |
Examples:
>>> raise NullsInReturnsError("returns", ["Asset1", "Asset2"])
Traceback (most recent call last):
...
jquantstats.exceptions.NullsInReturnsError: ...
Source code in src/jquantstats/exceptions.py
__init__(frame_name, columns)
¶
Initialize with the frame name and the columns that contain nulls.
Source code in src/jquantstats/exceptions.py
PositionExprColumnError
¶
Bases: JQuantStatsError, ValueError
Raised when a position expression creates columns that do not exist in prices.
Position expressions (cash_position, position, risk_position)
are evaluated against the prices frame and must overwrite existing asset
columns. An expression that creates a new column (e.g. via .alias)
leaves the original asset columns untouched, which would silently treat
raw prices as positions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
param
|
str
|
Name of the offending parameter (e.g. |
required |
extra
|
list[str]
|
Column names created by the expression that are absent from prices. |
required |
Examples:
>>> raise PositionExprColumnError("cash_position", ["A2"])
Traceback (most recent call last):
...
jquantstats.exceptions.PositionExprColumnError: ...
Source code in src/jquantstats/exceptions.py
__init__(param, extra)
¶
Initialize with the parameter name and the unexpected columns it created.
Source code in src/jquantstats/exceptions.py
RowCountMismatchError
¶
Bases: JQuantStatsError, ValueError
Raised when prices and cashposition have different numbers of rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prices_rows
|
int
|
Number of rows in the prices DataFrame. |
required |
cashposition_rows
|
int
|
Number of rows in the cashposition DataFrame. |
required |
Examples:
>>> raise RowCountMismatchError(10, 9)
Traceback (most recent call last):
...
jquantstats.exceptions.RowCountMismatchError: ...
Source code in src/jquantstats/exceptions.py
__init__(prices_rows, cashposition_rows)
¶
Initialize with the row counts of the two mismatched DataFrames.
Source code in src/jquantstats/exceptions.py
UncleanSeriesError
¶
Bases: JQuantStatsError, ValueError
Raised when a derived series contains null or non-finite values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the offending series (may be empty when unknown). |
required |
reason
|
str
|
Either |
required |
Examples:
>>> raise UncleanSeriesError("profit", "null")
Traceback (most recent call last):
...
jquantstats.exceptions.UncleanSeriesError: ...
Source code in src/jquantstats/exceptions.py
__init__(name, reason)
¶
Initialize with the series name and the kind of dirty value found.