def get_weights(self): code_list = list_jq2wind(self.code_list) w.start() return_value = np.array(w.wsd(code_list, "pct_chg", "ED-" + str(self.N - 1) + "TD", self.date, "").Data) return_value = return_value.transpose() return_value = pd.DataFrame(return_value, columns=code_list) optimizer = HRPOpt(return_value) hrp_portfolio = optimizer.hrp_portfolio() hrp_portfolio = dict(zip(list_wind2jq(list(hrp_portfolio.keys())), hrp_portfolio.values())) return hrp_portfolio
def wf(self, train, optimizer, test, test_months, annual_risk_free_rate=0.02): """Walk-Forward backtesting method Args: train (pandas.Series): training data optimizer (str): portfolio optimizer for PyPortfolioOpt test (pandas.Series): test data test_months (int): number of testing months annual_risk_free_rate (float, optional): annual risk free rate used in calculating Sharpe ratio. Defaults to 0.02. Returns: [pandas.Series, float]: expected and realised asset performance """ if optimizer == "hrp": returns = train.pct_change().dropna() hrp = HRPOpt(returns) weights = hrp.optimize() weights = pd.Series(weights) performance = hrp.portfolio_performance(verbose=True) realised_annual_return = sum( weights * ((test.iloc[-1] / test.iloc[0])**(12 / test_months) - 1)) realised_annual_volatility = sum( weights * np.std(test.pct_change().dropna()) * np.sqrt(251)) realised_sharpe_ratio = ( realised_annual_return - annual_risk_free_rate) / realised_annual_volatility return weights, performance, realised_annual_return, realised_annual_volatility, realised_sharpe_ratio else: mu = mean_historical_return(train) S = CovarianceShrinkage(train).ledoit_wolf() ef = EfficientFrontier(mu, S) weights = ef.max_sharpe( ) if optimizer == "msr" else ef.min_volatility() weights = pd.Series(weights) performance = ef.portfolio_performance() realised_annual_return = sum( weights * ((test.iloc[-1] / test.iloc[0])**(12 / test_months) - 1)) realised_annual_volatility = sum( weights * np.std(test.pct_change().dropna()) * np.sqrt(251)) realised_sharpe_ratio = ( realised_annual_return - annual_risk_free_rate) / realised_annual_volatility return weights, performance, realised_annual_return, realised_annual_volatility, realised_sharpe_ratio
def optimize_portfolio(): returns = get_investiments_returns() cov_matrix = returns.cov() opt = HRPOpt(returns, cov_matrix) weights = opt.optimize('ward') weights = json.dumps(weights)[1:-1].replace(',', '\n') performace = opt.portfolio_performance() expected_return = performace[0] annual_vol = performace[1] sharpe_ratio = performace[2] performace_formated = 'Retorno esperado: ' + str( expected_return) + '\n' + 'Volatilidade Anual: ' + str( annual_vol) + '\n' + 'Sharpe Ratio: ' + str(sharpe_ratio) return (weights, performace_formated)
end_date = datetime.date.today() end_date = datetime.date(2021, 3, 31) start_date = end_date - relativedelta(months=1) back_test_date = end_date - relativedelta(months=12) df = yf.download("AAPL,GOOG,FB", start=back_test_date, end=start_date) df = df["Adj Close"].dropna(how="all") test_df = yf.download("AAPL,GOOG,FB", start=start_date, end=end_date) test_df = test_df["Adj Close"].dropna(how="all") returns = df.pct_change().dropna() hrp = HRPOpt(returns) weights = hrp.optimize() performance = hrp.portfolio_performance(verbose=True) optimizer = "mvo" mu = mean_historical_return(df) S = CovarianceShrinkage(df).ledoit_wolf() ef = EfficientFrontier(mu, S) weights = ef.max_sharpe() if optimizer == "msr" else ef.min_volatility() cleaned_weights = ef.clean_weights() # maybe remove this bc simplicity performance = ef.portfolio_performance() weights = pd.Series(weights) total_asset_returns = (test_df.iloc[-1]-test_df.iloc[0])/test_df.iloc[0] test_months = 1
def cv(self, back_test_months, data, optimizer, test_months, annual_risk_free_rate=0.02): """Cross-Validation backtesting method Args: back_test_months (int): number of backtesting months data (pandas.Series): data that includes both training and testing data optimizer (str): portfolio optimizer for PyPortfolioOpt test_months (int): number of testing months annual_risk_free_rate (float, optional): annual risk free rate used in calculating Sharpe ratio. Defaults to 0.02. Returns: [pandas.Series, float]: expected and realised asset performance """ embargo = np.round_(0.01 * len(data), decimals=0) all_weights = np.zeros((back_test_months, np.shape(data)[1])) all_realised_annual_return = np.zeros(back_test_months) all_realised_annual_volatility = np.zeros(back_test_months) all_realised_sharpe_ratio = np.zeros(back_test_months) for i in range(back_test_months): test_start = i * len(data) / back_test_months test_end = test_start + len(data) / back_test_months - 1 test = data.iloc[int(test_start):int(test_end), :] train = data.iloc[np.r_[0:int(test_start), int(test_end) + int(embargo):len(data)], :] if optimizer == "hrp": train_returns = train.pct_change().dropna() hrp = HRPOpt(train_returns) weights = hrp.optimize() weights = pd.Series(weights) all_weights[i] = weights performance = hrp.portfolio_performance(verbose=True) else: mu = mean_historical_return(train) S = CovarianceShrinkage(train).ledoit_wolf() ef = EfficientFrontier(mu, S) weights = ef.max_sharpe( ) if optimizer == "msr" else ef.min_volatility() weights = pd.Series(weights) all_weights[i] = weights performance = ef.portfolio_performance() all_realised_annual_return[i] = sum(all_weights[i] * ((test.iloc[ (len(test) - 1)] / test.iloc[0])**(12 / test_months) - 1)) all_realised_annual_volatility[i] = sum( all_weights[i] * np.std(test.pct_change().dropna()) * np.sqrt(251)) all_realised_sharpe_ratio = ( all_realised_annual_return[i] - annual_risk_free_rate) / all_realised_annual_volatility[i] weights = np.mean(all_weights) realised_annual_return = np.mean(all_realised_annual_return) realised_annual_volatility = np.mean(all_realised_annual_volatility) realised_sharpe_ratio = np.mean(all_realised_sharpe_ratio) return weights, performance, realised_annual_return, realised_annual_volatility, realised_sharpe_ratio
def hrp_strategy(ld: LazyDictionary, **kwargs) -> None: ef = HRPOpt(returns=kwargs.get("returns")) ld["optimizer"] = ef ld["raw_weights"] = lambda ld: ld["optimizer"].optimize()
def hrp_strategy(returns): assert returns is not None ef = HRPOpt(returns=returns) weights = ef.optimize() return weights, portfolio_performance(ef), ef