portfolio_optimizer package

Submodules

portfolio_optimizer.frontier module

portfolio_optimizer.load_data module

class portfolio_optimizer.load_data.LoadData

Bases: object

Load the data from the tickers

Load Index data from nasdaq only, For Indian Index price is in INR (mostly)

Few Important Tickers are :

# Indices | ^GSPC | S&P500 | USD | | ^NSEI | Nifty 50 | INR | | ^NSEBANK | NiftyBank | INR | | ^BSESN | Sensex | INR |

# Crypto | BTC-USD | Bitcoin | USD | | ETH-USD | Ethereum | USD | | LTC-USD | Litecoin | USD | | DOGE-USD | Dogecoin | USD |

# Commodities | GC=F | Gold | USD | | SI=F | Silver | USD | | CL=F | Crude Oil | USD | | HG=F | Copper | USD | | ZC=F | Corn | USD |

# US treasury | ^IRX | 13 Week Treasury Bill | USD | | ^FVX | 5 Year Treasury Note | USD | | ^TNX | 10 Year Treasury Note | USD | | ^TYX | 30 Year Treasury Bond | USD |

# Indian NSE (National Stock Exchange) | RELIANCE.NS | Reliance Industries | INR | | TCS.NS | Tata Consultancy Services | INR | | HDFCBANK.NS | HDFC Bank | INR |

# Indian BSE (Bombay Stock Exchange) | RELIANCE.BO | Reliance Industries | INR | | TCS.BO | Tata Consultancy Services | INR | | HDFCBANK.BO | HDFC Bank | INR |

get_company_name(ticker, exchange)

Get the company name from the ticker

Parameters:
  • ticker (str) – Ticker of the company

  • exchange (str) – Exchange to get the ticker name from

Returns:

Return the company name

Return type:

str

get_ticker_names(exchange)
Parameters:

exchange (str) – Exchange to get the ticker name from

Returns:

Return the DataFrame of the Ticker and Company name listed on the specified exchanged

Return type:

DataFrame

load_data(tickers, exchange='nse')

Load the data from the tickers

Load Index data from nasdaq only, For Indian Index price is in INR (mostly)

Parameters:
  • tickers (list) – List of the tickers to load the data from

  • exchange (str) – Exchange to get the ticker name from

Returns:

  • dict – Return the dictionary of the dataframes of the tickers

  • if exchange = “nse” or “bse” – Returns the historical data in INR

  • if exchange = “nasdaq” – Returns the historical data in USD

  • by default exchange = “nse”

  • indices of nse are in INR and are available in nasdaq only

save_data(data, path)

Save the data to the path

Parameters:
  • data (dict) – Dictionary of the dataframes of the tickers

  • path (str) – Path to save the data

Return type:

None

portfolio_optimizer.portfolio module

class portfolio_optimizer.portfolio.Portfolio(freq, benchmark: dict, risk_free_rate=None)

Bases: object

add_stock(stock_dic)

Adds a stock to the dictionary

Parameters:

stock_dic (dict) –

stock_dic = {namestock}

name : Name of the stock stock : Stock dataframe

Return type:

None

cal_alpha(df=None, benchmark='snp500', freq='M')

Calculates the alpha and beta of a dataframe :param df: Merged Dataframe to calculate alpha and beta :type df: pd.DataFrame :param benchmark: Benchmark to calculate alpha and beta, by default “snp500” :type benchmark: pd.DataFrame

Returns:

Alpha

Return type:

pd.DataFrame

cal_beta(df=None, benchmark='snp500', freq='M')

Calculates the alpha and beta of a dataframe :param df: Merged Dataframe to calculate alpha and beta :type df: pd.DataFrame :param benchmark: Benchmark to calculate alpha and beta, by default “snp500” :type benchmark: pd.DataFrame

Returns:

Beta

Return type:

pd.DataFrame

cal_returns(df=None, freq='M')

Calculates the returns of a dataframe :param df: Dataframe to calculate returns :type df: pd.DataFrame

Returns:

Returns

Return type:

pd.DataFrame

cov_matrix(df=None, freq='M')

Calculates the covariance matrix of a dataframe :param df: Dataframe to calculate covariance matrix :type df: pd.DataFrame

Returns:

Covariance matrix

Return type:

pd.DataFrame

expected_returns(risk_free_rate=0.225, market_return=0.98, beta=None, model='CAPM')
Parameters:

risk_free_rate (float) –

market_return : float

betapd.DataFrame, optional

Beta of the stocks, by default None

modelstr, optional

Model to calculate expected returns, by default “CAPM”

Returns:

  • pd.DataFrame – Expected returns of the stocks

  • Eg

  • ——-

  • obj.expected_returns(0.225, 0.89, beta=np.array([0.5, 0.6]))

merge_dfs(stocks=None, join='inner', columns=['Close'])

Merges a list of dataframes into one. Uses the index as the key and pd.concat to merge the dataframes :param stocks: keys : Stocks name

values : Stocks DataFrame

Parameters:
  • join (str, optional) – How to join the dataframes, by default “inner”

  • columns (str, optional) – Which columns to merge, by default “Close”

Returns:

Merged dataframe

Return type:

pd.DataFrame

portfolio_expected_return(weights='equals', expected_returns=None, model='CAPM')

Calculates the portfolio return

Parameters:
  • weights (np.array) – Weights of the stocks or “equals” for equal weights

  • expected_returns (np.array) – Expected returns of the stocks

  • model (str, optional) – Model to calculate expected returns, by default “CAPM”

Returns:

  • float – Portfolio return

  • Eg

  • ——-

  • obj.portfolio_return(weights, expected_returns)

portfolio_std(weights='equals', cov_matrix=None)

Calculates the portfolio standard deviation

Parameters:
  • weights (np.array) – Weights of the stocks or “equals” for equal weights

  • cov_matrix (pd.DataFrame) – Covariance matrix of the stocks

Returns:

  • float – Portfolio standard deviation

  • Eg

  • ——-

  • obj.portfolio_std(weights, cov_matrix)

portfolio_stocks()
portfolio_summary(expected_returns=None, cov_matrix=None)

Calculates the portfolio summary

Parameters:
  • weights (np.array) – Weights of the stocks or “equals” for equal weights

  • expected_returns (np.array) – Expected returns of the stocks

  • cov_matrix (pd.DataFrame) – Covariance matrix of the stocks

Returns:

  • pd.DataFrame – Portfolio summary

  • Eg

  • ——-

  • obj.portfolio_summary(weights, expected_returns, cov_matrix)

portfolio_variance(weights='equals', cov_matrix=None)

Calculates the portfolio variance

Parameters:
  • weights (np.array) – Weights of the stocks or “equals” for equal weights

  • cov_matrix (pd.DataFrame) – Covariance matrix of the stocks

Returns:

  • float – Portfolio variance

  • Eg

  • ——-

  • obj.portfolio_variance(weights, cov_matrix)

remove_stock(names)

Removes a stock from the dictionary

Parameters:

names (list) – Names of the stocks

Return type:

None

portfolio_optimizer.optimizer module

class portfolio_optimizer.optimizer.Optimizer

Bases: object

Optimize the portfolio

Parameters:

portfolio (Portfolio) – Portfolio to optimize

portfolio

Portfolio to optimize

Type:

Portfolio

model(weights, model)

Calculate the expected return of the portfolio

optimize_portfolio(model, risk, short=False)

Optimize the portfolio

add_portfolio(portfolio: Portfolio)

Add the portfolio to optimize

Parameters:

portfolio (Portfolio) – Portfolio to optimize

model(weights, model)

CAPM Model

Parameters:
  • weights (list) – weights of each stocks

  • model (str) – Model to use for the the calculation of the expected return

Returns:

Return of the expected return of the portfolio

Return type:

float

optimize_portfolio(model, max_risk, short=False)

Optimize the portfolio

Parameters:
  • model (str) – Model to use for the optimization

  • max_risk (float) – Risk of the portfolio

  • short (bool, optional) – Allow shorting, by default False

Return type:

Returns the optimized weights of the portfolio and maximized portfolio_returns

class portfolio_optimizer.frontier.CurveFitting

Bases: object

A class to implement mth order polynomial regression using the least squares method. Use the fit method to fit the model. Then predict the Y values given X values usingthe predict method.

fit(X, Y, order=3)

Polynomial regression of order m using least squares method. :param X: Independent variable. :type X: array_like :param Y: Dependent variable. :type Y: array_like :param order: Order of the polynomial. Default is 3. :type order: int, optional

Returns:

beta – Coefficients of the polynomial regression model.

Return type:

array_like

predict(X_l)

Predict the Y values given X values. :param X_l: Independent variable. :type X_l: array_like

Returns:

Y_l – Predicted Y values.

Return type:

array_like

class portfolio_optimizer.frontier.EfficientFrontier

Bases: object

add_portfolio(portfolio: Portfolio)
Parameters:

portfolio (Portfolio) – Portfolio object.

Return type:

None, just add the portfolio to the EfficientFrontier object.

plot_frontier(short=False, model='capm')

Creates a plot of the efficient frontier. :param short: Whether to allow shorting, by default False :type short: bool, optional :param model: The model to use, by default “capm”. Supported models are ‘capm’, ‘sim’

(If you want to use ‘fff3’ or ‘fff5’, first load the fff parameters.)

Returns:

fig

Return type:

plotly.graph_objects.Figure

Examples

>>> ef = EfficientFrontier(portfolio)
>>> ef.plot_frontier()

Notes

You have to create a Portoflio object first. Then you need to load data. Only then you can call plot_frontier().

plot_sim(model, short=False)

Plot the efficient frontier. :param model: The model to use for calculating the expected returns. Default is “mean”. :type model: str :param short: Whether to allow shorting of stocks. Default is False. :type short: bool, optional

Returns:

fig – Plotly figure object.

Return type:

plotly.graph_objects.Figure

Module contents