def max_cagr_asset(self) -> dict: """ Find an asset with max CAGR. """ max_asset_cagr = Frame.get_cagr(self.ror).max() ticker_with_largest_cagr = Frame.get_cagr(self.ror).nlargest(1, keep='first').index.values[0] return {'max_asset_cagr': max_asset_cagr, 'ticker_with_largest_cagr': ticker_with_largest_cagr, 'list_position': self.symbols.index(ticker_with_largest_cagr) }
def target_cagr_range_left(self) -> np.ndarray: """ Full range of cagr values (from min to max). """ max_cagr = self.global_max_return_portfolio['CAGR'] min_cagr = Frame.get_cagr(self.ror).min() return np.linspace(min_cagr, max_cagr, self.n_points)
def max_cagr_asset_right_to_max_cagr(self) -> Optional[dict]: """ The asset with max CAGR lieing to the right of the global max CAGR point (risk should be more than self.max_return['Risk']). Global max return point should not be an asset. """ tolerance = 0.01 # assets CAGR should be less than max CAGR with certain tolerance global_max_cagr_is_not_asset = (self.get_cagr() < self.global_max_return_portfolio['CAGR'] * (1 - tolerance)).all() if global_max_cagr_is_not_asset: condition = self.risk_annual.values > self.global_max_return_portfolio['Risk'] ror_selected = self.ror.loc[:, condition] if not ror_selected.empty: cagr_selected = Frame.get_cagr(ror_selected) max_asset_cagr = cagr_selected.max() ticker_with_largest_cagr = cagr_selected.nlargest(1, keep='first').index.values[0] return {'max_asset_cagr': max_asset_cagr, 'ticker_with_largest_cagr': ticker_with_largest_cagr, 'list_position': self.symbols.index(ticker_with_largest_cagr) }
def get_monte_carlo(self, n: int = 100) -> pd.DataFrame: """ Generate N random risk / cagr point for rebalanced portfolios. Risk and cagr are calculated for a set of random weights. """ weights_df = Float.get_random_weights(n, self.ror.shape[1]) # Portfolio risk and cagr for each set of weights portfolios_ror = weights_df.aggregate(Rebalance.rebalanced_portfolio_return_ts, ror=self.ror, period=self.reb_period) random_portfolios = pd.DataFrame() for _, data in portfolios_ror.iterrows(): risk_monthly = data.std() mean_return = data.mean() risk = Float.annualize_risk(risk_monthly, mean_return) cagr = Frame.get_cagr(data) row = { 'Risk': risk, 'CAGR': cagr } random_portfolios = random_portfolios.append(row, ignore_index=True) return random_portfolios
def minimize_risk( self, target_return: float, monthly_return: bool = False, tolerance: float = 1e-08, ) -> Dict[str, float]: """ Finds minimal risk given the target return. Returns a "point" with monthly values: - weights - mean return - CAGR - risk (std) Target return is a monthly or annual value: monthly_return = False / True tolerance - sets the accuracy for the solver """ if not monthly_return: target_return = Float.get_monthly_return_from_annual(target_return) ror = self.ror n = ror.shape[1] # number of assets init_guess = np.repeat(1 / n, n) # initial weights def objective_function(w): return Frame.get_portfolio_risk(w, ror) # construct the constraints weights_sum_to_1 = {"type": "eq", "fun": lambda weights: np.sum(weights) - 1} return_is_target = { "type": "eq", "fun": lambda weights: target_return - Frame.get_portfolio_mean_return(weights, ror), } weights = minimize( objective_function, init_guess, method="SLSQP", constraints=(weights_sum_to_1, return_is_target), bounds=self.bounds, options={"disp": False, "ftol": tolerance}, ) if weights.success: # Calculate point of EF given optimal weights risk = weights.fun # Annualize risk and return a_r = Float.annualize_return(target_return) a_risk = Float.annualize_risk(risk=risk, mean_return=target_return) # # Risk adjusted return approximation # r_gmean = Float.approx_return_risk_adjusted(mean_return=a_r, std=a_risk) # CAGR calculation portfolio_return_ts = Frame.get_portfolio_return_ts(weights.x, ror) cagr = Frame.get_cagr(portfolio_return_ts) if not self.labels_are_tickers: asset_labels = list(self.names.values()) else: asset_labels = self.symbols point = {x: y for x, y in zip(asset_labels, weights.x)} point["Mean return"] = a_r point["CAGR"] = cagr # point['CAGR (approx)'] = r_gmean point["Risk"] = a_risk else: raise Exception("No solutions were found") return point