portfolio_toolkit.math package

Submodules

portfolio_toolkit.math.get_log_returns module

portfolio_toolkit.math.get_log_returns.get_log_returns(price_series: Series) Series[source]

Calculates the logarithmic returns of a price series.

Parameters:

price_series (pd.Series) – Series of prices.

Returns:

Series of logarithmic returns.

Return type:

pd.Series

portfolio_toolkit.math.get_matrix_returns module

portfolio_toolkit.math.get_matrix_returns.get_matrix_returns(market_assets: List[MarketAsset]) DataFrame[source]

Creates a DataFrame of logarithmic returns from a list of MarketAsset objects.

Parameters:

market_assets (List[MarketAsset]) – List of MarketAsset objects, each containing a ‘price’ attribute as pd.Series with price data

Returns:

DataFrame where:
  • Rows are dates (datetime index from price series)

  • Columns are ticker symbols from MarketAsset.ticker

  • Values are logarithmic returns calculated using get_log_returns()

Return type:

pd.DataFrame

Example

>>> market_assets = [
...     MarketAsset(ticker="AAPL", price=aapl_prices),
...     MarketAsset(ticker="MSFT", price=msft_prices),
...     MarketAsset(ticker="GOOGL", price=googl_prices)
... ]
>>> returns_df = get_matrix_returns(market_assets)
>>> print(returns_df.head())

AAPL MSFT GOOGL

2023-01-01 NaN NaN NaN 2023-01-02 0.0123 0.0089 0.0156 2023-01-03 -0.0067 0.0034 -0.0023

Notes

  • First row will contain NaN values (no previous price for return calculation)

  • Uses get_log_returns() function for consistent logarithmic return calculation

  • Automatically aligns dates across all assets

  • Missing data points will appear as NaN in the resulting DataFrame

portfolio_toolkit.math.get_matrix_returns.get_matrix_returns_aligned(market_assets: List[MarketAsset], start_date: str = None, end_date: str = None) DataFrame[source]

Creates an aligned DataFrame of returns with optional date filtering.

Parameters:
  • market_assets – List of MarketAsset objects

  • start_date – Start date in ‘YYYY-MM-DD’ format (optional)

  • end_date – End date in ‘YYYY-MM-DD’ format (optional)

Returns:

Aligned returns DataFrame with only overlapping dates

Return type:

pd.DataFrame

Example

>>> # Get returns for specific period
>>> returns_df = get_matrix_returns_aligned(
...     market_assets,
...     start_date="2023-01-01",
...     end_date="2023-12-31"
... )

portfolio_toolkit.math.get_var module

portfolio_toolkit.math.get_var.get_covariance_matrix(returns_df: DataFrame) DataFrame[source]

Calculates the covariance matrix from a DataFrame of logarithmic returns.

This matrix is used for Value at Risk (VaR) calculations and portfolio optimization.

Parameters:

returns_df (pd.DataFrame) – DataFrame where: - Rows are dates (datetime index) - Columns are ticker symbols - Values are logarithmic returns for each asset

Returns:

Symmetric covariance matrix where:
  • Rows and columns are ticker symbols

  • Diagonal elements are variances

  • Off-diagonal elements are covariances

Return type:

pd.DataFrame

Example

>>> dates = pd.date_range('2023-01-01', periods=100, freq='D')
>>> returns_df = pd.DataFrame({
...     'AAPL': np.random.normal(0.001, 0.02, 100),
...     'MSFT': np.random.normal(0.0008, 0.018, 100),
...     'GOOGL': np.random.normal(0.0012, 0.025, 100)
... }, index=dates)
>>> cov_matrix = get_covariance_matrix(returns_df)
>>> print(cov_matrix)

Notes

  • Uses pandas .cov() method which calculates sample covariance

  • Automatically handles missing values (NaN) by pairwise deletion

  • Matrix is symmetric: cov(A,B) = cov(B,A)

  • Diagonal values are variances: cov(A,A) = var(A)

portfolio_toolkit.math.get_var.get_correlation_matrix(returns_df: DataFrame) DataFrame[source]

Calculates the correlation matrix from a DataFrame of logarithmic returns.

Parameters:

returns_df (pd.DataFrame) – DataFrame of returns (same format as get_covariance_matrix)

Returns:

Correlation matrix with values between -1 and 1

Return type:

pd.DataFrame

Example

>>> corr_matrix = get_correlation_matrix(returns_df)
portfolio_toolkit.math.get_var.get_portfolio_variance(weights: ndarray | Series, covariance_matrix: DataFrame) float[source]

Calculates portfolio variance using weights and covariance matrix.

Formula: σ²_p = w^T * Σ * w Where:

  • w = vector of portfolio weights

  • Σ = covariance matrix

  • σ²_p = portfolio variance

Parameters:
  • weights – Portfolio weights (must sum to 1)

  • covariance_matrix – Covariance matrix from get_covariance_matrix()

Returns:

Portfolio variance

Return type:

float

Example

>>> weights = np.array([0.4, 0.4, 0.2])  # 40% AAPL, 40% MSFT, 20% GOOGL
>>> portfolio_var = get_portfolio_variance(weights, cov_matrix)
portfolio_toolkit.math.get_var.get_portfolio_volatility(weights: ndarray | Series, covariance_matrix: DataFrame) float[source]

Calculates portfolio volatility (standard deviation).

Parameters:
  • weights – Portfolio weights

  • covariance_matrix – Covariance matrix

Returns:

Portfolio volatility (sqrt of variance)

Return type:

float

portfolio_toolkit.math.get_var.calculate_var(weights: ndarray | Series, covariance_matrix: DataFrame, portfolio_value: float = 1000000, confidence_level: float = 0.95, time_horizon: int = 1) float[source]

Calculates Value at Risk (VaR) for a portfolio using parametric method.

VaR represents the maximum expected loss over a given time horizon at a specified confidence level, assuming normal distribution of returns.

Formula: VaR = -z_α * σ_p * √t * V Where:

  • z_α = z-score for confidence level (e.g., -1.645 for 95%)

  • σ_p = portfolio volatility (daily)

  • t = time horizon in days

  • V = portfolio value

Parameters:
  • weights – Portfolio weights (must sum to 1)

  • covariance_matrix – Covariance matrix of asset returns

  • portfolio_value – Total portfolio value in monetary units (default: 1,000,000)

  • confidence_level – Confidence level as decimal (default: 0.95 = 95%)

  • time_horizon – Time horizon in days (default: 1 day)

Returns:

Value at Risk in monetary units (positive value represents potential loss)

Return type:

float

Example

>>> weights = np.array([0.4, 0.4, 0.2])
>>> cov_matrix = get_covariance_matrix(returns_df)
>>> var_95 = calculate_var(weights, cov_matrix, portfolio_value=1000000)
>>> print(f"1-day VaR at 95% confidence: ${var_95:,.2f}")
>>> # 10-day VaR at 99% confidence
>>> var_99_10d = calculate_var(weights, cov_matrix,
...                          portfolio_value=1000000,
...                          confidence_level=0.99,
...                          time_horizon=10)

Notes

  • Assumes normal distribution of returns (parametric VaR)

  • Uses daily volatility from covariance matrix

  • Higher confidence levels give higher VaR values

  • Longer time horizons give higher VaR values (scales with √time)

  • Returns positive value representing potential loss

portfolio_toolkit.math.get_var.calculate_expected_shortfall(weights: ndarray | Series, covariance_matrix: DataFrame, portfolio_value: float = 1000000, confidence_level: float = 0.95, time_horizon: int = 1) float[source]

Calculates Expected Shortfall (ES) / Conditional Value at Risk (CVaR).

ES represents the expected loss given that the loss exceeds the VaR threshold. It provides information about tail risk beyond VaR.

Parameters:
  • weights – Portfolio weights

  • covariance_matrix – Covariance matrix of asset returns

  • portfolio_value – Portfolio value in monetary units

  • confidence_level – Confidence level (default: 0.95)

  • time_horizon – Time horizon in days (default: 1)

Returns:

Expected Shortfall in monetary units

Return type:

float

Example

>>> es_95 = calculate_expected_shortfall(weights, cov_matrix)
>>> print(f"Expected Shortfall at 95%: ${es_95:,.2f}")

Module contents