API Reference

finsim package

Subpackages

finsim.data package

Submodules

finsim.data.finnhub module

class finsim.data.finnhub.FinnHubStockReader(token)[source]

Bases: object

A class to read stock data from FinnHub API.

Parameters:

token (str)

get_all_US_symbols()[source]

Get all US stock symbols from FinnHub.

Returns:

A list of dictionaries containing stock symbol information

Return type:

list[dict[str, Any]]

get_stock_candlestick(symbol, startdate, enddate)[source]

Get stock candlestick data for a given symbol and date range.

Parameters:
  • symbol (str) – The stock symbol

  • startdate (str) – The start date in ‘YYYY-MM-DD’ format

  • enddate (str) – The end date in ‘YYYY-MM-DD’ format

Returns:

TimeStamp, High, Low, Open, Close, Volume

Return type:

A DataFrame containing the candlestick data with columns

Raises:

Exception – If the API request fails

finsim.data.preader module

finsim.data.preader.dataframe_to_hdf(df, filepath, key)[source]

Save a DataFrame to an HDF file.

Parameters:
  • df (DataFrame) – The DataFrame to save

  • filepath (PathLike | str) – Path to the HDF file

  • key (str) – Key to store the DataFrame under

Return type:

None

finsim.data.preader.extract_batch_online_yahoofinance_data(symbols, startdate, enddate, threads=True)[source]

Extract stock data for multiple symbols from Yahoo Finance in batch.

Parameters:
  • symbols (list[str]) – List of stock symbols to retrieve

  • startdate (str) – Start date in ‘YYYY-MM-DD’ format

  • enddate (str) – End date in ‘YYYY-MM-DD’ format

  • threads (bool) – Whether to use threading for parallel downloads

Returns:

A dictionary mapping symbols to DataFrames containing stock data

Return type:

dict[str, DataFrame]

finsim.data.preader.extract_online_yahoofinance_data(symbol, startdate, enddate)[source]

Extract stock data for a single symbol from Yahoo Finance.

Parameters:
  • symbol (str) – The stock symbol to retrieve

  • startdate (str) – Start date in ‘YYYY-MM-DD’ format

  • enddate (str) – End date in ‘YYYY-MM-DD’ format

Returns:

TimeStamp, High, Low, Open, Close, Adj Close, Volume

Return type:

A DataFrame containing the stock data with columns

finsim.data.preader.finding_missing_symbols_in_cache(symbols, startdate, enddate, cacheddir)[source]

Find symbols that are missing from the cache.

Parameters:
  • symbols (list[str]) – List of stock symbols

  • startdate (str) – Start date in ‘YYYY-MM-DD’ format

  • enddate (str) – End date in ‘YYYY-MM-DD’ format

  • cacheddir (str | PathLike) – Directory for caching data

Returns:

List of symbols missing from cache

Return type:

list[str]

finsim.data.preader.generating_cached_yahoofinance_data(symbols, startdate, enddate, cacheddir, slicebatch=50, waittime=1, yfinance_multithreads=False, io_multithreads=False)[source]

Generate cached Yahoo Finance data for a list of symbols.

Parameters:
  • symbols (list[str]) – List of stock symbols

  • startdate (str) – Start date in ‘YYYY-MM-DD’ format

  • enddate (str) – End date in ‘YYYY-MM-DD’ format

  • cacheddir (PathLike | str) – Directory for caching data

  • slicebatch (int) – Number of symbols to process in each batch (default: 50)

  • waittime (int) – Time to wait between batches in seconds (default: 1)

  • yfinance_multithreads (bool) – Whether to use multithreading for yfinance (default: False)

  • io_multithreads (bool) – Whether to use multithreading for I/O operations (default: False)

Return type:

None

finsim.data.preader.get_dividends_df(symbol)[source]

Get dividend data for a symbol.

Parameters:

symbol (str) – The stock symbol

Returns:

A DataFrame containing dividend data with columns TimeStamp and Dividends

Return type:

DataFrame

finsim.data.preader.get_symbol_closing_price(symbol, datestr, epsilon=1e-10, cacheddir=None, backtrack=False)[source]

Get the closing price for a symbol on a specific date.

Parameters:
  • symbol (str) – The stock symbol

  • datestr (str) – The date in ‘YYYY-MM-DD’ format

  • epsilon (float) – Small value for numerical precision (default: 1e-10)

  • cacheddir (str | PathLike | None) – Directory for caching data (optional)

  • backtrack (bool) – Whether to backtrack to previous days if price not found

Returns:

The closing price for the symbol on the specified date

Raises:

IndexError – If price is not found and backtrack is False

Return type:

float

finsim.data.preader.get_yahoofinance_data(symbol, startdate, enddate, cacheddir=None)[source]

Get Yahoo Finance data for a symbol, with optional caching.

Parameters:
  • symbol (str) – The stock symbol to retrieve

  • startdate (str) – Start date in ‘YYYY-MM-DD’ format

  • enddate (str) – End date in ‘YYYY-MM-DD’ format

  • cacheddir (str | PathLike | None) – Directory for caching data (optional)

Returns:

A DataFrame containing the stock data

Return type:

DataFrame

finsim.data.quandl module

class finsim.data.quandl.QuandlReader(token)[source]

Bases: object

A class to read financial data from Quandl.

Parameters:

token (str)

get_treasury_longterm_rates()[source]

Get Treasury long-term rates.

Returns:

A DataFrame containing Treasury long-term rates

Return type:

DataFrame

get_treasury_real_longterm_rates()[source]

Get Treasury real long-term rates.

Returns:

A DataFrame containing Treasury real long-term rates

Return type:

DataFrame

get_treasury_real_yield_curve_rates()[source]

Get Treasury real yield curve rates.

Returns:

A DataFrame containing Treasury real yield curve rates

Return type:

DataFrame

get_treasury_yield_curve_rates()[source]

Get Treasury yield curve rates.

Returns:

A DataFrame containing Treasury yield curve rates

Return type:

DataFrame

finsim.estimate package

Submodules

finsim.estimate.fit module

finsim.estimate.fit.fit_BlackScholesMerton_model(timestamps, prices, unit='year')[source]

Fit a Black-Scholes-Merton model to price data to estimate rate of return and volatility.

This function estimates the parameters of the Black-Scholes-Merton model, which describes the dynamics of a financial asset. It calculates the expected rate of return and volatility from historical price data.

Parameters:
  • timestamps (Annotated[ndarray[tuple[int, ...], dtype[datetime64]], Literal['1D array']]) – Array of timestamps corresponding to price observations

  • prices (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of asset prices corresponding to the timestamps

  • unit (Literal['second', 'minute', 'hour', 'day', 'year']) – Time unit for calculations. Options are ‘second’, ‘minute’, ‘hour’, ‘day’, ‘year’. Default is ‘year’.

Returns:

  • rate (float): Estimated rate of return (drift parameter)

  • sigma (float): Estimated volatility (diffusion parameter)

Return type:

Tuple containing

Note

The function internally converts timestamps to seconds and then to the specified unit. The calculation uses the Python implementation of the Black-Scholes-Merton model.

finsim.estimate.fit.fit_multivariate_BlackScholesMerton_model(timestamps, multiprices, unit='year')[source]

Fit a multivariate Black-Scholes-Merton model to price data for multiple assets.

This function estimates the parameters of the multivariate Black-Scholes-Merton model, which describes the dynamics of multiple financial assets and their correlations.

Parameters:
  • timestamps (Annotated[ndarray[tuple[int, ...], dtype[datetime64]], Literal['1D array']]) – Array of timestamps corresponding to price observations

  • multiprices (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – 2D array of asset prices for multiple assets. Each row represents a different asset, and each column represents prices at a specific time

  • unit (Literal['second', 'minute', 'hour', 'day', 'year']) – Time unit for calculations. Options are ‘second’, ‘minute’, ‘hour’, ‘day’, ‘year’. Default is ‘year’.

Returns:

  • rates (NDArray[Shape[“*”], Float]): Array of estimated rates of return for each asset

  • covariance_matrix (NDArray[Shape[”*, *”], Float]): Estimated covariance matrix of returns

Return type:

Tuple containing

Note

The function internally converts timestamps to seconds and then to the specified unit. The calculation uses the Python implementation of the multivariate Black-Scholes-Merton model.

finsim.estimate.fit.fit_timeweighted_BlackScholesMerton_model(timestamps, prices, weights, unit='year')[source]

Fit a time-weighted Black-Scholes-Merton model to price data.

This function estimates the parameters of the Black-Scholes-Merton model using time-weighted observations, giving different importance to different time periods.

Parameters:
  • timestamps (Annotated[ndarray[tuple[int, ...], dtype[datetime64]], Literal['1D array']]) – Array of timestamps corresponding to price observations

  • prices (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of asset prices corresponding to the timestamps

  • weights (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of weights for time-weighted calculations (same length as timestamps)

  • unit (Literal['second', 'minute', 'hour', 'day', 'year']) – Time unit for calculations. Options are ‘second’, ‘minute’, ‘hour’, ‘day’, ‘year’. Default is ‘year’.

Returns:

  • rate (float): Time-weighted estimated rate of return

  • sigma (float): Time-weighted estimated volatility

Return type:

Tuple containing

finsim.estimate.fit.fit_timeweighted_multivariate_BlackScholesMerton_model(timestamps, multiprices, weights, unit='year')[source]

Fit a time-weighted multivariate Black-Scholes-Merton model to price data for multiple assets.

This function estimates the parameters of the multivariate Black-Scholes-Merton model using time-weighted observations for multiple assets.

Parameters:
  • timestamps (Annotated[ndarray[tuple[int, ...], dtype[datetime64]], Literal['1D array']]) – Array of timestamps corresponding to price observations

  • multiprices (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['2D array']]) – 2D array of asset prices for multiple assets. Each row represents a different asset, and each column represents prices at a specific time

  • weights (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of weights for time-weighted calculations (same length as timestamps)

  • unit (Literal['second', 'minute', 'hour', 'day', 'year']) – Time unit for calculations. Options are ‘second’, ‘minute’, ‘hour’, ‘day’, ‘year’. Default is ‘year’.

Returns:

  • rates (NDArray[Shape[“*”], Float]): Array of time-weighted estimated rates of return

  • covariance_matrix (NDArray[Shape[”*, *”], Float]): Time-weighted estimated covariance matrix

Return type:

Tuple containing

finsim.estimate.risk module

finsim.estimate.risk.estimate_beta(timestamps, prices, market_prices, unit='year')[source]

Estimate the beta coefficient of an asset relative to market performance.

Beta measures the sensitivity of an asset’s returns to market returns. A beta of 1 indicates the asset moves in line with the market, while a beta greater than 1 indicates higher volatility than the market.

Parameters:
  • timestamps (Annotated[ndarray[tuple[int, ...], dtype[datetime64]], Literal['1D array']]) – Array of timestamps corresponding to price observations

  • prices (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of asset prices corresponding to the timestamps

  • market_prices (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of market index prices corresponding to the timestamps

  • unit (Literal['second', 'minute', 'hour', 'day', 'year']) – Time unit for calculations. Options are ‘second’, ‘minute’, ‘hour’, ‘day’, ‘year’. Default is ‘year’.

Returns:

The estimated beta coefficient

Return type:

float

Note

The function uses linear regression to calculate beta, where the slope of the regression line represents the beta coefficient.

finsim.estimate.risk.estimate_downside_risk(timestamps, prices, target_return, unit='year')[source]

Estimate the downside risk of an asset based on historical price data.

Downside risk measures the volatility of returns that fall below a target return, focusing on negative deviations rather than total volatility.

Parameters:
  • timestamps (Annotated[ndarray[tuple[int, ...], dtype[datetime64]], Literal['1D array']]) – Array of timestamps corresponding to price observations

  • prices (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of asset prices corresponding to the timestamps

  • target_return (float) – The target return threshold for calculating downside risk

  • unit (Literal['second', 'minute', 'hour', 'day', 'year']) – Time unit for calculations. Options are ‘second’, ‘minute’, ‘hour’, ‘day’, ‘year’. Default is ‘year’.

Returns:

The estimated downside risk (standard deviation of returns below target)

Return type:

float

Note

The function internally converts timestamps to seconds and then to the specified unit. The calculation uses the Python implementation of downside risk estimation.

finsim.estimate.risk.estimate_upside_risk(timestamps, prices, target_return, unit='year')[source]

Estimate the upside risk of an asset based on historical price data.

Upside risk measures the volatility of returns that exceed a target return, focusing on positive deviations above a minimum acceptable return.

Parameters:
  • timestamps (Annotated[ndarray[tuple[int, ...], dtype[datetime64]], Literal['1D array']]) – Array of timestamps corresponding to price observations

  • prices (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of asset prices corresponding to the timestamps

  • target_return (float) – The target return threshold for calculating upside risk

  • unit (Literal['second', 'minute', 'hour', 'day', 'year']) – Time unit for calculations. Options are ‘second’, ‘minute’, ‘hour’, ‘day’, ‘year’. Default is ‘year’.

Returns:

The estimated upside risk (standard deviation of returns above target)

Return type:

float

Note

The function internally converts timestamps to seconds and then to the specified unit. The calculation uses the Python implementation of upside risk estimation.

finsim.estimate.constants module

Subpackages

finsim.estimate.native package

Submodules

finsim.estimate.native.pyfit module

finsim.estimate.native.pyfit.python_fit_BlackScholesMerton_model(ts, prices)[source]

Fit a Black-Scholes-Merton model to price data using Python implementation.

This function estimates the parameters of the Black-Scholes-Merton model, which describes the dynamics of a financial asset. It calculates the expected rate of return and volatility from historical price data.

Parameters:
  • ts (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of time values (converted to specified unit)

  • prices (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of asset prices corresponding to the time values

Returns:

  • r (float): Estimated rate of return (drift parameter)

  • sigma (float): Estimated volatility (diffusion parameter)

Return type:

Tuple containing

finsim.estimate.native.pyfit.python_fit_multivariate_BlackScholesMerton_model(ts, multiprices)[source]

Fit a multivariate Black-Scholes-Merton model to price data for multiple assets.

This function estimates the parameters of the multivariate Black-Scholes-Merton model, which describes the dynamics of multiple financial assets and their correlations.

Parameters:
  • ts (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of time values (converted to specified unit)

  • multiprices (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['2D array']]) – 2D array of asset prices for multiple assets. Each row represents a different asset, and each column represents prices at a specific time

Returns:

  • r (NDArray[Shape[“*”], Float]): Array of estimated rates of return for each asset

  • cov (NDArray[Shape[”*, *”], Float]): Estimated covariance matrix of returns

Return type:

Tuple containing

finsim.estimate.native.pyrisk module

finsim.estimate.native.pyrisk.python_estimate_downside_risk(ts, prices, target_return)[source]

Estimate the downside risk of an asset based on historical price data.

Downside risk measures the volatility of returns that fall below a target return, focusing on negative deviations rather than total volatility.

Parameters:
  • ts (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of time values (converted to specified unit)

  • prices (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of asset prices corresponding to the time values

  • target_return (float) – The target return threshold for calculating downside risk

Returns:

The estimated downside risk (standard deviation of returns below target)

Return type:

float

finsim.estimate.native.pyrisk.python_estimate_upside_risk(ts, prices, target_return)[source]

Estimate the upside risk of an asset based on historical price data.

Upside risk measures the volatility of returns that exceed a target return, focusing on positive deviations above a minimum acceptable return.

Parameters:
  • ts (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of time values (converted to specified unit)

  • prices (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of asset prices corresponding to the time values

  • target_return (float) – The target return threshold for calculating upside risk

Returns:

The estimated upside risk (standard deviation of returns above target)

Return type:

float

finsim.portfolio package

Submodules

finsim.portfolio.create module

finsim.portfolio.create.get_exponential_timeweightdf(startdate, enddate, yearscale)[source]

Generate exponential time weights for portfolio optimization.

This function creates a DataFrame with exponentially decaying weights over time, which can be used for time-weighted portfolio optimization.

Parameters:
  • startdate (str) – Start date in ‘YYYY-MM-DD’ format

  • enddate (str) – End date in ‘YYYY-MM-DD’ format

  • yearscale (float) – Time scale parameter for exponential decay

Returns:

DataFrame with ‘TimeStamp’ and ‘weight’ columns

Return type:

pd.DataFrame

finsim.portfolio.create.get_optimized_exponential_timeweighted_portfolio_on_mpt_entropy_costfunction(rf, symbols, totalworth, presetdate, estimating_startdate, estimating_enddate, yearscale, lamb0, lamb1, V=10.0, cacheddir=None, include_dividends=False)[source]

Create an optimized time-weighted portfolio using exponential weights and entropy cost function.

This function creates a portfolio optimized using an entropy cost function approach from Modern Portfolio Theory (MPT) with exponential time weighting. It estimates asset returns and covariances using the Black-Scholes-Merton model with time weights and then optimizes weights using an entropy cost function.

Parameters:
  • rf (float) – Risk-free rate

  • symbols (list[str]) – List of stock symbols to include in the portfolio

  • totalworth (float) – Total value of the portfolio

  • presetdate (str) – Date for which to calculate the portfolio composition

  • estimating_startdate (str) – Start date for return estimation

  • estimating_enddate (str) – End date for return estimation

  • yearscale (float) – Time scale parameter for exponential decay

  • lamb0 (float) – Lambda 0 parameter for the entropy cost function

  • lamb1 (float) – Lambda 1 parameter for the entropy cost function

  • V (float) – Portfolio value parameter (default: 10.0)

  • cacheddir (str | PathLike | None) – Directory for cached data (optional)

  • include_dividends (bool) – Whether to include dividends in calculations (default: False)

Returns:

An optimized time-weighted portfolio object with calculated weights

Return type:

OptimizedPortfolio

finsim.portfolio.create.get_optimized_portfolio_on_mpt_costfunction(rf, symbols, totalworth, presetdate, estimating_startdate, estimating_enddate, lamb, V0=10.0, cacheddir=None, include_dividends=False)[source]

Create an optimized portfolio based on the MPT cost function optimization method.

This function creates a portfolio optimized using a cost function approach from Modern Portfolio Theory (MPT). It estimates asset returns and covariances using the Black-Scholes-Merton model and then optimizes weights using a cost function.

Parameters:
  • rf (float) – Risk-free rate

  • symbols (list[str]) – List of stock symbols to include in the portfolio

  • totalworth (float) – Total value of the portfolio

  • presetdate (str) – Date for which to calculate the portfolio composition

  • estimating_startdate (str) – Start date for return estimation

  • estimating_enddate (str) – End date for return estimation

  • lamb (float) – Lambda parameter for the cost function

  • V0 (float) – Initial portfolio value (default: 10.0)

  • cacheddir (str | PathLike | None) – Directory for cached data (optional)

  • include_dividends (bool) – Whether to include dividends in calculations (default: False)

Returns:

An optimized portfolio object with calculated weights

Return type:

OptimizedPortfolio

finsim.portfolio.create.get_optimized_portfolio_on_mpt_entropy_costfunction(rf, symbols, totalworth, presetdate, estimating_startdate, estimating_enddate, lamb0, lamb1, V=10.0, cacheddir=None, include_dividends=False)[source]

Create an optimized portfolio based on the MPT entropy cost function optimization method.

This function creates a portfolio optimized using an entropy cost function approach from Modern Portfolio Theory (MPT). It estimates asset returns and covariances using the Black-Scholes-Merton model and then optimizes weights using an entropy cost function.

Parameters:
  • rf (float) – Risk-free rate

  • symbols (list[str]) – List of stock symbols to include in the portfolio

  • totalworth (float) – Total value of the portfolio

  • presetdate (str) – Date for which to calculate the portfolio composition

  • estimating_startdate (str) – Start date for return estimation

  • estimating_enddate (str) – End date for return estimation

  • lamb0 (float) – Lambda 0 parameter for the entropy cost function

  • lamb1 (float) – Lambda 1 parameter for the entropy cost function

  • V (float) – Portfolio value parameter (default: 10.0)

  • cacheddir (str | PathLike | None) – Directory for cached data (optional)

  • include_dividends (bool) – Whether to include dividends in calculations (default: False)

Returns:

An optimized portfolio object with calculated weights

Return type:

OptimizedPortfolio

finsim.portfolio.create.get_optimized_portfolio_on_sharpe_ratio(rf, symbols, totalworth, presetdate, estimating_startdate, estimating_enddate, minweight=0.0, lazy=False, cacheddir=None, include_dividends=False)[source]

Create an optimized portfolio based on the Sharpe ratio optimization method.

This function creates a portfolio optimized using the Sharpe ratio maximization approach from Modern Portfolio Theory (MPT). It estimates asset returns and covariances using the Black-Scholes-Merton model and then optimizes weights to maximize the Sharpe ratio.

Parameters:
  • rf (float) – Risk-free rate

  • symbols (list[str]) – List of stock symbols to include in the portfolio

  • totalworth (float) – Total value of the portfolio

  • presetdate (str) – Date for which to calculate the portfolio composition

  • estimating_startdate (str) – Start date for return estimation

  • estimating_enddate (str) – End date for return estimation

  • minweight (float) – Minimum weight for each asset (default: 0.0)

  • lazy (bool) – Deprecated parameter (default: False)

  • cacheddir (str | PathLike | None) – Directory for cached data (optional)

  • include_dividends (bool) – Whether to include dividends in calculations (default: False)

Returns:

An optimized portfolio object with calculated weights

Return type:

OptimizedPortfolio

finsim.portfolio.dynamic module

class finsim.portfolio.dynamic.DynamicPortfolio(symbol_nbshares, current_date, cacheddir=None)[source]

Bases: Portfolio

A class representing a dynamic portfolio that can change over time.

This class extends the basic Portfolio class to support time-series operations on portfolios, allowing for tracking of portfolio changes over time and performing trades at specific dates.

Parameters:
dumps_json()[source]

Serialize the dynamic portfolio to a JSON string.

Returns:

JSON string representation of the dynamic portfolio

Return type:

str

find_cursor_for_date(date)[source]

Find the index of the time series entry for a given date.

Parameters:

date (str) – Date in ‘YYYY-MM-DD’ format

Returns:

Index of the time series entry for the given date

Return type:

int

generate_dynamic_portfolio_dict()[source]

Generate a dictionary representation of the dynamic portfolio.

Returns:

Dictionary representation of the dynamic portfolio

Return type:

dict[str, Any]

get_portfolio_value(datestr)[source]

Calculate the total value of the portfolio on a specific date.

Parameters:

datestr (str) – Date in ‘YYYY-MM-DD’ format

Returns:

Total portfolio value on the specified date

Return type:

float

get_portfolio_values_overtime(startdate, enddate, cacheddir=None, progressbar=False)[source]

Calculate the portfolio value over a time period.

Parameters:
  • startdate (str) – Start date in ‘YYYY-MM-DD’ format

  • enddate (str) – End date in ‘YYYY-MM-DD’ format

  • cacheddir (str | PathLike | None) – Directory for cached data (optional)

  • progressbar (bool) – Whether to show a progress bar (default: False)

Returns:

DataFrame with ‘TimeStamp’ and ‘value’ columns

Return type:

pd.DataFrame

is_sorted()[source]

Check if the time series is sorted by date.

Returns:

True if the time series is sorted, False otherwise

Return type:

bool

classmethod load_from_dict(dynportdict, cacheddir=None)[source]

Load a dynamic portfolio from a dictionary.

Parameters:
  • dynportdict (dict[str, Any]) – Dictionary representation of the dynamic portfolio

  • cacheddir (str | PathLike | None) – Directory for cached data (optional)

Returns:

A new DynamicPortfolio object loaded from the dictionary

Return type:

Self

classmethod load_from_json(fileobj, cacheddir=None)[source]

Load a dynamic portfolio from a JSON file.

Parameters:
  • fileobj (TextIOWrapper) – File object to read the portfolio data from

  • cacheddir (str | PathLike | None) – Directory for cached data (optional)

Returns:

A new DynamicPortfolio object loaded from the JSON file

Return type:

Self

move_cursor_to_date(newdate)[source]

Move the cursor to a specific date.

Parameters:

newdate (str) – Date in ‘YYYY-MM-DD’ format

Return type:

None

save_to_json(fileobj)[source]

Save the dynamic portfolio to a JSON file.

Parameters:

fileobj (TextIOWrapper) – File object to write the portfolio data to

Return type:

None

sort_time_series()[source]

Sort the time series by date.

Return type:

None

trade(trade_date, buy_stocks=None, sell_stocks=None, check_valid=False, raise_insufficient_stock_error=False)[source]

Perform a trade on a specific date.

Parameters:
  • trade_date (str) – Date of the trade in ‘YYYY-MM-DD’ format

  • buy_stocks (dict[str, float | int] | None) – Dictionary mapping symbols to number of shares to buy (optional)

  • sell_stocks (dict[str, float | int] | None) – Dictionary mapping symbols to number of shares to sell (optional)

  • check_valid (bool) – Whether to check if the trade is valid (default: False)

  • raise_insufficient_stock_error (bool) – Whether to raise an error for insufficient stocks (default: False)

Return type:

None

class finsim.portfolio.dynamic.DynamicPortfolioWithDividends(symbol_nbshares, current_date, cash=0.0, cacheddir=None)[source]

Bases: DynamicPortfolio

A class representing a dynamic portfolio that includes dividend calculations.

This class extends the DynamicPortfolio class to include calculations for dividends received over time, providing a more complete picture of portfolio performance.

Parameters:
calculate_cash_from_dividends(enddate)[source]

Calculate cash from dividends received over time.

Parameters:

enddate (str) – End date for dividend calculations in ‘YYYY-MM-DD’ format

Return type:

None

get_portfolio_values_overtime(startdate, enddate, cacheddir=None, progressbar=False)[source]

Calculate the portfolio value over a time period, including dividends.

Parameters:
  • startdate (str) – Start date in ‘YYYY-MM-DD’ format

  • enddate (str) – End date in ‘YYYY-MM-DD’ format

  • cacheddir (str | PathLike | None) – Directory for cached data (optional)

  • progressbar (bool) – Whether to show a progress bar (default: False)

Returns:

DataFrame with ‘TimeStamp’, ‘stock_value’, ‘cash’, and ‘value’ columns

Return type:

pd.DataFrame

finsim.portfolio.helper module

exception finsim.portfolio.helper.InsufficientSharesException[source]

Bases: Exception

Exception raised when there are insufficient shares for a transaction.

finsim.portfolio.helper.align_timestamps_stock_dataframes(stocks_data_dfs, timestamps_as_index=False)[source]

Align multiple stock data DataFrames to have consistent timestamps.

This function takes a list of stock data DataFrames and aligns their timestamps to ensure they all have the same time points, filling in missing data with forward-filled values.

Parameters:
  • stocks_data_dfs (list[DataFrame]) – List of stock data DataFrames to align

  • timestamps_as_index (bool) – Whether to use timestamps as the DataFrame index (default: False)

Returns:

List of aligned stock data DataFrames

Return type:

pd.DataFrame

finsim.portfolio.portfolio module

class finsim.portfolio.portfolio.OptimizedPortfolio(policy, totalworth, presetdate, cacheddir=None)[source]

Bases: Portfolio

A class representing an optimized portfolio of financial assets.

This class extends the basic Portfolio class to include optimization features based on Modern Portfolio Theory, with methods for calculating optimal weights and portfolio metrics.

Parameters:
compute()[source]

Compute the optimized portfolio composition.

This method calculates the number of shares for each asset based on the optimization policy and the total portfolio value.

Return type:

None

property correlation_matrix: Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['2D array']]

Get the correlation matrix of the optimized portfolio.

Returns:

Correlation matrix of the portfolio

Return type:

Annotated[NDArray[np.float64], Literal[“2D array”]]

dumps_json()[source]

Serialize the optimized portfolio to a JSON string.

Returns:

JSON string representation of the portfolio

Return type:

str

get_portfolio()[source]

Get the underlying Portfolio object.

Returns:

The underlying Portfolio object

Return type:

Portfolio

classmethod load_from_dict(portdict, cacheddir=None)[source]

Load an optimized portfolio from a dictionary.

Note: This method is not implemented for OptimizedPortfolio. Use Portfolio.load_from_dict instead.

Parameters:
  • portdict (TextIOWrapper) – Dictionary mapping symbols to number of shares

  • cacheddir (str | PathLike | None) – Directory for cached data (optional)

Raises:

NotImplementedError – Always raised as this method is not implemented

Return type:

Self

classmethod load_from_json(fileobj, cacheddir=None)[source]

Load an optimized portfolio from a JSON file.

Note: This method is not implemented for OptimizedPortfolio. Use Portfolio.load_from_json instead.

Parameters:
  • fileobj (TextIOWrapper) – File object to read the portfolio data from

  • cacheddir (str | PathLike | None) – Directory for cached data (optional)

Raises:

NotImplementedError – Always raised as this method is not implemented

Return type:

Self

property named_correlation_matrix: DataFrame

Get the named correlation matrix of the optimized portfolio.

Returns:

Named correlation matrix of the portfolio

Return type:

pd.DataFrame

property portfolio_summary: dict[str, Any]

Get a summary of the optimized portfolio.

Returns:

Dictionary containing portfolio summary information

Return type:

dict[str, Any]

property portfolio_symbols: list[str]

Get the list of symbols in the portfolio.

Returns:

List of symbols in the portfolio

Return type:

list[str]

property portfolio_yield: float

Get the expected yield of the optimized portfolio.

Returns:

Expected yield of the portfolio

Return type:

float

save_to_json(fileobj)[source]

Save the optimized portfolio to a JSON file.

Parameters:

fileobj (TextIOWrapper) – File object to write the portfolio data to

Return type:

None

property volatility: float

Get the volatility of the optimized portfolio.

Returns:

Volatility of the portfolio

Return type:

float

property weights: Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]

Get the optimized weights for each asset.

Returns:

Array of optimized weights

Return type:

Annotated[NDArray[np.float64], Literal[“1D array”]]

class finsim.portfolio.portfolio.Portfolio(symbols_nbshares, cacheddir=None)[source]

Bases: object

A class representing a portfolio of financial assets.

This class manages a collection of assets (stocks) with their respective quantities and provides methods for calculating portfolio values, performing operations on portfolios, and saving/loading portfolio data.

Parameters:
__add__(other)[source]

Add two portfolios together.

This method combines two portfolios by adding the quantities of the same assets.

Parameters:

other (Self) – Another Portfolio object to add to this one

Returns:

A new Portfolio object representing the combined portfolios

Return type:

Self

__eq__(other)[source]

Check if two portfolios are equal.

This method compares two portfolios to see if they have the same assets and quantities.

Parameters:

other (Self) – Another Portfolio object to compare with this one

Returns:

True if portfolios are equal, False otherwise

Return type:

bool

__mul__(other)[source]

Multiply the portfolio by a scalar factor.

This method creates a new portfolio with the number of shares for each asset multiplied by the specified factor.

Parameters:

other (int | float) – The factor by which to multiply the number of shares

Returns:

A new Portfolio object with multiplied share quantities

Return type:

Self

__ne__(other)[source]

Check if two portfolios are not equal.

This method compares two portfolios to see if they have different assets or quantities.

Parameters:

other (Self) – Another Portfolio object to compare with this one

Returns:

True if portfolios are not equal, False otherwise

Return type:

bool

__rmul__(other)[source]

Multiply the portfolio by a scalar factor.

This method creates a new portfolio with the number of shares for each asset multiplied by the specified factor.

Parameters:

other (int | float) – The factor by which to multiply the number of shares

Returns:

A new Portfolio object with multiplied share quantities

Return type:

Self

__sub__(other)[source]

Subtract one portfolio from another.

This method subtracts the quantities of assets in one portfolio from another.

Parameters:

other (Self) – Another Portfolio object to subtract from this one

Returns:

A new Portfolio object representing the difference between portfolios

Return type:

Self

dumps_json()[source]

Serialize the portfolio to a JSON string.

Returns:

JSON string representation of the portfolio

Return type:

str

get_portfolio_value(datestr)[source]

Calculate the total value of the portfolio on a specific date.

Parameters:

datestr (str) – Date in ‘YYYY-MM-DD’ format

Returns:

Total portfolio value on the specified date

Return type:

float

get_portfolio_values_overtime(startdate, enddate, cacheddir=None, progressbar=False)[source]
Parameters:
Return type:

DataFrame

classmethod load_from_dict(portdict, cacheddir=None)[source]

Load a portfolio from a dictionary.

Parameters:
  • portdict (dict[str, int | float]) – Dictionary mapping symbols to number of shares

  • cacheddir (str | PathLike | None) – Directory for cached data (optional)

Returns:

A new Portfolio object loaded from the dictionary

Return type:

Self

classmethod load_from_json(fileobj, cacheddir=None)[source]

Load a portfolio from a JSON file.

Parameters:
  • fileobj (TextIOWrapper) – File object to read the portfolio data from

  • cacheddir (str | PathLike | None) – Directory for cached data (optional)

Returns:

A new Portfolio object loaded from the JSON file

Return type:

Self

multiply(factor)[source]

Multiply the number of shares for all assets by a factor.

This method modifies the portfolio in-place by multiplying the number of shares for each asset by the specified factor.

Parameters:

factor (float) – The factor by which to multiply the number of shares

Return type:

None

property portfolio_symbols_nbshares: dict[str, int | float]

Get the dictionary of symbols and number of shares.

Returns:

Dictionary mapping symbols to number of shares

Return type:

dict[str, Union[int, float]]

roundoff_nbshares()[source]

Round off the number of shares for all assets to the nearest integer.

This method modifies the portfolio in-place by rounding the number of shares for each asset to the nearest integer.

Return type:

None

save_to_json(fileobj)[source]

Save the portfolio to a JSON file.

Parameters:

fileobj (TextIOWrapper) – File object to write the portfolio data to

Return type:

None

Subpackages

finsim.portfolio.optimize package

Submodules

finsim.portfolio.optimize.metrics module

finsim.portfolio.optimize.metrics.mpt_costfunction(weights, r, cov, rf, lamb, V0=10.0)[source]

Calculate the MPT cost function for a portfolio.

Parameters:
  • weights (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of portfolio weights

  • r (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of expected returns

  • cov (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['2D array']]) – Covariance matrix

  • rf (float) – Risk-free rate

  • lamb (float) – Lambda parameter for the cost function

  • V0 (float) – Initial portfolio value (default: 10.0)

Returns:

MPT cost function value

Return type:

float

finsim.portfolio.optimize.metrics.mpt_entropy_costfunction(weights, r, cov, rf, lamb0, lamb1, V=10.0)[source]

Calculate the MPT entropy cost function for a portfolio.

Parameters:
  • weights (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of portfolio weights

  • r (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of expected returns

  • cov (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['2D array']]) – Covariance matrix

  • rf (float) – Risk-free rate

  • lamb0 (float) – Lambda 0 parameter for the entropy cost function

  • lamb1 (float) – Lambda 1 parameter for the entropy cost function

  • V (float) – Portfolio value parameter (default: 10.0)

Returns:

MPT entropy cost function value

Return type:

float

Raises:

ValueError – If Cython fitting is attempted (no longer supported)

finsim.portfolio.optimize.metrics.sharpe_ratio(weights, r, cov, rf)[source]

Calculate the Sharpe ratio for a portfolio.

Parameters:
  • weights (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of portfolio weights

  • r (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of expected returns

  • cov (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['2D array']]) – Covariance matrix

  • rf (float) – Risk-free rate

Returns:

Sharpe ratio value

Return type:

float

finsim.portfolio.optimize.numerics module

finsim.portfolio.optimize.numerics.checksumarray(array, total)[source]

Calculate the difference between a total and the sum of an array.

Parameters:
  • array (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Input array

  • total (float) – Total value to compare against

Returns:

Difference between total and sum of array

Return type:

float

finsim.portfolio.optimize.numerics.get_BlackScholesMerton_stocks_estimation(symbols, startdate, enddate, progressbar=True, cacheddir=None, include_dividends=False)[source]

Get Black-Scholes-Merton model estimations for a list of stocks.

Parameters:
  • symbols (list[str]) – List of stock symbols

  • startdate (str) – Start date in ‘YYYY-MM-DD’ format

  • enddate (str) – End date in ‘YYYY-MM-DD’ format

  • progressbar (bool) – Whether to show a progress bar (default: True)

  • cacheddir (str | PathLike | None) – Directory for cached data (optional)

  • include_dividends (bool) – Whether to include dividends in the calculation (default: False)

Returns:

Tuple of (rarray, covmat)

Return type:

tuple[NDArray[Shape[“*”], Float], NDArray[Shape[”*, *”], Float]]

finsim.portfolio.optimize.numerics.get_stocks_timeweighted_estimation(symbols, timeweightdf, progressbar=True, cacheddir=None, include_dividends=False)[source]

Get time-weighted estimations for a list of stocks.

Parameters:
  • symbols (list[str]) – List of stock symbols

  • timeweightdf (DataFrame) – DataFrame containing timestamps and weights

  • progressbar (bool) – Whether to show a progress bar (default: True)

  • cacheddir (str | PathLike | None) – Directory for cached data (optional)

  • include_dividends (bool) – Whether to include dividends in the calculation (default: False)

Returns:

Tuple of (rarray, covmat)

Return type:

tuple[NDArray[Shape[“*”], Float], NDArray[Shape[”*, *”], Float]]

finsim.portfolio.optimize.numerics.getarrayelementminusminvalue(array, minvalue, index)[source]

Get the difference between an array element and a minimum value.

Parameters:
  • array (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Input array

  • minvalue (float) – Minimum value to subtract

  • index (int) – Index of the element in the array

Returns:

Difference between array element and minimum value

Return type:

float

finsim.portfolio.optimize.numerics.intermediate_wrangle_stock_df_with_dividends(stock_df, symbol)[source]

Process stock data with dividends.

Parameters:
  • stock_df (DataFrame) – DataFrame containing stock data

  • symbol (str) – Stock symbol

Returns:

Processed stock DataFrame with ‘EffVal’ column including dividends

Return type:

pd.DataFrame

finsim.portfolio.optimize.numerics.intermediate_wrangle_stock_df_without_dividends(stock_df)[source]

Process stock data without dividends.

Parameters:

stock_df (DataFrame) – DataFrame containing stock data

Returns:

Processed stock DataFrame with ‘EffVal’ column

Return type:

pd.DataFrame

finsim.portfolio.optimize.numerics.optimized_portfolio_mpt_costfunction(r, cov, rf, lamb, V0=10.0)[source]

Optimize a portfolio based on the MPT cost function.

Parameters:
  • r (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of expected returns

  • cov (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['2D array']]) – Covariance matrix

  • rf (float) – Risk-free rate

  • lamb (float) – Lambda parameter for the cost function

  • V0 (float) – Initial portfolio value (default: 10.0)

Returns:

Optimization result object

Return type:

OptimizeResult

finsim.portfolio.optimize.numerics.optimized_portfolio_mpt_entropy_costfunction(r, cov, rf, lamb0, lamb1, V=10.0)[source]

Optimize a portfolio based on the MPT entropy cost function.

Parameters:
  • r (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of expected returns

  • cov (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['2D array']]) – Covariance matrix

  • rf (float) – Risk-free rate

  • lamb0 (float) – Lambda 0 parameter for the entropy cost function

  • lamb1 (float) – Lambda 1 parameter for the entropy cost function

  • V (float) – Portfolio value parameter (default: 10.0)

Returns:

Optimization result object

Return type:

OptimizeResult

finsim.portfolio.optimize.numerics.optimized_portfolio_on_sharperatio(r, cov, rf, minweight=0.0)[source]

Optimize a portfolio based on the Sharpe ratio.

Parameters:
  • r (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of expected returns

  • cov (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['2D array']]) – Covariance matrix

  • rf (float) – Risk-free rate

  • minweight (float) – Minimum weight for each asset (default: 0.0)

Returns:

Optimization result object

Return type:

OptimizeResult

finsim.portfolio.optimize.policy module

class finsim.portfolio.optimize.policy.OptimizedWeightingPolicy(rf, r=None, cov=None, symbols=None)[source]

Bases: ABC

Abstract base class for optimized weighting policies.

This class defines the interface for optimization policies used in portfolio optimization, including methods for calculating weights, yields, and volatilities.

Parameters:
property correlation_matrix: Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['2D array']]

Get the correlation matrix of the optimized portfolio.

Returns:

Correlation matrix of the portfolio

Return type:

Annotated[NDArray[np.float64], Literal[“2D array”]]

property named_correlation_matrix: DataFrame

Get the named correlation matrix of the optimized portfolio.

Returns:

Named correlation matrix of the portfolio

Return type:

pd.DataFrame

abstract optimize(r, cov, symbols=None)[source]

Optimize the portfolio weights.

Parameters:
  • r (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of expected returns

  • cov (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['2D array']]) – Covariance matrix

  • symbols (list[str] | None) – List of symbols (optional)

Return type:

None

property policytype: str

Get the type of the optimization policy.

Returns:

Type of the optimization policy

Return type:

str

property portfolio_summary: dict[str, Any]

Get a summary of the optimized portfolio.

Returns:

Dictionary containing portfolio summary information

Return type:

dict[str, Any]

property portfolio_symbols: list[str]

Get the list of symbols in the portfolio.

Returns:

List of symbols in the portfolio

Return type:

list[str]

abstract property portfolio_yield: float

Get the expected yield of the optimized portfolio.

Returns:

Expected yield of the portfolio

Return type:

float

abstract property volatility: float

Get the volatility of the optimized portfolio.

Returns:

Volatility of the portfolio

Return type:

float

abstract property weights: Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]

Get the optimized weights for each asset.

Returns:

Array of optimized weights

Return type:

Annotated[NDArray[np.float64], Literal[“1D array”]]

class finsim.portfolio.optimize.policy.OptimizedWeightingPolicyUsingMPTCostFunction(rf, r, cov, symbols=None, lamb=0.0, V0=10.0)[source]

Bases: OptimizedWeightingPolicy

Optimized weighting policy using the MPT cost function.

This class implements portfolio optimization based on a cost function from Modern Portfolio Theory.

Parameters:
property mpt_costfunction: float

Get the MPT cost function value of the optimized portfolio.

Returns:

MPT cost function value of the portfolio

Return type:

float

optimize(r, cov, symbols=None)[source]

Optimize the portfolio weights using the MPT cost function.

Parameters:
  • r (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of expected returns

  • cov (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['2D array']]) – Covariance matrix

  • symbols (list[str] | None) – List of symbols (optional)

Return type:

None

property policytype: str

Get the type of the optimization policy.

Returns:

Type of the optimization policy

Return type:

str

property portfolio_summary: dict[str, Any]

Get a summary of the optimized portfolio.

Returns:

Dictionary containing portfolio summary information

Return type:

dict[str, Any]

property portfolio_yield: float

Get the expected yield of the optimized portfolio.

Returns:

Expected yield of the portfolio

Return type:

float

property volatility: float

Get the volatility of the optimized portfolio.

Returns:

Volatility of the portfolio

Return type:

float

property weights: Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]

Get the optimized weights for each asset.

Returns:

Array of optimized weights

Return type:

Annotated[NDArray[np.float64], Literal[“1D array”]]

class finsim.portfolio.optimize.policy.OptimizedWeightingPolicyUsingMPTEntropyCostFunction(rf, r=None, cov=None, symbols=None, lamb0=0.0, lamb1=0.0, V=10.0)[source]

Bases: OptimizedWeightingPolicy

Optimized weighting policy using the MPT entropy cost function.

This class implements portfolio optimization based on an entropy cost function from Modern Portfolio Theory.

Parameters:
property mpt_entropy_costfunction: float

Get the MPT entropy cost function value of the optimized portfolio.

Returns:

MPT entropy cost function value of the portfolio

Return type:

float

optimize(r, cov, symbols=None)[source]

Optimize the portfolio weights using the MPT entropy cost function.

Parameters:
  • r (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of expected returns

  • cov (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['2D array']]) – Covariance matrix

  • symbols (list[str] | None) – List of symbols (optional)

Return type:

None

property policytype: str

Get the type of the optimization policy.

Returns:

Type of the optimization policy

Return type:

str

property portfolio_summary: dict[str, Any]

Get a summary of the optimized portfolio.

Returns:

Dictionary containing portfolio summary information

Return type:

dict[str, Any]

property portfolio_yield: float

Get the expected yield of the optimized portfolio.

Returns:

Expected yield of the portfolio

Return type:

float

property volatility: float

Get the volatility of the optimized portfolio.

Returns:

Volatility of the portfolio

Return type:

float

property weights: Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]

Get the optimized weights for each asset.

Returns:

Array of optimized weights

Return type:

Annotated[NDArray[np.float64], Literal[“1D array”]]

class finsim.portfolio.optimize.policy.OptimizedWeightingPolicyUsingMPTSharpeRatio(rf, r=None, cov=None, symbols=None, minweight=0.0)[source]

Bases: OptimizedWeightingPolicy

Optimized weighting policy using the Sharpe ratio from Modern Portfolio Theory.

This class implements portfolio optimization based on maximizing the Sharpe ratio, which is the ratio of excess return to volatility.

Parameters:
optimize(r, cov, symbols=None)[source]

Optimize the portfolio weights using the Sharpe ratio.

Parameters:
  • r (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of expected returns

  • cov (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['2D array']]) – Covariance matrix

  • symbols (list[str] | None) – List of symbols (optional)

Return type:

None

property policytype: str

Get the type of the optimization policy.

Returns:

Type of the optimization policy

Return type:

str

property portfolio_summary: dict[str, Any]

Get a summary of the optimized portfolio.

Returns:

Dictionary containing portfolio summary information

Return type:

dict[str, Any]

property portfolio_yield: float

Get the expected yield of the optimized portfolio.

Returns:

Expected yield of the portfolio

Return type:

float

property sharpe_ratio: float

Get the Sharpe ratio of the optimized portfolio.

Returns:

Sharpe ratio of the portfolio

Return type:

float

property volatility: float

Get the volatility of the optimized portfolio.

Returns:

Volatility of the portfolio

Return type:

float

property weights: Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]

Get the optimized weights for each asset.

Returns:

Array of optimized weights

Return type:

Annotated[NDArray[np.float64], Literal[“1D array”]]

finsim.portfolio.optimize.policy.mat_to_list(mat)[source]

Convert a 2D numpy array to a list of lists.

Parameters:

mat (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['2D array']]) – 2D numpy array to convert

Returns:

List of lists representation of the matrix

Return type:

list[list[float]]

Subpackages

finsim.portfolio.optimize.native package

Submodules

finsim.portfolio.optimize.native.pymetrics module

finsim.portfolio.optimize.native.pymetrics.python_mpt_costfunction(weights, r, cov, rf, lamb, V0=10.0)[source]

Calculate the MPT cost function for a portfolio using Python/Numba.

Parameters:
  • weights (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of portfolio weights

  • r (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of expected returns

  • cov (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['2D array']]) – Covariance matrix

  • rf (float) – Risk-free rate

  • lamb (float) – Lambda parameter for the cost function

  • V0 (float) – Initial portfolio value (default: 10.0)

Returns:

MPT cost function value

Return type:

float

finsim.portfolio.optimize.native.pymetrics.python_mpt_entropy_costfunction(weights, r, cov, rf, lamb0, lamb1, V=10.0)[source]

Calculate the MPT entropy cost function for a portfolio using Python/Numba.

Parameters:
  • weights (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of portfolio weights

  • r (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of expected returns

  • cov (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['2D array']]) – Covariance matrix

  • rf (float) – Risk-free rate

  • lamb0 (float) – Lambda 0 parameter for the entropy cost function

  • lamb1 (float) – Lambda 1 parameter for the entropy cost function

  • V (float) – Portfolio value parameter (default: 10.0)

Returns:

MPT entropy cost function value

Return type:

float

finsim.portfolio.optimize.native.pymetrics.python_sharpe_ratio(weights, r, cov, rf)[source]

Calculate the Sharpe ratio for a portfolio using Python/Numba.

Parameters:
  • weights (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of portfolio weights

  • r (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['1D array']]) – Array of expected returns

  • cov (Annotated[ndarray[tuple[int, ...], dtype[float64]], Literal['2D array']]) – Covariance matrix

  • rf (float) – Risk-free rate

Returns:

Sharpe ratio value

Return type:

float

finsim.simulation package

Submodules

finsim.simulation.stock module

class finsim.simulation.stock.AbstractStochasticValue[source]

Bases: ABC

Abstract base class for stochastic value generators.

abstract generate_time_series(T, dt, nbsimulations=1)[source]

Generate a time series of values.

Parameters:
  • T (float) – Time horizon

  • dt (float) – Time step

  • nbsimulations (int) – Number of simulations (default: 1)

class finsim.simulation.stock.BlackScholesMertonStockPrices(S0, r, sigma)[source]

Bases: AbstractStochasticValue

Generate stock prices using the Black-Scholes-Merton model.

This class implements the Black-Scholes-Merton model for stock price simulation.

Parameters:
generate_time_series(T, dt, nbsimulations=1)[source]

Generate a time series of stock prices using the Black-Scholes-Merton model.

Parameters:
  • T (float) – Time horizon

  • dt (float) – Time step

  • nbsimulations (int) – Number of simulations (default: 1)

Returns:

Array of stock prices

Return type:

NDArray[Shape[“*”], Float]

class finsim.simulation.stock.HestonStockPrices(S0, r, v0, theta, kappa, sigma_v, rho)[source]

Bases: AbstractStochasticValue

Generate stock prices using the Heston model.

This class implements the Heston model for stock price simulation with stochastic volatility.

Parameters:
generate_time_series(T, dt, nbsimulations=1)[source]

Generate a time series of stock prices using the Heston model.

Parameters:
  • T (float) – Time horizon

  • dt (float) – Time step

  • nbsimulations (int) – Number of simulations (default: 1)

Returns:

Array of stock prices

Return type:

NDArray[Shape[“*”], Float]

class finsim.simulation.stock.MertonJumpDiffusionStockPrices(S0, r, sigma, mu, lamb, delta)[source]

Bases: AbstractStochasticValue

Generate stock prices using the Merton jump-diffusion model.

This class implements the Merton jump-diffusion model for stock price simulation.

Parameters:
generate_time_series(T, dt, nbsimulations=1)[source]

Generate a time series of stock prices using the Merton jump-diffusion model.

Parameters:
  • T (float) – Time horizon

  • dt (float) – Time step

  • nbsimulations (int) – Number of simulations (default: 1)

Returns:

Array of stock prices

Return type:

NDArray[Shape[“*”], Float]

class finsim.simulation.stock.SquareRootDiffusionProcesses(x0, theta, kappa, sigma)[source]

Bases: AbstractStochasticValue

Generate values using the square root diffusion process.

This class implements the square root diffusion process for value simulation.

Parameters:
generate_time_series(T, dt, nbsimulations=1)[source]

Generate a time series of values using the square root diffusion process.

Parameters:
  • T (float) – Time horizon

  • dt (float) – Time step

  • nbsimulations (int) – Number of simulations (default: 1)

Returns:

Array of values

Return type:

NDArray[Shape[“*”], Float]

finsim.tech package

Submodules

finsim.tech.ma module

finsim.tech.ma.get_movingaverage_price_data(symbol, startdate, enddate, dayswindow, cacheddir=None)[source]

Get moving average price data for a stock symbol.

Parameters:
  • symbol (str) – Stock symbol

  • startdate (str) – Start date in ‘YYYY-MM-DD’ format

  • enddate (str) – End date in ‘YYYY-MM-DD’ format

  • dayswindow (int) – Number of days for the moving average window

  • cacheddir (str | PathLike | None) – Directory for cached data (optional)

Returns:

DataFrame with ‘TimeStamp’ and ‘MA’ (moving average) columns

Return type:

pd.DataFrame

finsim.retrieve_stock_symbols_cli package

Submodules

finsim.retrieve_stock_symbols_cli.cli module

finsim.retrieve_stock_symbols_cli.cli.get_argparser()[source]

Create and configure the argument parser for the CLI.

Returns:

Configured argument parser

Return type:

ArgumentParser

finsim.retrieve_stock_symbols_cli.cli.main_cli()[source]

Main CLI function to retrieve stock symbols from Finnhub and save them to a file.

This function parses command line arguments, retrieves stock symbols from Finnhub, optionally filters them, and saves them to a file in various formats.