API Reference
finsim package
Subpackages
finsim.data package
Submodules
finsim.data.finnhub module
- class finsim.data.finnhub.FinnHubStockReader(token)[source]
Bases:
objectA class to read stock data from FinnHub API.
- Parameters:
token (str)
finsim.data.preader module
- 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:
- Returns:
A dictionary mapping symbols to DataFrames containing stock data
- Return type:
- finsim.data.preader.extract_online_yahoofinance_data(symbol, startdate, enddate)[source]
Extract stock data for a single symbol from Yahoo Finance.
- finsim.data.preader.finding_missing_symbols_in_cache(symbols, startdate, enddate, cacheddir)[source]
Find symbols that are missing from the cache.
- 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:
startdate (str) – Start date in ‘YYYY-MM-DD’ format
enddate (str) – End date in ‘YYYY-MM-DD’ format
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:
finsim.data.quandl module
- class finsim.data.quandl.QuandlReader(token)[source]
Bases:
objectA 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
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:
- 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:
- 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:
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:
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:
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:
- 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:
- 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:
- 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:
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.
- 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:
- 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:
- 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:
- 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:
finsim.portfolio.dynamic module
- class finsim.portfolio.dynamic.DynamicPortfolio(symbol_nbshares, current_date, cacheddir=None)[source]
Bases:
PortfolioA 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:
- generate_dynamic_portfolio_dict()[source]
Generate a dictionary representation of the dynamic portfolio.
- get_portfolio_value(datestr)[source]
Calculate the total value of the portfolio on a specific date.
- get_portfolio_values_overtime(startdate, enddate, cacheddir=None, progressbar=False)[source]
Calculate the portfolio value over a time period.
- Parameters:
- 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:
- classmethod load_from_dict(dynportdict, cacheddir=None)[source]
Load a dynamic portfolio from a dictionary.
- classmethod load_from_json(fileobj, cacheddir=None)[source]
Load a dynamic portfolio from a JSON file.
- 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
- 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:
DynamicPortfolioA 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
finsim.portfolio.helper module
Bases:
ExceptionException 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.
finsim.portfolio.portfolio module
- class finsim.portfolio.portfolio.OptimizedPortfolio(policy, totalworth, presetdate, cacheddir=None)[source]
Bases:
PortfolioA 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:
policy (OptimizedWeightingPolicy)
totalworth (float)
presetdate (str)
- 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:
- get_portfolio()[source]
Get the underlying Portfolio object.
- Returns:
The underlying Portfolio object
- Return type:
- 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:
- 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:
- 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_yield: float
Get the expected yield of the optimized portfolio.
- Returns:
Expected yield of the portfolio
- Return type:
- 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
- class finsim.portfolio.portfolio.Portfolio(symbols_nbshares, cacheddir=None)[source]
Bases:
objectA 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.
- __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:
- __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.
- __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:
- __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.
- __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:
- get_portfolio_value(datestr)[source]
Calculate the total value of the portfolio on a specific date.
- 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
Get the dictionary of symbols and number of shares.
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
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:
- 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:
- 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:
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.
- 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:
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:
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.
- 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.policy module
- class finsim.portfolio.optimize.policy.OptimizedWeightingPolicy(rf, r=None, cov=None, symbols=None)[source]
Bases:
ABCAbstract 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
- property policytype: str
Get the type of the optimization policy.
- Returns:
Type of the optimization policy
- Return type:
- abstract property portfolio_yield: float
Get the expected yield of the optimized portfolio.
- Returns:
Expected yield of the portfolio
- Return type:
- class finsim.portfolio.optimize.policy.OptimizedWeightingPolicyUsingMPTCostFunction(rf, r, cov, symbols=None, lamb=0.0, V0=10.0)[source]
Bases:
OptimizedWeightingPolicyOptimized 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:
- property policytype: str
Get the type of the optimization policy.
- Returns:
Type of the optimization policy
- Return type:
- property portfolio_yield: float
Get the expected yield of the optimized portfolio.
- Returns:
Expected yield of the portfolio
- Return type:
- class finsim.portfolio.optimize.policy.OptimizedWeightingPolicyUsingMPTEntropyCostFunction(rf, r=None, cov=None, symbols=None, lamb0=0.0, lamb1=0.0, V=10.0)[source]
Bases:
OptimizedWeightingPolicyOptimized 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:
- optimize(r, cov, symbols=None)[source]
Optimize the portfolio weights using the MPT entropy cost function.
- property policytype: str
Get the type of the optimization policy.
- Returns:
Type of the optimization policy
- Return type:
- property portfolio_yield: float
Get the expected yield of the optimized portfolio.
- Returns:
Expected yield of the portfolio
- Return type:
- class finsim.portfolio.optimize.policy.OptimizedWeightingPolicyUsingMPTSharpeRatio(rf, r=None, cov=None, symbols=None, minweight=0.0)[source]
Bases:
OptimizedWeightingPolicyOptimized 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:
- property policytype: str
Get the type of the optimization policy.
- Returns:
Type of the optimization policy
- Return type:
- property portfolio_yield: float
Get the expected yield of the optimized portfolio.
- Returns:
Expected yield of the portfolio
- Return type:
- property sharpe_ratio: float
Get the Sharpe ratio of the optimized portfolio.
- Returns:
Sharpe ratio of the portfolio
- Return type:
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:
- 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:
- 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:
finsim.simulation package
Submodules
finsim.simulation.stock module
- class finsim.simulation.stock.AbstractStochasticValue[source]
Bases:
ABCAbstract base class for stochastic value generators.
- class finsim.simulation.stock.BlackScholesMertonStockPrices(S0, r, sigma)[source]
Bases:
AbstractStochasticValueGenerate stock prices using the Black-Scholes-Merton model.
This class implements the Black-Scholes-Merton model for stock price simulation.
- class finsim.simulation.stock.HestonStockPrices(S0, r, v0, theta, kappa, sigma_v, rho)[source]
Bases:
AbstractStochasticValueGenerate stock prices using the Heston model.
This class implements the Heston model for stock price simulation with stochastic volatility.
- class finsim.simulation.stock.MertonJumpDiffusionStockPrices(S0, r, sigma, mu, lamb, delta)[source]
Bases:
AbstractStochasticValueGenerate stock prices using the Merton jump-diffusion model.
This class implements the Merton jump-diffusion model for stock price simulation.
- class finsim.simulation.stock.SquareRootDiffusionProcesses(x0, theta, kappa, sigma)[source]
Bases:
AbstractStochasticValueGenerate values using the square root diffusion process.
This class implements the square root diffusion process for value simulation.