From 34bc290dded1bd2418fc3c6b375a79f9cdd68d5a Mon Sep 17 00:00:00 2001 From: Riskfolio Date: Tue, 3 May 2022 06:54:01 -0500 Subject: [PATCH] New portfolio optimization menu (#1642) * New-Portfolio-Optimization-Menu * New-Portfolio-Optimization-Menu * New-Portfolio-Optimization-Menu * Update _index.md * New-Portfolio-Optimization-Menu * New-Portfolio-Optimization-Menu * configure portfolio optimization parameters ini * minor improvement * Revert "New-Portfolio-Optimization-Menu" This reverts commit b4b7169cfbc8f28c379eb1920307c2cdd2e47a0f. * Add in Excel functionality and improve the capabilities * Add Excel load function * Tidying up the functions * New-Portfolio-Optimization-Menu * New-Portfolio-Optimization-Menu * New-Portfolio-Optimization-Menu * Re-add my code * Some spacing and details * Add folder structure for portfolio * Update terminal file loading * New-Portfolio-Optimization-Menu * Make it possible to move from params to po with loaded file * New-Portfolio-Optimization-Menu * New-Portfolio-Optimization-Menu * Making the connection between the parameters file and the functions * Add in allocation and new params files * Improve params default settings * New-Portfolio-Optimization-Menu * Update Portfolios and Params sheets * Update sheets * Update command to load in correct sheet * Adjust function to only read specific columns * Update portfolio * Small correction * New-Portfolio-Optimization-Menu * New-Portfolio-Optimization-Menu * New-Portfolio-Optimization-Menu * Patched up show error * Add Equity portfolio * Make functions more robust * New-Portfolio-Optimization-Menu * New-Portfolio-Optimization-Menu * Add in Params documentation * Fixing Linting * Add in Requirements and Poetry Updates * Update website * linting * Update tests * Minor fix * remove unneccesary READMEs * Remove expected variable type * Improve documentation * Clean up the code * Refractoring * Adjust names to make it OS friendly Co-authored-by: Jeroen Bouma Co-authored-by: jmaslek Co-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com> Co-authored-by: DidierRLopes --- openbb_terminal/portfolio/README.md | 13 - .../portfolio/portfolio_analysis/README.md | 67 - .../portfolio_optimization/README.md | 20 - .../portfolio_optimization/excel_model.py | 179 + .../portfolio_optimization/optimizer_model.py | 1509 +++- .../portfolio_optimization/optimizer_view.py | 4030 +++++++++- .../parameters/params_controller.py | 387 + .../parameters/params_view.py | 319 + .../portfolio_optimization/po_api.py | 26 +- .../portfolio_optimization/po_controller.py | 6898 +++++++++++++++-- .../yahoo_finance_model.py | 353 +- poetry.lock | 185 +- portfolio/allocation/.gitkeep | 0 .../allocation/50_30_10_10_Portfolio.xlsx | Bin 0 -> 17970 bytes portfolio/allocation/60_40_Portfolio.xlsx | Bin 0 -> 17533 bytes .../allocation/Fixed_Income_Portfolio.xlsx | Bin 0 -> 16638 bytes .../OpenBB_Portfolio_Template_v1.0.0.xlsx | Bin 0 -> 17954 bytes .../allocation/Public_Equity_Portfolio.xlsx | Bin 0 -> 17305 bytes portfolio/allocation/SP_500_Portfolio.xlsx | Bin 0 -> 44809 bytes portfolio/optimization/.gitkeep | 0 .../OpenBB_Parameters_Template_v1.0.0.xlsx | Bin 0 -> 26047 bytes portfolio/optimization/defaults.ini | 8 + pyproject.toml | 1 + requirements-full.txt | 8 +- requirements.txt | 63 +- .../test_po_controller.py | 51 +- .../test_po_controller/test_print_help.txt | 51 +- .../content/terminal/portfolio/po/_index.md | 52 + .../add/_index.md | 0 .../portfolio/po/blacklitterman/_index.md | 135 + .../terminal/portfolio/po/dividend/_index.md | 105 + .../terminal/portfolio/po/ef/_index.md | 61 + .../terminal/portfolio/po/equal/_index.md | 105 + .../terminal/portfolio/po/file/_index.md | 34 + .../terminal/portfolio/po/herc/_index.md | 178 + .../terminal/portfolio/po/hrp/_index.md | 178 + .../terminal/portfolio/po/load/_index.md | 14 + .../terminal/portfolio/po/maxdecorr/_index.md | 106 + .../terminal/portfolio/po/maxdiv/_index.md | 105 + .../terminal/portfolio/po/maxret/_index.md | 135 + .../terminal/portfolio/po/maxsharpe/_index.md | 144 + .../terminal/portfolio/po/maxutil/_index.md | 139 + .../terminal/portfolio/po/minrisk/_index.md | 139 + .../terminal/portfolio/po/mktcap/_index.md | 105 + .../terminal/portfolio/po/nco/_index.md | 161 + .../terminal/portfolio/po/params/_index.md | 43 + .../portfolio/po/params/arg/_index.md | 48 + .../portfolio/po/params/clear/_index.md | 106 + .../portfolio/po/params/file/_index.md | 17 + .../portfolio/po/params/save/_index.md | 16 + .../portfolio/po/params/set/_index.md | 48 + .../terminal/portfolio/po/plot/_index.md | 89 + .../terminal/portfolio/po/property/_index.md | 109 + .../portfolio/po/relriskparity/_index.md | 104 + .../portfolio/po/riskparity/_index.md | 120 + .../rmv/_index.md | 0 .../terminal/portfolio/po/rpf/_index.md | 12 + .../select/_index.md | 0 .../terminal/portfolio/po/show/_index.md | 14 + .../portfolio_optimization/_index.md | 31 - .../portfolio_optimization/dividend/_index.md | 38 - .../portfolio_optimization/ef/_index.md | 26 - .../portfolio_optimization/effret/_index.md | 28 - .../portfolio_optimization/effrisk/_index.md | 19 - .../portfolio_optimization/equal/_index.md | 37 - .../maxquadutil/_index.md | 45 - .../maxsharpe/_index.md | 35 - .../portfolio_optimization/minvol/_index.md | 26 - .../portfolio_optimization/mktcap/_index.md | 36 - .../portfolio_optimization/property/_index.md | 50 - website/data/menu/main.yml | 77 +- website/public/katex-38042a7abd.min.css | 1106 ++- website/public/katex-4ff918ea95.min.css | 1115 ++- website/public/main-5e7fc0c942.min.css | 216 +- website/public/main-cc3cbe901b.min.css | 205 +- 75 files changed, 17891 insertions(+), 1989 deletions(-) delete mode 100644 openbb_terminal/portfolio/README.md delete mode 100644 openbb_terminal/portfolio/portfolio_analysis/README.md delete mode 100644 openbb_terminal/portfolio/portfolio_optimization/README.md create mode 100644 openbb_terminal/portfolio/portfolio_optimization/excel_model.py create mode 100644 openbb_terminal/portfolio/portfolio_optimization/parameters/params_controller.py create mode 100644 openbb_terminal/portfolio/portfolio_optimization/parameters/params_view.py create mode 100644 portfolio/allocation/.gitkeep create mode 100644 portfolio/allocation/50_30_10_10_Portfolio.xlsx create mode 100644 portfolio/allocation/60_40_Portfolio.xlsx create mode 100644 portfolio/allocation/Fixed_Income_Portfolio.xlsx create mode 100644 portfolio/allocation/OpenBB_Portfolio_Template_v1.0.0.xlsx create mode 100644 portfolio/allocation/Public_Equity_Portfolio.xlsx create mode 100644 portfolio/allocation/SP_500_Portfolio.xlsx create mode 100644 portfolio/optimization/.gitkeep create mode 100644 portfolio/optimization/OpenBB_Parameters_Template_v1.0.0.xlsx create mode 100644 portfolio/optimization/defaults.ini create mode 100644 website/content/terminal/portfolio/po/_index.md rename website/content/terminal/portfolio/{portfolio_optimization => po}/add/_index.md (100%) create mode 100644 website/content/terminal/portfolio/po/blacklitterman/_index.md create mode 100644 website/content/terminal/portfolio/po/dividend/_index.md create mode 100644 website/content/terminal/portfolio/po/ef/_index.md create mode 100644 website/content/terminal/portfolio/po/equal/_index.md create mode 100644 website/content/terminal/portfolio/po/file/_index.md create mode 100644 website/content/terminal/portfolio/po/herc/_index.md create mode 100644 website/content/terminal/portfolio/po/hrp/_index.md create mode 100644 website/content/terminal/portfolio/po/load/_index.md create mode 100644 website/content/terminal/portfolio/po/maxdecorr/_index.md create mode 100644 website/content/terminal/portfolio/po/maxdiv/_index.md create mode 100644 website/content/terminal/portfolio/po/maxret/_index.md create mode 100644 website/content/terminal/portfolio/po/maxsharpe/_index.md create mode 100644 website/content/terminal/portfolio/po/maxutil/_index.md create mode 100644 website/content/terminal/portfolio/po/minrisk/_index.md create mode 100644 website/content/terminal/portfolio/po/mktcap/_index.md create mode 100644 website/content/terminal/portfolio/po/nco/_index.md create mode 100644 website/content/terminal/portfolio/po/params/_index.md create mode 100644 website/content/terminal/portfolio/po/params/arg/_index.md create mode 100644 website/content/terminal/portfolio/po/params/clear/_index.md create mode 100644 website/content/terminal/portfolio/po/params/file/_index.md create mode 100644 website/content/terminal/portfolio/po/params/save/_index.md create mode 100644 website/content/terminal/portfolio/po/params/set/_index.md create mode 100644 website/content/terminal/portfolio/po/plot/_index.md create mode 100644 website/content/terminal/portfolio/po/property/_index.md create mode 100644 website/content/terminal/portfolio/po/relriskparity/_index.md create mode 100644 website/content/terminal/portfolio/po/riskparity/_index.md rename website/content/terminal/portfolio/{portfolio_optimization => po}/rmv/_index.md (100%) create mode 100644 website/content/terminal/portfolio/po/rpf/_index.md rename website/content/terminal/portfolio/{portfolio_optimization => po}/select/_index.md (100%) create mode 100644 website/content/terminal/portfolio/po/show/_index.md delete mode 100644 website/content/terminal/portfolio/portfolio_optimization/_index.md delete mode 100644 website/content/terminal/portfolio/portfolio_optimization/dividend/_index.md delete mode 100644 website/content/terminal/portfolio/portfolio_optimization/ef/_index.md delete mode 100644 website/content/terminal/portfolio/portfolio_optimization/effret/_index.md delete mode 100644 website/content/terminal/portfolio/portfolio_optimization/effrisk/_index.md delete mode 100644 website/content/terminal/portfolio/portfolio_optimization/equal/_index.md delete mode 100644 website/content/terminal/portfolio/portfolio_optimization/maxquadutil/_index.md delete mode 100644 website/content/terminal/portfolio/portfolio_optimization/maxsharpe/_index.md delete mode 100644 website/content/terminal/portfolio/portfolio_optimization/minvol/_index.md delete mode 100644 website/content/terminal/portfolio/portfolio_optimization/mktcap/_index.md delete mode 100644 website/content/terminal/portfolio/portfolio_optimization/property/_index.md diff --git a/openbb_terminal/portfolio/README.md b/openbb_terminal/portfolio/README.md deleted file mode 100644 index e1e8a469ec9..00000000000 --- a/openbb_terminal/portfolio/README.md +++ /dev/null @@ -1,13 +0,0 @@ -# Portfolio [>>](https://openbb-finance.github.io/OpenBBTerminal/portfolio/) - -Command|Description ------- | ------------ -`load` |load data into the portfolio -`save` |save your portfolio for future use -`show` |show existing transactions -`add` |add a security to your portfolio -`rmv` |remove a security from your portfolio -| -`ar` |annual report for performance of a given portfolio -| -`rmr` |graph your returns versus the market's returns diff --git a/openbb_terminal/portfolio/portfolio_analysis/README.md b/openbb_terminal/portfolio/portfolio_analysis/README.md deleted file mode 100644 index f1404d7c610..00000000000 --- a/openbb_terminal/portfolio/portfolio_analysis/README.md +++ /dev/null @@ -1,67 +0,0 @@ -# PORTFOLIO ANALYSIS - -This menu aims to analyze a portfolio loaded through csv/json/xlsx, and the usage of the following commands along with -an example will be exploited below. - -* [load](#load) - * load portfolio from a file -* [group](#group) - * view holdings by a user input group - -## load - -```text -usage: load [-p PATH] [--no_sector] [--no_last_price] [--nan] -``` - -This function allows you to load from a predefined file. The file can contain any information you want, but the stocks -should be under a column `Ticker`. The number owned should be defined in `Shares`. By default, this will loop through -all Tickers and pull sector and latest price. An example column that could be added would be if the ticker is considered -a Value or Growth stock. - -* -p/--path : Path to portfolio file. A template is supplied and the default path points to it. -* --no_sector : Flag to avoid getting the sector of each stock. -* --no_last_price : Flag to avoid getting the latest price for each supplied stock. -* --nan : Flag to display NaN columns. Useful if importing partial information. - -```python -(✨) (pa)> load -╒════╤══════════╤══════════╤════════════════════╤══════════════╤═════════╕ -│ │ Ticker │ Shares │ sector │ last_price │ value │ -╞════╪══════════╪══════════╪════════════════════╪══════════════╪═════════╡ -│ 0 │ AAPL │ 5 │ Technology │ 129.64 │ 648.2 │ -├────┼──────────┼──────────┼────────────────────┼──────────────┼─────────┤ -│ 1 │ GME │ 5 │ Consumer Cyclical │ 222.5 │ 1112.5 │ -├────┼──────────┼──────────┼────────────────────┼──────────────┼─────────┤ -│ 2 │ MSFT │ 3 │ Technology │ 258.36 │ 775.08 │ -├────┼──────────┼──────────┼────────────────────┼──────────────┼─────────┤ -│ 3 │ O │ 2 │ Real Estate │ 69.61 │ 139.22 │ -├────┼──────────┼──────────┼────────────────────┼──────────────┼─────────┤ -│ 4 │ BAC │ 3 │ Financial Services │ 41.39 │ 124.17 │ -╘════╧══════════╧══════════╧════════════════════╧══════════════╧═════════╛ -``` - -## group - -```text -usage: group [-g GROUP] -``` - -Displays data in groups based on columns. Currently this only looks at the `value` column. - -* -g/--group : Column to group data by. Ex: "sector" - -```python -(✨) (pa)> group -g sector -╒════════════════════╤═════════╕ -│ sector │ value │ -╞════════════════════╪═════════╡ -│ Consumer Cyclical │ 1112.5 │ -├────────────────────┼─────────┤ -│ Financial Services │ 124.17 │ -├────────────────────┼─────────┤ -│ Real Estate │ 139.22 │ -├────────────────────┼─────────┤ -│ Technology │ 1423.28 │ -╘════════════════════╧═════════╛ -``` diff --git a/openbb_terminal/portfolio/portfolio_optimization/README.md b/openbb_terminal/portfolio/portfolio_optimization/README.md deleted file mode 100644 index d1b557de76d..00000000000 --- a/openbb_terminal/portfolio/portfolio_optimization/README.md +++ /dev/null @@ -1,20 +0,0 @@ -# Portfolio Optimization [>>](https://openbb-finance.github.io/OpenBBTerminal/portfolio/portfolio_optimization/) - -Command|Description ------- | ------------ -`select` |select list of tickers to be optimized -`add` |add tickers to the list of the tickers to be optimized -`rmv` |remove tickers from the list of the tickers to be optimized -| -`equal` |equally weighted -`mktcap` |weighted according to market cap (property marketCap) -`dividend` |weighted according to dividend yield (property dividendYield) -`property` |weight according to selected info property -| -`maxsharpe` |optimizes for maximal Sharpe ratio (a.k.a the tangency portfolio -`minvol` |optimizes for minimum volatility -`maxquadutil` |maximises the quadratic utility, given some risk aversion -`effret` |maximises return for a given target risk -`effrisk` |minimises risk for a given target return -| -`ef` |show the efficient frontier diff --git a/openbb_terminal/portfolio/portfolio_optimization/excel_model.py b/openbb_terminal/portfolio/portfolio_optimization/excel_model.py new file mode 100644 index 00000000000..df32787f76b --- /dev/null +++ b/openbb_terminal/portfolio/portfolio_optimization/excel_model.py @@ -0,0 +1,179 @@ +"""Excel Model""" +__docformat__ = "numpy" + +# pylint: disable=abstract-class-instantiated + +import logging + +import pandas as pd + +from openbb_terminal.decorators import log_start_end +from openbb_terminal.rich_config import console + +logger = logging.getLogger(__name__) + + +@log_start_end(log=logger) +def load_configuration(excel_file: str): + """ + Load in the Excel file to determine the configuration that needs to be set. + + Parameters + ---------- + excel_file: str + The location of the Excel file that needs to be loaded. + + Returns + ------- + configuration: dictionary + Returns a dictionary with the configurations set. + """ + # Read in the Optimization template + df = pd.read_excel( + excel_file, + sheet_name="Optimization", + skiprows=2, + usecols="B:D", + names=["Parameter", "Value", "Description"], + index_col="Parameter", + ) + + # Remove completely empty NaN rows + cleaned_df = df.dropna(axis="rows", thresh=2) + + # Filter out any general columns + filtered_df = cleaned_df[cleaned_df["Description"] != "Description"] + + # Convert to Dictionary + configuration = filtered_df.to_dict() + + return configuration["Value"], configuration["Description"] + + +@log_start_end(log=logger) +def load_allocation(excel_file: str): + """ + Load in the Excel file to determine the allocation that needs to be set. + + Parameters + ---------- + excel_file: str + The location of the Excel file that needs to be loaded. + + Returns + ------- + tickers: list + Returns a list with ticker symbols + categories: dictionary + Returns a dictionary that specifies each category + """ + if str(excel_file).endswith(".xlsx"): + categories = pd.read_excel(excel_file, sheet_name="Allocation", usecols="A:G") + categories = categories.dropna(axis="rows") + elif str(excel_file).endswith(".csv"): + categories = pd.read_excel(excel_file) + categories = categories.dropna(axis="rows") + else: + console.print("Only Excel (.xlsx and .csv) files are accepted.\n") + return [], {} + + categories.columns = [ + col.upper().strip().replace(" ", "_") for col in categories.columns + ] + categories = categories.apply(lambda x: x.astype(str).str.upper()) + categories = categories[~categories.index.duplicated(keep="first")] + + try: + categories.set_index("TICKER", inplace=True) + categories.sort_index(inplace=True) + except KeyError: + console.print("Allocation table needs a TICKER column\n") + return [], {} + + tickers = list(categories.index) + tickers.sort() + categories = categories.to_dict() + + return tickers, categories + + +@log_start_end(log=logger) +def load_bl_views(excel_file: str): + """ + Load a Excel file with views for Black Litterman model. + + Parameters + ---------- + excel_file: str + The location of the Excel file that needs to be loaded. + + Returns + ------- + p_views: list + Returns a list with p_views matrix + q_views: list + Returns a list with q_views matrix + """ + if str(excel_file).endswith(".xlsx"): + try: + p_views = pd.read_excel(excel_file, sheet_name="p_views", index_col=0) + p_views = p_views.fillna(0) + p_views = p_views.dropna(axis="rows") + except KeyError: + console.print("Excel file needs a p_views sheet\n") + return {}, {} + try: + q_views = pd.read_excel(excel_file, sheet_name="q_views", index_col=0) + q_views = q_views.dropna(axis="rows") + except KeyError: + console.print("Excel file needs a p_views sheet\n") + return {}, {} + else: + console.print("Only Excel (.xlsx) files are accepted.\n") + return {}, {} + + p_views = p_views.T.sort_index() + p_views = p_views.T.to_csv(index=False, header=0).replace("\n", ";") + p_views = p_views[:-1] + p_views = [[float(item) for item in row.split(",")] for row in p_views.split(";")] + q_views = q_views.to_csv(index=False, header=0).replace("\n", ",") + q_views = q_views[:-1] + q_views = [float(item) for item in q_views.split(",")] + + return p_views, q_views + + +@log_start_end(log=logger) +def excel_bl_views(file: str, stocks: str, n: int = 3): + """ + Create an Excel file with required format to build n views for Black Litterman cmd. + + Parameters + ---------- + stocks: str + List of stocks used to build the Black Litterman model views. + n: int + The number of views that will be created. + + Returns + ------- + file: excel + Returns a list with ticker symbols + """ + if len(stocks) < 2: + console.print("Please have at least 2 loaded tickers to create views.\n") + + p_views = [[""] * len(stocks) for i in range(n)] + p_views_df = pd.DataFrame(p_views, columns=stocks) + + q_views = [[""] for i in range(n)] + q_views_df = pd.DataFrame(q_views, columns=["Returns"]) + + if file.endswith(".xlsx"): + pass + else: + file += ".xlsx" + + with pd.ExcelWriter(file) as writer: + p_views_df.to_excel(writer, sheet_name="p_views") + q_views_df.to_excel(writer, sheet_name="q_views") diff --git a/openbb_terminal/portfolio/portfolio_optimization/optimizer_model.py b/openbb_terminal/portfolio/portfolio_optimization/optimizer_model.py index 8969ff72067..67b0b8a87d8 100644 --- a/openbb_terminal/portfolio/portfolio_optimization/optimizer_model.py +++ b/openbb_terminal/portfolio/portfolio_optimization/optimizer_model.py @@ -1,14 +1,15 @@ """Optimization Model""" __docformat__ = "numpy" +# pylint: disable=R0913, C0302, E1101 + import logging from typing import Dict, List, Tuple import numpy as np import pandas as pd +import riskfolio as rp import yfinance as yf -from pypfopt import expected_returns, risk_models -from pypfopt.efficient_frontier import EfficientFrontier from openbb_terminal.decorators import log_start_end from openbb_terminal.portfolio.portfolio_optimization import yahoo_finance_model @@ -16,36 +17,142 @@ from openbb_terminal.rich_config import console logger = logging.getLogger(__name__) +upper_risk = { + "MV": "upperdev", + "MAD": "uppermad", + "MSV": "uppersdev", + "FLPM": "upperflpm", + "SLPM": "upperslpm", + "CVaR": "upperCVaR", + "EVaR": "upperEVaR", + "WR": "upperwr", + "MDD": "uppermdd", + "ADD": "upperadd", + "CDaR": "upperCDaR", + "EDaR": "upperEDaR", + "UCI": "upperuci", +} + +time_factor = { + "D": 252.0, + "W": 52.0, + "M": 12.0, +} + @log_start_end(log=logger) -def get_equal_weights(stocks: List[str], value: float = 1.0) -> Dict: +def get_equal_weights( + stocks: List[str], + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + value: float = 1.0, +) -> Tuple: """Equally weighted portfolio, where weight = 1/# of stocks Parameters ---------- - stocks: List[str] - List of tickers to be included in optimization - value : float - Amount of money to allocate instead of percentage + stocks : List[str] + List of portfolio stocks + period : str, optional + Period to get stock data, by default "3mo" + start: str, optional + If not using period, start date string (YYYY-MM-DD) + end: str, optional + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool, optional + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float + Value used to replace outliers that are higher to threshold. + method: str + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + value : float, optional + Amount to allocate. Returns percentages if set to 1. Returns ------- dict Dictionary of weights where keys are the tickers """ - return {stock: value * round(1 / len(stocks), 5) for stock in stocks} + + stock_prices = yahoo_finance_model.process_stocks(stocks, period, start, end) + stock_returns = yahoo_finance_model.process_returns( + stock_prices, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + ) + + weights = {stock: value * round(1 / len(stocks), 5) for stock in stocks} + + return weights, stock_returns @log_start_end(log=logger) def get_property_weights( - stocks: List[str], s_property: str, value: float = 1.0 -) -> Dict: + stocks: List[str], + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + s_property: str = "marketCap", + value: float = 1.0, +) -> Tuple: """Calculate portfolio weights based on selected property Parameters ---------- stocks : List[str] List of portfolio stocks + period : str, optional + Period to get stock data, by default "3mo" + start: str, optional + If not using period, start date string (YYYY-MM-DD) + end: str, optional + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool, optional + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float + Value used to replace outliers that are higher to threshold. + method: str + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. s_property : str Property to weight portfolio by value : float, optional @@ -56,6 +163,17 @@ def get_property_weights( Dict Dictionary of portfolio weights or allocations """ + + stock_prices = yahoo_finance_model.process_stocks(stocks, period, start, end) + stock_returns = yahoo_finance_model.process_returns( + stock_prices, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + ) + prop = {} prop_sum = 0 for stock in stocks: @@ -67,71 +185,38 @@ def get_property_weights( if prop_sum == 0: console.print(f"No {s_property} was found on list of tickers provided", "\n") - return {} + return None, None - return {k: value * v / prop_sum for k, v in prop.items()} + weights = {k: value * v / prop_sum for k, v in prop.items()} + + return weights, stock_returns @log_start_end(log=logger) -def get_maxsharpe_portfolio( - stocks: List[str], period: str, rfrate: float -) -> Tuple[Dict, EfficientFrontier]: - """Generate weights for max sharpe portfolio - - Parameters - ---------- - stocks : List[str] - List of portfolio tickers - period : str, optional - Period to get stock data, by default "3mo" - rfrate : float, optional - Risk free rate, by default 0.02 - - Returns - ------- - Dict - Dictionary of tickers and weights - EfficientFrontier - EfficientFrontier object - """ - stock_prices = yahoo_finance_model.process_stocks(stocks, period) - ef = prepare_efficient_frontier(stock_prices) - return dict(ef.max_sharpe(rfrate)), ef - - -@log_start_end(log=logger) -def get_minvol_portfolio( - stocks: List[str], period: str = "3mo" -) -> Tuple[Dict, EfficientFrontier]: - """Generate weights for minimum volatility portfolio - - Parameters - ---------- - stocks : List[str] - List of portfolio tickers - period : str, optional - Period to get stock data, by default "3mo" - - Returns - ------- - Dict - Dictionary of tickers and weights - EfficientFrontier - EfficientFrontier object - """ - stock_prices = yahoo_finance_model.process_stocks(stocks, period) - ef = prepare_efficient_frontier(stock_prices) - return dict(ef.min_volatility()), ef - - -@log_start_end(log=logger) -def get_maxquadutil_portfolio( +def get_mean_risk_portfolio( stocks: List[str], - period: str = "3mo", - risk_aversion: float = 1.0, - market_neutral: bool = False, -) -> Tuple[Dict, EfficientFrontier]: - """Get portfolio maximizing quadratic utility at a given risk aversion + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + risk_measure: str = "MV", + objective: str = "Sharpe", + risk_free_rate: float = 0, + risk_aversion: float = 1, + alpha: float = 0.05, + target_return: float = -1, + target_risk: float = -1, + mean: str = "hist", + covariance: str = "hist", + d_ewma: float = 0.94, + value: float = 1.0, + value_short: float = 0.0, +) -> Tuple: + """Builds a mean risk optimal portfolio Parameters ---------- @@ -139,31 +224,186 @@ def get_maxquadutil_portfolio( List of portfolio stocks period : str, optional Period to get stock data, by default "3mo" - risk_aversion : float, optional - Risk aversion level, by default 1.0 - market_neutral : bool, optional - Whether portfolio is market neutral, by default False + start: str, optional + If not using period, start date string (YYYY-MM-DD) + end: str, optional + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool, optional + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float + Value used to replace outliers that are higher to threshold. + method: str + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + objective: str + Objective function of the optimization model. + The default is 'Sharpe'. Possible values are: + + - 'MinRisk': Minimize the selected risk measure. + - 'Utility': Maximize the risk averse utility function. + - 'Sharpe': Maximize the risk adjusted return ratio based on the selected risk measure. + - 'MaxRet': Maximize the expected return of the portfolio. + + risk_measure: str, optional + The risk measure used to optimize the portfolio. + The default is 'MV'. Possible values are: + + - 'MV': Standard Deviation. + - 'MAD': Mean Absolute Deviation. + - 'MSV': Semi Standard Deviation. + - 'FLPM': First Lower Partial Moment (Omega Ratio). + - 'SLPM': Second Lower Partial Moment (Sortino Ratio). + - 'CVaR': Conditional Value at Risk. + - 'EVaR': Entropic Value at Risk. + - 'WR': Worst Realization. + - 'ADD': Average Drawdown of uncompounded cumulative returns. + - 'UCI': Ulcer Index of uncompounded cumulative returns. + - 'CDaR': Conditional Drawdown at Risk of uncompounded cumulative returns. + - 'EDaR': Entropic Drawdown at Risk of uncompounded cumulative returns. + - 'MDD': Maximum Drawdown of uncompounded cumulative returns. + + risk_free_rate: float, optional + Risk free rate, must be in annual frequency. Used for + 'FLPM' and 'SLPM' and Sharpe objective function. The default is 0. + risk_aversion: float, optional + Risk aversion factor of the 'Utility' objective function. + The default is 1. + alpha: float, optional + Significance level of CVaR, EVaR, CDaR and EDaR + target_return: float, optional + Constraint on minimum level of portfolio's return. + target_risk: float, optional + Constraint on maximum level of portfolio's risk. + mean: str, optional + The method used to estimate the expected returns. + The default value is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + + covariance: str, optional + The method used to estimate the covariance matrix: + The default is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + - 'ledoit': use the Ledoit and Wolf Shrinkage method. + - 'oas': use the Oracle Approximation Shrinkage method. + - 'shrunk': use the basic Shrunk Covariance method. + - 'gl': use the basic Graphical Lasso Covariance method. + - 'jlogo': use the j-LoGo Covariance method. For more information see: :cite:`a-jLogo`. + - 'fixed': denoise using fixed method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'spectral': denoise using spectral method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'shrink': denoise using shrink method. For more information see chapter 2 of :cite:`a-MLforAM`. + + d_ewma: float, optional + The smoothing factor of ewma methods. + The default is 0.94. + value : float, optional + Amount of money to allocate. The default is 1. + value_short : float, optional + Amount to allocate to portfolio in short positions. The default is 0. Returns ------- - Dict - Dictionary of portfolio weights - EfficientFrontier - EfficientFrontier object + Tuple + Dictionary of portfolio weights and DataFrame of stock returns """ - stock_prices = yahoo_finance_model.process_stocks(stocks, period) - ef = prepare_efficient_frontier(stock_prices) - return ef.max_quadratic_utility(risk_aversion, market_neutral), ef + stock_prices = yahoo_finance_model.process_stocks(stocks, period, start, end) + stock_returns = yahoo_finance_model.process_returns( + stock_prices, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + ) + + risk_free_rate = risk_free_rate / time_factor[freq.upper()] + + # Building the portfolio object + port = rp.Portfolio(returns=stock_returns, alpha=alpha) + + # Estimate input parameters: + port.assets_stats(method_mu=mean, method_cov=covariance, d=d_ewma) + + # Budget constraints + port.upperlng = value + if value_short > 0: + port.sht = True + port.uppersht = value_short + port.budget = value - value_short + else: + port.budget = value + + # Estimate optimal portfolio: + model = "Classic" + hist = True + + if target_return > -1: + port.lowerret = float(target_return) / time_factor[freq.upper()] + + if target_risk > -1: + if risk_measure not in ["ADD", "MDD", "CDaR", "EDaR", "UCI"]: + setattr( + port, + upper_risk[risk_measure], + float(target_risk) / time_factor[freq.upper()] ** 0.5, + ) + else: + setattr(port, upper_risk[risk_measure], float(target_risk)) + + weights = port.optimization( + model=model, + rm=risk_measure, + obj=objective, + rf=risk_free_rate, + l=risk_aversion, + hist=hist, + ) + + if weights is not None: + weights = weights.round(5) + weights = weights.squeeze().to_dict() + + return weights, stock_returns @log_start_end(log=logger) -def get_efficient_risk_portfolio( +def get_max_diversification_portfolio( stocks: List[str], - period: str = "3mo", - target_vol: float = 0.1, - market_neutral: bool = False, -) -> Tuple[Dict, EfficientFrontier]: - """Get portfolio that maximizes returns at given volatility + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + covariance: str = "hist", + d_ewma: float = 0.94, + value: float = 1.0, + value_short: float = 0, +) -> Tuple: + """Builds a maximal diversification portfolio Parameters ---------- @@ -171,31 +411,113 @@ def get_efficient_risk_portfolio( List of portfolio stocks period : str, optional Period to get stock data, by default "3mo" - target_vol : float, optional - Target volatility level, by default 0.1 - market_neutral : bool, optional - Whether portfolio is market neutral, by default False + start: str + If not using period, start date string (YYYY-MM-DD) + end: str + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float + Value used to replace outliers that are higher to threshold. + method: str + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + covariance: str, optional + The method used to estimate the covariance matrix: + The default is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + - 'ledoit': use the Ledoit and Wolf Shrinkage method. + - 'oas': use the Oracle Approximation Shrinkage method. + - 'shrunk': use the basic Shrunk Covariance method. + - 'gl': use the basic Graphical Lasso Covariance method. + - 'jlogo': use the j-LoGo Covariance method. For more information see: :cite:`a-jLogo`. + - 'fixed': denoise using fixed method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'spectral': denoise using spectral method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'shrink': denoise using shrink method. For more information see chapter 2 of :cite:`a-MLforAM`. + + d_ewma: float, optional + The smoothing factor of ewma methods. + The default is 0.94. + value : float, optional + Amount of money to allocate. The default is 1. + value_short : float, optional + Amount to allocate to portfolio in short positions. The default is 0. Returns ------- - Dict - Dictionary of weights - EfficientFrontier - Efficient Frontier object + Tuple + Dictionary of portfolio weights and DataFrame of stock returns """ - stock_prices = yahoo_finance_model.process_stocks(stocks, period) - ef = prepare_efficient_frontier(stock_prices) - return ef.efficient_risk(target_vol, market_neutral), ef + stock_prices = yahoo_finance_model.process_stocks(stocks, period, start, end) + stock_returns = yahoo_finance_model.process_returns( + stock_prices, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + ) + + # Building the portfolio object + port = rp.Portfolio(returns=stock_returns) + + # Estimate input parameters: + port.assets_stats(method_mu="hist", method_cov=covariance, d=d_ewma) + port.mu = stock_returns.std().to_frame().T + + # Budget constraints + port.upperlng = value + if value_short > 0: + port.sht = True + port.uppersht = value_short + port.budget = value - value_short + else: + port.budget = value + + # Estimate optimal portfolio: + weights = port.optimization(model="Classic", rm="MV", obj="Sharpe", rf=0, hist=True) + + if weights is not None: + weights = weights.round(5) + weights = weights.squeeze().to_dict() + + return weights, stock_returns @log_start_end(log=logger) -def get_efficient_return_portfolio( +def get_max_decorrelation_portfolio( stocks: List[str], - period: str = "3mo", - target_return: float = 0.1, - market_neutral: bool = False, -) -> Tuple[Dict, EfficientFrontier]: - """Get portfolio that minimizes volatility at given return + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + covariance: str = "hist", + d_ewma: float = 0.94, + value: float = 1.0, + value_short: float = 0, +) -> Tuple: + """Builds a maximal decorrelation portfolio Parameters ---------- @@ -203,67 +525,972 @@ def get_efficient_return_portfolio( List of portfolio stocks period : str, optional Period to get stock data, by default "3mo" - target_return : float, optional - Target return level, by default 0.1 - market_neutral : bool, optional - Whether portfolio is market neutral, by default False + start: str + If not using period, start date string (YYYY-MM-DD) + end: str + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float + Value used to replace outliers that are higher to threshold. + method: str + Method used to fill nan values. Default value is 'time'. For more information see + s`interpolate `_. + covariance: str, optional + The method used to estimate the covariance matrix: + The default is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + - 'ledoit': use the Ledoit and Wolf Shrinkage method. + - 'oas': use the Oracle Approximation Shrinkage method. + - 'shrunk': use the basic Shrunk Covariance method. + - 'gl': use the basic Graphical Lasso Covariance method. + - 'jlogo': use the j-LoGo Covariance method. For more information see: :cite:`a-jLogo`. + - 'fixed': denoise using fixed method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'spectral': denoise using spectral method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'shrink': denoise using shrink method. For more information see chapter 2 of :cite:`a-MLforAM`. + + d_ewma: float, optional + The smoothing factor of ewma methods. + The default is 0.94. + value : float, optional + Amount of money to allocate. The default is 1. + value_short : float, optional + Amount to allocate to portfolio in short positions. The default is 0. Returns ------- - Dict - Dictionary of weights - EfficientFrontier - Efficient Frontier object + Tuple + Dictionary of portfolio weights and DataFrame of stock returns """ - stock_prices = yahoo_finance_model.process_stocks(stocks, period) - ef = prepare_efficient_frontier(stock_prices) - return ef.efficient_return(target_return, market_neutral), ef + stock_prices = yahoo_finance_model.process_stocks(stocks, period, start, end) + stock_returns = yahoo_finance_model.process_returns( + stock_prices, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + ) + + # Building the portfolio object + port = rp.Portfolio(returns=stock_returns) + + # Estimate input parameters: + port.assets_stats(method_mu="hist", method_cov=covariance, d=d_ewma) + port.cov = rp.cov2corr(port.cov) + + # Budget constraints + port.upperlng = value + if value_short > 0: + port.sht = True + port.uppersht = value_short + port.budget = value - value_short + else: + port.budget = value + + # Estimate optimal portfolio: + weights = port.optimization( + model="Classic", rm="MV", obj="MinRisk", rf=0, hist=True + ) + + if weights is not None: + weights = weights.round(5) + weights = weights.squeeze().to_dict() + + return weights, stock_returns @log_start_end(log=logger) -def prepare_efficient_frontier(stock_prices: pd.DataFrame): - """Take in a dataframe of prices and return an efficient frontier object +def get_black_litterman_portfolio( + stocks: List[str], + benchmark: Dict, + p_views: List, + q_views: List, + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + objective: str = "Sharpe", + risk_free_rate: float = 0, + risk_aversion: float = 1, + delta: float = None, + equilibrium: bool = True, + optimize: bool = True, + value: float = 1.0, + value_short: float = 0, +) -> Tuple: + """Builds a maximal diversification portfolio Parameters ---------- - stock_prices : DataFrame - DataFrame where indices are DateTime and columns are stocks + stocks : List[str] + List of portfolio stocks + benchmark : Dict + Dict of portfolio weights + p_views: List + Matrix P of views that shows relationships among assets and returns. + Default value to None. + q_views: List + Matrix Q of expected returns of views. Default value is None. + period : str, optional + Period to get stock data, by default "3mo" + start: str + If not using period, start date string (YYYY-MM-DD) + end: str + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float + Value used to replace outliers that are higher to threshold. + method: str + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + objective: str + Objective function of the optimization model. + The default is 'Sharpe'. Possible values are: + + - 'MinRisk': Minimize the selected risk measure. + - 'Utility': Maximize the risk averse utility function. + - 'Sharpe': Maximize the risk adjusted return ratio based on the selected risk measure. + - 'MaxRet': Maximize the expected return of the portfolio. + + risk_free_rate: float, optional + Risk free rate, must be in annual frequency. The default is 0. + risk_aversion: float, optional + Risk aversion factor of the 'Utility' objective function. + The default is 1. + delta: float, optional + Risk aversion factor of Black Litterman model. Default value is None. + equilibrium: bool, optional + If True excess returns are based on equilibrium market portfolio, if False + excess returns are calculated as historical returns minus risk free rate. + Default value is True. + optimize: bool, optional + If True Black Litterman estimates are used as inputs of mean variance model, + if False returns equilibrium weights from Black Litterman model + Default value is True. + value : float, optional + Amount of money to allocate. The default is 1. + value_short : float, optional + Amount to allocate to portfolio in short positions. The default is 0. Returns ------- - EfficientFrontier - EfficientFrontier object + Tuple + Dictionary of portfolio weights and DataFrame of stock returns """ + stock_prices = yahoo_finance_model.process_stocks(stocks, period, start, end) + stock_returns = yahoo_finance_model.process_returns( + stock_prices, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + ) - mu = expected_returns.mean_historical_return(stock_prices) - S = risk_models.sample_cov(stock_prices) - return EfficientFrontier(mu, S) + # By theory default benchmark is market capitalization portfolio + if benchmark is None: + benchmark, _ = get_property_weights( + stocks=stocks, + period=period, + start=start, + end=end, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + s_property="marketCap", + value=value, + ) + + factor = time_factor[freq.upper()] + risk_free_rate = risk_free_rate / factor + + mu, cov, weights = black_litterman( + stock_returns=stock_returns, + benchmark=benchmark, + p_views=p_views, + q_views=q_views, + delta=delta, + risk_free_rate=risk_free_rate, + equilibrium=equilibrium, + factor=factor, + ) + weights = pd.DataFrame(weights) + + if optimize: + # Building the portfolio object + port = rp.Portfolio(returns=stock_returns) + + # Estimate input parameters: + port.assets_stats(method_mu="hist", method_cov="hist") + port.mu_bl = pd.DataFrame(mu).T + port.cov_bl = pd.DataFrame(cov) + + # Budget constraints + port.upperlng = value + if value_short > 0: + port.sht = True + port.uppersht = value_short + port.budget = value - value_short + else: + port.budget = value + + # Estimate optimal portfolio: + weights = port.optimization( + model="BL", + rm="MV", + obj=objective, + rf=risk_free_rate, + l=risk_aversion, + hist=True, + ) + + if weights is not None: + weights = weights.round(5) + weights = weights.squeeze().to_dict() + + return weights, stock_returns + + +@log_start_end(log=logger) +def get_risk_parity_portfolio( + stocks: List[str], + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + risk_measure: str = "MV", + risk_cont: List[str] = None, + risk_free_rate: float = 0, + alpha: float = 0.05, + target_return: float = -1, + mean: str = "hist", + covariance: str = "hist", + d_ewma: float = 0.94, + value: float = 1.0, +) -> Tuple: + """Builds a risk parity portfolio using the risk budgeting approach + + Parameters + ---------- + stocks : List[str] + List of portfolio stocks + period : str, optional + Period to get stock data, by default "3mo" + start: str, optional + If not using period, start date string (YYYY-MM-DD) + end: str, optional + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool, optional + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float, optional + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float, optional + Value used to replace outliers that are higher to threshold. + method: str, optional + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + risk_measure: str, optional + The risk measure used to optimize the portfolio. + The default is 'MV'. Possible values are: + + - 'MV': Standard Deviation. + - 'MAD': Mean Absolute Deviation. + - 'MSV': Semi Standard Deviation. + - 'FLPM': First Lower Partial Moment (Omega Ratio). + - 'SLPM': Second Lower Partial Moment (Sortino Ratio). + - 'CVaR': Conditional Value at Risk. + - 'EVaR': Entropic Value at Risk. + - 'UCI': Ulcer Index of uncompounded cumulative returns. + - 'CDaR': Conditional Drawdown at Risk of uncompounded cumulative returns. + - 'EDaR': Entropic Drawdown at Risk of uncompounded cumulative returns. + + risk_cont: List[str], optional + The vector of risk contribution per asset. If empty, the default is + 1/n (number of assets). + risk_free_rate: float, optional + Risk free rate, must be in annual frequency. Used for + 'FLPM' and 'SLPM' and Sharpe objective function. The default is 0. + alpha: float, optional + Significance level of CVaR, EVaR, CDaR and EDaR + target_return: float, optional + Constraint on minimum level of portfolio's return. + mean: str, optional + The method used to estimate the expected returns. + The default value is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + + covariance: str, optional + The method used to estimate the covariance matrix: + The default is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + - 'ledoit': use the Ledoit and Wolf Shrinkage method. + - 'oas': use the Oracle Approximation Shrinkage method. + - 'shrunk': use the basic Shrunk Covariance method. + - 'gl': use the basic Graphical Lasso Covariance method. + - 'jlogo': use the j-LoGo Covariance method. For more information see: :cite:`a-jLogo`. + - 'fixed': denoise using fixed method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'spectral': denoise using spectral method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'shrink': denoise using shrink method. For more information see chapter 2 of :cite:`a-MLforAM`. + + d_ewma: float, optional + The smoothing factor of ewma methods. + The default is 0.94. + value : float, optional + Amount of money to allocate. The default is 1. + + Returns + ------- + Tuple + Dictionary of portfolio weights and DataFrame of stock returns + """ + stock_prices = yahoo_finance_model.process_stocks(stocks, period, start, end) + stock_returns = yahoo_finance_model.process_returns( + stock_prices, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + ) + + risk_free_rate = risk_free_rate / time_factor[freq.upper()] + + # Building the portfolio object + port = rp.Portfolio(returns=stock_returns, alpha=alpha) + + # Calculating optimal portfolio + port.assets_stats(method_mu=mean, method_cov=covariance, d=d_ewma) + + # Estimate optimal portfolio: + model = "Classic" + hist = True + + if risk_cont is None: + risk_cont_ = None # Risk contribution constraints vector + else: + risk_cont_ = np.array(risk_cont).reshape(1, -1) + risk_cont_ = risk_cont_ / np.sum(risk_cont_) + + if target_return > -1: + port.lowerret = float(target_return) / time_factor[freq.upper()] + + weights = port.rp_optimization( + model=model, rm=risk_measure, rf=risk_free_rate, b=risk_cont_, hist=hist + ) + + if weights is not None: + if value > 0.0: + weights = value * weights + weights = weights.round(5) + weights = weights.squeeze().to_dict() + + return weights, stock_returns + + +@log_start_end(log=logger) +def get_rel_risk_parity_portfolio( + stocks: List[str], + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + version: str = "A", + risk_cont: List[str] = None, + penal_factor: float = 1, + target_return: float = -1, + mean: str = "hist", + covariance: str = "hist", + d_ewma: float = 0.94, + value: float = 1.0, +) -> Tuple: + """Builds a relaxed risk parity portfolio using the least squares approach + + Parameters + ---------- + stocks : List[str] + List of portfolio stocks + period : str, optional + Period to get stock data, by default "3mo" + start: str, optional + If not using period, start date string (YYYY-MM-DD) + end: str, optional + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool, optional + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float, optional + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float, optional + Value used to replace outliers that are higher to threshold. + method: str, optional + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + version : str, optional + Relaxed risk parity model version. The default is 'A'. + Possible values are: + + - 'A': without regularization and penalization constraints. + - 'B': with regularization constraint but without penalization constraint. + - 'C': with regularization and penalization constraints. + + risk_cont: List[str], optional + The vector of risk contribution per asset. If empty, the default is + 1/n (number of assets). + penal_factor: float, optional + The penalization factor of penalization constraints. Only used with + version 'C'. The default is 1. + target_return: float, optional + Constraint on minimum level of portfolio's return. + mean: str, optional + The method used to estimate the expected returns. + The default value is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + + covariance: str, optional + The method used to estimate the covariance matrix: + The default is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + - 'ledoit': use the Ledoit and Wolf Shrinkage method. + - 'oas': use the Oracle Approximation Shrinkage method. + - 'shrunk': use the basic Shrunk Covariance method. + - 'gl': use the basic Graphical Lasso Covariance method. + - 'jlogo': use the j-LoGo Covariance method. For more information see: :cite:`a-jLogo`. + - 'fixed': denoise using fixed method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'spectral': denoise using spectral method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'shrink': denoise using shrink method. For more information see chapter 2 of :cite:`a-MLforAM`. + + d_ewma: float, optional + The smoothing factor of ewma methods. + The default is 0.94. + value : float, optional + Amount of money to allocate. The default is 1. + + Returns + ------- + Tuple + Dictionary of portfolio weights and DataFrame of stock returns + """ + stock_prices = yahoo_finance_model.process_stocks(stocks, period, start, end) + stock_returns = yahoo_finance_model.process_returns( + stock_prices, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + ) + + # Building the portfolio object + port = rp.Portfolio(returns=stock_returns) + + # Calculating optimal portfolio + port.assets_stats(method_mu=mean, method_cov=covariance, d=d_ewma) + + # Estimate optimal portfolio: + model = "Classic" + hist = True + + if risk_cont is None: + risk_cont_ = None # Risk contribution constraints vector + else: + risk_cont_ = np.array(risk_cont).reshape(1, -1) + risk_cont_ = risk_cont_ / np.sum(risk_cont_) + + if target_return > -1: + port.lowerret = float(target_return) / time_factor[freq.upper()] + + weights = port.rrp_optimization( + model=model, version=version, l=penal_factor, b=risk_cont_, hist=hist + ) + + if weights is not None: + if value > 0.0: + weights = value * weights + weights = weights.round(5) + weights = weights.squeeze().to_dict() + + return weights, stock_returns + + +@log_start_end(log=logger) +def get_hcp_portfolio( + stocks: List[str], + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + model: str = "HRP", + codependence: str = "pearson", + covariance: str = "hist", + objective: str = "MinRisk", + risk_measure: str = "MV", + risk_free_rate: float = 0, + risk_aversion: float = 1, + alpha: float = 0.05, + a_sim: int = 100, + beta: float = None, + b_sim: int = None, + linkage: str = "single", + k: int = 0, + max_k: int = 10, + bins_info: str = "KN", + alpha_tail: float = 0.05, + leaf_order: bool = True, + d_ewma: float = 0.94, + value: float = 1.0, +) -> Tuple: + """Builds hierarchical clustering based portfolios + + Parameters + ---------- + stocks : List[str] + List of portfolio stocks + period : str, optional + Period to get stock data, by default "3mo" + start: str, optional + If not using period, start date string (YYYY-MM-DD) + end: str, optional + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool, optional + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float, optional + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float, optional + Value used to replace outliers that are higher to threshold. + method: str, optional + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + model: str, optional + The hierarchical cluster portfolio model used for optimize the + portfolio. The default is 'HRP'. Possible values are: + + - 'HRP': Hierarchical Risk Parity. + - 'HERC': Hierarchical Equal Risk Contribution. + - 'NCO': Nested Clustered Optimization. + + codependence: str, optional + The codependence or similarity matrix used to build the distance + metric and clusters. The default is 'pearson'. Possible values are: + + - 'pearson': pearson correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{0.5(1-\rho^{pearson}_{i,j})}`. + - 'spearman': spearman correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{0.5(1-\rho^{spearman}_{i,j})}`. + - 'abs_pearson': absolute value pearson correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{(1-|\rho^{pearson}_{i,j}|)}`. + - 'abs_spearman': absolute value spearman correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{(1-|\rho^{spearman}_{i,j}|)}`. + - 'distance': distance correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{(1-\rho^{distance}_{i,j})}`. + - 'mutual_info': mutual information matrix. Distance used is variation information matrix. + - 'tail': lower tail dependence index matrix. Dissimilarity formula: + :math:`D_{i,j} = -\\log{\\lambda_{i,j}}`. + + covariance: str, optional + The method used to estimate the covariance matrix: + The default is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + - 'ledoit': use the Ledoit and Wolf Shrinkage method. + - 'oas': use the Oracle Approximation Shrinkage method. + - 'shrunk': use the basic Shrunk Covariance method. + - 'gl': use the basic Graphical Lasso Covariance method. + - 'jlogo': use the j-LoGo Covariance method. For more information see: :cite:`c-jLogo`. + - 'fixed': denoise using fixed method. For more information see chapter 2 of :cite:`c-MLforAM`. + - 'spectral': denoise using spectral method. For more information see chapter 2 of :cite:`c-MLforAM`. + - 'shrink': denoise using shrink method. For more information see chapter 2 of :cite:`c-MLforAM`. + + objective: str, optional + Objective function used by the NCO model. + The default is 'MinRisk'. Possible values are: + + - 'MinRisk': Minimize the selected risk measure. + - 'Utility': Maximize the risk averse utility function. + - 'Sharpe': Maximize the risk adjusted return ratio based on the selected risk measure. + - 'ERC': Equally risk contribution portfolio of the selected risk measure. + + risk_measure: str, optional + The risk measure used to optimize the portfolio. If model is 'NCO', + the risk measures available depends on the objective function. + The default is 'MV'. Possible values are: + + - 'MV': Variance. + - 'MAD': Mean Absolute Deviation. + - 'MSV': Semi Standard Deviation. + - 'FLPM': First Lower Partial Moment (Omega Ratio). + - 'SLPM': Second Lower Partial Moment (Sortino Ratio). + - 'VaR': Value at Risk. + - 'CVaR': Conditional Value at Risk. + - 'TG': Tail Gini. + - 'EVaR': Entropic Value at Risk. + - 'WR': Worst Realization (Minimax). + - 'RG': Range of returns. + - 'CVRG': CVaR range of returns. + - 'TGRG': Tail Gini range of returns. + - 'MDD': Maximum Drawdown of uncompounded cumulative returns (Calmar Ratio). + - 'ADD': Average Drawdown of uncompounded cumulative returns. + - 'DaR': Drawdown at Risk of uncompounded cumulative returns. + - 'CDaR': Conditional Drawdown at Risk of uncompounded cumulative returns. + - 'EDaR': Entropic Drawdown at Risk of uncompounded cumulative returns. + - 'UCI': Ulcer Index of uncompounded cumulative returns. + - 'MDD_Rel': Maximum Drawdown of compounded cumulative returns (Calmar Ratio). + - 'ADD_Rel': Average Drawdown of compounded cumulative returns. + - 'DaR_Rel': Drawdown at Risk of compounded cumulative returns. + - 'CDaR_Rel': Conditional Drawdown at Risk of compounded cumulative returns. + - 'EDaR_Rel': Entropic Drawdown at Risk of compounded cumulative returns. + - 'UCI_Rel': Ulcer Index of compounded cumulative returns. + + risk_free_rate: float, optional + Risk free rate, must be in annual frequency. + Used for 'FLPM' and 'SLPM'. The default is 0. + risk_aversion: float, optional + Risk aversion factor of the 'Utility' objective function. + The default is 1. + alpha: float, optional + Significance level of VaR, CVaR, EDaR, DaR, CDaR, EDaR, Tail Gini of losses. + The default is 0.05. + a_sim: float, optional + Number of CVaRs used to approximate Tail Gini of losses. The default is 100. + beta: float, optional + Significance level of CVaR and Tail Gini of gains. If None it duplicates alpha value. + The default is None. + b_sim: float, optional + Number of CVaRs used to approximate Tail Gini of gains. If None it duplicates a_sim value. + The default is None. + linkage: str, optional + Linkage method of hierarchical clustering. For more information see + `linkage `_. + The default is 'single'. Possible values are: + + - 'single'. + - 'complete'. + - 'average'. + - 'weighted'. + - 'centroid'. + - 'median'. + - 'ward'. + - 'dbht': Direct Bubble Hierarchical Tree. + + k: int, optional + Number of clusters. This value is took instead of the optimal number + of clusters calculated with the two difference gap statistic. + The default is None. + max_k: int, optional + Max number of clusters used by the two difference gap statistic + to find the optimal number of clusters. The default is 10. + bins_info: str, optional + Number of bins used to calculate variation of information. The default + value is 'KN'. Possible values are: + + - 'KN': Knuth's choice method. For more information see + `knuth_bin_width `_. + - 'FD': Freedman–Diaconis' choice method. For more information see + `freedman_bin_width `_. + - 'SC': Scotts' choice method. For more information see + `scott_bin_width `_. + - 'HGR': Hacine-Gharbi and Ravier' choice method. + + alpha_tail: float, optional + Significance level for lower tail dependence index. The default is 0.05. + leaf_order: bool, optional + Indicates if the cluster are ordered so that the distance between + successive leaves is minimal. The default is True. + d_ewma: float, optional + The smoothing factor of ewma methods. + The default is 0.94. + value : float, optional + Amount of money to allocate. The default is 1. + + Returns + ------- + Tuple + Dictionary of portfolio weights and DataFrame of stock returns + """ + stock_prices = yahoo_finance_model.process_stocks(stocks, period, start, end) + stock_returns = yahoo_finance_model.process_returns( + stock_prices, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + ) + + if linkage == "dbht": + linkage = linkage.upper() + + risk_free_rate = risk_free_rate / time_factor[freq.upper()] + # Building the portfolio object + port = rp.HCPortfolio( + returns=stock_returns, + alpha=alpha, + a_sim=a_sim, + beta=beta, + b_sim=b_sim, + ) + + weights = port.optimization( + model=model, + codependence=codependence, + covariance=covariance, + obj=objective, + rm=risk_measure, + rf=risk_free_rate, + l=risk_aversion, + linkage=linkage, + k=k, + max_k=max_k, + bins_info=bins_info, + alpha_tail=alpha_tail, + leaf_order=leaf_order, + d=d_ewma, + ) + + if weights is not None: + if value > 0.0: + weights = value * weights + weights = weights.round(5) + weights = weights.squeeze().to_dict() + + return weights, stock_returns + + +@log_start_end(log=logger) +def black_litterman( + stock_returns: pd.DataFrame, + benchmark, + p_views, + q_views, + delta=None, + risk_free_rate: float = 0, + equilibrium: bool = True, + factor: float = 252, +) -> Tuple: + """ + Calculates Black-Litterman estimates following He and Litterman (1999) + + Parameters + ---------- + stock_returns: pd.DataFrame + _description_ + benchmark: Dict + lala + p_views: List + Matrix P of views that shows relationships among assets and returns. + Default value to None. + q_views: List + Matrix Q of expected returns of views in annual frequency. Default value is None. + delta: float + Risk aversion factor. Default value is None. + risk_free_rate: float, optional + Risk free rate, must be in annual frequency. Default value is 0. + equilibrium: bool, optional + If True excess returns are based on equilibrium market portfolio, if False + excess returns are calculated as historical returns minus risk free rate. + Default value is True. + factor: int + The time factor + + Returns + ------- + Tuple: + Black-Litterman model estimates of expected returns, + covariance matrix and portfolio weights. + """ + stocks = stock_returns.columns.tolist() + benchmark = pd.Series(benchmark).to_numpy().reshape(-1, 1) + + mu = stock_returns.mean().to_numpy().reshape(-1, 1) + S = stock_returns.cov().to_numpy() + + if delta is None: + a = mu.T @ benchmark + delta = (a - risk_free_rate) / (benchmark.T @ S @ benchmark) + delta = delta.item() + + if equilibrium: + PI_eq = delta * (S @ benchmark) + else: + PI_eq = mu - risk_free_rate + + flag = False + if p_views is None or q_views is None: + p_views = np.identity(S.shape[0]) + q_views = PI_eq + flag = True + else: + p_views = np.array(p_views, dtype=float) + q_views = np.array(q_views, dtype=float).reshape(-1, 1) / factor + + tau = 1 / stock_returns.shape[0] + Omega = np.diag(np.diag(p_views @ (tau * S) @ p_views.T)) + + PI = np.linalg.inv( + np.linalg.inv(tau * S) + p_views.T @ np.linalg.inv(Omega) @ p_views + ) @ (np.linalg.inv(tau * S) @ PI_eq + p_views.T @ np.linalg.inv(Omega) @ q_views) + + if flag: + M = 0 + else: + M = np.linalg.inv( + np.linalg.inv(tau * S) + p_views.T @ np.linalg.inv(Omega) @ p_views + ) + + mu = PI + risk_free_rate + cov = S + M + weights = np.linalg.inv(delta * cov) @ PI + + mu = pd.DataFrame(mu, index=stocks).to_dict() + cov = pd.DataFrame(cov, index=stocks, columns=stocks).to_dict() + weights = pd.DataFrame(weights, index=stocks).to_dict() + + return mu, cov, weights @log_start_end(log=logger) def generate_random_portfolios( - stocks: List[str], period: str = "3mo", n_portfolios: int = 300 -): - """[summary] + stocks: List[str], + n_portfolios: int = 100, + seed: int = 123, + value: float = 1.0, +) -> pd.DataFrame: + """Build random portfolios Parameters ---------- stocks : List[str] - [description] - period : str, optional - [description], by default "3mo" - n_portfolios : int, optional - [description], by default 300 + List of portfolio stocks + n_portfolios: int, optional + "Number of portfolios to simulate. The default value is 100. + seed: int, optional + Seed used to generate random portfolios. The default value is 123. + value : float, optional + Amount of money to allocate. The default is 1. """ - stock_prices = yahoo_finance_model.process_stocks(stocks, period) - mu = expected_returns.mean_historical_return(stock_prices) - S = risk_models.sample_cov(stock_prices) - ef = EfficientFrontier(mu, S) + assets = stocks.copy() # Generate random portfolios - n_samples = n_portfolios - w = np.random.dirichlet(np.ones(len(mu)), n_samples) - rets = w.dot(mu) - stds = np.sqrt(np.diag(w @ S @ w.T)) + n_samples = int(n_portfolios / 3) + rs = np.random.RandomState(seed=seed) - return ef, rets, stds + # Equal probability for each asset + w1 = rs.dirichlet(np.ones(len(assets)), n_samples) + + # More concentrated + w2 = rs.dirichlet(np.ones(len(assets)) * 0.65, n_samples) + + # More diversified + w3 = rs.dirichlet(np.ones(len(assets)) * 2, n_samples) + + # Each individual asset + w4 = np.identity(len(assets)) + w = np.concatenate((w1, w2, w3, w4), axis=0) + w = pd.DataFrame(w, columns=assets).T + + if value > 0.0: + w = value * w + + return w diff --git a/openbb_terminal/portfolio/portfolio_optimization/optimizer_view.py b/openbb_terminal/portfolio/portfolio_optimization/optimizer_view.py index 209f9cca9ba..3d65bff154f 100644 --- a/openbb_terminal/portfolio/portfolio_optimization/optimizer_view.py +++ b/openbb_terminal/portfolio/portfolio_optimization/optimizer_view.py @@ -1,46 +1,299 @@ """Optimization View""" __docformat__ = "numpy" -import copy +# pylint: disable=R0913, R0914, C0302, too-many-branches, too-many-statements + import logging import math -from typing import List, Optional +import warnings +from datetime import date +from typing import Dict, List, Optional +import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd +import riskfolio as rp +from dateutil.relativedelta import relativedelta, FR +from matplotlib.gridspec import GridSpec from matplotlib.lines import Line2D -from pypfopt import plotting +from scipy.interpolate import interp1d from openbb_terminal.config_plot import PLOT_DPI -from openbb_terminal.decorators import log_start_end -from openbb_terminal.helper_funcs import get_rf, plot_autoscale, print_rich_table -from openbb_terminal.portfolio.portfolio_optimization import optimizer_model -from openbb_terminal.rich_config import console from openbb_terminal.config_terminal import theme +from openbb_terminal.decorators import log_start_end +from openbb_terminal.helper_funcs import plot_autoscale, print_rich_table +from openbb_terminal.portfolio.portfolio_optimization import ( + optimizer_model, + yahoo_finance_model, +) +from openbb_terminal.rich_config import console + +warnings.filterwarnings("ignore") logger = logging.getLogger(__name__) -d_period = { - "1d": "[1 Day]", - "5d": "[5 Days]", - "1mo": "[1 Month]", - "3mo": "[3 Months]", - "6mo": "[6 Months]", - "1y": "[1 Year]", - "2y": "[2 Years]", - "5y": "[5 Years]", - "10y": "[10 Years]", - "ytd": "[Year-to-Date]", - "max": "[All-time]", +objectives_choices = { + "minrisk": "MinRisk", + "sharpe": "Sharpe", + "utility": "Utility", + "maxret": "MaxRet", + "erc": "ERC", } -# pylint:disable=no-member +risk_names = { + "mv": "volatility", + "mad": "mean absolute deviation", + "gmd": "gini mean difference", + "msv": "semi standard deviation", + "var": "value at risk (VaR)", + "cvar": "conditional value at risk (CVaR)", + "tg": "tail gini", + "evar": "entropic value at risk (EVaR)", + "rg": "range", + "cvrg": "CVaR range", + "tgrg": "tail gini range", + "wr": "worst realization", + "flpm": "first lower partial moment", + "slpm": "second lower partial moment", + "mdd": "maximum drawdown uncompounded", + "add": "average drawdown uncompounded", + "dar": "drawdown at risk (DaR) uncompounded", + "cdar": "conditional drawdown at risk (CDaR) uncompounded", + "edar": "entropic drawdown at risk (EDaR) uncompounded", + "uci": "ulcer index uncompounded", + "mdd_rel": "maximum drawdown compounded", + "add_rel": "average drawdown compounded", + "dar_rel": "drawdown at risk (DaR) compounded", + "cdar_rel": "conditional drawdown at risk (CDaR) compounded", + "edar_rel": "entropic drawdown at risk (EDaR) compounded", + "uci_rel": "ulcer index compounded", +} + +risk_choices = { + "mv": "MV", + "mad": "MAD", + "gmd": "GMD", + "msv": "MSV", + "var": "VaR", + "cvar": "CVaR", + "tg": "TG", + "evar": "EVaR", + "rg": "RG", + "cvrg": "CVRG", + "tgrg": "TGRG", + "wr": "WR", + "flpm": "FLPM", + "slpm": "SLPM", + "mdd": "MDD", + "add": "ADD", + "dar": "DaR", + "cdar": "CDaR", + "edar": "EDaR", + "uci": "UCI", + "mdd_rel": "MDD_Rel", + "add_rel": "ADD_Rel", + "dar_rel": "DaR_Rel", + "cdar_rel": "CDaR_Rel", + "edar_rel": "EDaR_Rel", + "uci_rel": "UCI_Rel", +} + +time_factor = { + "D": 252.0, + "W": 52.0, + "M": 12.0, +} + +dict_conversion = {"period": "historic_period", "start": "start_period"} + + +@log_start_end(log=logger) +def d_period(period: str, start: str, end: str): + """ + Builds a date range string + + Parameters + ---------- + period : str + Period starting today + start: str + If not using period, start date string (YYYY-MM-DD) + end: str + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + """ + extra_choices = { + "ytd": "[Year-to-Date]", + "max": "[All-time]", + } + + if start == "": + if period in extra_choices: + p = extra_choices[period] + else: + if period[-1] == "d": + p = "[" + period[:-1] + " Days]" + elif period[-1] == "w": + p = "[" + period[:-1] + " Weeks]" + elif period[-1] == "o": + p = "[" + period[:-2] + " Months]" + elif period[-1] == "y": + p = "[" + period[:-1] + " Years]" + if p[1:3] == "1 ": + p = p.replace("s", "") + else: + if end == "": + end_ = date.today() + if end_.weekday() >= 5: + end_ = end_ + relativedelta(weekday=FR(-1)) + end = end_.strftime("%Y-%m-%d") + p = "[From " + start + " to " + end + "]" + + return p + + +@log_start_end(log=logger) +def portfolio_performance( + weights: dict, + stock_returns: pd.DataFrame, + freq: str = "D", + risk_measure: str = "MV", + risk_free_rate: float = 0, + alpha: float = 0.05, + a_sim: float = 100, + beta: float = None, + b_sim: float = None, +): + """ + Prints portfolio performance indicators + + Parameters + ---------- + weights: dict + Portfolio weights + stock_returns: pd.DataFrame + Stock returns dataframe + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + risk_measure : str, optional + The risk measure used. The default is 'MV'. Possible values are: + + - 'MV': Variance. + - 'MAD': Mean Absolute Deviation. + - 'MSV': Semi Standard Deviation. + - 'FLPM': First Lower Partial Moment (Omega Ratio). + - 'SLPM': Second Lower Partial Moment (Sortino Ratio). + - 'VaR': Value at Risk. + - 'CVaR': Conditional Value at Risk. + - 'TG': Tail Gini. + - 'EVaR': Entropic Value at Risk. + - 'WR': Worst Realization (Minimax). + - 'RG': Range of returns. + - 'CVRG': CVaR range of returns. + - 'TGRG': Tail Gini range of returns. + - 'MDD': Maximum Drawdown of uncompounded cumulative returns (Calmar Ratio). + - 'ADD': Average Drawdown of uncompounded cumulative returns. + - 'DaR': Drawdown at Risk of uncompounded cumulative returns. + - 'CDaR': Conditional Drawdown at Risk of uncompounded cumulative returns. + - 'EDaR': Entropic Drawdown at Risk of uncompounded cumulative returns. + - 'UCI': Ulcer Index of uncompounded cumulative returns. + - 'MDD_Rel': Maximum Drawdown of compounded cumulative returns (Calmar Ratio). + - 'ADD_Rel': Average Drawdown of compounded cumulative returns. + - 'DaR_Rel': Drawdown at Risk of compounded cumulative returns. + - 'CDaR_Rel': Conditional Drawdown at Risk of compounded cumulative returns. + - 'EDaR_Rel': Entropic Drawdown at Risk of compounded cumulative returns. + - 'UCI_Rel': Ulcer Index of compounded cumulative returns. + + risk_free_rate : float, optional + risk free rate. + alpha : float, optional + Significance level of VaR, CVaR, EDaR, DaR, CDaR, EDaR, Tail Gini of + losses. The default is 0.05. + a_sim : float, optional + Number of CVaRs used to approximate Tail Gini of losses. The default + is 100. + beta : float, optional + Significance level of CVaR and Tail Gini of gains. If None it + duplicates alpha value. The default is None. + b_sim : float, optional + Number of CVaRs used to approximate Tail Gini of gains. If None + it duplicates a_sim value. The default is None. + """ + freq = freq.upper() + weights = pd.Series(weights).to_frame() + returns = stock_returns @ weights + mu = returns.mean().item() * time_factor[freq] + sigma = returns.std().item() * time_factor[freq] ** 0.5 + sharpe = (mu - risk_free_rate) / sigma + + factor_1 = str(int(time_factor[freq])) + ") " + factor_2 = "√" + factor_1 + + print("Annual (by " + factor_1 + f"expected return: {100 * mu:.2f}%") + print("Annual (by " + factor_2 + f"volatility: {100 * sigma:.2f}%") + print(f"Sharpe ratio: {sharpe:.4f}") + + if risk_measure != "MV": + risk = rp.Sharpe_Risk( + weights, + cov=stock_returns.cov(), + returns=stock_returns, + rm=risk_measure, + rf=risk_free_rate, + alpha=alpha, + a_sim=a_sim, + beta=beta, + b_sim=b_sim, + ) + + drawdowns = [ + "MDD", + "ADD", + "DaR", + "CDaR", + "EDaR", + "UCI", + "MDD_Rel", + "ADD_Rel", + "DaR_Rel", + "CDaR_Rel", + "EDaR_Rel", + "UCI_Rel", + ] + + if risk_measure in drawdowns: + sharpe_2 = (mu - risk_free_rate) / risk + print( + risk_names[risk_measure.lower()].capitalize() + + " : " + + f"{100 * risk:.2f}%" + ) + else: + risk = risk * time_factor[freq] ** 0.5 + sharpe_2 = (mu - risk_free_rate) / risk + print( + "Annual (by " + + factor_2 + + risk_names[risk_measure.lower()] + + " : " + + f"{100 * risk:.2f}%" + ) + + print( + "Return / " + risk_names[risk_measure.lower()] + f" ratio: {sharpe_2:.4f}" + ) @log_start_end(log=logger) def display_weights(weights: dict, market_neutral: bool = False): - """Print weights in a nice format + """ + Prints weights in a nice format Parameters ---------- @@ -54,15 +307,22 @@ def display_weights(weights: dict, market_neutral: bool = False): weight_df = pd.DataFrame.from_dict(data=weights, orient="index", columns=["value"]) if not market_neutral: if math.isclose(weight_df.sum()["value"], 1, rel_tol=0.1): - weight_df["value"] = (weight_df["value"] * 100).astype(str).apply( - lambda s: " " + s[:4] if s.find(".") == 1 else "" + s[:5] + weight_df["value"] = (weight_df["value"] * 100).apply( + lambda s: f"{s:.2f}" ) + " %" - else: weight_df["value"] = ( weight_df["value"] .astype(str) - .apply(lambda s: " " + s[:4] if s.find(".") == 1 else "" + s[:5]) - + " $" + .apply(lambda s: " " * (8 - len(s)) + s if len(s) < 8 else "" + s) + ) + else: + weight_df["value"] = (weight_df["value"] * 100).apply( + lambda s: f"{s:.0f}" + ) + " $" + weight_df["value"] = ( + weight_df["value"] + .astype(str) + .apply(lambda s: " " * (16 - len(s)) + s if len(s) < 16 else "" + s) ) print_rich_table(weight_df, headers=["Value"], show_index=True, title="Weights") @@ -71,359 +331,3182 @@ def display_weights(weights: dict, market_neutral: bool = False): tot_value = weight_df["value"].abs().mean() header = "Value ($)" if tot_value > 1.01 else "Value (%)" print_rich_table(weight_df, headers=[header], show_index=True, title="Weights") - console.print("") + + +@log_start_end(log=logger) +def display_weights_sa(weights: dict, weights_sa: dict): + """ + Prints weights in a nice format + + Parameters + ---------- + weights: dict + weights to display. Keys are stocks. Values are either weights or values + market_neutral : bool + Flag indicating shorting allowed (negative weights) + """ + if not weights or not weights_sa: + return + weight_df = pd.DataFrame.from_dict( + data=weights, orient="index", columns=["value"], dtype=float + ) + weight_sa_df = pd.DataFrame.from_dict( + data=weights_sa, orient="index", columns=["value s.a."], dtype=float + ) + weight_df = weight_df.join(weight_sa_df, how="inner") + weight_df["value vs value s.a."] = weight_df["value"] - weight_df["value s.a."] + + weight_df["value"] = (weight_df["value"] * 100).apply(lambda s: f"{s:.2f}") + " %" + weight_df["value"] = ( + weight_df["value"] + .astype(str) + .apply(lambda s: " " * (8 - len(s)) + s if len(s) < 8 else "" + s) + ) + weight_df["value s.a."] = (weight_df["value s.a."] * 100).apply( + lambda s: f"{s:.2f}" + ) + " %" + weight_df["value s.a."] = ( + weight_df["value s.a."] + .astype(str) + .apply( + lambda s: " " * (len("value s.a.") - len(s)) + s + if len(s) < len("value s.a.") + else "" + s + ) + ) + weight_df["value vs value s.a."] = (weight_df["value vs value s.a."] * 100).apply( + lambda s: f"{s:.2f}" + ) + " %" + weight_df["value vs value s.a."] = ( + weight_df["value vs value s.a."] + .astype(str) + .apply( + lambda s: " " * (len("value vs value s.a.") - len(s)) + s + if len(s) < len("value vs value s.a.") + else "" + s + ) + ) + + headers = list(weight_df.columns) + headers = [s.title() for s in headers] + print_rich_table( + weight_df, headers=headers, show_index=True, title="Weights Comparison" + ) + + +@log_start_end(log=logger) +def display_categories(weights: dict, categories: dict, column: str, title: str = ""): + """ + Prints categories in a nice format + + Parameters + ---------- + weights: dict + weights to display. Keys are stocks. Values are either weights or values + categories: dict + categories to display. Keys are stocks. Values are either weights or values + column: int. + column selected to show table + - ASSET_CLASS + - SECTOR + - INDUSTRY + - COUNTRY + """ + if not weights: + return + weight_df = pd.DataFrame.from_dict( + data=weights, orient="index", columns=["value"], dtype=float + ) + categories_df = pd.DataFrame.from_dict(data=categories, dtype=float) + + col = list(categories_df.columns).index(column) + categories_df = weight_df.join(categories_df.iloc[:, [col, 4, 5]], how="inner") + categories_df.set_index(column, inplace=True) + categories_df.groupby(level=0).sum() + + table_df = pd.pivot_table( + categories_df, + values=["value", "CURRENT_INVESTED_AMOUNT"], + index=["CURRENCY", column], + aggfunc=np.sum, + ) + table_df["CURRENT_WEIGHTS"] = ( + table_df["CURRENT_INVESTED_AMOUNT"] + .groupby(level=0) + .transform(lambda x: x / sum(x)) + ) + table_df["value"] = ( + table_df["value"].groupby(level=0).transform(lambda x: x / sum(x)) + ) + table_df = pd.concat( + [ + d.append(d.sum().rename((k, "TOTAL " + k))) + for k, d in table_df.groupby(level=0) + ] + ) + table_df = table_df.iloc[:, [0, 2, 1]] + + table_df["value"] = (table_df["value"] * 100).apply(lambda s: f"{s:.2f}") + " %" + table_df["value"] = ( + table_df["value"] + .astype(str) + .apply(lambda s: " " * (8 - len(s)) + s if len(s) < 8 else "" + s) + ) + table_df["CURRENT_WEIGHTS"] = (table_df["CURRENT_WEIGHTS"] * 100).apply( + lambda s: f"{s:.2f}" + ) + " %" + table_df["CURRENT_WEIGHTS"] = ( + table_df["CURRENT_WEIGHTS"] + .astype(str) + .apply( + lambda s: " " * (len("CURRENT_WEIGHTS") - len(s)) + s + if len(s) < len("CURRENT_WEIGHTS") + else "" + s + ) + ) + table_df["CURRENT_INVESTED_AMOUNT"] = ( + table_df["CURRENT_INVESTED_AMOUNT"].apply(lambda s: f"{s:,.0f}") + " $" + ) + table_df["CURRENT_INVESTED_AMOUNT"] = ( + table_df["CURRENT_INVESTED_AMOUNT"] + .astype(str) + .apply( + lambda s: " " * (len("CURRENT_INVESTED_AMOUNT") - len(s)) + s + if len(s) < len("CURRENT_INVESTED_AMOUNT") + else "" + s + ) + ) + + table_df.reset_index(inplace=True) + table_df.set_index("CURRENCY", inplace=True) + + headers = list(table_df.columns) + headers = [s.title() for s in headers] + print_rich_table(table_df, headers=headers, show_index=True, title=title) + + +@log_start_end(log=logger) +def display_categories_sa( + weights: dict, weights_sa: dict, categories: dict, column: str, title: str = "" +): + """ + Prints categories in a nice format + + Parameters + ---------- + weights: dict + weights to display. Keys are stocks. Values are either weights or values + weights_sa: dict + weights of sensitivity analysis to display. Keys are stocks. Values are either weights or values + categories: dict + categories to display. Keys are stocks. Values are either weights or values + column: int. + column selected to show table + - ASSET_CLASS + - SECTOR + - INDUSTRY + - COUNTRY + """ + if not weights or not weights_sa: + return + weight_df = pd.DataFrame.from_dict( + data=weights, orient="index", columns=["value"], dtype=float + ) + weight_sa_df = pd.DataFrame.from_dict( + data=weights_sa, orient="index", columns=["value s.a."], dtype=float + ) + categories_df = pd.DataFrame.from_dict(data=categories, dtype=float) + + col = list(categories_df.columns).index(column) + categories_df = weight_df.join(categories_df.iloc[:, [col, 4, 5]], how="inner") + categories_df = categories_df.join(weight_sa_df, how="inner") + categories_df.set_index(column, inplace=True) + categories_df.groupby(level=0).sum() + + table_df = pd.pivot_table( + categories_df, + values=["value", "value s.a.", "CURRENT_INVESTED_AMOUNT"], + index=["CURRENCY", column], + aggfunc=np.sum, + ) + table_df["CURRENT_WEIGHTS"] = ( + table_df["CURRENT_INVESTED_AMOUNT"] + .groupby(level=0) + .transform(lambda x: x / sum(x)) + ) + table_df["value"] = ( + table_df["value"].groupby(level=0).transform(lambda x: x / sum(x)) + ) + table_df["value s.a."] = ( + table_df["value s.a."].groupby(level=0).transform(lambda x: x / sum(x)) + ) + table_df = pd.concat( + [ + d.append(d.sum().rename((k, "TOTAL " + k))) + for k, d in table_df.groupby(level=0) + ] + ) + table_df["value vs value s.a."] = table_df["value"] - table_df["value s.a."] + + table_df = table_df.iloc[:, [0, 3, 1, 2, 4]] + + table_df["value"] = (table_df["value"] * 100).apply(lambda s: f"{s:.2f}") + " %" + table_df["value"] = ( + table_df["value"] + .astype(str) + .apply(lambda s: " " * (8 - len(s)) + s if len(s) < 8 else "" + s) + ) + table_df["value s.a."] = (table_df["value s.a."] * 100).apply( + lambda s: f"{s:.2f}" + ) + " %" + table_df["value s.a."] = ( + table_df["value s.a."] + .astype(str) + .apply( + lambda s: " " * (len("value s.a.") - len(s)) + s + if len(s) < len("value s.a.") + else "" + s + ) + ) + table_df["value vs value s.a."] = (table_df["value vs value s.a."] * 100).apply( + lambda s: f"{s:.2f}" + ) + " %" + table_df["value vs value s.a."] = ( + table_df["value vs value s.a."] + .astype(str) + .apply( + lambda s: " " * (len("value vs value s.a.") - len(s)) + s + if len(s) < len("value vs value s.a.") + else "" + s + ) + ) + table_df["CURRENT_WEIGHTS"] = (table_df["CURRENT_WEIGHTS"] * 100).apply( + lambda s: f"{s:.2f}" + ) + " %" + table_df["CURRENT_WEIGHTS"] = ( + table_df["CURRENT_WEIGHTS"] + .astype(str) + .apply( + lambda s: " " * (len("CURRENT_WEIGHTS") - len(s)) + s + if len(s) < len("CURRENT_WEIGHTS") + else "" + s + ) + ) + table_df["CURRENT_INVESTED_AMOUNT"] = ( + table_df["CURRENT_INVESTED_AMOUNT"].apply(lambda s: f"{s:,.0f}") + " $" + ) + table_df["CURRENT_INVESTED_AMOUNT"] = ( + table_df["CURRENT_INVESTED_AMOUNT"] + .astype(str) + .apply( + lambda s: " " * (len("CURRENT_INVESTED_AMOUNT") - len(s)) + s + if len(s) < len("CURRENT_INVESTED_AMOUNT") + else "" + s + ) + ) + + table_df.reset_index(inplace=True) + table_df.set_index("CURRENCY", inplace=True) + + headers = list(table_df.columns) + headers = [s.title() for s in headers] + print_rich_table(table_df, headers=headers, show_index=True, title=title) @log_start_end(log=logger) def display_equal_weight( stocks: List[str], - value: float, - pie: bool = False, - external_axes: Optional[List[plt.Axes]] = None, -): - """Equally weighted portfolio, where weight = 1/# of stocks + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + risk_measure="mv", + risk_free_rate: float = 0, + alpha: float = 0.05, + value: float = 1, + table: bool = False, +) -> Dict: + """ + Equally weighted portfolio, where weight = 1/# of stocks Parameters ---------- - stocks: List[str] - List of tickers to be included in optimization - value : float - Amount of money to allocate. 1 indicates percentage of portfolio - pie : bool, optional - Display a pie chart of values - external_axes: Optional[List[plt.Axes]] - Optional axes to plot data on - """ - values = optimizer_model.get_equal_weights(stocks, value) - if pie: - pie_chart_weights(values, "Equally Weighted Portfolio", external_axes) + stocks : List[str] + List of portfolio tickers + period : str, optional + Period to look at returns from + start: str, optional + If not using period, start date string (YYYY-MM-DD) + end: str, optional + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool, optional + If True calculate log returns, else arithmetic returns. Default value + is False. + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. - display_weights(values) + maxnan: float, optional + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float, optional + Value used to replace outliers that are higher to threshold. + method: str + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + risk_measure: str, optional + The risk measure used to optimize the portfolio. + The default is 'MV'. Possible values are: + + - 'MV': Standard Deviation. + - 'MAD': Mean Absolute Deviation. + - 'MSV': Semi Standard Deviation. + - 'FLPM': First Lower Partial Moment (Omega Ratio). + - 'SLPM': Second Lower Partial Moment (Sortino Ratio). + - 'CVaR': Conditional Value at Risk. + - 'EVaR': Entropic Value at Risk. + - 'WR': Worst Realization. + - 'ADD': Average Drawdown of uncompounded cumulative returns. + - 'UCI': Ulcer Index of uncompounded cumulative returns. + - 'CDaR': Conditional Drawdown at Risk of uncompounded cumulative returns. + - 'EDaR': Entropic Drawdown at Risk of uncompounded cumulative returns. + - 'MDD': Maximum Drawdown of uncompounded cumulative returns. + + risk_free_rate: float, optional + Risk free rate, must be in the same period of assets returns. Used for + 'FLPM' and 'SLPM' and Sharpe objective function. The default is 0. + alpha: float, optional + Significance level of CVaR, EVaR, CDaR and EDaR. + value : float, optional + Amount to allocate to portfolio, by default 1.0 + table: bool, optional + True if plot table weights, by default False + """ + p = d_period(period, start, end) + s_title = f"{p} Equally Weighted Portfolio\n" + + weights, stock_returns = optimizer_model.get_equal_weights( + stocks=stocks, + period=period, + start=start, + end=end, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + value=value, + ) + + if table: + console.print("\n", s_title) + display_weights(weights) + portfolio_performance( + weights=weights, + stock_returns=stock_returns, + risk_measure=risk_choices[risk_measure], + risk_free_rate=risk_free_rate, + alpha=alpha, + # a_sim=a_sim, + # beta=beta, + # b_sim=beta_sim, + freq=freq, + ) + console.print("") + + return weights @log_start_end(log=logger) def display_property_weighting( stocks: List[str], - s_property: str, - value: float = 1.0, - pie: bool = False, - external_axes: Optional[List[plt.Axes]] = None, -): - """Display portfolio weighted by selected property + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + s_property: str = "marketCap", + risk_measure="mv", + risk_free_rate: float = 0, + alpha=0.05, + value: float = 1, + table: bool = False, +) -> Dict: + """ + Builds a portfolio weighted by selected property Parameters ---------- stocks : List[str] - Stocks in portfolio + List of portfolio tickers + period : str, optional + Period to look at returns from + start: str, optional + If not using period, start date string (YYYY-MM-DD) + end: str, optional + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool, optional + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float, optional + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float, optional + Value used to replace outliers that are higher to threshold. + method: str + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. s_property : str Property to get weighted portfolio of - value : float, optional - Amount to allocate. Returns percentages if set to 1. - pie : bool, optional - Display weights as a pie chart - external_axes: Optional[List[plt.Axes]] - Optional axes to plot data on - """ - values = optimizer_model.get_property_weights(stocks, s_property, value) + risk_measure: str, optional + The risk measure used to compute indicators. + The default is 'MV'. Possible values are: - if pie: - pie_chart_weights( - values, "Weighted Portfolio based on " + s_property, external_axes + - 'MV': Standard Deviation. + - 'MAD': Mean Absolute Deviation. + - 'MSV': Semi Standard Deviation. + - 'FLPM': First Lower Partial Moment (Omega Ratio). + - 'SLPM': Second Lower Partial Moment (Sortino Ratio). + - 'CVaR': Conditional Value at Risk. + - 'EVaR': Entropic Value at Risk. + - 'WR': Worst Realization. + - 'ADD': Average Drawdown of uncompounded cumulative returns. + - 'UCI': Ulcer Index of uncompounded cumulative returns. + - 'CDaR': Conditional Drawdown at Risk of uncompounded cumulative returns. + - 'EDaR': Entropic Drawdown at Risk of uncompounded cumulative returns. + - 'MDD': Maximum Drawdown of uncompounded cumulative returns. + + risk_free_rate: float, optional + Risk free rate, must be in the same period of assets returns. Used for + 'FLPM' and 'SLPM' and Sharpe objective function. The default is 0. + alpha: float, optional + Significance level of CVaR, EVaR, CDaR and EDaR. + value : float, optional + Amount to allocate to portfolio, by default 1.0 + table: bool, optional + True if plot table weights, by default False + """ + p = d_period(period, start, end) + s_title = f"{p} Weighted Portfolio based on " + s_property + "\n" + + weights, stock_returns = optimizer_model.get_property_weights( + stocks=stocks, + period=period, + start=start, + end=end, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + s_property=s_property, + value=value, + ) + + if table: + console.print("\n", s_title) + display_weights(weights) + portfolio_performance( + weights=weights, + stock_returns=stock_returns, + risk_measure=risk_choices[risk_measure], + risk_free_rate=risk_free_rate, + alpha=alpha, + # a_sim=a_sim, + # beta=beta, + # b_sim=beta_sim, + freq=freq, ) - else: - display_weights(values) + console.print("") + + return weights + + +@log_start_end(log=logger) +def display_mean_risk( + stocks: List[str], + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + risk_measure: str = "mv", + objective: str = "sharpe", + risk_free_rate: float = 0, + risk_aversion: float = 1, + alpha: float = 0.05, + target_return: float = -1, + target_risk: float = -1, + mean: str = "hist", + covariance: str = "hist", + d_ewma: float = 0.94, + value: float = 1.0, + value_short: float = 0.0, + table: bool = False, +) -> Dict: + """ + Builds a mean risk optimal portfolio + + Parameters + ---------- + stocks : List[str] + List of portfolio tickers + period : str, optional + Period to look at returns from + start: str, optional + If not using period, start date string (YYYY-MM-DD) + end: str, optional + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool, optional + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float, optional + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float, optional + Value used to replace outliers that are higher to threshold. + method: str + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + risk_measure: str, optional + The risk measure used to optimize the portfolio. + The default is 'MV'. Possible values are: + + - 'MV': Standard Deviation. + - 'MAD': Mean Absolute Deviation. + - 'MSV': Semi Standard Deviation. + - 'FLPM': First Lower Partial Moment (Omega Ratio). + - 'SLPM': Second Lower Partial Moment (Sortino Ratio). + - 'CVaR': Conditional Value at Risk. + - 'EVaR': Entropic Value at Risk. + - 'WR': Worst Realization. + - 'ADD': Average Drawdown of uncompounded cumulative returns. + - 'UCI': Ulcer Index of uncompounded cumulative returns. + - 'CDaR': Conditional Drawdown at Risk of uncompounded cumulative returns. + - 'EDaR': Entropic Drawdown at Risk of uncompounded cumulative returns. + - 'MDD': Maximum Drawdown of uncompounded cumulative returns. + + objective: str + Objective function of the optimization model. + The default is 'Sharpe'. Possible values are: + + - 'MinRisk': Minimize the selected risk measure. + - 'Utility': Maximize the risk averse utility function. + - 'Sharpe': Maximize the risk adjusted return ratio based on the selected risk measure. + - 'MaxRet': Maximize the expected return of the portfolio. + + risk_free_rate: float, optional + Risk free rate, must be in the same period of assets returns. Used for + 'FLPM' and 'SLPM' and Sharpe objective function. The default is 0. + risk_aversion: float, optional + Risk aversion factor of the 'Utility' objective function. + The default is 1. + alpha: float, optional + Significance level of CVaR, EVaR, CDaR and EDaR + target_return: float, optional + Constraint on minimum level of portfolio's return. + target_risk: float, optional + Constraint on maximum level of portfolio's risk. + mean: str, optional + The method used to estimate the expected returns. + The default value is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + + covariance: str, optional + The method used to estimate the covariance matrix: + The default is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + - 'ledoit': use the Ledoit and Wolf Shrinkage method. + - 'oas': use the Oracle Approximation Shrinkage method. + - 'shrunk': use the basic Shrunk Covariance method. + - 'gl': use the basic Graphical Lasso Covariance method. + - 'jlogo': use the j-LoGo Covariance method. For more information see: :cite:`a-jLogo`. + - 'fixed': denoise using fixed method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'spectral': denoise using spectral method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'shrink': denoise using shrink method. For more information see chapter 2 of :cite:`a-MLforAM`. + + d_ewma: float, optional + The smoothing factor of ewma methods. + The default is 0.94. + value : float, optional + Amount to allocate to portfolio in long positions, by default 1.0 + value_short : float, optional + Amount to allocate to portfolio in short positions, by default 0.0 + table: bool, optional + True if plot table weights, by default False + """ + p = d_period(period, start, end) + if objective == "sharpe": + s_title = f"{p} Maximal return/risk ratio portfolio using " + elif objective == "minrisk": + s_title = f"{p} Minimum risk portfolio using " + elif objective == "maxret": + s_title = f"{p} Maximal return portfolio using " + elif objective == "utility": + s_title = f"{p} Maximal risk averse utility function portfolio using " + s_title += risk_names[risk_measure] + " as risk measure\n" + + weights, stock_returns = optimizer_model.get_mean_risk_portfolio( + stocks=stocks, + period=period, + start=start, + end=end, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + risk_measure=risk_choices[risk_measure], + objective=objectives_choices[objective], + risk_free_rate=risk_free_rate, + risk_aversion=risk_aversion, + alpha=alpha, + target_return=target_return, + target_risk=target_risk, + mean=mean, + covariance=covariance, + d_ewma=d_ewma, + value=value, + value_short=value_short, + ) + + if weights is None: + console.print("\n", "There is no solution with these parameters") + return {} + + if table: + console.print("\n", s_title) + display_weights(weights) + portfolio_performance( + weights=weights, + stock_returns=stock_returns, + risk_measure=risk_choices[risk_measure], + risk_free_rate=risk_free_rate, + alpha=alpha, + # a_sim=a_sim, + # beta=beta, + # b_sim=beta_sim, + freq=freq, + ) + console.print("") + + return weights @log_start_end(log=logger) def display_max_sharpe( stocks: List[str], - period: str, - value: float, - rfrate: float, - pie: bool = False, - external_axes: Optional[List[plt.Axes]] = None, -): - """Display portfolio that maximizes Sharpe Ratio over stocks - - Parameters - ---------- - stocks : List[str] - List of portfolio tickers - period : str - Period to look at returns from - value : float, optional - Amount to allocate to portfolio, by default 1.0 - rfrate : float, optional - Risk Free Rate, by default current US T-Bill rate - pie : bool, optional - Boolean to show weights as a pie chart, by default False - external_axes: Optional[List[plt.Axes]] - Optional axes to plot data on - """ - p = d_period[period] - s_title = f"{p} Weights that maximize Sharpe ratio" - ef_opt, ef = optimizer_model.get_maxsharpe_portfolio(stocks, period, rfrate) - weights = {key: value * round(port_value, 5) for key, port_value in ef_opt.items()} - if pie: - pie_chart_weights(weights, s_title, external_axes) - else: - console.print("\n", s_title) - display_weights(weights) - ef.portfolio_performance(verbose=True, risk_free_rate=rfrate) - console.print("") - - -@log_start_end(log=logger) -def display_min_volatility( - stocks: List[str], - period: str = "3mo", + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + risk_measure: str = "MV", + risk_free_rate: float = 0, + alpha: float = 0.05, + target_return: float = -1, + target_risk: float = -1, + mean: str = "hist", + covariance: str = "hist", + d_ewma: float = 0.94, value: float = 1.0, - pie: bool = False, - external_axes: Optional[List[plt.Axes]] = None, -): - """Display portfolio with minimum volatility - - Parameters - ---------- - stocks : List[str] - List of portfolio tickers - period : str - Period to look at returns from - value : float, optional - Amount to allocate to portfolio, by default 1.0 - pie : bool, optional - Boolean to show weights as a pie chart, by default False - external_axes: Optional[List[plt.Axes]] - Optional axes to plot data on + value_short: float = 0.0, + table: bool = False, +) -> Dict: """ - s_title = f"{d_period[period]} Weights that minimize volatility" - ef_opt, ef = optimizer_model.get_minvol_portfolio(stocks, period) - weights = {key: value * round(port_value, 5) for key, port_value in ef_opt.items()} - if pie: - pie_chart_weights(weights, s_title, external_axes) - else: - console.print("\n", s_title) - display_weights(weights) - ef.portfolio_performance(verbose=True) - console.print("") - - -@log_start_end(log=logger) -def display_max_quadratic_utility( - stocks: List[str], - period: str = "3mo", - value: float = 1.0, - risk_aversion: float = 1.0, - market_neutral: bool = False, - pie: bool = False, - external_axes: Optional[List[plt.Axes]] = None, -): - """Display portfolio weights that maximize utility function given some risk aversion + Builds a maximal return/risk ratio portfolio Parameters ---------- stocks : List[str] List of portfolio tickers period : str, optional - Period to get data for, by default "3mo" + Period to look at returns from + start: str, optional + If not using period, start date string (YYYY-MM-DD) + end: str, optional + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool, optional + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float, optional + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float, optional + Value used to replace outliers that are higher to threshold. + method: str + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + risk_measure: str, optional + The risk measure used to optimize the portfolio. + The default is 'MV'. Possible values are: + + - 'MV': Standard Deviation. + - 'MAD': Mean Absolute Deviation. + - 'MSV': Semi Standard Deviation. + - 'FLPM': First Lower Partial Moment (Omega Ratio). + - 'SLPM': Second Lower Partial Moment (Sortino Ratio). + - 'CVaR': Conditional Value at Risk. + - 'EVaR': Entropic Value at Risk. + - 'WR': Worst Realization. + - 'ADD': Average Drawdown of uncompounded cumulative returns. + - 'UCI': Ulcer Index of uncompounded cumulative returns. + - 'CDaR': Conditional Drawdown at Risk of uncompounded cumulative returns. + - 'EDaR': Entropic Drawdown at Risk of uncompounded cumulative returns. + - 'MDD': Maximum Drawdown of uncompounded cumulative returns. + + risk_free_rate: float, optional + Risk free rate, must be in the same period of assets returns. Used for + 'FLPM' and 'SLPM' and Sharpe objective function. The default is 0. + alpha: float, optional + Significance level of CVaR, EVaR, CDaR and EDaR + target_return: float, optional + Constraint on minimum level of portfolio's return. + target_risk: float, optional + Constraint on maximum level of portfolio's risk. + mean: str, optional + The method used to estimate the expected returns. + The default value is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + + covariance: str, optional + The method used to estimate the covariance matrix: + The default is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + - 'ledoit': use the Ledoit and Wolf Shrinkage method. + - 'oas': use the Oracle Approximation Shrinkage method. + - 'shrunk': use the basic Shrunk Covariance method. + - 'gl': use the basic Graphical Lasso Covariance method. + - 'jlogo': use the j-LoGo Covariance method. For more information see: :cite:`a-jLogo`. + - 'fixed': denoise using fixed method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'spectral': denoise using spectral method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'shrink': denoise using shrink method. For more information see chapter 2 of :cite:`a-MLforAM`. + + d_ewma: float, optional + The smoothing factor of ewma methods. + The default is 0.94. value : float, optional - Amount to allocate to portfolio, by default 1.0 - risk_aversion : float, optional - Max risk aversion for optimization, by default 1.0 - market_neutral : bool, optional - Boolean to allow for shorting, by default False - pie : bool, optional - Boolean to display weights as pie chart by default False - external_axes: Optional[List[plt.Axes]] - Optional axes to plot data on + Amount to allocate to portfolio in long positions, by default 1.0 + value_short : float, optional + Amount to allocate to portfolio in short positions, by default 0.0 + table: bool, optional + True if plot table weights, by default False """ - s_title = f"{d_period[period]} Weights that maximise quadratic utility with risk aversion: {risk_aversion}" - ef_opt, ef = optimizer_model.get_maxquadutil_portfolio( - stocks, period, risk_aversion, market_neutral + weights = display_mean_risk( + stocks=stocks, + period=period, + start=start, + end=end, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + risk_measure=risk_measure, + objective="sharpe", + risk_free_rate=risk_free_rate, + alpha=alpha, + target_return=target_return, + target_risk=target_risk, + mean=mean, + covariance=covariance, + d_ewma=d_ewma, + value=value, + value_short=value_short, + table=table, ) - weights = {key: value * round(port_value, 5) for key, port_value in ef_opt.items()} - - if not market_neutral and pie: - pie_chart_weights(weights, s_title, external_axes) - ef.portfolio_performance(verbose=True) - console.print("") - return - - console.print(s_title) - display_weights(weights, market_neutral) - ef.portfolio_performance(verbose=True) - console.print("") + return weights @log_start_end(log=logger) -def display_efficient_risk( +def display_min_risk( stocks: List[str], - period: str = "3mo", + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + risk_measure: str = "MV", + risk_free_rate: float = 0, + alpha: float = 0.05, + target_return: float = -1, + target_risk: float = -1, + mean: str = "hist", + covariance: str = "hist", + d_ewma: float = 0.94, value: float = 1.0, - target_volatility: float = 1.0, - market_neutral: bool = False, - pie: bool = False, - external_axes: Optional[List[plt.Axes]] = None, -): - """Displays portfolio that maximizes returns at given volatility + value_short: float = 0.0, + table: bool = False, +) -> Dict: + """ + Builds a minimum risk portfolio Parameters ---------- stocks : List[str] List of portfolio tickers period : str, optional - Period to get data for, by default "3mo" + Period to look at returns from + start: str, optional + If not using period, start date string (YYYY-MM-DD) + end: str, optional + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool, optional + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float, optional + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float, optional + Value used to replace outliers that are higher to threshold. + method: str + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + risk_measure: str, optional + The risk measure used to optimize the portfolio. + The default is 'MV'. Possible values are: + + - 'MV': Standard Deviation. + - 'MAD': Mean Absolute Deviation. + - 'MSV': Semi Standard Deviation. + - 'FLPM': First Lower Partial Moment (Omega Ratio). + - 'SLPM': Second Lower Partial Moment (Sortino Ratio). + - 'CVaR': Conditional Value at Risk. + - 'EVaR': Entropic Value at Risk. + - 'WR': Worst Realization. + - 'ADD': Average Drawdown of uncompounded cumulative returns. + - 'UCI': Ulcer Index of uncompounded cumulative returns. + - 'CDaR': Conditional Drawdown at Risk of uncompounded cumulative returns. + - 'EDaR': Entropic Drawdown at Risk of uncompounded cumulative returns. + - 'MDD': Maximum Drawdown of uncompounded cumulative returns. + + risk_free_rate: float, optional + Risk free rate, must be in the same period of assets returns. Used for + 'FLPM' and 'SLPM' and Sharpe objective function. The default is 0. + alpha: float, optional + Significance level of CVaR, EVaR, CDaR and EDaR + target_return: float, optional + Constraint on minimum level of portfolio's return. + target_risk: float, optional + Constraint on maximum level of portfolio's risk. + mean: str, optional + The method used to estimate the expected returns. + The default value is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + + covariance: str, optional + The method used to estimate the covariance matrix: + The default is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + - 'ledoit': use the Ledoit and Wolf Shrinkage method. + - 'oas': use the Oracle Approximation Shrinkage method. + - 'shrunk': use the basic Shrunk Covariance method. + - 'gl': use the basic Graphical Lasso Covariance method. + - 'jlogo': use the j-LoGo Covariance method. For more information see: :cite:`a-jLogo`. + - 'fixed': denoise using fixed method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'spectral': denoise using spectral method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'shrink': denoise using shrink method. For more information see chapter 2 of :cite:`a-MLforAM`. + + d_ewma: float, optional + The smoothing factor of ewma methods. + The default is 0.94. value : float, optional - Amount to allocate to portfolio, by default 1.0 - target_volatility : float, optional - Target volatility level, by default 0.1 - market_neutral : bool, optional - Boolean to allow for shorting, by default False - pie : bool, optional - Boolean to display weights as pie chart by default False - external_axes: Optional[List[plt.Axes]] - Optional axes to plot data on + Amount to allocate to portfolio in long positions, by default 1.0 + value_short : float, optional + Amount to allocate to portfolio in short positions, by default 0.0 + table: bool, optional + True if plot table weights, by default False """ - s_title = f"{d_period[period]} Weights that maximise returns at target volatility: {target_volatility}" - try: - ef_opt, ef = optimizer_model.get_efficient_risk_portfolio( - stocks, period, target_volatility, market_neutral - ) - except ValueError as e: - console.print(f"[red]{e}[/red]\n") - return - weights = {key: value * round(port_value, 5) for key, port_value in ef_opt.items()} - - if not market_neutral and pie: - pie_chart_weights(weights, s_title, external_axes) - ef.portfolio_performance(verbose=True) - console.print("") - return - - console.print(s_title) - display_weights(weights, market_neutral) - ef.portfolio_performance(verbose=True) - console.print("") + weights = display_mean_risk( + stocks=stocks, + period=period, + start=start, + end=end, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + risk_measure=risk_measure, + objective="minrisk", + risk_free_rate=risk_free_rate, + alpha=alpha, + target_return=target_return, + target_risk=target_risk, + mean=mean, + covariance=covariance, + d_ewma=d_ewma, + value=value, + value_short=value_short, + table=table, + ) + return weights @log_start_end(log=logger) -def display_efficient_return( +def display_max_util( stocks: List[str], - period: str = "3mo", + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + risk_measure: str = "MV", + risk_free_rate: float = 0, + risk_aversion: float = 1, + alpha: float = 0.05, + target_return: float = -1, + target_risk: float = -1, + mean: str = "hist", + covariance: str = "hist", + d_ewma: float = 0.94, value: float = 1.0, - target_return: float = 1.0, - market_neutral: bool = False, - pie: bool = False, - external_axes: Optional[List[plt.Axes]] = None, -): - """Displays portfolio that minimizes volatility at given return + value_short: float = 0.0, + table: bool = False, +) -> Dict: + """ + Builds a maximal risk averse utility portfolio Parameters ---------- stocks : List[str] List of portfolio tickers period : str, optional - Period to get data for, by default "3mo" + Period to look at returns from + start: str, optional + If not using period, start date string (YYYY-MM-DD) + end: str, optional + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool, optional + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float, optional + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float, optional + Value used to replace outliers that are higher to threshold. + method: str + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + risk_measure: str, optional + The risk measure used to optimize the portfolio. + The default is 'MV'. Possible values are: + + - 'MV': Standard Deviation. + - 'MAD': Mean Absolute Deviation. + - 'MSV': Semi Standard Deviation. + - 'FLPM': First Lower Partial Moment (Omega Ratio). + - 'SLPM': Second Lower Partial Moment (Sortino Ratio). + - 'CVaR': Conditional Value at Risk. + - 'EVaR': Entropic Value at Risk. + - 'WR': Worst Realization. + - 'ADD': Average Drawdown of uncompounded cumulative returns. + - 'UCI': Ulcer Index of uncompounded cumulative returns. + - 'CDaR': Conditional Drawdown at Risk of uncompounded cumulative returns. + - 'EDaR': Entropic Drawdown at Risk of uncompounded cumulative returns. + - 'MDD': Maximum Drawdown of uncompounded cumulative returns. + + risk_free_rate: float, optional + Risk free rate, must be in the same period of assets returns. Used for + 'FLPM' and 'SLPM' and Sharpe objective function. The default is 0. + risk_aversion: float, optional + Risk aversion factor of the 'Utility' objective function. + The default is 1. + alpha: float, optional + Significance level of CVaR, EVaR, CDaR and EDaR + target_return: float, optional + Constraint on minimum level of portfolio's return. + target_risk: float, optional + Constraint on maximum level of portfolio's risk. + mean: str, optional + The method used to estimate the expected returns. + The default value is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + + covariance: str, optional + The method used to estimate the covariance matrix: + The default is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + - 'ledoit': use the Ledoit and Wolf Shrinkage method. + - 'oas': use the Oracle Approximation Shrinkage method. + - 'shrunk': use the basic Shrunk Covariance method. + - 'gl': use the basic Graphical Lasso Covariance method. + - 'jlogo': use the j-LoGo Covariance method. For more information see: :cite:`a-jLogo`. + - 'fixed': denoise using fixed method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'spectral': denoise using spectral method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'shrink': denoise using shrink method. For more information see chapter 2 of :cite:`a-MLforAM`. + + d_ewma: float, optional + The smoothing factor of ewma methods. + The default is 0.94. value : float, optional - Amount to allocate to portfolio, by default 1.0 - target_return : float, optional - Target return level, by default 0.1 - market_neutral : bool, optional - Boolean to allow for shorting, by default False - pie : bool, optional - Boolean to display weights as pie chart by default False - external_axes: Optional[List[plt.Axes]] - Optional axes to plot data on + Amount to allocate to portfolio in long positions, by default 1.0 + value_short : float, optional + Amount to allocate to portfolio in short positions, by default 0.0 + table: bool, optional + True if plot table weights, by default False """ - s_title = f"{d_period[period]} Weights that minimizes volatility at target return: {target_return}" - try: - ef_opt, ef = optimizer_model.get_efficient_return_portfolio( - stocks, period, target_return, market_neutral + weights = display_mean_risk( + stocks=stocks, + period=period, + start=start, + end=end, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + risk_measure=risk_measure, + objective="utility", + risk_free_rate=risk_free_rate, + risk_aversion=risk_aversion, + alpha=alpha, + target_return=target_return, + target_risk=target_risk, + mean=mean, + covariance=covariance, + d_ewma=d_ewma, + value=value, + value_short=value_short, + table=table, + ) + return weights + + +@log_start_end(log=logger) +def display_max_ret( + stocks: List[str], + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + risk_measure: str = "MV", + risk_free_rate: float = 0, + alpha: float = 0.05, + target_return: float = -1, + target_risk: float = -1, + mean: str = "hist", + covariance: str = "hist", + d_ewma: float = 0.94, + value: float = 1.0, + value_short: float = 0.0, + table: bool = False, +) -> Dict: + """ + Builds a maximal return portfolio + + Parameters + ---------- + stocks : List[str] + List of portfolio tickers + period : str, optional + Period to look at returns from + start: str, optional + If not using period, start date string (YYYY-MM-DD) + end: str, optional + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool, optional + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float, optional + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float, optional + Value used to replace outliers that are higher to threshold. + method: str + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + risk_measure: str, optional + The risk measure used to optimize the portfolio. + The default is 'MV'. Possible values are: + + - 'MV': Standard Deviation. + - 'MAD': Mean Absolute Deviation. + - 'MSV': Semi Standard Deviation. + - 'FLPM': First Lower Partial Moment (Omega Ratio). + - 'SLPM': Second Lower Partial Moment (Sortino Ratio). + - 'CVaR': Conditional Value at Risk. + - 'EVaR': Entropic Value at Risk. + - 'WR': Worst Realization. + - 'ADD': Average Drawdown of uncompounded cumulative returns. + - 'UCI': Ulcer Index of uncompounded cumulative returns. + - 'CDaR': Conditional Drawdown at Risk of uncompounded cumulative returns. + - 'EDaR': Entropic Drawdown at Risk of uncompounded cumulative returns. + - 'MDD': Maximum Drawdown of uncompounded cumulative returns. + + risk_free_rate: float, optional + Risk free rate, must be in the same period of assets returns. Used for + 'FLPM' and 'SLPM' and Sharpe objective function. The default is 0. + alpha: float, optional + Significance level of CVaR, EVaR, CDaR and EDaR + target_return: float, optional + Constraint on minimum level of portfolio's return. + target_risk: float, optional + Constraint on maximum level of portfolio's risk. + mean: str, optional + The method used to estimate the expected returns. + The default value is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + + covariance: str, optional + The method used to estimate the covariance matrix: + The default is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + - 'ledoit': use the Ledoit and Wolf Shrinkage method. + - 'oas': use the Oracle Approximation Shrinkage method. + - 'shrunk': use the basic Shrunk Covariance method. + - 'gl': use the basic Graphical Lasso Covariance method. + - 'jlogo': use the j-LoGo Covariance method. For more information see: :cite:`a-jLogo`. + - 'fixed': denoise using fixed method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'spectral': denoise using spectral method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'shrink': denoise using shrink method. For more information see chapter 2 of :cite:`a-MLforAM`. + + d_ewma: float, optional + The smoothing factor of ewma methods. + The default is 0.94. + value : float, optional + Amount to allocate to portfolio in long positions, by default 1.0 + value_short : float, optional + Amount to allocate to portfolio in short positions, by default 0.0 + table: bool, optional + True if plot table weights, by default False + """ + weights = display_mean_risk( + stocks=stocks, + period=period, + start=start, + end=end, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + risk_measure=risk_measure, + objective="maxret", + risk_free_rate=risk_free_rate, + alpha=alpha, + target_return=target_return, + target_risk=target_risk, + mean=mean, + covariance=covariance, + d_ewma=d_ewma, + value=value, + value_short=value_short, + table=table, + ) + return weights + + +@log_start_end(log=logger) +def display_max_div( + stocks: List[str], + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + covariance: str = "hist", + d_ewma: float = 0.94, + value: float = 1.0, + value_short: float = 0.0, + table: bool = False, +) -> Dict: + """ + Builds a maximal diversification portfolio + + Parameters + ---------- + stocks : List[str] + List of portfolio tickers + period : str, optional + Period to look at returns from + start: str, optional + If not using period, start date string (YYYY-MM-DD) + end: str, optional + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool, optional + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float, optional + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float, optional + Value used to replace outliers that are higher to threshold. + method: str + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + covariance: str, optional + The method used to estimate the covariance matrix: + The default is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + - 'ledoit': use the Ledoit and Wolf Shrinkage method. + - 'oas': use the Oracle Approximation Shrinkage method. + - 'shrunk': use the basic Shrunk Covariance method. + - 'gl': use the basic Graphical Lasso Covariance method. + - 'jlogo': use the j-LoGo Covariance method. For more information see: :cite:`a-jLogo`. + - 'fixed': denoise using fixed method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'spectral': denoise using spectral method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'shrink': denoise using shrink method. For more information see chapter 2 of :cite:`a-MLforAM`. + + d_ewma: float, optional + The smoothing factor of ewma methods. + The default is 0.94. + value : float, optional + Amount to allocate to portfolio in long positions, by default 1.0 + value_short : float, optional + Amount to allocate to portfolio in short positions, by default 0.0 + table: bool, optional + True if plot table weights, by default False + """ + p = d_period(period, start, end) + s_title = f"{p} Maximal diversification portfolio\n" + + weights, stock_returns = optimizer_model.get_max_diversification_portfolio( + stocks=stocks, + period=period, + start=start, + end=end, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + covariance=covariance, + d_ewma=d_ewma, + value=value, + value_short=value_short, + ) + if weights is None: + console.print("\n", "There is no solution with this parameters") + return {} + + if table: + console.print("\n", s_title) + display_weights(weights) + portfolio_performance( + weights=weights, + stock_returns=stock_returns, + risk_measure="MV", + risk_free_rate=0, + # alpha=0.05, + # a_sim=100, + # beta=None, + # b_sim=None, + freq=freq, ) - except ValueError as e: - # This means optimization failed - console.print(f"[red]{e}[/red]\n") - return - - weights = {key: value * round(port_value, 5) for key, port_value in ef_opt.items()} - - if not market_neutral and pie: - pie_chart_weights(weights, s_title, external_axes) - ef.portfolio_performance(verbose=True) console.print("") - return - console.print(s_title) - display_weights(weights, market_neutral) - ef.portfolio_performance(verbose=True) - console.print("") + return weights + + +@log_start_end(log=logger) +def display_max_decorr( + stocks: List[str], + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + covariance: str = "hist", + d_ewma: float = 0.94, + value: float = 1.0, + value_short: float = 0.0, + table: bool = False, +) -> Dict: + """ + Builds a maximal decorrelation portfolio + + Parameters + ---------- + stocks : List[str] + List of portfolio tickers + period : str, optional + Period to look at returns from + start: str, optional + If not using period, start date string (YYYY-MM-DD) + end: str, optional + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool, optional + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float, optional + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float, optional + Value used to replace outliers that are higher to threshold. + method: str + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + covariance: str, optional + The method used to estimate the covariance matrix: + The default is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + - 'ledoit': use the Ledoit and Wolf Shrinkage method. + - 'oas': use the Oracle Approximation Shrinkage method. + - 'shrunk': use the basic Shrunk Covariance method. + - 'gl': use the basic Graphical Lasso Covariance method. + - 'jlogo': use the j-LoGo Covariance method. For more information see: :cite:`a-jLogo`. + - 'fixed': denoise using fixed method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'spectral': denoise using spectral method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'shrink': denoise using shrink method. For more information see chapter 2 of :cite:`a-MLforAM`. + + d_ewma: float, optional + The smoothing factor of ewma methods. + The default is 0.94. + value : float, optional + Amount to allocate to portfolio in long positions, by default 1.0 + value_short : float, optional + Amount to allocate to portfolio in short positions, by default 0.0 + table: bool, optional + True if plot table weights, by default False + """ + p = d_period(period, start, end) + s_title = f"{p} Maximal decorrelation portfolio\n" + + weights, stock_returns = optimizer_model.get_max_decorrelation_portfolio( + stocks=stocks, + period=period, + start=start, + end=end, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + covariance=covariance, + d_ewma=d_ewma, + value=value, + value_short=value_short, + ) + + if weights is None: + console.print("\n", "There is no solution with this parameters") + return {} + + if table: + console.print("\n", s_title) + display_weights(weights) + portfolio_performance( + weights=weights, + stock_returns=stock_returns, + risk_measure="MV", + risk_free_rate=0, + # alpha=alpha, + # a_sim=a_sim, + # beta=beta, + # b_simb_sim, + freq=freq, + ) + console.print("") + + return weights + + +@log_start_end(log=logger) +def display_black_litterman( + stocks: List[str], + p_views: List, + q_views: List, + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + benchmark: Dict = None, + objective: str = "Sharpe", + risk_free_rate: float = 0, + risk_aversion: float = 1, + delta: float = None, + equilibrium: bool = True, + optimize: bool = True, + value: float = 1.0, + value_short: float = 0, + table: bool = False, +) -> Dict: + """ + Builds a black litterman portfolio + + Parameters + ---------- + stocks : List[str] + List of portfolio tickers + p_views: List + Matrix P of views that shows relationships among assets and returns. + Default value to None. + q_views: List + Matrix Q of expected returns of views. Default value is None. + period : str, optional + Period to look at returns from + start: str, optional + If not using period, start date string (YYYY-MM-DD) + end: str, optional + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool, optional + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float, optional + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float, optional + Value used to replace outliers that are higher to threshold. + method: str + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + benchmark : Dict + Dict of portfolio weights + objective: str + Objective function of the optimization model. + The default is 'Sharpe'. Possible values are: + + - 'MinRisk': Minimize the selected risk measure. + - 'Utility': Maximize the risk averse utility function. + - 'Sharpe': Maximize the risk adjusted return ratio based on the selected risk measure. + - 'MaxRet': Maximize the expected return of the portfolio. + + risk_free_rate: float, optional + Risk free rate, must be in annual frequency. The default is 0. + risk_aversion: float, optional + Risk aversion factor of the 'Utility' objective function. + The default is 1. + delta: float, optional + Risk aversion factor of Black Litterman model. Default value is None. + equilibrium: bool, optional + If True excess returns are based on equilibrium market portfolio, if False + excess returns are calculated as historical returns minus risk free rate. + Default value is True. + optimize: bool, optional + If True Black Litterman estimates are used as inputs of mean variance model, + if False returns equilibrium weights from Black Litterman model + Default value is True. + value : float, optional + Amount of money to allocate. The default is 1. + value_short : float, optional + Amount to allocate to portfolio in short positions. The default is 0. + table: bool, optional + True if plot table weights, by default False + """ + p = d_period(period, start, end) + s_title = f"{p} Black Litterman portfolio\n" + weights, stock_returns = optimizer_model.get_black_litterman_portfolio( + stocks=stocks, + benchmark=benchmark, + p_views=p_views, + q_views=q_views, + period=period, + start=start, + end=end, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + objective=objectives_choices[objective], + risk_free_rate=risk_free_rate, + risk_aversion=risk_aversion, + delta=delta, + equilibrium=equilibrium, + optimize=optimize, + value=value, + value_short=value_short, + ) + + if weights is None: + console.print("\n", "There is no solution with this parameters") + return {} + + if table: + console.print("\n", s_title) + display_weights(weights) + portfolio_performance( + weights=weights, + stock_returns=stock_returns, + risk_measure="MV", + risk_free_rate=0, + # alpha=alpha, + # a_sim=a_sim, + # beta=beta, + # b_simb_sim, + freq=freq, + ) + console.print("") + + return weights @log_start_end(log=logger) def display_ef( stocks: List[str], - period: str = "3mo", - n_portfolios: int = 300, - risk_free: bool = False, + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + risk_measure: str = "MV", + risk_free_rate: float = 0, + alpha: float = 0.05, + value: float = 1.0, + value_short: float = 0.0, + n_portfolios: int = 100, + seed: int = 123, + tangency: bool = False, external_axes: Optional[List[plt.Axes]] = None, ): - """Display efficient frontier + """ + Display efficient frontier Parameters ---------- stocks : List[str] - List of the stocks to be included in the weights - period : str - Time period to get returns for - n_portfolios: int - Number of portfolios to simulate + List of portfolio tickers + period : str, optional + Period to look at returns from + start: str, optional + If not using period, start date string (YYYY-MM-DD) + end: str, optional + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool, optional + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float, optional + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float, optional + Value used to replace outliers that are higher to threshold. + method: str + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + risk_measure: str, optional + The risk measure used to optimize the portfolio. + The default is 'MV'. Possible values are: + + - 'MV': Standard Deviation. + - 'MAD': Mean Absolute Deviation. + - 'MSV': Semi Standard Deviation. + - 'FLPM': First Lower Partial Moment (Omega Ratio). + - 'SLPM': Second Lower Partial Moment (Sortino Ratio). + - 'CVaR': Conditional Value at Risk. + - 'EVaR': Entropic Value at Risk. + - 'WR': Worst Realization. + - 'ADD': Average Drawdown of uncompounded cumulative returns. + - 'UCI': Ulcer Index of uncompounded cumulative returns. + - 'CDaR': Conditional Drawdown at Risk of uncompounded cumulative returns. + - 'EDaR': Entropic Drawdown at Risk of uncompounded cumulative returns. + - 'MDD': Maximum Drawdown of uncompounded cumulative returns. + + risk_free_rate: float, optional + Risk free rate, must be in the same period of assets returns. Used for + 'FLPM' and 'SLPM' and Sharpe objective function. The default is 0. + alpha: float, optional + Significance level of CVaR, EVaR, CDaR and EDaR + The default is 0.05. + value : float, optional + Amount to allocate to portfolio in long positions, by default 1.0 + value_short : float, optional + Amount to allocate to portfolio in short positions, by default 0.0 + n_portfolios: int, optional + "Number of portfolios to simulate. The default value is 100. + seed: int, optional + Seed used to generate random portfolios. The default value is 123. + tangency: bool, optional + Adds the optimal line with the risk-free asset. external_axes: Optional[List[plt.Axes]] - Optional axes to plot on + Optional axes to plot data on """ + stock_prices = yahoo_finance_model.process_stocks(stocks, period, start, end) + stock_returns = yahoo_finance_model.process_returns( + stock_prices, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + ) + + risk_free_rate = risk_free_rate / time_factor[freq.upper()] + + # Building the portfolio object + port = rp.Portfolio(returns=stock_returns, alpha=alpha) + + # Estimate input parameters: + port.assets_stats(method_mu="hist", method_cov="hist") + + # Budget constraints + port.upperlng = value + if value_short > 0: + port.sht = True + port.uppersht = value_short + port.budget = value - value_short + else: + port.budget = value + + # Estimate tangency portfolio: + weights = port.optimization( + model="Classic", + rm=risk_choices[risk_measure], + obj="Sharpe", + rf=risk_free_rate, + hist=True, + ) + + points = 20 # Number of points of the frontier + frontier = port.efficient_frontier( + model="Classic", + rm=risk_choices[risk_measure], + points=points, + rf=risk_free_rate, + hist=True, + ) + + random_weights = optimizer_model.generate_random_portfolios( + stocks=stocks, + n_portfolios=n_portfolios, + seed=seed, + ) + + mu = stock_returns.mean().to_frame().T + cov = stock_returns.cov() + Y = (mu @ frontier).to_numpy() * time_factor[freq.upper()] + Y = np.ravel(Y) + X = np.zeros_like(Y) + + for i in range(frontier.shape[1]): + w = np.array(frontier.iloc[:, i], ndmin=2).T + risk = rp.Sharpe_Risk( + w, + cov=cov, + returns=stock_returns, + rm=risk_choices[risk_measure], + rf=risk_free_rate, + alpha=alpha, + # a_sim=a_sim, + # beta=beta, + # b_sim=b_sim, + ) + X[i] = risk + + if risk_choices[risk_measure] not in ["ADD", "MDD", "CDaR", "EDaR", "UCI"]: + X = X * time_factor[freq.upper()] ** 0.5 + f = interp1d(X, Y, kind="quadratic") + X1 = np.linspace(X[0], X[-1], num=100) + Y1 = f(X1) + if external_axes is None: _, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) else: ax = external_axes[0] - ef, rets, stds = optimizer_model.generate_random_portfolios( - stocks, period, n_portfolios - ) - # The ef needs to be deep-copied to avoid error in plotting sharpe - ef2 = copy.deepcopy(ef) - sharpes = rets / stds - ax.scatter(stds, rets, marker=".", c=sharpes) - plotting.plot_efficient_frontier(ef, ax=ax, show_assets=False) - - for ticker, ret, std in zip( - ef.tickers, ef.expected_returns, np.sqrt(np.diag(ef.cov_matrix)) - ): - ax.scatter(std, ret, s=50, marker=".", c="w") - ax.annotate(ticker, (std * 1.01, ret)) - # Find the tangency portfolio - rfrate = get_rf() - ef2.max_sharpe(risk_free_rate=rfrate) - ret_sharpe, std_sharpe, _ = ef2.portfolio_performance( - verbose=True, risk_free_rate=rfrate + frontier = pd.concat([frontier, random_weights], axis=1) + ax = rp.plot_frontier( + w_frontier=frontier, + mu=mu, + cov=cov, + returns=stock_returns, + rm=risk_choices[risk_measure], + rf=risk_free_rate, + alpha=alpha, + cmap="RdYlBu", + w=weights, + label="", + marker="*", + s=16, + c="r", + t_factor=time_factor[freq.upper()], + ax=ax, ) - ax.scatter(std_sharpe, ret_sharpe, marker="*", s=100, c="r", label="Max Sharpe") + # Add risk free line - if risk_free: - y = ret_sharpe * 1.2 - b = get_rf() - m = (ret_sharpe - b) / std_sharpe + if tangency: + ret_sharpe = (mu @ weights).to_numpy().item() * time_factor[freq.upper()] + risk_sharpe = rp.Sharpe_Risk( + weights, + cov=cov, + returns=stock_returns, + rm=risk_choices[risk_measure], + rf=risk_free_rate, + alpha=alpha, + # a_sim=a_sim, + # beta=beta, + # b_sim=b_sim, + ) + if risk_choices[risk_measure] not in ["ADD", "MDD", "CDaR", "EDaR", "UCI"]: + risk_sharpe = risk_sharpe * time_factor[freq.upper()] ** 0.5 + + y = ret_sharpe * 1.5 + b = risk_free_rate * time_factor[freq.upper()] + m = (ret_sharpe - b) / risk_sharpe x2 = (y - b) / m x = [0, x2] y = [b, y] line = Line2D(x, y, label="Capital Allocation Line") - ax.set_xlim(xmin=min(stds) * 0.8) + ax.set_xlim(xmin=min(X1) * 0.8) ax.add_line(line) + + ax.plot(X1, Y1, color="b") + ax.set_title(f"Efficient Frontier simulating {n_portfolios} portfolios") - ax.legend(loc="best", scatterpoints=1) - theme.style_primary_axis(ax) + l, b, w, h = ax.get_position().bounds + ax.set_position([l, b, w * 0.9, h]) + ax1 = ax.get_figure().axes + ll, bb, ww, hh = ax1[-1].get_position().bounds + ax1[-1].set_position([ll * 1.02, bb, ww, hh]) if external_axes is None: - theme.visualize_output() + theme.visualize_output(force_tight_layout=False) + + +@log_start_end(log=logger) +def display_risk_parity( + stocks: List[str], + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + risk_measure: str = "mv", + risk_cont: List[str] = None, + risk_free_rate: float = 0, + alpha: float = 0.05, + target_return: float = -1, + mean: str = "hist", + covariance: str = "hist", + d_ewma: float = 0.94, + value: float = 1.0, + table: bool = False, +) -> Dict: + """ + Builds a risk parity portfolio using the risk budgeting approach + + Parameters + ---------- + stocks : List[str] + List of portfolio tickers + period : str + Period to look at returns from + start: str + If not using period, start date string (YYYY-MM-DD) + end: str + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + - X (integer days) for returns calculated every X days. + + maxnan: float + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float + Value used to replace outliers that are higher to threshold. + method: str + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + risk_measure: str + The risk measure used to optimize the portfolio. + The default is 'MV'. Possible values are: + + - 'MV': Standard Deviation. + - 'MAD': Mean Absolute Deviation. + - 'MSV': Semi Standard Deviation. + - 'FLPM': First Lower Partial Moment (Omega Ratio). + - 'SLPM': Second Lower Partial Moment (Sortino Ratio). + - 'CVaR': Conditional Value at Risk. + - 'EVaR': Entropic Value at Risk. + - 'CDaR': Conditional Drawdown at Risk of uncompounded cumulative returns. + - 'EDaR': Entropic Drawdown at Risk of uncompounded cumulative returns. + - 'UCI': Ulcer Index of uncompounded cumulative returns. + + risk_cont: List[str], optional + The vector of risk contribution per asset. If empty, the default is + 1/n (number of assets). + risk_free_rate: float, optional + Risk free rate, must be in the same period of assets returns. Used for + 'FLPM' and 'SLPM' and Sharpe objective function. The default is 0. + alpha: float, optional + Significance level of CVaR, EVaR, CDaR and EDaR + target_return: float, optional + Constraint on minimum level of portfolio's return. + mean: str, optional + The method used to estimate the expected returns. + The default value is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + + covariance: str, optional + The method used to estimate the covariance matrix: + The default is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + - 'ledoit': use the Ledoit and Wolf Shrinkage method. + - 'oas': use the Oracle Approximation Shrinkage method. + - 'shrunk': use the basic Shrunk Covariance method. + - 'gl': use the basic Graphical Lasso Covariance method. + - 'jlogo': use the j-LoGo Covariance method. For more information see: :cite:`a-jLogo`. + - 'fixed': denoise using fixed method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'spectral': denoise using spectral method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'shrink': denoise using shrink method. For more information see chapter 2 of :cite:`a-MLforAM`. + + d_ewma: float, optional + The smoothing factor of ewma methods. + The default is 0.94. + value : float, optional + Amount to allocate to portfolio, by default 1.0 + table: bool, optional + True if plot table weights, by default False + """ + p = d_period(period, start, end) + s_title = f"{p} Risk parity portfolio based on risk budgeting approach\n" + s_title += "using " + risk_names[risk_measure] + " as risk measure\n" + weights, stock_returns = optimizer_model.get_risk_parity_portfolio( + stocks=stocks, + period=period, + start=start, + end=end, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + risk_measure=risk_choices[risk_measure], + risk_cont=risk_cont, + risk_free_rate=risk_free_rate, + alpha=alpha, + target_return=target_return, + mean=mean, + covariance=covariance, + d_ewma=d_ewma, + value=value, + ) + + if weights is None: + console.print("\n", "There is no solution with this parameters") + return {} + + if table: + console.print("\n", s_title) + display_weights(weights) + portfolio_performance( + weights=weights, + stock_returns=stock_returns, + risk_measure=risk_choices[risk_measure], + risk_free_rate=risk_free_rate, + freq=freq, + ) + console.print("") + + return weights + + +@log_start_end(log=logger) +def display_rel_risk_parity( + stocks: List[str], + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + version: str = "A", + risk_cont: List[str] = None, + penal_factor: float = 1, + target_return: float = -1, + mean: str = "hist", + covariance: str = "hist", + d_ewma: float = 0.94, + value: float = 1.0, + table: bool = False, +) -> Dict: + """ + Builds a relaxed risk parity portfolio using the least squares approach + + Parameters + ---------- + stocks : List[str] + List of portfolio tickers + period : str, optional + Period to look at returns from + start: str, optional + If not using period, start date string (YYYY-MM-DD) + end: str, optional + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool, optional + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + - X (integer days) for returns calculated every X days. + + maxnan: float, optional + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float, optional + Value used to replace outliers that are higher to threshold. + method: str, optional + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + version : str, optional + Relaxed risk parity model version. The default is 'A'. + Possible values are: + + - 'A': without regularization and penalization constraints. + - 'B': with regularization constraint but without penalization constraint. + - 'C': with regularization and penalization constraints. + + risk_cont: List[str], optional + The vector of risk contribution per asset. If empty, the default is + 1/n (number of assets). + penal_factor: float, optional + The penalization factor of penalization constraints. Only used with + version 'C'. The default is 1. + target_return: float, optional + Constraint on minimum level of portfolio's return. + mean: str, optional + The method used to estimate the expected returns. + The default value is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + + covariance: str, optional + The method used to estimate the covariance matrix: + The default is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + - 'ledoit': use the Ledoit and Wolf Shrinkage method. + - 'oas': use the Oracle Approximation Shrinkage method. + - 'shrunk': use the basic Shrunk Covariance method. + - 'gl': use the basic Graphical Lasso Covariance method. + - 'jlogo': use the j-LoGo Covariance method. For more information see: :cite:`a-jLogo`. + - 'fixed': denoise using fixed method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'spectral': denoise using spectral method. For more information see chapter 2 of :cite:`a-MLforAM`. + - 'shrink': denoise using shrink method. For more information see chapter 2 of :cite:`a-MLforAM`. + + d_ewma: float, optional + The smoothing factor of ewma methods. + The default is 0.94. + value : float, optional + Amount to allocate to portfolio, by default 1.0 + table: bool, optional + True if plot table weights, by default False + """ + p = d_period(period, start, end) + s_title = f"{p} Relaxed risk parity portfolio based on least squares approach\n" + weights, stock_returns = optimizer_model.get_rel_risk_parity_portfolio( + stocks=stocks, + period=period, + start=start, + end=end, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + version=version.upper(), + risk_cont=risk_cont, + penal_factor=penal_factor, + target_return=target_return, + mean=mean, + covariance=covariance, + d_ewma=d_ewma, + value=value, + ) + + if weights is None: + console.print("\n", "There is no solution with this parameters") + return {} + + if table: + console.print("\n", s_title) + display_weights(weights) + portfolio_performance( + weights=weights, + stock_returns=stock_returns, + risk_measure=risk_choices["mv"], + freq=freq, + ) + console.print("") + + return weights + + +@log_start_end(log=logger) +def display_hcp( + stocks: List[str], + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + model: str = "HRP", + codependence: str = "pearson", + covariance: str = "hist", + objective: str = "minrisk", + risk_measure: str = "mv", + risk_free_rate: float = 0.0, + risk_aversion: float = 1.0, + alpha: float = 0.05, + a_sim: int = 100, + beta: float = None, + b_sim: int = None, + linkage: str = "ward", + k: int = 0, + max_k: int = 10, + bins_info: str = "KN", + alpha_tail: float = 0.05, + leaf_order: bool = True, + d_ewma: float = 0.94, + value: float = 1.0, + table: bool = False, +) -> Dict: + """ + Builds a hierarchical clustering portfolio + + Parameters + ---------- + stocks : List[str] + List of portfolio tickers + period : str + Period to look at returns from + start: str, optional + If not using period, start date string (YYYY-MM-DD) + end: str, optional + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool, optional + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float, optional + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float, optional + Value used to replace outliers that are higher to threshold. + method: str, optional + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + model: str, optional + The hierarchical cluster portfolio model used for optimize the + portfolio. The default is 'HRP'. Possible values are: + + - 'HRP': Hierarchical Risk Parity. + - 'HERC': Hierarchical Equal Risk Contribution. + - 'NCO': Nested Clustered Optimization. + + codependence: str, optional + The codependence or similarity matrix used to build the distance + metric and clusters. The default is 'pearson'. Possible values are: + + - 'pearson': pearson correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{0.5(1-\rho^{pearson}_{i,j})}`. + - 'spearman': spearman correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{0.5(1-\rho^{spearman}_{i,j})}`. + - 'abs_pearson': absolute value pearson correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{(1-|\rho^{pearson}_{i,j}|)}`. + - 'abs_spearman': absolute value spearman correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{(1-|\rho^{spearman}_{i,j}|)}`. + - 'distance': distance correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{(1-\rho^{distance}_{i,j})}`. + - 'mutual_info': mutual information matrix. Distance used is variation information matrix. + - 'tail': lower tail dependence index matrix. Dissimilarity formula: + :math:`D_{i,j} = -\\log{\\lambda_{i,j}}`. + + covariance: str, optional + The method used to estimate the covariance matrix: + The default is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + - 'ledoit': use the Ledoit and Wolf Shrinkage method. + - 'oas': use the Oracle Approximation Shrinkage method. + - 'shrunk': use the basic Shrunk Covariance method. + - 'gl': use the basic Graphical Lasso Covariance method. + - 'jlogo': use the j-LoGo Covariance method. For more information see: :cite:`c-jLogo`. + - 'fixed': denoise using fixed method. For more information see chapter 2 of :cite:`c-MLforAM`. + - 'spectral': denoise using spectral method. For more information see chapter 2 of :cite:`c-MLforAM`. + - 'shrink': denoise using shrink method. For more information see chapter 2 of :cite:`c-MLforAM`. + + objective: str, optional + Objective function used by the NCO model. + The default is 'MinRisk'. Possible values are: + + - 'MinRisk': Minimize the selected risk measure. + - 'Utility': Maximize the risk averse utility function. + - 'Sharpe': Maximize the risk adjusted return ratio based on the selected risk measure. + - 'ERC': Equally risk contribution portfolio of the selected risk measure. + + risk_measure: str, optional + The risk measure used to optimize the portfolio. If model is 'NCO', + the risk measures available depends on the objective function. + The default is 'MV'. Possible values are: + + - 'MV': Variance. + - 'MAD': Mean Absolute Deviation. + - 'MSV': Semi Standard Deviation. + - 'FLPM': First Lower Partial Moment (Omega Ratio). + - 'SLPM': Second Lower Partial Moment (Sortino Ratio). + - 'VaR': Value at Risk. + - 'CVaR': Conditional Value at Risk. + - 'TG': Tail Gini. + - 'EVaR': Entropic Value at Risk. + - 'WR': Worst Realization (Minimax). + - 'RG': Range of returns. + - 'CVRG': CVaR range of returns. + - 'TGRG': Tail Gini range of returns. + - 'MDD': Maximum Drawdown of uncompounded cumulative returns (Calmar Ratio). + - 'ADD': Average Drawdown of uncompounded cumulative returns. + - 'DaR': Drawdown at Risk of uncompounded cumulative returns. + - 'CDaR': Conditional Drawdown at Risk of uncompounded cumulative returns. + - 'EDaR': Entropic Drawdown at Risk of uncompounded cumulative returns. + - 'UCI': Ulcer Index of uncompounded cumulative returns. + - 'MDD_Rel': Maximum Drawdown of compounded cumulative returns (Calmar Ratio). + - 'ADD_Rel': Average Drawdown of compounded cumulative returns. + - 'DaR_Rel': Drawdown at Risk of compounded cumulative returns. + - 'CDaR_Rel': Conditional Drawdown at Risk of compounded cumulative returns. + - 'EDaR_Rel': Entropic Drawdown at Risk of compounded cumulative returns. + - 'UCI_Rel': Ulcer Index of compounded cumulative returns. + + risk_free_rate: float, optional + Risk free rate, must be in the same period of assets returns. + Used for 'FLPM' and 'SLPM'. The default is 0. + risk_aversion: float, optional + Risk aversion factor of the 'Utility' objective function. + The default is 1. + alpha: float, optional + Significance level of VaR, CVaR, EDaR, DaR, CDaR, EDaR, Tail Gini of losses. + The default is 0.05. + a_sim: float, optional + Number of CVaRs used to approximate Tail Gini of losses. The default is 100. + beta: float, optional + Significance level of CVaR and Tail Gini of gains. If None it duplicates alpha value. + The default is None. + b_sim: float, optional + Number of CVaRs used to approximate Tail Gini of gains. If None it duplicates a_sim value. + The default is None. + linkage: str, optional + Linkage method of hierarchical clustering. For more information see + `linkage `_. + The default is 'single'. Possible values are: + + - 'single'. + - 'complete'. + - 'average'. + - 'weighted'. + - 'centroid'. + - 'median'. + - 'ward'. + - 'dbht': Direct Bubble Hierarchical Tree. + + k: int, optional + Number of clusters. This value is took instead of the optimal number + of clusters calculated with the two difference gap statistic. + The default is None. + max_k: int, optional + Max number of clusters used by the two difference gap statistic + to find the optimal number of clusters. The default is 10. + bins_info: str, optional + Number of bins used to calculate variation of information. The default + value is 'KN'. Possible values are: + + - 'KN': Knuth's choice method. For more information see + `knuth_bin_width `_. + - 'FD': Freedman–Diaconis' choice method. For more information see + `freedman_bin_width `_. + - 'SC': Scotts' choice method. For more information see + `scott_bin_width `_. + - 'HGR': Hacine-Gharbi and Ravier' choice method. + + alpha_tail: float, optional + Significance level for lower tail dependence index. The default is 0.05. + leaf_order: bool, optional + Indicates if the cluster are ordered so that the distance between + successive leaves is minimal. The default is True. + d: float, optional + The smoothing factor of ewma methods. + The default is 0.94. + value : float, optional + Amount to allocate to portfolio, by default 1.0 + table: bool, optional + True if plot table weights, by default False + """ + p = d_period(period, start, end) + + if model == "HRP": + s_title = f"{p} Hierarchical risk parity portfolio" + s_title += " using " + codependence + " codependence,\n" + linkage + elif model == "HERC": + s_title = f"{p} Hierarchical equal risk contribution portfolio" + s_title += " using " + codependence + "\ncodependence," + linkage + elif model == "NCO": + s_title = f"{p} Nested clustered optimization" + s_title += " using " + codependence + " codependence,\n" + linkage + s_title += " linkage and " + risk_names[risk_measure] + " as risk measure\n" + + weights, stock_returns = optimizer_model.get_hcp_portfolio( + stocks=stocks, + period=period, + start=start, + end=end, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + model=model, + codependence=codependence, + covariance=covariance, + objective=objectives_choices[objective], + risk_measure=risk_choices[risk_measure], + risk_free_rate=risk_free_rate, + risk_aversion=risk_aversion, + alpha=alpha, + a_sim=a_sim, + beta=beta, + b_sim=b_sim, + linkage=linkage, + k=k, + max_k=max_k, + bins_info=bins_info, + alpha_tail=alpha_tail, + leaf_order=leaf_order, + d_ewma=d_ewma, + value=value, + ) + + if weights is None: + console.print("\n", "There is no solution with this parameters") + return {} + + if table: + console.print("\n", s_title) + display_weights(weights) + portfolio_performance( + weights=weights, + stock_returns=stock_returns, + risk_measure=risk_choices[risk_measure], + risk_free_rate=risk_free_rate, + alpha=alpha, + a_sim=a_sim, + beta=beta, + b_sim=b_sim, + freq=freq, + ) + console.print("") + + return weights + + +@log_start_end(log=logger) +def display_hrp( + stocks: List[str], + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + codependence: str = "pearson", + covariance: str = "hist", + risk_measure: str = "mv", + risk_free_rate: float = 0.0, + alpha: float = 0.05, + a_sim: int = 100, + beta: float = None, + b_sim: int = None, + linkage: str = "ward", + k: int = 0, + max_k: int = 10, + bins_info: str = "KN", + alpha_tail: float = 0.05, + leaf_order: bool = True, + d_ewma: float = 0.94, + value: float = 1.0, + table: bool = False, +) -> Dict: + """ + Builds a hierarchical risk parity portfolio + + Parameters + ---------- + stocks : List[str] + List of portfolio tickers + period : str + Period to look at returns from + start: str, optional + If not using period, start date string (YYYY-MM-DD) + end: str, optional + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool, optional + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float, optional + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float, optional + Value used to replace outliers that are higher to threshold. + method: str, optional + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + codependence: str, optional + The codependence or similarity matrix used to build the distance + metric and clusters. The default is 'pearson'. Possible values are: + + - 'pearson': pearson correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{0.5(1-\rho^{pearson}_{i,j})}`. + - 'spearman': spearman correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{0.5(1-\rho^{spearman}_{i,j})}`. + - 'abs_pearson': absolute value pearson correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{(1-|\rho^{pearson}_{i,j}|)}`. + - 'abs_spearman': absolute value spearman correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{(1-|\rho^{spearman}_{i,j}|)}`. + - 'distance': distance correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{(1-\rho^{distance}_{i,j})}`. + - 'mutual_info': mutual information matrix. Distance used is variation information matrix. + - 'tail': lower tail dependence index matrix. Dissimilarity formula: + :math:`D_{i,j} = -\\log{\\lambda_{i,j}}`. + + covariance: str, optional + The method used to estimate the covariance matrix: + The default is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + - 'ledoit': use the Ledoit and Wolf Shrinkage method. + - 'oas': use the Oracle Approximation Shrinkage method. + - 'shrunk': use the basic Shrunk Covariance method. + - 'gl': use the basic Graphical Lasso Covariance method. + - 'jlogo': use the j-LoGo Covariance method. For more information see: :cite:`c-jLogo`. + - 'fixed': denoise using fixed method. For more information see chapter 2 of :cite:`c-MLforAM`. + - 'spectral': denoise using spectral method. For more information see chapter 2 of :cite:`c-MLforAM`. + - 'shrink': denoise using shrink method. For more information see chapter 2 of :cite:`c-MLforAM`. + + risk_measure: str, optional + The risk measure used to optimize the portfolio. If model is 'NCO', + the risk measures available depends on the objective function. + The default is 'MV'. Possible values are: + + - 'MV': Variance. + - 'MAD': Mean Absolute Deviation. + - 'MSV': Semi Standard Deviation. + - 'FLPM': First Lower Partial Moment (Omega Ratio). + - 'SLPM': Second Lower Partial Moment (Sortino Ratio). + - 'VaR': Value at Risk. + - 'CVaR': Conditional Value at Risk. + - 'TG': Tail Gini. + - 'EVaR': Entropic Value at Risk. + - 'WR': Worst Realization (Minimax). + - 'RG': Range of returns. + - 'CVRG': CVaR range of returns. + - 'TGRG': Tail Gini range of returns. + - 'MDD': Maximum Drawdown of uncompounded cumulative returns (Calmar Ratio). + - 'ADD': Average Drawdown of uncompounded cumulative returns. + - 'DaR': Drawdown at Risk of uncompounded cumulative returns. + - 'CDaR': Conditional Drawdown at Risk of uncompounded cumulative returns. + - 'EDaR': Entropic Drawdown at Risk of uncompounded cumulative returns. + - 'UCI': Ulcer Index of uncompounded cumulative returns. + - 'MDD_Rel': Maximum Drawdown of compounded cumulative returns (Calmar Ratio). + - 'ADD_Rel': Average Drawdown of compounded cumulative returns. + - 'DaR_Rel': Drawdown at Risk of compounded cumulative returns. + - 'CDaR_Rel': Conditional Drawdown at Risk of compounded cumulative returns. + - 'EDaR_Rel': Entropic Drawdown at Risk of compounded cumulative returns. + - 'UCI_Rel': Ulcer Index of compounded cumulative returns. + + risk_free_rate: float, optional + Risk free rate, must be in the same period of assets returns. + Used for 'FLPM' and 'SLPM'. The default is 0. + alpha: float, optional + Significance level of VaR, CVaR, EDaR, DaR, CDaR, EDaR, Tail Gini of losses. + The default is 0.05. + a_sim: float, optional + Number of CVaRs used to approximate Tail Gini of losses. The default is 100. + beta: float, optional + Significance level of CVaR and Tail Gini of gains. If None it duplicates alpha value. + The default is None. + b_sim: float, optional + Number of CVaRs used to approximate Tail Gini of gains. If None it duplicates a_sim value. + The default is None. + linkage: str, optional + Linkage method of hierarchical clustering. For more information see + `linkage `_. + The default is 'single'. Possible values are: + + - 'single'. + - 'complete'. + - 'average'. + - 'weighted'. + - 'centroid'. + - 'median'. + - 'ward'. + - 'dbht': Direct Bubble Hierarchical Tree. + + k: int, optional + Number of clusters. This value is took instead of the optimal number + of clusters calculated with the two difference gap statistic. + The default is None. + max_k: int, optional + Max number of clusters used by the two difference gap statistic + to find the optimal number of clusters. The default is 10. + bins_info: str, optional + Number of bins used to calculate variation of information. The default + value is 'KN'. Possible values are: + + - 'KN': Knuth's choice method. For more information see + `knuth_bin_width `_. + - 'FD': Freedman–Diaconis' choice method. For more information see + `freedman_bin_width `_. + - 'SC': Scotts' choice method. For more information see + `scott_bin_width `_. + - 'HGR': Hacine-Gharbi and Ravier' choice method. + + alpha_tail: float, optional + Significance level for lower tail dependence index. The default is 0.05. + leaf_order: bool, optional + Indicates if the cluster are ordered so that the distance between + successive leaves is minimal. The default is True. + d: float, optional + The smoothing factor of ewma methods. + The default is 0.94. + value : float, optional + Amount to allocate to portfolio in long positions, by default 1.0 + value_short : float, optional + Amount to allocate to portfolio in short positions, by default 0.0 + table: bool, optional + True if plot table weights, by default False + """ + weights = display_hcp( + stocks=stocks, + period=period, + start=start, + end=end, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + model="HRP", + codependence=codependence, + covariance=covariance, + risk_measure=risk_measure, + risk_free_rate=risk_free_rate, + alpha=alpha, + a_sim=a_sim, + beta=beta, + b_sim=b_sim, + linkage=linkage, + k=k, + max_k=max_k, + bins_info=bins_info, + alpha_tail=alpha_tail, + leaf_order=leaf_order, + d_ewma=d_ewma, + value=value, + table=table, + ) + return weights + + +@log_start_end(log=logger) +def display_herc( + stocks: List[str], + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + codependence: str = "pearson", + covariance: str = "hist", + risk_measure: str = "mv", + risk_free_rate: float = 0.0, + alpha: float = 0.05, + a_sim: int = 100, + beta: float = None, + b_sim: int = None, + linkage: str = "ward", + k: int = 0, + max_k: int = 10, + bins_info: str = "KN", + alpha_tail: float = 0.05, + leaf_order: bool = True, + d_ewma: float = 0.94, + value: float = 1.0, + table: bool = False, +) -> Dict: + """ + Builds a hierarchical equal risk contribution portfolio + + Parameters + ---------- + stocks : List[str] + List of portfolio tickers + period : str + Period to look at returns from + start: str, optional + If not using period, start date string (YYYY-MM-DD) + end: str, optional + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool, optional + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float, optional + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float, optional + Value used to replace outliers that are higher to threshold. + method: str, optional + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + model: str, optional + The hierarchical cluster portfolio model used for optimize the + portfolio. The default is 'HRP'. Possible values are: + + - 'HRP': Hierarchical Risk Parity. + - 'HERC': Hierarchical Equal Risk Contribution. + - 'NCO': Nested Clustered Optimization. + + codependence: str, optional + The codependence or similarity matrix used to build the distance + metric and clusters. The default is 'pearson'. Possible values are: + + - 'pearson': pearson correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{0.5(1-\rho^{pearson}_{i,j})}`. + - 'spearman': spearman correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{0.5(1-\rho^{spearman}_{i,j})}`. + - 'abs_pearson': absolute value pearson correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{(1-|\rho^{pearson}_{i,j}|)}`. + - 'abs_spearman': absolute value spearman correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{(1-|\rho^{spearman}_{i,j}|)}`. + - 'distance': distance correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{(1-\rho^{distance}_{i,j})}`. + - 'mutual_info': mutual information matrix. Distance used is variation information matrix. + - 'tail': lower tail dependence index matrix. Dissimilarity formula: + :math:`D_{i,j} = -\\log{\\lambda_{i,j}}`. + + covariance: str, optional + The method used to estimate the covariance matrix: + The default is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + - 'ledoit': use the Ledoit and Wolf Shrinkage method. + - 'oas': use the Oracle Approximation Shrinkage method. + - 'shrunk': use the basic Shrunk Covariance method. + - 'gl': use the basic Graphical Lasso Covariance method. + - 'jlogo': use the j-LoGo Covariance method. For more information see: :cite:`c-jLogo`. + - 'fixed': denoise using fixed method. For more information see chapter 2 of :cite:`c-MLforAM`. + - 'spectral': denoise using spectral method. For more information see chapter 2 of :cite:`c-MLforAM`. + - 'shrink': denoise using shrink method. For more information see chapter 2 of :cite:`c-MLforAM`. + + risk_measure: str, optional + The risk measure used to optimize the portfolio. If model is 'NCO', + the risk measures available depends on the objective function. + The default is 'MV'. Possible values are: + + - 'MV': Variance. + - 'MAD': Mean Absolute Deviation. + - 'MSV': Semi Standard Deviation. + - 'FLPM': First Lower Partial Moment (Omega Ratio). + - 'SLPM': Second Lower Partial Moment (Sortino Ratio). + - 'VaR': Value at Risk. + - 'CVaR': Conditional Value at Risk. + - 'TG': Tail Gini. + - 'EVaR': Entropic Value at Risk. + - 'WR': Worst Realization (Minimax). + - 'RG': Range of returns. + - 'CVRG': CVaR range of returns. + - 'TGRG': Tail Gini range of returns. + - 'MDD': Maximum Drawdown of uncompounded cumulative returns (Calmar Ratio). + - 'ADD': Average Drawdown of uncompounded cumulative returns. + - 'DaR': Drawdown at Risk of uncompounded cumulative returns. + - 'CDaR': Conditional Drawdown at Risk of uncompounded cumulative returns. + - 'EDaR': Entropic Drawdown at Risk of uncompounded cumulative returns. + - 'UCI': Ulcer Index of uncompounded cumulative returns. + - 'MDD_Rel': Maximum Drawdown of compounded cumulative returns (Calmar Ratio). + - 'ADD_Rel': Average Drawdown of compounded cumulative returns. + - 'DaR_Rel': Drawdown at Risk of compounded cumulative returns. + - 'CDaR_Rel': Conditional Drawdown at Risk of compounded cumulative returns. + - 'EDaR_Rel': Entropic Drawdown at Risk of compounded cumulative returns. + - 'UCI_Rel': Ulcer Index of compounded cumulative returns. + + risk_free_rate: float, optional + Risk free rate, must be in the same period of assets returns. + Used for 'FLPM' and 'SLPM'. The default is 0. + alpha: float, optional + Significance level of VaR, CVaR, EDaR, DaR, CDaR, EDaR, Tail Gini of losses. + The default is 0.05. + a_sim: float, optional + Number of CVaRs used to approximate Tail Gini of losses. The default is 100. + beta: float, optional + Significance level of CVaR and Tail Gini of gains. If None it duplicates alpha value. + The default is None. + b_sim: float, optional + Number of CVaRs used to approximate Tail Gini of gains. If None it duplicates a_sim value. + The default is None. + linkage: str, optional + Linkage method of hierarchical clustering. For more information see + `linkage `_. + The default is 'single'. Possible values are: + + - 'single'. + - 'complete'. + - 'average'. + - 'weighted'. + - 'centroid'. + - 'median'. + - 'ward'. + - 'dbht': Direct Bubble Hierarchical Tree. + + k: int, optional + Number of clusters. This value is took instead of the optimal number + of clusters calculated with the two difference gap statistic. + The default is None. + max_k: int, optional + Max number of clusters used by the two difference gap statistic + to find the optimal number of clusters. The default is 10. + bins_info: str, optional + Number of bins used to calculate variation of information. The default + value is 'KN'. Possible values are: + + - 'KN': Knuth's choice method. For more information see + `knuth_bin_width `_. + - 'FD': Freedman–Diaconis' choice method. For more information see + `freedman_bin_width `_. + - 'SC': Scotts' choice method. For more information see + `scott_bin_width `_. + - 'HGR': Hacine-Gharbi and Ravier' choice method. + + alpha_tail: float, optional + Significance level for lower tail dependence index. The default is 0.05. + leaf_order: bool, optional + Indicates if the cluster are ordered so that the distance between + successive leaves is minimal. The default is True. + d: float, optional + The smoothing factor of ewma methods. + The default is 0.94. + value : float, optional + Amount to allocate to portfolio in long positions, by default 1.0 + value_short : float, optional + Amount to allocate to portfolio in short positions, by default 0.0 + table: bool, optional + True if plot table weights, by default False + """ + weights = display_hcp( + stocks=stocks, + period=period, + start=start, + end=end, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + model="HERC", + codependence=codependence, + covariance=covariance, + risk_measure=risk_measure, + risk_free_rate=risk_free_rate, + alpha=alpha, + a_sim=a_sim, + beta=beta, + b_sim=b_sim, + linkage=linkage, + k=k, + max_k=max_k, + bins_info=bins_info, + alpha_tail=alpha_tail, + leaf_order=leaf_order, + d_ewma=d_ewma, + value=value, + table=table, + ) + return weights + + +@log_start_end(log=logger) +def display_nco( + stocks: List[str], + period: str = "3y", + start: str = "", + end: str = "", + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", + codependence: str = "pearson", + covariance: str = "hist", + objective: str = "MinRisk", + risk_measure: str = "mv", + risk_free_rate: float = 0.0, + risk_aversion: float = 2.0, + alpha: float = 0.05, + linkage: str = "ward", + k: int = 0, + max_k: int = 10, + bins_info: str = "KN", + alpha_tail: float = 0.05, + leaf_order: bool = True, + d_ewma: float = 0.94, + value: float = 1.0, + table: bool = False, +) -> Dict: + """ + Builds a nested clustered optimization portfolio + + Parameters + ---------- + stocks : List[str] + List of portfolio tickers + period : str + Period to look at returns from + start: str, optional + If not using period, start date string (YYYY-MM-DD) + end: str, optional + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. + log_returns: bool, optional + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: float, optional + Max percentage of nan values accepted per asset to be included in + returns. + threshold: float, optional + Value used to replace outliers that are higher to threshold. + method: str, optional + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + model: str, optional + The hierarchical cluster portfolio model used for optimize the + portfolio. The default is 'HRP'. Possible values are: + + - 'HRP': Hierarchical Risk Parity. + - 'HERC': Hierarchical Equal Risk Contribution. + - 'NCO': Nested Clustered Optimization. + + codependence: str, optional + The codependence or similarity matrix used to build the distance + metric and clusters. The default is 'pearson'. Possible values are: + + - 'pearson': pearson correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{0.5(1-\rho^{pearson}_{i,j})}`. + - 'spearman': spearman correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{0.5(1-\rho^{spearman}_{i,j})}`. + - 'abs_pearson': absolute value pearson correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{(1-|\rho^{pearson}_{i,j}|)}`. + - 'abs_spearman': absolute value spearman correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{(1-|\rho^{spearman}_{i,j}|)}`. + - 'distance': distance correlation matrix. Distance formula: + :math:`D_{i,j} = \\sqrt{(1-\rho^{distance}_{i,j})}`. + - 'mutual_info': mutual information matrix. Distance used is variation information matrix. + - 'tail': lower tail dependence index matrix. Dissimilarity formula: + :math:`D_{i,j} = -\\log{\\lambda_{i,j}}`. + + covariance: str, optional + The method used to estimate the covariance matrix: + The default is 'hist'. Possible values are: + + - 'hist': use historical estimates. + - 'ewma1': use ewma with adjust=True. For more information see + `EWM `_. + - 'ewma2': use ewma with adjust=False. For more information see + `EWM `_. + - 'ledoit': use the Ledoit and Wolf Shrinkage method. + - 'oas': use the Oracle Approximation Shrinkage method. + - 'shrunk': use the basic Shrunk Covariance method. + - 'gl': use the basic Graphical Lasso Covariance method. + - 'jlogo': use the j-LoGo Covariance method. For more information see: :cite:`c-jLogo`. + - 'fixed': denoise using fixed method. For more information see chapter 2 of :cite:`c-MLforAM`. + - 'spectral': denoise using spectral method. For more information see chapter 2 of :cite:`c-MLforAM`. + - 'shrink': denoise using shrink method. For more information see chapter 2 of :cite:`c-MLforAM`. + + objective: str, optional + Objective function used by the NCO model. + The default is 'MinRisk'. Possible values are: + + - 'MinRisk': Minimize the selected risk measure. + - 'Utility': Maximize the risk averse utility function. + - 'Sharpe': Maximize the risk adjusted return ratio based on the selected risk measure. + - 'ERC': Equally risk contribution portfolio of the selected risk measure. + + risk_measure: str, optional + The risk measure used to optimize the portfolio. If model is 'NCO', + the risk measures available depends on the objective function. + The default is 'MV'. Possible values are: + + - 'MV': Variance. + - 'MAD': Mean Absolute Deviation. + - 'MSV': Semi Standard Deviation. + - 'FLPM': First Lower Partial Moment (Omega Ratio). + - 'SLPM': Second Lower Partial Moment (Sortino Ratio). + - 'VaR': Value at Risk. + - 'CVaR': Conditional Value at Risk. + - 'TG': Tail Gini. + - 'EVaR': Entropic Value at Risk. + - 'WR': Worst Realization (Minimax). + - 'RG': Range of returns. + - 'CVRG': CVaR range of returns. + - 'TGRG': Tail Gini range of returns. + - 'MDD': Maximum Drawdown of uncompounded cumulative returns (Calmar Ratio). + - 'ADD': Average Drawdown of uncompounded cumulative returns. + - 'DaR': Drawdown at Risk of uncompounded cumulative returns. + - 'CDaR': Conditional Drawdown at Risk of uncompounded cumulative returns. + - 'EDaR': Entropic Drawdown at Risk of uncompounded cumulative returns. + - 'UCI': Ulcer Index of uncompounded cumulative returns. + - 'MDD_Rel': Maximum Drawdown of compounded cumulative returns (Calmar Ratio). + - 'ADD_Rel': Average Drawdown of compounded cumulative returns. + - 'DaR_Rel': Drawdown at Risk of compounded cumulative returns. + - 'CDaR_Rel': Conditional Drawdown at Risk of compounded cumulative returns. + - 'EDaR_Rel': Entropic Drawdown at Risk of compounded cumulative returns. + - 'UCI_Rel': Ulcer Index of compounded cumulative returns. + + risk_free_rate: float, optional + Risk free rate, must be in the same period of assets returns. + Used for 'FLPM' and 'SLPM'. The default is 0. + risk_aversion: float, optional + Risk aversion factor of the 'Utility' objective function. + The default is 1. + alpha: float, optional + Significance level of VaR, CVaR, EDaR, DaR, CDaR, EDaR, Tail Gini of losses. + The default is 0.05. + a_sim: float, optional + Number of CVaRs used to approximate Tail Gini of losses. The default is 100. + beta: float, optional + Significance level of CVaR and Tail Gini of gains. If None it duplicates alpha value. + The default is None. + b_sim: float, optional + Number of CVaRs used to approximate Tail Gini of gains. If None it duplicates a_sim value. + The default is None. + linkage: str, optional + Linkage method of hierarchical clustering. For more information see + `linkage `_. + The default is 'single'. Possible values are: + + - 'single'. + - 'complete'. + - 'average'. + - 'weighted'. + - 'centroid'. + - 'median'. + - 'ward'. + - 'dbht': Direct Bubble Hierarchical Tree. + + k: int, optional + Number of clusters. This value is took instead of the optimal number + of clusters calculated with the two difference gap statistic. + The default is None. + max_k: int, optional + Max number of clusters used by the two difference gap statistic + to find the optimal number of clusters. The default is 10. + bins_info: str, optional + Number of bins used to calculate variation of information. The default + value is 'KN'. Possible values are: + + - 'KN': Knuth's choice method. For more information see + `knuth_bin_width `_. + - 'FD': Freedman–Diaconis' choice method. For more information see + `freedman_bin_width `_. + - 'SC': Scotts' choice method. For more information see + `scott_bin_width `_. + - 'HGR': Hacine-Gharbi and Ravier' choice method. + + alpha_tail: float, optional + Significance level for lower tail dependence index. The default is 0.05. + leaf_order: bool, optional + Indicates if the cluster are ordered so that the distance between + successive leaves is minimal. The default is True. + d: float, optional + The smoothing factor of ewma methods. + The default is 0.94. + value : float, optional + Amount to allocate to portfolio in long positions, by default 1.0 + value_short : float, optional + Amount to allocate to portfolio in short positions, by default 0.0 + table: bool, optional + True if plot table weights, by default False + """ + weights = display_hcp( + stocks=stocks, + period=period, + start=start, + end=end, + log_returns=log_returns, + freq=freq, + maxnan=maxnan, + threshold=threshold, + method=method, + model="NCO", + codependence=codependence, + covariance=covariance, + objective=objective, + risk_measure=risk_measure, + risk_free_rate=risk_free_rate, + risk_aversion=risk_aversion, + alpha=alpha, + linkage=linkage, + k=k, + max_k=max_k, + bins_info=bins_info, + alpha_tail=alpha_tail, + leaf_order=leaf_order, + d_ewma=d_ewma, + value=value, + table=table, + ) + return weights @log_start_end(log=logger) @@ -445,7 +3528,7 @@ def pie_chart_weights( ---------- weights: dict Weights to display, where keys are tickers, and values are either weights or values if -v specified - title: str + title_opt: str Title to be used on the plot title external_axes:Optiona[List[plt.Axes]] Optional external axes to plot data on @@ -463,6 +3546,7 @@ def pie_chart_weights( sizes.append(size) total_size = np.sum(sizes) + colors = theme.get_colors() if external_axes is None: _, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) @@ -470,22 +3554,28 @@ def pie_chart_weights( ax = external_axes[0] if math.isclose(sum(sizes), 1, rel_tol=0.1): - wedges, _, autotexts = ax.pie( + _, _, autotexts = ax.pie( sizes, labels=stocks, autopct=my_autopct, - textprops=dict(color="k"), - wedgeprops={"linewidth": 3.0, "edgecolor": "white"}, + colors=colors, + textprops=dict(color="white"), + wedgeprops={"linewidth": 0.5, "edgecolor": "white"}, + labeldistance=1.05, + startangle=45, normalize=True, ) plt.setp(autotexts, color="white", fontweight="bold") else: - wedges, _, autotexts = ax.pie( + _, _, autotexts = ax.pie( sizes, labels=stocks, autopct="", - textprops=dict(color="k"), - wedgeprops={"linewidth": 3.0, "edgecolor": "white"}, + colors=colors, + textprops=dict(color="white"), + wedgeprops={"linewidth": 0.5, "edgecolor": "white"}, + labeldistance=1.05, + startangle=45, normalize=True, ) plt.setp(autotexts, color="white", fontweight="bold") @@ -497,32 +3587,346 @@ def pie_chart_weights( ax.axis("equal") - leg1 = ax.legend( - wedges, - [str(s) for s in stocks], - title=" Ticker", - loc="upper left", - bbox_to_anchor=(0.80, 0, 0.5, 1), - frameon=False, - ) - leg2 = ax.legend( - wedges, - [ - f"{' ' if ((100*s/total_size) < 10) else ''}{100*s/total_size:.2f}%" - for s in sizes - ], - title=" ", - loc="upper left", - handlelength=0, - bbox_to_anchor=(0.91, 0, 0.5, 1), - frameon=False, - ) - ax.add_artist(leg1) - ax.add_artist(leg2) + # leg1 = ax.legend( + # wedges, + # [str(s) for s in stocks], + # title=" Ticker", + # loc="upper left", + # bbox_to_anchor=(0.80, 0, 0.5, 1), + # frameon=False, + # ) + # leg2 = ax.legend( + # wedges, + # [ + # f"{' ' if ((100*s/total_size) < 10) else ''}{100*s/total_size:.2f}%" + # for s in sizes + # ], + # title=" ", + # loc="upper left", + # handlelength=0, + # bbox_to_anchor=(0.91, 0, 0.5, 1), + # frameon=False, + # ) + # ax.add_artist(leg1) + # ax.add_artist(leg2) plt.setp(autotexts, size=8, weight="bold") - ax.set_title(title_opt, pad=20) + title = "Portfolio - " + title_opt + "\n" + title += "Portfolio Composition" + ax.set_title(title) if external_axes is None: theme.visualize_output() + + +@log_start_end(log=logger) +def additional_plots( + weights, + stock_returns: pd.DataFrame, + category: Dict, + title_opt: str, + freq: str, + risk_measure: str, + risk_free_rate: float, + alpha: float, + a_sim: float, + beta: float, + b_sim: float, + pie: bool, + hist: bool, + dd: bool, + rc_chart: bool, + heat: bool, + external_axes: Optional[List[plt.Axes]], +): + """ + Plot additional charts + + Parameters + ---------- + weights: Dict + Dict of portfolio weights + stock_returns: pd.DataFrame + DataFrame of stock returns + title_opt: str + Title to be used on the pie chart + freq: str, optional + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + risk_measure: str, optional + The risk measure used to optimize the portfolio. If model is 'NCO', + the risk measures available depends on the objective function. + The default is 'MV'. Possible values are: + + - 'MV': Variance. + - 'MAD': Mean Absolute Deviation. + - 'MSV': Semi Standard Deviation. + - 'FLPM': First Lower Partial Moment (Omega Ratio). + - 'SLPM': Second Lower Partial Moment (Sortino Ratio). + - 'VaR': Value at Risk. + - 'CVaR': Conditional Value at Risk. + - 'TG': Tail Gini. + - 'EVaR': Entropic Value at Risk. + - 'WR': Worst Realization (Minimax). + - 'RG': Range of returns. + - 'CVRG': CVaR range of returns. + - 'TGRG': Tail Gini range of returns. + - 'MDD': Maximum Drawdown of uncompounded cumulative returns (Calmar Ratio). + - 'ADD': Average Drawdown of uncompounded cumulative returns. + - 'DaR': Drawdown at Risk of uncompounded cumulative returns. + - 'CDaR': Conditional Drawdown at Risk of uncompounded cumulative returns. + - 'EDaR': Entropic Drawdown at Risk of uncompounded cumulative returns. + - 'UCI': Ulcer Index of uncompounded cumulative returns. + - 'MDD_Rel': Maximum Drawdown of compounded cumulative returns (Calmar Ratio). + - 'ADD_Rel': Average Drawdown of compounded cumulative returns. + - 'DaR_Rel': Drawdown at Risk of compounded cumulative returns. + - 'CDaR_Rel': Conditional Drawdown at Risk of compounded cumulative returns. + - 'EDaR_Rel': Entropic Drawdown at Risk of compounded cumulative returns. + - 'UCI_Rel': Ulcer Index of compounded cumulative returns. + + risk_free_rate: float, optional + Risk free rate, must be in the same period of assets returns. + Used for 'FLPM' and 'SLPM'. The default is 0. + alpha: float, optional + Significance level of VaR, CVaR, EDaR, DaR, CDaR, EDaR, Tail Gini of losses. + The default is 0.05. + a_sim: float, optional + Number of CVaRs used to approximate Tail Gini of losses. The default is 100. + beta: float, optional + Significance level of CVaR and Tail Gini of gains. If None it duplicates alpha value. + The default is None. + b_sim: float, optional + Number of CVaRs used to approximate Tail Gini of gains. If None it duplicates a_sim value. + The default is None. + pie : bool, optional + Display a pie chart of values, by default False + hist : bool, optional + Display a histogram with risk measures, by default False + dd : bool, optional + Display a drawdown chart with risk measures, by default False + rc-chart : float, optional + Display a risk contribution chart for assets, by default False + heat : float, optional + Display a heatmap of correlation matrix with dendrogram, by default False + external_axes: Optional[List[plt.Axes]] + Optional axes to plot data on + """ + if category is not None: + weights = pd.DataFrame.from_dict( + data=weights, orient="index", columns=["value"], dtype=float + ) + category_df = pd.DataFrame.from_dict( + data=category, orient="index", columns=["category"] + ) + weights = weights.join(category_df, how="inner") + weights.sort_index(inplace=True) + + # Calculating classes returns + classes = list(set(weights["category"])) + weights_classes = weights.groupby(["category"]).sum() + matrix_classes = np.zeros((len(weights), len(classes))) + labels = weights["category"].tolist() + + j_value = 0 + for i in classes: + matrix_classes[:, j_value] = np.array( + [1 if x == i else 0 for x in labels], dtype=float + ) + matrix_classes[:, j_value] = ( + matrix_classes[:, j_value] + * weights["value"] + / weights_classes.loc[i, "value"] + ) + j_value += 1 + + matrix_classes = pd.DataFrame( + matrix_classes, columns=classes, index=weights.index + ) + stock_returns = stock_returns @ matrix_classes + weights = weights_classes["value"].copy() + weights.replace(0, np.nan, inplace=True) + weights.dropna(inplace=True) + weights.sort_values(ascending=True, inplace=True) + stock_returns = stock_returns[weights.index.tolist()] + stock_returns.columns = [i.title() for i in stock_returns.columns] + weights.index = [i.title() for i in weights.index] + weights = weights.to_dict() + + colors = theme.get_colors() + if pie: + pie_chart_weights(weights, title_opt, external_axes) + + if hist: + if external_axes is None: + _, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) + else: + ax = external_axes[0] + + ax = rp.plot_hist( + stock_returns, w=pd.Series(weights).to_frame(), alpha=alpha, ax=ax + ) + ax.legend(fontsize="x-small", loc="best") + + # Changing colors + for i in ax.get_children()[:-1]: + if isinstance(i, matplotlib.patches.Rectangle): + i.set_color(colors[0]) + i.set_alpha(0.7) + + k = 1 + for i, j in zip(ax.get_legend().get_lines()[::-1], ax.get_lines()[::-1]): + i.set_color(colors[k]) + j.set_color(colors[k]) + k += 1 + + title = "Portfolio - " + title_opt + "\n" + title += ax.get_title(loc="left") + ax.set_title(title) + + if external_axes is None: + theme.visualize_output() + + if dd: + if external_axes is None: + _, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) + else: + ax = external_axes[0] + + nav = stock_returns.cumsum() + ax = rp.plot_drawdown( + nav=nav, w=pd.Series(weights).to_frame(), alpha=alpha, ax=ax + ) + + ax[0].remove() + ax = ax[1] + fig = ax.get_figure() + gs = GridSpec(1, 1, figure=fig) + ax.set_position(gs[0].get_position(fig)) + ax.set_subplotspec(gs[0]) + + # Changing colors + ax.get_lines()[0].set_color(colors[0]) + k = 1 + for i, j in zip(ax.get_legend().get_lines()[::-1], ax.get_lines()[1:][::-1]): + i.set_color(colors[k]) + j.set_color(colors[k]) + k += 1 + + ax.get_children()[1].set_facecolor(colors[0]) + ax.get_children()[1].set_alpha(0.7) + + title = "Portfolio - " + title_opt + "\n" + title += ax.get_title(loc="left") + ax.set_title(title) + + if external_axes is None: + theme.visualize_output() + + if rc_chart: + if external_axes is None: + _, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) + else: + ax = external_axes[0] + + ax = rp.plot_risk_con( + w=pd.Series(weights).to_frame(), + cov=stock_returns.cov(), + returns=stock_returns, + rm=risk_choices[risk_measure], + rf=risk_free_rate, + alpha=alpha, + a_sim=a_sim, + beta=beta, + b_sim=b_sim, + color=colors[1], + t_factor=time_factor[freq.upper()], + ax=ax, + ) + + # Changing colors + for i in ax.get_children()[:-1]: + if isinstance(i, matplotlib.patches.Rectangle): + i.set_width(i.get_width()) + i.set_color(colors[0]) + + title = "Portfolio - " + title_opt + "\n" + title += ax.get_title(loc="left") + ax.set_title(title) + + if external_axes is None: + theme.visualize_output() + + if heat: + if external_axes is None: + _, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) + else: + ax = external_axes[0] + + if len(weights) <= 3: + number_of_clusters = len(weights) + else: + number_of_clusters = None + + ax = rp.plot_clusters( + returns=stock_returns, + codependence="pearson", + linkage="ward", + k=number_of_clusters, + max_k=10, + leaf_order=True, + dendrogram=True, + cmap="RdYlBu", + # linecolor='tab:purple', + ax=ax, + ) + + ax = ax.get_figure().axes + ax[0].grid(False) + ax[0].axis("off") + + if category is None: + # Vertical dendrogram + l, b, w, h = ax[4].get_position().bounds + l1 = l * 0.5 + w1 = w * 0.2 + b1 = h * 0.05 + ax[4].set_position([l - l1, b + b1, w * 0.8, h * 0.95]) + # Heatmap + l, b, w, h = ax[1].get_position().bounds + ax[1].set_position([l - l1 - w1, b + b1, w * 0.8, h * 0.95]) + w2 = w * 0.2 + # colorbar + l, b, w, h = ax[2].get_position().bounds + ax[2].set_position([l - l1 - w1 - w2, b, w, h]) + # Horizontal dendrogram + l, b, w, h = ax[3].get_position().bounds + ax[3].set_position([l - l1 - w1, b, w * 0.8, h]) + else: + # Vertical dendrogram + l, b, w, h = ax[4].get_position().bounds + l1 = l * 0.5 + w1 = w * 0.4 + b1 = h * 0.2 + ax[4].set_position([l - l1, b + b1, w * 0.6, h * 0.8]) + # Heatmap + l, b, w, h = ax[1].get_position().bounds + ax[1].set_position([l - l1 - w1, b + b1, w * 0.6, h * 0.8]) + w2 = w * 0.05 + # colorbar + l, b, w, h = ax[2].get_position().bounds + ax[2].set_position([l - l1 - w1 - w2, b, w, h]) + # Horizontal dendrogram + l, b, w, h = ax[3].get_position().bounds + ax[3].set_position([l - l1 - w1, b, w * 0.6, h]) + + title = "Portfolio - " + title_opt + "\n" + title += ax[3].get_title(loc="left") + ax[3].set_title(title) + + if external_axes is None: + theme.visualize_output(force_tight_layout=True) diff --git a/openbb_terminal/portfolio/portfolio_optimization/parameters/params_controller.py b/openbb_terminal/portfolio/portfolio_optimization/parameters/params_controller.py new file mode 100644 index 00000000000..b483921f4fb --- /dev/null +++ b/openbb_terminal/portfolio/portfolio_optimization/parameters/params_controller.py @@ -0,0 +1,387 @@ +""" Parameters Controller Module """ +__docformat__ = "numpy" + +# pylint: disable=C0302, no-else-return + +import argparse +import configparser +import logging +import os +from pathlib import Path +from typing import List, Optional + +from prompt_toolkit.completion import NestedCompleter + +from openbb_terminal import feature_flags as gtff +from openbb_terminal.decorators import log_start_end +from openbb_terminal.helper_funcs import parse_known_args_and_warn, log_and_raise +from openbb_terminal.menu import session +from openbb_terminal.parent_classes import BaseController +from openbb_terminal.portfolio.portfolio_optimization.parameters import params_view +from openbb_terminal.portfolio.portfolio_optimization.parameters.params_view import ( + AVAILABLE_OPTIONS, + DEFAULT_PARAMETERS, + MODEL_PARAMS, +) +from openbb_terminal.rich_config import console + +logger = logging.getLogger(__name__) + + +def check_save_file(file: str) -> str: + """Argparse type to check parameter file to be saved""" + if file == "defaults.ini": + log_and_raise( + argparse.ArgumentTypeError( + "Cannot overwrite defaults.ini file, please save with a different name" + ) + ) + else: + if not file.endswith(".ini") and not file.endswith(".xlsx"): + log_and_raise( + argparse.ArgumentTypeError("File to be saved needs to be .ini or .xlsx") + ) + + return file + + +class ParametersController(BaseController): + """Portfolio Optimization Parameters Controller class""" + + CHOICES_COMMANDS = [ + "set", + "file", + "save", + "new", + "clear", + "arg", + ] + CHOICES_PARAMS = ["freq", "threshold", "method", "alpha", "maxnan"] + CHOICES_COMMANDS += CHOICES_PARAMS + + PATH = "/portfolio/po/params/" + + models = [ + "maxsharpe", + "minrisk", + "maxutil", + "maxret", + "maxdiv", + "maxdecorr", + "ef", + "riskparity", + "relriskparity", + "hrp", + "herc", + "nco", + ] + + current_model = "" + current_file = "" + params = configparser.RawConfigParser() + + def __init__( + self, + file: str, + queue: List[str] = None, + params=None, + current_model=None, + ): + """Constructor""" + super().__init__(queue) + + self.current_file = file + self.current_model = current_model + self.description: Optional[str] = None + self.DEFAULT_PATH = os.path.abspath( + os.path.join( + os.path.dirname(__file__), + "..", + "..", + "..", + "..", + "portfolio", + "optimization", + ) + ) + + self.file_types = ["xlsx", "ini"] + self.DATA_FILES = { + filepath.name: filepath + for file_type in self.file_types + for filepath in Path(self.DEFAULT_PATH).rglob(f"*.{file_type}") + if filepath.is_file() + } + + if params: + self.params = params + else: + pass + # TODO: Enable .ini reading + # self.params.read( + # os.path.join( + # self.DEFAULT_PATH, + # self.current_file if self.current_file else "defaults.ini", + # ) + # ) + # self.params.optionxform = str # type: ignore + # self.params = self.params["OPENBB"] + + if session and gtff.USE_PROMPT_TOOLKIT: + choices: dict = {c: {} for c in self.controller_choices} + choices["set"] = {c: None for c in self.models} + choices["set"]["-m"] = {c: None for c in self.models} + choices["arg"] = {c: None for c in AVAILABLE_OPTIONS} + choices["file"] = {c: None for c in self.DATA_FILES} + self.completer = NestedCompleter.from_nested_dict(choices) + + def print_help(self): + """Print help""" + help_text = f""" +[info]Portfolio Risk Parameters (.ini or .xlsx)[/info] + +[param]Loaded file:[/param] {self.current_file} [cmds] + + file load portfolio risk parameters + save save portfolio risk parameters to specified file[/cmds] + +[param]Model of interest:[/param] {self.current_model} [cmds] + + clear clear model of interest from filtered parameters + set set model of interest to filter parameters + arg set a different value for an argument[/cmds] +""" + if self.current_model: + max_len = max(len(k) for k in self.params.keys()) + help_text += "\n[info]Parameters:[/info]\n" + for k, v in self.params.items(): + all_params = DEFAULT_PARAMETERS + MODEL_PARAMS[self.current_model] + if k in all_params: + help_text += ( + f" [param]{k}{' ' * (max_len - len(k))} :[/param] {v}\n" + ) + else: + max_len = max(len(k) for k in self.params.keys()) + help_text += "\n[info]Parameters:[/info]\n" + for k, v in self.params.items(): + help_text += f" [param]{k}{' ' * (max_len - len(k))} :[/param] {v}\n" + + console.print( + text=help_text, menu="Portfolio - Portfolio Optimization - Parameters" + ) + + def custom_reset(self): + """Class specific component of reset command""" + if self.current_file: + if self.current_model: + return [ + "portfolio", + "po", + f"file {self.current_file}", + "params", + f"set {self.current_model}", + ] + else: + return ["portfolio", "po", f"file {self.current_file}", "params"] + return [] + + @log_start_end(log=logger) + def call_file(self, other_args: List[str]): + """Process load command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="file", + description="Load portfolio risk parameters (ini or xlsx)", + ) + + parser.add_argument( + "-f", + "--file", + required=True, + nargs="+", + dest="file", + help="Parameter file to be used", + ) + + if other_args and "-" not in other_args[0][0]: + other_args.insert(0, "-f") + ns_parser = parse_known_args_and_warn(parser, other_args) + + if ns_parser: + self.current_file = " ".join(ns_parser.file) + + if self.current_file in self.DATA_FILES: + file_location = str(self.DATA_FILES[self.current_file]) + else: + file_location = str(self.current_file) + + self.params, self.current_model = params_view.load_file(file_location) + + console.print() + + @log_start_end(log=logger) + def call_save(self, other_args: List[str]): + """Process save command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="save", + description="Save portfolio risk parameters (ini or xlsx)", + ) + parser.add_argument( + "-f", + "--file", + required=True, + type=check_save_file, + dest="file", + help="Filename to be saved", + ) + if other_args and "-" not in other_args[0][0]: + other_args.insert(0, "-f") + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + if ns_parser.file.endswith(".ini"): + # Create file if it does not exist + filepath = os.path.abspath( + os.path.join( + os.path.dirname(__file__), + ".", + "portfolio", + "optimization", + ns_parser.file, + ) + ) + Path(filepath) + + with open(filepath, "w") as configfile: + self.params.write(configfile) + + self.current_file = ns_parser.file + console.print() + + elif ns_parser.file.endswith(".xlsx"): + console.print("It is not yet possible to save to .xlsx") + + @log_start_end(log=logger) + def call_clear(self, other_args: List[str]): + """Process set command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="clear", + description="Clear selected portfolio optimization models", + ) + ns_parser = parse_known_args_and_warn(parser, other_args) + + if ns_parser: + self.current_model = "" + console.print("") + + @log_start_end(log=logger) + def call_set(self, other_args: List[str]): + """Process set command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="set", + description="Select one of the portfolio optimization models", + ) + parser.add_argument( + "-m", + "--model", + required=True, + dest="model", + help="Frequency used to calculate returns", + choices=self.models, + ) + if other_args and "-" not in other_args[0][0]: + other_args.insert(0, "-m") + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + self.current_model = ns_parser.model + console.print("") + + @log_start_end(log=logger) + def call_arg(self, other_args: List[str]): + """Process arg command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="arg", + description="Set a different value for one of the available arguments.", + ) + + parser.add_argument( + "-a", + "--argument", + nargs=2, + dest="argument", + help="Set a value for an argument", + ) + + parser.add_argument( + "-s", + "--show_arguments", + dest="show", + action="store_true", + default=False, + help="Show the available arguments, the options and a description.", + ) + + if other_args and "-" not in other_args[0][0]: + other_args.insert(0, "-a") + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + if ns_parser.show: + params_view.show_arguments(AVAILABLE_OPTIONS, self.description) + + if ns_parser.argument: + argument = ns_parser.argument[0] + value = ns_parser.argument[1] + + if self.current_model: + if argument not in self.params: + console.print( + "[red]The parameter you are trying to access is unused in this model.[/red]\n" + ) + + try: + value = float(value) + except ValueError: + pass + + if argument == "historic_period": + for option in AVAILABLE_OPTIONS[argument]: + if option in str(value): + self.params[argument] = value + break + if self.params[argument] != value: + console.print( + f"[red]The value {value} is not an option for {argument}.\n" + f"Please select enter a " + f"number before the option d, w, mo and y or select ytd or max. For example: 252d, " + f"12w, 10y or max[/red]" + ) + elif ( + value in AVAILABLE_OPTIONS[argument] + or "Any" in AVAILABLE_OPTIONS[argument] + ): + self.params[argument] = value + else: + if len(AVAILABLE_OPTIONS[argument]) > 15: + minimum = min(AVAILABLE_OPTIONS[argument]) + maximum = max(AVAILABLE_OPTIONS[argument]) + options = ( + f"between {minimum} and {maximum} in steps of " + f"{maximum / sum(x > 0 for x in AVAILABLE_OPTIONS[argument])}" + ) + else: + options = AVAILABLE_OPTIONS[argument] + + console.print( + f"[red]The value {value} is not an option for {argument}.\n" + f"The value needs to be {options}[/red]" + ) + + console.print() diff --git a/openbb_terminal/portfolio/portfolio_optimization/parameters/params_view.py b/openbb_terminal/portfolio/portfolio_optimization/parameters/params_view.py new file mode 100644 index 00000000000..07daf9fa517 --- /dev/null +++ b/openbb_terminal/portfolio/portfolio_optimization/parameters/params_view.py @@ -0,0 +1,319 @@ +import configparser + +import pandas as pd + +from openbb_terminal.helper_funcs import print_rich_table +from openbb_terminal.portfolio.portfolio_optimization import excel_model +from openbb_terminal.rich_config import console + +DEFAULT_RANGE = [value / 1000 for value in range(0, 1001)] + +AVAILABLE_OPTIONS = { + "historic_period": ["d", "w", "mo", "y", "ytd", "max"], + "start_period": ["Any"], + "end_period": ["Any"], + "log_returns": ["0", "1"], + "return_frequency": ["d", "w", "m"], + "max_nan": DEFAULT_RANGE, + "threshold_value": DEFAULT_RANGE, + "nan_fill_method": [ + "linear", + "time", + "nearest", + "zero", + "slinear", + "quadratic", + "cubic", + ], + "risk_free": DEFAULT_RANGE, + "significance_level": DEFAULT_RANGE, + "risk_measure": [ + "MV", + "MAD", + "MSV", + "FLPM", + "SLPM", + "CVaR", + "EVaR", + "WR", + "ADD", + "UCI", + "CDaR", + "EDaR", + "MDD", + ], + "target_return": DEFAULT_RANGE + [-x for x in DEFAULT_RANGE], + "target_risk": DEFAULT_RANGE + [-x for x in DEFAULT_RANGE], + "expected_return": ["hist", "ewma1", "ewma2"], + "covariance": [ + "hist", + "ewma1", + "ewma2", + "ledoit", + "oas", + "shrunk", + "gl", + "jlogo", + "fixed", + "spectral", + "shrink", + ], + "smoothing_factor_ewma": DEFAULT_RANGE, + "long_allocation": DEFAULT_RANGE, + "short_allocation": DEFAULT_RANGE, + "risk_aversion": [value / 100 for value in range(-500, 501)], + "amount_portfolios": range(1, 10001), + "random_seed": range(1, 10001), + "tangency": ["0", "1"], + "risk_parity_model": ["A", "B", "C"], + "penal_factor": DEFAULT_RANGE + [-x for x in DEFAULT_RANGE], + "co_dependence": [ + "pearson", + "spearman", + "abs_pearson", + "abs_spearman", + "distance", + "mutual_info", + "tail", + ], + "cvar_simulations": range(1, 10001), + "cvar_significance": DEFAULT_RANGE, + "linkage": [ + "single", + "complete", + "average", + "weighted", + "centroid", + "ward", + "dbht", + ], + "max_clusters": range(1, 101), + "amount_bins": ["KN", "FD", "SC", "HGR", "Integer"], + "alpha_tail": DEFAULT_RANGE, + "leaf_order": ["0", "1"], + "objective": ["MinRisk", "Utility", "Sharpe", "MaxRet"], +} + +DEFAULT_PARAMETERS = [ + "historic_period", + "start_period", + "end_period", + "log_returns", + "return_frequency", + "max_nan", + "threshold_value", + "nan_fill_method", + "risk_free", + "significance_level", +] +MODEL_PARAMS = { + "maxsharpe": [ + "risk_measure", + "target_return", + "target_risk", + "expected_return", + "covariance", + "smoothing_factor_ewma", + "long_allocation", + "short_allocation", + ], + "minrisk": [ + "risk_measure", + "target_return", + "target_risk", + "expected_return", + "covariance", + "smoothing_factor_ewma", + "long_allocation", + "short_allocation", + ], + "maxutil": [ + "risk_measure", + "target_return", + "target_risk", + "expected_return", + "covariance", + "smoothing_factor_ewma", + "long_allocation", + "short_allocation", + "risk_aversion", + ], + "maxret": [ + "risk_measure", + "target_return", + "target_risk", + "expected_return", + "covariance", + "smoothing_factor_ewma", + "long_allocation", + ], + "maxdiv": ["covariance", "long_allocation"], + "maxdecorr": ["covariance", "long_allocation"], + "ef": [ + "risk_measure", + "long_allocation", + "short_allocation", + "amount_portfolios", + "random_seed", + "tangency", + ], + "equal": ["risk_measure", "long_allocation"], + "mktcap": ["risk_measure", "long_allocation"], + "dividend": ["risk_measure", "long_allocation"], + "riskparity": [ + "risk_measure", + "target_return", + "long_allocation", + "risk_contribution", + ], + "relriskparity": [ + "risk_measure", + "covariance", + "smoothing_factor_ewma", + "long_allocation", + "risk_contribution", + "risk_parity_model", + "penal_factor", + ], + "hrp": [ + "risk_measure", + "covariance", + "smoothing_factor_ewma", + "long_allocation", + "co_dependence", + "cvar_simulations", + "cvar_significance", + "linkage", + "amount_clusters", + "max_clusters", + "amount_bins", + "alpha_tail", + "leaf_order", + "objective", + ], + "herc": [ + "risk_measure", + "covariance", + "smoothing_factor_ewma", + "long_allocation", + "co_dependence", + "cvar_simulations", + "cvar_significance", + "linkage", + "amount_clusters", + "max_clusters", + "amount_bins", + "alpha_tail", + "leaf_order", + "objective", + ], + "nco": [ + "risk_measure", + "covariance", + "smoothing_factor_ewma", + "long_allocation", + "co_dependence", + "cvar_simulations", + "cvar_significance", + "linkage", + "amount_clusters", + "max_clusters", + "amount_bins", + "alpha_tail", + "leaf_order", + "objective", + ], +} + + +def load_file(file_location=None): + """ + Loads in the configuration file and return the parameters in a dictionary including the model if available. + + Parameters + ---------- + file_location: str + The location of the file to be loaded in either xlsx or ini. + + Returns + ------- + Return the parameters and the model, if available. + """ + if str(file_location).endswith(".ini"): + params = configparser.RawConfigParser() + params.read(file_location) + params.optionxform = str # type: ignore + params = params["OPENBB"] + + if "technique" in params: + current_model = params["technique"] + else: + current_model = None + + elif str(file_location).endswith(".xlsx"): + params, _ = excel_model.load_configuration(file_location) + current_model = params["technique"] + else: + console.print( + "Can not load in the file due to not being an .ini or .xlsx file." + ) + return None, None + + max_len = max(len(k) for k in params.keys()) + help_text = "[info]Parameters:[/info]\n" + + if current_model: + for k, v in params.items(): + all_params = DEFAULT_PARAMETERS + MODEL_PARAMS[current_model] + if k in all_params: + help_text += f" [param]{k}{' ' * (max_len - len(k))} :[/param] {v}\n" + else: + for k, v in params.items(): + help_text += f" [param]{k}{' ' * (max_len - len(k))} :[/param] {v}\n" + + console.print(help_text) + + return params, current_model + + +def show_arguments(arguments, description=None): + """ + Show the available arguments and the choices you have for each. If available, also show + the description of the argument. + + Parameters + ---------- + arguments: Dictionary + A dictionary containing the keys and the possible values. + description: Dictionary + A dictionary containing the keys equal to arguments and the descriptions. + + Returns + ------- + A table containing the parameter names, possible values and (if applicable) the description. + """ + adjusted_arguments = {} + + for variable in arguments: + if len(arguments[variable]) > 15: + minimum = min(arguments[variable]) + maximum = max(arguments[variable]) + adjusted_arguments[variable] = ( + f"Between {minimum} and {maximum} in steps of " + f"{maximum / sum(x > 0 for x in arguments[variable])}" + ) + else: + adjusted_arguments[variable] = ", ".join(arguments[variable]) + + if description: + df = pd.DataFrame([adjusted_arguments, description]).T + columns = ["Options", "Description"] + else: + df = pd.DataFrame([adjusted_arguments]).T + columns = ["Options"] + + df = df[df.index != "technique"] + + print_rich_table( + df, headers=list(columns), show_index=True, index_name="Parameters" + ) diff --git a/openbb_terminal/portfolio/portfolio_optimization/po_api.py b/openbb_terminal/portfolio/portfolio_optimization/po_api.py index 6b2cd69a34d..ef39486ce93 100644 --- a/openbb_terminal/portfolio/portfolio_optimization/po_api.py +++ b/openbb_terminal/portfolio/portfolio_optimization/po_api.py @@ -16,20 +16,38 @@ from openbb_terminal.portfolio.portfolio_optimization.optimizer_view import ( display_max_sharpe as max_sharpe, ) from openbb_terminal.portfolio.portfolio_optimization.optimizer_view import ( - display_min_volatility as min_vol, + display_min_risk as min_risk, ) from openbb_terminal.portfolio.portfolio_optimization.optimizer_view import ( - display_max_quadratic_utility as maxquadutil, + display_max_util as max_util, ) from openbb_terminal.portfolio.portfolio_optimization.optimizer_view import ( - display_efficient_risk as effrisk, + display_max_ret as max_ret, ) from openbb_terminal.portfolio.portfolio_optimization.optimizer_view import ( - display_efficient_return as effret, + display_max_div as max_div, +) +from openbb_terminal.portfolio.portfolio_optimization.optimizer_view import ( + display_max_decorr as max_decorr, ) from openbb_terminal.portfolio.portfolio_optimization.optimizer_view import ( display_ef as ef, ) +from openbb_terminal.portfolio.portfolio_optimization.optimizer_view import ( + display_risk_parity as risk_parity, +) +from openbb_terminal.portfolio.portfolio_optimization.optimizer_view import ( + display_rel_risk_parity as rel_risk_parity, +) +from openbb_terminal.portfolio.portfolio_optimization.optimizer_view import ( + display_hrp as hrp, +) +from openbb_terminal.portfolio.portfolio_optimization.optimizer_view import ( + display_herc as herc, +) +from openbb_terminal.portfolio.portfolio_optimization.optimizer_view import ( + display_nco as nco, +) # Models models = _models(os.path.abspath(os.path.dirname(__file__))) diff --git a/openbb_terminal/portfolio/portfolio_optimization/po_controller.py b/openbb_terminal/portfolio/portfolio_optimization/po_controller.py index 04b859cb88f..dbc41aa20ec 100644 --- a/openbb_terminal/portfolio/portfolio_optimization/po_controller.py +++ b/openbb_terminal/portfolio/portfolio_optimization/po_controller.py @@ -1,13 +1,18 @@ """ Portfolio Optimization Controller Module """ __docformat__ = "numpy" +# pylint: disable=C0302, protected-access, too-many-instance-attributes + import argparse import logging -from typing import List +import os +from pathlib import Path +from typing import List, Dict, Set from prompt_toolkit.completion import NestedCompleter from openbb_terminal import feature_flags as obbff +from openbb_terminal import parent_classes from openbb_terminal.decorators import log_start_end from openbb_terminal.helper_funcs import ( check_non_negative, @@ -16,15 +21,19 @@ from openbb_terminal.helper_funcs import ( ) from openbb_terminal.menu import session from openbb_terminal.parent_classes import BaseController +from openbb_terminal.portfolio.portfolio_optimization import excel_model from openbb_terminal.portfolio.portfolio_optimization import ( optimizer_helper, + optimizer_model, optimizer_view, ) +from openbb_terminal.portfolio.portfolio_optimization import yahoo_finance_model +from openbb_terminal.portfolio.portfolio_optimization.parameters import ( + params_controller, + params_view, +) from openbb_terminal.rich_config import console -# pylint: disable=C0302 - - logger = logging.getLogger(__name__) @@ -35,20 +44,33 @@ class PortfolioOptimizationController(BaseController): "select", "add", "rmv", + "show", + "rpf", + "load", + "plot", "equal", "mktcap", "dividend", "property", "maxsharpe", - "minvol", - "effret", - "effrisk", - "maxquadutil", + "minrisk", + "maxutil", + "maxret", + "maxdiv", + "maxdecorr", + "blacklitterman", + "riskparity", + "relriskparity", + "hrp", + "herc", + "nco", "ef", "yolo", + "file", + "params", ] - period_choices = [ + PERIOD_CHOICES = [ "1d", "5d", "1mo", @@ -62,714 +84,405 @@ class PortfolioOptimizationController(BaseController): "max", ] - yf_info_choices = [ - "previousClose", - "regularMarketOpen", - "twoHundredDayAverage", - "trailingAnnualDividendYield", - "payoutRatio", - "volume24Hr", - "regularMarketDayHigh", - "navPrice", - "averageDailyVolume10Day", - "totalAssets", - "regularMarketPreviousClose", - "fiftyDayAverage", - "trailingAnnualDividendRate", - "open", - "toCurrency", - "averageVolume10days", - "expireDate", - "yield", - "algorithm", - "dividendRate", - "exDividendDate", - "beta", - "circulatingSupply", - "regularMarketDayLow", - "priceHint", - "currency", - "trailingPE", - "regularMarketVolume", - "lastMarket", - "maxSupply", - "openInterest", - "marketCap", - "volumeAllCurrencies", - "strikePrice", - "averageVolume", - "priceToSalesTrailing12Months", - "dayLow", - "ask", - "ytdReturn", - "askSize", - "volume", - "fiftyTwoWeekHigh", - "forwardPE", - "fromCurrency", - "fiveYearAvgDividendYield", - "fiftyTwoWeekLow", - "bid", - "dividendYield", - "bidSize", - "dayHigh", - "annualHoldingsTurnover", - "enterpriseToRevenue", - "beta3Year", - "profitMargins", - "enterpriseToEbitda", - "52WeekChange", - "morningStarRiskRating", - "forwardEps", - "revenueQuarterlyGrowth", - "sharesOutstanding", - "fundInceptionDate", - "annualReportExpenseRatio", - "bookValue", - "sharesShort", - "sharesPercentSharesOut", - "heldPercentInstitutions", - "netIncomeToCommon", - "trailingEps", - "lastDividendValue", - "SandP52WeekChange", - "priceToBook", - "heldPercentInsiders", - "shortRatio", - "sharesShortPreviousMonthDate", - "floatShares", - "enterpriseValue", - "fundFamily", - "threeYearAverageReturn", - "lastSplitFactor", - "legalType", - "lastDividendDate", - "morningStarOverallRating", - "earningsQuarterlyGrowth", - "pegRatio", - "lastCapGain", - "shortPercentOfFloat", - "sharesShortPriorMonth", - "impliedSharesOutstanding", - "fiveYearAverageReturn", - "regularMarketPrice", + MEAN_RISK_CHOICES = [ + "MV", + "MAD", + "MSV", + "FLPM", + "SLPM", + "CVaR", + "EVaR", + "WR", + "ADD", + "UCI", + "CDaR", + "EDaR", + "MDD", ] + + RISK_PARITY_CHOICES = [ + "MV", + "MAD", + "MSV", + "FLPM", + "SLPM", + "CVaR", + "EVaR", + "CDaR", + "EDaR", + "UCI", + ] + + REL_RISK_PARITY_CHOICES = [ + "A", + "B", + "C", + ] + + HCP_CHOICES = [ + "MV", + "MAD", + "GMD", + "MSV", + "VaR", + "CVaR", + "TG", + "EVaR", + "RG", + "CVRG", + "TGRG", + "WR", + "FLPM", + "SLPM", + "MDD", + "ADD", + "DaR", + "CDaR", + "EDaR", + "UCI", + "MDD_Rel", + "ADD_Rel", + "DaR_Rel", + "CDaR_Rel", + "EDaR_Rel", + "UCI_Rel", + ] + + RISK_CHOICES = { + "mv": "MV", + "mad": "MAD", + "gmd": "GMD", + "msv": "MSV", + "var": "VaR", + "cvar": "CVaR", + "tg": "TG", + "evar": "EVaR", + "rg": "RG", + "cvrg": "CVRG", + "tgrg": "TGRG", + "wr": "WR", + "flpm": "FLPM", + "slpm": "SLPM", + "mdd": "MDD", + "add": "ADD", + "dar": "DaR", + "cdar": "CDaR", + "edar": "EDaR", + "uci": "UCI", + "mdd_rel": "MDD_Rel", + "add_rel": "ADD_Rel", + "dar_rel": "DaR_Rel", + "cdar_rel": "CDaR_Rel", + "edar_rel": "EDaR_Rel", + "uci_rel": "UCI_Rel", + } + MEAN_CHOICES = [ + "hist", + "ewma1", + "ewma2", + ] + + CODEPENDENCE_CHOICES = [ + "pearson", + "spearman", + "abs_pearson", + "abs_spearman", + "distance", + "mutual_info", + "tail", + ] + + COVARIANCE_CHOICES = [ + "hist", + "ewma1", + "ewma2", + "ledoit", + "oas", + "shrunk", + "gl", + "jlogo", + "fixed", + "spectral", + "shrink", + ] + + OBJECTIVE_CHOICES = [ + "MinRisk", + "Utility", + "Sharpe", + "MaxRet", + ] + + NCO_OBJECTIVE_CHOICES = [ + "MinRisk", + "Utility", + "Sharpe", + "ERC", + ] + + LINKAGE_CHOICES = [ + "single", + "complete", + "average", + "weighted", + "centroid", + "median", + "ward", + "dbht", + ] + + BINS_CHOICES = [ + "KN", + "FD", + "SC", + "HGR", + ] + + FREQ_CHOICES = [ + "d", + "w", + "m", + ] + + METHOD_CHOICES = [ + "linear", + "time", + "nearest", + "zero", + "slinear", + "quadratic", + "cubic", + "barycentric", + ] + PATH = "/portfolio/po/" - def __init__(self, tickers: List[str] = None, queue: List[str] = None): + files_available: List = list() + + def __init__( + self, + tickers: List[str] = None, + portfolios: Dict = None, + categories: Dict = None, + queue: List[str] = None, + ): """Constructor""" super().__init__(queue) + self.current_model = None if tickers: self.tickers = list(set(tickers)) + self.tickers.sort() else: self.tickers = list() + if portfolios: + self.portfolios = dict(portfolios) + else: + self.portfolios = dict() + + if categories: + self.categories = dict(categories) + else: + self.categories = dict() + + self.count = 0 + + models = [ + "maxsharpe", + "minrisk", + "maxutil", + "maxret", + "maxdiv", + "maxdecorr", + "blacklitterman", + "ef", + "riskparity", + "relriskparity", + "hrp", + "herc", + "nco", + ] + self.file_types = ["xlsx", "ini"] + self.DEFAULT_ALLOCATION_PATH = os.path.abspath( + os.path.join( + os.path.dirname(__file__), "..", "..", "..", "portfolio", "allocation" + ) + ) + + self.DATA_ALLOCATION_FILES = { + filepath.name: filepath + for file_type in self.file_types + for filepath in Path(self.DEFAULT_ALLOCATION_PATH).rglob(f"*.{file_type}") + if filepath.is_file() + } + + self.current_file = "" + self.DEFAULT_OPTIMIZATION_PATH = os.path.abspath( + os.path.join( + os.path.dirname(__file__), "..", "..", "..", "portfolio", "optimization" + ) + ) + self.DATA_OPTIMIZATION_FILES = { + filepath.name: filepath + for file_type in self.file_types + for filepath in Path(self.DEFAULT_OPTIMIZATION_PATH).rglob(f"*.{file_type}") + if filepath.is_file() + } + + self.params: Dict = {} + if session and obbff.USE_PROMPT_TOOLKIT: - choices: dict = {c: {} for c in self.controller_choices} - choices["property"]["-p"] = {c: None for c in self.yf_info_choices} - choices["property"]["--property"] = {c: None for c in self.yf_info_choices} - for fn in ["maxsharpe", "minvol", "maxquadutil", "effret", "effrisk", "ef"]: - choices[fn]["-p"] = {c: None for c in self.period_choices} - choices[fn]["--period"] = {c: None for c in self.period_choices} - self.completer = NestedCompleter.from_nested_dict(choices) + self.choices: dict = {c: {} for c in self.controller_choices} + self.choices["property"]["-p"] = { + c: None for c in yahoo_finance_model.yf_info_choices + } + self.choices["property"]["--property"] = { + c: None for c in yahoo_finance_model.yf_info_choices + } + self.choices["file"] = {c: None for c in self.DATA_OPTIMIZATION_FILES} + self.choices["load"] = {c: None for c in self.DATA_ALLOCATION_FILES} + + for fn in models: + self.choices[fn]["-p"] = {c: None for c in self.PERIOD_CHOICES} + self.choices[fn]["--period"] = {c: None for c in self.PERIOD_CHOICES} + self.choices[fn]["-f"] = {c: None for c in self.FREQ_CHOICES} + self.choices[fn]["--freq"] = {c: None for c in self.FREQ_CHOICES} + self.choices[fn]["-mt"] = {c: None for c in self.METHOD_CHOICES} + self.choices[fn]["--method"] = {c: None for c in self.METHOD_CHOICES} + + for fn in ["maxsharpe", "minrisk", "maxutil", "maxret", "nco", "ef"]: + self.choices[fn]["-rm"] = {c: None for c in self.MEAN_RISK_CHOICES} + self.choices[fn]["--risk-measure"] = { + c: None for c in self.MEAN_RISK_CHOICES + } + + self.choices["riskparity"]["-rm"] = { + c: None for c in self.RISK_PARITY_CHOICES + } + self.choices["riskparity"]["--risk-measure"] = { + c: None for c in self.RISK_PARITY_CHOICES + } + self.choices["relriskparity"]["-ve"] = { + c: None for c in self.RISK_PARITY_CHOICES + } + self.choices["relriskparity"]["--version"] = { + c: None for c in self.RISK_PARITY_CHOICES + } + + for fn in [ + "maxsharpe", + "minrisk", + "maxutil", + "maxret", + "riskparity", + "relriskparity", + ]: + self.choices[fn]["-m"] = {c: None for c in self.MEAN_CHOICES} + self.choices[fn]["--mean"] = {c: None for c in self.MEAN_CHOICES} + self.choices[fn]["-cv"] = {c: None for c in self.COVARIANCE_CHOICES} + self.choices[fn]["--covariance"] = { + c: None for c in self.COVARIANCE_CHOICES + } + + for fn in ["maxdiv", "maxdecorr"]: + self.choices[fn]["-cv"] = {c: None for c in self.COVARIANCE_CHOICES} + self.choices[fn]["--covariance"] = { + c: None for c in self.COVARIANCE_CHOICES + } + + for fn in ["hrp", "herc"]: + self.choices[fn]["-rm"] = {c: None for c in self.HCP_CHOICES} + self.choices[fn]["--risk-measure"] = {c: None for c in self.HCP_CHOICES} + + for fn in ["hrp", "herc", "nco"]: + self.choices[fn]["-cd"] = {c: None for c in self.CODEPENDENCE_CHOICES} + self.choices[fn]["--codependence"] = { + c: None for c in self.CODEPENDENCE_CHOICES + } + self.choices[fn]["-cv"] = {c: None for c in self.COVARIANCE_CHOICES} + self.choices[fn]["--covariance"] = { + c: None for c in self.COVARIANCE_CHOICES + } + self.choices[fn]["-lk"] = {c: None for c in self.LINKAGE_CHOICES} + self.choices[fn]["--linkage"] = {c: None for c in self.LINKAGE_CHOICES} + self.choices[fn]["-bi"] = {c: None for c in self.BINS_CHOICES} + self.choices[fn]["--bins-info"] = {c: None for c in self.BINS_CHOICES} + + self.choices["blacklitterman"]["-o"] = { + c: None for c in self.OBJECTIVE_CHOICES + } + self.choices["blacklitterman"]["--objective"] = { + c: None for c in self.OBJECTIVE_CHOICES + } + self.choices["nco"]["-o"] = {c: None for c in self.NCO_OBJECTIVE_CHOICES} + self.choices["nco"]["--objective"] = { + c: None for c in self.NCO_OBJECTIVE_CHOICES + } + self.completer = NestedCompleter.from_nested_dict(self.choices) + + def update_runtime_choices(self): + if session and obbff.USE_PROMPT_TOOLKIT: + if self.portfolios: + self.choices["show"] = {c: None for c in list(self.portfolios.keys())} + self.choices["plot"] = {c: None for c in list(self.portfolios.keys())} + self.completer = NestedCompleter.from_nested_dict(self.choices) def print_help(self): """Print help""" - help_text = f"""[cmds] - select select list of tickers to be optimized - add add tickers to the list of the tickers to be optimized - rmv remove tickers from the list of the tickers to be optimized[/cmds] + help_text = f""" +[param]Parameter file: [/param] {self.current_file}[cmds] + + file select portfolio parameter file[/cmds][menu] +> params specify and show portfolio risk parameters[/menu][cmds] + load load tickers and categories from .xlsx or .csv file[/cmds] [param]Tickers: [/param]{('None', ', '.join(self.tickers))[bool(self.tickers)]} +[param]Categories: [/param]{('None', ', '.join(self.categories.keys()))[bool(self.categories.keys())]} +[param]Portfolios: [/param]{('None', ', '.join(self.portfolios.keys()))[bool(self.portfolios.keys())]} +[cmds] + add add tickers to the list of the tickers to be optimized + rmv remove tickers from the list of the tickers to be optimized + show show selected portfolios and categories from the list of saved portfolios + rpf remove portfolios from the list of saved portfolios + plot plot selected charts from the list of saved portfolios[/cmds] -[info]Optimization:[/info][cmds] - equal equally weighted - mktcap weighted according to market cap (property marketCap) - dividend weighted according to dividend yield (property dividendYield) - property weight according to selected info property +[info]Mean Risk Optimization:[/info][cmds] + maxsharpe maximal Sharpe ratio portfolio (a.k.a the tangency portfolio) + minrisk minimum risk portfolio + maxutil maximal risk averse utility function, given some risk + aversion parameter + maxret maximal return portfolio + maxdiv maximum diversification portfolio + maxdecorr maximum decorrelation portfolio + blacklitterman black litterman portfolio + ef show the efficient frontier[/cmds] -[info]Mean Variance Optimization:[/info] - maxsharpe optimizes for maximal Sharpe ratio (a.k.a the tangency portfolio - minvol optimizes for minimum volatility - maxquadutil maximises the quadratic utility, given some risk aversion - effret maximises return for a given target risk - effrisk minimises risk for a given target return +[info]Risk Parity Optimization:[/info][cmds] + riskparity risk parity portfolio using risk budgeting approach + relriskparity relaxed risk parity using least squares approach[/cmds] - ef show the efficient frontier[/cmds] +[info]Hierarchical Clustering Models:[/info][cmds] + hrp hierarchical risk parity + herc hierarchical equal risk contribution + nco nested clustering optimization[/cmds] + +[info]Other Optimization Techniques:[/info][cmds] + equal equally weighted + mktcap weighted according to market cap (property marketCap) + dividend weighted according to dividend yield (property dividendYield) + property weight according to selected info property[/cmds] """ console.print(text=help_text, menu="Portfolio - Portfolio Optimization") - @log_start_end(log=logger) - def call_select(self, other_args: List[str]): - """Process select command""" - self.tickers = [] - self.add_stocks(other_args) + def custom_reset(self): + """Class specific component of reset command""" + if self.current_file: + return ["portfolio", "po", f"file {self.current_file}"] + return [] @log_start_end(log=logger) def call_add(self, other_args: List[str]): - """Process add command""" - self.add_stocks(other_args) - - @log_start_end(log=logger) - def call_rmv(self, other_args: List[str]): - """Process rmv command""" - self.rmv_stocks(other_args) - - @log_start_end(log=logger) - def call_equal(self, other_args: List[str]): - """Process equal command""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="equal", - description="Returns an equally weighted portfolio", - ) - parser.add_argument( - "-v", - "--value", - default=1, - type=float, - dest="value", - help="Amount to allocate to portfolio", - ) - parser.add_argument( - "--pie", - action="store_true", - dest="pie", - default=False, - help="Display a pie chart for weights", - ) - - ns_parser = parse_known_args_and_warn(parser, other_args) - if ns_parser: - if len(self.tickers) < 2: - console.print( - "Please have at least 2 loaded tickers to calculate weights.\n" - ) - return - - optimizer_view.display_equal_weight( - stocks=self.tickers, value=ns_parser.value, pie=ns_parser.pie - ) - - @log_start_end(log=logger) - def call_mktcap(self, other_args: List[str]): - """Process mktcap command""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="mktcap", - description="Returns a portfolio that is weighted based on Market Cap.", - ) - parser.add_argument( - "-v", - "--value", - default=1, - type=float, - dest="value", - help="Amount to allocate to portfolio", - ) - parser.add_argument( - "--pie", - action="store_true", - dest="pie", - default=False, - help="Display a pie chart for weights", - ) - ns_parser = parse_known_args_and_warn(parser, other_args) - if ns_parser: - if len(self.tickers) < 2: - console.print( - "Please have at least 2 stocks selected to perform calculations." - ) - return - - optimizer_view.display_property_weighting( - self.tickers, - s_property="marketCap", - value=ns_parser.value, - pie=ns_parser.pie, - ) - - @log_start_end(log=logger) - def call_dividend(self, other_args: List[str]): - """Process dividend command""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="dividend", - description="Returns a portfolio that is weighted based dividend yield.", - ) - parser.add_argument( - "-v", - "--value", - default=1, - type=float, - dest="value", - help="Amount to allocate to portfolio", - ) - parser.add_argument( - "--pie", - action="store_true", - dest="pie", - default=False, - help="Display a pie chart for weights", - ) - ns_parser = parse_known_args_and_warn(parser, other_args) - if ns_parser: - if len(self.tickers) < 2: - console.print( - "Please have at least 2 stocks selected to perform calculations." - ) - return - - optimizer_view.display_property_weighting( - self.tickers, - s_property="dividendYield", - value=ns_parser.value, - pie=ns_parser.pie, - ) - - @log_start_end(log=logger) - def call_property(self, other_args: List[str]): - """Process property command""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="property", - description="Returns a portfolio that is weighted based on selected property.", - ) - parser.add_argument( - "-p", - "--property", - required=bool("-h" not in other_args), - type=optimizer_helper.check_valid_property_type, - dest="property", - choices=self.yf_info_choices, - help="""Property info to weigh. Use one of yfinance info options.""", - ) - parser.add_argument( - "-v", - "--value", - default=1, - type=float, - dest="value", - help="Amount to allocate to portfolio", - ) - parser.add_argument( - "--pie", - action="store_true", - dest="pie", - default=False, - help="Display a pie chart for weights", - ) - ns_parser = parse_known_args_and_warn(parser, other_args) - if ns_parser: - if len(self.tickers) < 2: - console.print( - "Please have at least 2 stocks selected to perform calculations." - ) - return - - optimizer_view.display_property_weighting( - self.tickers, - s_property=ns_parser.property, - value=ns_parser.value, - pie=ns_parser.pie, - ) - - @log_start_end(log=logger) - def call_maxsharpe(self, other_args: List[str]): - """Process maxsharpe command""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="maxsharpe", - description="Maximise the Sharpe Ratio", - ) - parser.add_argument( - "-p", - "--period", - default="1y", - dest="period", - help="period to get yfinance data from", - choices=self.period_choices, - ) - parser.add_argument( - "-v", - "--value", - dest="value", - help="Amount to allocate to portfolio", - type=float, - default=1.0, - ) - parser.add_argument( - "--pie", - action="store_true", - dest="pie", - default=False, - help="Display a pie chart for weights", - ) - parser.add_argument( - "-r", - "--risk-free-rate", - type=float, - dest="risk_free_rate", - default=get_rf(), - help="""Risk-free rate of borrowing/lending. The period of the risk-free rate - should correspond to the frequency of expected returns.""", - ) - - ns_parser = parse_known_args_and_warn(parser, other_args) - if ns_parser: - if len(self.tickers) < 2: - console.print( - "Please have at least 2 loaded tickers to calculate weights.\n" - ) - return - - optimizer_view.display_max_sharpe( - stocks=self.tickers, - period=ns_parser.period, - value=ns_parser.value, - rfrate=ns_parser.risk_free_rate, - pie=ns_parser.pie, - ) - - @log_start_end(log=logger) - def call_minvol(self, other_args: List[str]): - """Process minvol command""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="minvol", - description="Optimizes for minimum volatility", - ) - parser.add_argument( - "-p", - "--period", - default="1y", - dest="period", - help="period to get yfinance data from", - choices=self.period_choices, - ) - parser.add_argument( - "-v", - "--value", - dest="value", - help="Amount to allocate to portfolio", - type=float, - default=1.0, - ) - parser.add_argument( - "--pie", - action="store_true", - dest="pie", - default=False, - help="Display a pie chart for weights", - ) - ns_parser = parse_known_args_and_warn(parser, other_args) - - if ns_parser: - if len(self.tickers) < 2: - console.print( - "Please have at least 2 loaded tickers to calculate weights.\n" - ) - return - - optimizer_view.display_min_volatility( - stocks=self.tickers, - period=ns_parser.period, - value=ns_parser.value, - pie=ns_parser.pie, - ) - - @log_start_end(log=logger) - def call_maxquadutil(self, other_args: List[str]): - """Process maxquadutil command""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="maxquadutil", - description="Maximises the quadratic utility, given some risk aversion", - ) - parser.add_argument( - "-p", - "--period", - default="1y", - dest="period", - help="period to get yfinance data from", - choices=self.period_choices, - ) - parser.add_argument( - "-v", - "--value", - dest="value", - help="Amount to allocate to portfolio", - type=float, - default=1.0, - ) - parser.add_argument( - "-n", - "--market-neutral", - action="store_true", - default=False, - dest="market_neutral", - help="""whether the portfolio should be market neutral (weights sum to zero), defaults to False. - Requires negative lower weight bound.""", - ) - parser.add_argument( - "--pie", - action="store_true", - dest="pie", - default=False, - help="Display a pie chart for weights. Only if neutral flag is left False.", - ) - parser.add_argument( - "-r", - "--risk-aversion", - type=float, - dest="risk_aversion", - default=1.0, - help="risk aversion parameter", - ) - - ns_parser = parse_known_args_and_warn(parser, other_args) - if ns_parser: - if len(self.tickers) < 2: - console.print( - "Please have at least 2 loaded tickers to calculate weights.\n" - ) - return - - if ns_parser.pie and ns_parser.market_neutral: - console.print( - "Cannot show pie chart for market neutral due to negative weights." - ) - - optimizer_view.display_max_quadratic_utility( - stocks=self.tickers, - period=ns_parser.period, - value=ns_parser.value, - risk_aversion=ns_parser.risk_aversion, - market_neutral=ns_parser.market_neutral, - pie=ns_parser.pie, - ) - - @log_start_end(log=logger) - def call_effrisk(self, other_args: List[str]): - """Process effrisk command""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="effrisk", - description="""Maximise return for a target risk. The resulting portfolio will have - a volatility less than the target (but not guaranteed to be equal)""", - ) - parser.add_argument( - "-p", - "--period", - default="1y", - dest="period", - help="period to get yfinance data from", - choices=self.period_choices, - ) - parser.add_argument( - "-v", - "--value", - dest="value", - help="Amount to allocate to portfolio", - type=float, - default=1.0, - ) - parser.add_argument( - "-n", - "--market-neutral", - action="store_true", - default=False, - dest="market_neutral", - help="""whether the portfolio should be market neutral (weights sum to zero), defaults to False. - Requires negative lower weight bound.""", - ) - - parser.add_argument( - "--pie", - action="store_true", - dest="pie", - default=False, - help="Display a pie chart for weights. Only if neutral flag is left False.", - ) - - if other_args and "-" not in other_args[0][0]: - other_args.insert(0, "-t") - parser.add_argument( - "-t", - "--target-volatility", - type=float, - dest="target_volatility", - default=0.1, - help="The desired maximum volatility of the resulting portfolio", - ) - - ns_parser = parse_known_args_and_warn(parser, other_args) - if ns_parser: - if len(self.tickers) < 2: - console.print( - "Please have at least 2 loaded tickers to calculate weights.\n" - ) - return - - if ns_parser.pie and ns_parser.market_neutral: - console.print( - "Cannot show pie chart for market neutral due to negative weights." - ) - return - - optimizer_view.display_efficient_risk( - stocks=self.tickers, - period=ns_parser.period, - value=ns_parser.value, - target_volatility=ns_parser.target_volatility, - market_neutral=ns_parser.market_neutral, - pie=ns_parser.pie, - ) - - @log_start_end(log=logger) - def call_effret(self, other_args: List[str]): - """Process effret command""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="effret", - description="Calculate the 'Markowitz portfolio', minimising volatility for a given target return", - ) - parser.add_argument( - "-p", - "--period", - default="1y", - dest="period", - help="period to get yfinance data from", - choices=self.period_choices, - ) - parser.add_argument( - "-v", - "--value", - dest="value", - help="Amount to allocate to portfolio", - type=float, - default=1.0, - ) - parser.add_argument( - "-n", - "--market-neutral", - action="store_true", - default=False, - dest="market_neutral", - help="""whether the portfolio should be market neutral (weights sum to zero), defaults to False. - Requires negative lower weight bound.""", - ) - parser.add_argument( - "--pie", - action="store_true", - dest="pie", - default=False, - help="Display a pie chart for weights. Only if neutral flag is left False.", - ) - - if other_args and "-" not in other_args[0][0]: - other_args.insert(0, "-t") - - parser.add_argument( - "-t", - "--target-return", - type=float, - dest="target_return", - default=0.1, - help="the desired return of the resulting portfolio", - ) - ns_parser = parse_known_args_and_warn(parser, other_args) - if ns_parser: - if len(self.tickers) < 2: - console.print( - "Please have at least 2 loaded tickers to calculate weights.\n" - ) - return - - if ns_parser.pie and ns_parser.market_neutral: - console.print( - "Cannot show pie chart for market neutral due to negative weights." - ) - return - - optimizer_view.display_efficient_return( - stocks=self.tickers, - period=ns_parser.period, - value=ns_parser.value, - target_return=ns_parser.target_return, - market_neutral=ns_parser.market_neutral, - pie=ns_parser.pie, - ) - - @log_start_end(log=logger) - def call_ef(self, other_args): - """Process ef command""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="ef", - description="""This function plots random portfolios based - on their risk and returns and shows the efficient frontier.""", - ) - parser.add_argument( - "-p", - "--period", - default="1y", - dest="period", - help="period to get yfinance data from", - choices=self.period_choices, - ) - if other_args and "-" not in other_args[0][0]: - other_args.insert(0, "-n") - parser.add_argument( - "-n", - "--number-portfolios", - default=300, - type=check_non_negative, - dest="n_port", - help="number of portfolios to simulate", - ) - parser.add_argument( - "-r", - "--risk-free", - action="store_true", - dest="risk_free", - default=False, - help="Adds the optimal line with the risk-free asset", - ) - - ns_parser = parse_known_args_and_warn(parser, other_args) - if ns_parser: - if len(self.tickers) < 2: - console.print( - "Please have at least 2 loaded tickers to calculate weights.\n" - ) - return - - optimizer_view.display_ef( - stocks=self.tickers, - period=ns_parser.period, - n_portfolios=ns_parser.n_port, - risk_free=ns_parser.risk_free, - ) - - @log_start_end(log=logger) - def call_yolo(self, _): - # Easter egg :) - console.print("DFV YOLO") - console.print("GME: ALL", "\n") - - def add_stocks(self, other_args: List[str]): """Add ticker or Select tickers for portfolio to be optimized""" parser = argparse.ArgumentParser( add_help=False, @@ -790,19 +503,23 @@ class PortfolioOptimizationController(BaseController): ns_parser = parse_known_args_and_warn(parser, other_args) if ns_parser: - tickers = set(self.tickers) + tickers: Set = set(self.tickers) for ticker in ns_parser.add_tickers: tickers.add(ticker) + tickers_list: List = list(tickers) + tickers_list.sort() + self.tickers = tickers_list + if self.tickers: console.print( - f"\nCurrent Tickers: {('None', ', '.join(tickers))[bool(tickers)]}" + f"\nCurrent Tickers: {('None', ', '.join(tickers_list))[bool(tickers_list)]}" ) - self.tickers = list(tickers) console.print("") - def rmv_stocks(self, other_args: List[str]): + @log_start_end(log=logger) + def call_rmv(self, other_args: List[str]): """Remove one of the tickers to be optimized""" parser = argparse.ArgumentParser( add_help=False, @@ -827,10 +544,5799 @@ class PortfolioOptimizationController(BaseController): for ticker in ns_parser.rmv_tickers: tickers.remove(ticker) + self.tickers = list(tickers) + self.tickers.sort() + if self.tickers: console.print( f"\nCurrent Tickers: {('None', ', '.join(tickers))[bool(tickers)]}" ) - self.tickers = list(tickers) console.print("") + + @log_start_end(log=logger) + def call_file(self, other_args: List[str]): + """Process file command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="file", + description="Select parameter file to use", + ) + + parser.add_argument( + "-f", + "--file", + required=True, + nargs="+", + dest="file", + help="Parameter file to be used", + ) + + if other_args and "-" not in other_args[0][0]: + other_args.insert(0, "-f") + ns_parser = parse_known_args_and_warn(parser, other_args) + + if ns_parser: + self.current_file = " ".join(ns_parser.file) + + if self.current_file in self.DATA_OPTIMIZATION_FILES: + file_location = self.DATA_OPTIMIZATION_FILES[self.current_file] + else: + file_location = self.current_file # type: ignore + + self.params, self.current_model = params_view.load_file(file_location) + + @log_start_end(log=logger) + def call_params(self, _): + """Process params command""" + self.queue = self.load_class( + params_controller.ParametersController, + self.current_file, + self.queue, + self.params, + self.current_model, + ) + + self.current_file = parent_classes.controllers[ + "/portfolio/po/params/" + ].current_file + self.current_model = parent_classes.controllers[ + "/portfolio/po/params/" + ].current_model + self.params = parent_classes.controllers["/portfolio/po/params/"].params + + @log_start_end(log=logger) + def call_show(self, other_args: List[str]): + """Show saved portfolios""" + parser = argparse.ArgumentParser( + add_help=False, + prog="show", + description="""Show selected saved portfolios""", + ) + parser.add_argument( + "-pf", + "--portfolios", + dest="portfolios", + type=lambda s: [str(item).upper() for item in s.split(",")], + default=[], + help="Show selected saved portfolios", + ) + parser.add_argument( + "-ct", + "--categories", + dest="categories", + type=lambda s: [str(item).upper() for item in s.split(",")], + default=[], + help="Show selected categories", + ) + if other_args: + if "-" not in other_args[0]: + other_args.insert(0, "-pf") + + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + portfolios = set(self.portfolios.keys()) + if not ns_parser.categories: + categories = ["ASSET_CLASS", "COUNTRY", "SECTOR", "INDUSTRY"] + else: + categories = ns_parser.categories + + flag = True + for portfolio in ns_parser.portfolios: + if portfolio in portfolios: + console.print("") + console.print("Portfolio - " + portfolio) + optimizer_view.display_weights(self.portfolios[portfolio]) + + for category in categories: + console.print("") + optimizer_view.display_categories( + weights=self.portfolios[portfolio], + categories=self.categories, + column=category, + title="Category - " + category.title(), + ) + flag = False + + if flag: + console.print( + f"\nCurrent Portfolios: {('None', ', '.join(portfolios))[bool(portfolios)]}" + ) + console.print( + f"\nCurrent Categories: {('None', ', '.join(categories))[bool(categories)]}" + ) + console.print("") + + @log_start_end(log=logger) + def call_rpf(self, other_args: List[str]): + """Remove one portfolio""" + parser = argparse.ArgumentParser( + add_help=False, + prog="rpf", + description="""Remove one of the portfolios""", + ) + parser.add_argument( + "-pf", + "--portfolios", + dest="portfolios", + type=lambda s: [str(item).upper() for item in s.split(",")], + default=[], + help="portfolios to be removed from the saved portfolios", + ) + if other_args: + if "-" not in other_args[0]: + other_args.insert(0, "-pf") + + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + portfolios = set(self.portfolios.keys()) + for portfolio in ns_parser.portfolios: + if portfolio in portfolios: + self.portfolios.pop(portfolio) + portfolios.remove(portfolio) + + if self.portfolios: + console.print( + f"\nCurrent Portfolios: {('None', ', '.join(portfolios))[bool(portfolios)]}" + ) + + self.update_runtime_choices() + console.print("") + + @log_start_end(log=logger) + def call_load(self, other_args: List[str]): + """Load file with stocks tickers and categories""" + parser = argparse.ArgumentParser( + add_help=False, + prog="load", + description="""Load file of stocks tickers with optional categories""", + ) + + parser.add_argument( + "-f", + "--file", + required=True, + nargs="+", + dest="file", + help="Allocation file to be used", + ) + if other_args and "-" not in other_args[0][0]: + other_args.insert(0, "-f") + ns_parser = parse_known_args_and_warn(parser, other_args) + + if ns_parser: + filename = " ".join(ns_parser.file) + + if filename in self.DATA_ALLOCATION_FILES: + file_location = self.DATA_ALLOCATION_FILES[filename] + else: + file_location = filename # type: ignore + + self.tickers, self.categories = excel_model.load_allocation(file_location) + self.portfolios = dict() + self.update_runtime_choices() + + @log_start_end(log=logger) + def call_plot(self, other_args: List[str]): + """Process plot command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="plot", + description="Plot selected charts for portfolios", + ) + parser.add_argument( + "-pf", + "--portfolios", + type=lambda s: [str(item).upper() for item in s.split(",")], + default=[], + dest="portfolios", + help="Selected portfolios that will be plotted", + ) + parser.add_argument( + "-ct", + "--categories", + dest="categories", + type=lambda s: [str(item).upper() for item in s.split(",")], + default=[], + help="Show selected categories", + ) + parser.add_argument( + "-p", + "--period", + default=self.params["historic_period"] + if "historic_period" in self.params + else "3y", + dest="historic_period", + help="""Period to get yfinance data from. + Possible frequency strings are: + 'd': means days, for example '252d' means 252 days + 'w': means weeks, for example '52w' means 52 weeks + 'mo': means months, for example '12mo' means 12 months + 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset""", + ) + parser.add_argument( + "-s", + "--start", + default=self.params["start_period"] + if "start_period" in self.params + else "", + dest="start_period", + help="""Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-e", + "--end", + default=self.params["end_period"] if "end_period" in self.params else "", + dest="end_period", + help="""End date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-lr", + "--log-returns", + action="store_true", + default=self.params["log_returns"] + if "log_returns" in self.params + else False, + dest="log_returns", + help="If use logarithmic or arithmetic returns to calculate returns", + ) + parser.add_argument( + "-f", + "--freq", + default=self.params["return_frequency"] + if "return_frequency" in self.params + else "d", + dest="return_frequency", + help="""Frequency used to calculate returns. Possible values are: + 'd': for daily returns + 'w': for weekly returns + 'm': for monthly returns + """, + choices=self.FREQ_CHOICES, + ) + parser.add_argument( + "-mn", + "--maxnan", + type=float, + default=self.params["max_nan"] if "max_nan" in self.params else 0.05, + dest="max_nan", + help="""Max percentage of nan values accepted per asset to be + considered in the optimization process""", + ) + parser.add_argument( + "-th", + "--threshold", + type=float, + default=self.params["threshold_value"] + if "threshold_value" in self.params + else 0.30, + dest="threshold_value", + help="""Value used to replace outliers that are higher to threshold + in absolute value""", + ) + parser.add_argument( + "-mt", + "--method", + default=self.params["nan_fill_method"] + if "nan_fill_method" in self.params + else "time", + dest="nan_fill_method", + help="""Method used to fill nan values in time series, by default time. + Possible values are: + 'linear': linear interpolation + 'time': linear interpolation based on time index + 'nearest': use nearest value to replace nan values + 'zero': spline of zeroth order + 'slinear': spline of first order + 'quadratic': spline of second order + 'cubic': spline of third order + 'barycentric': builds a polynomial that pass for all points""", + ) + parser.add_argument( + "-rm", + "--risk-measure", + default=self.params["risk_measure"] + if "risk_measure" in self.params + else "MV", + dest="risk_measure", + help="""Risk measure used to optimize the portfolio. Possible values are: + 'MV' : Variance + 'MAD' : Mean Absolute Deviation + 'MSV' : Semi Variance (Variance of negative returns) + 'FLPM' : First Lower Partial Moment + 'SLPM' : Second Lower Partial Moment + 'CVaR' : Conditional Value at Risk + 'EVaR' : Entropic Value at Risk + 'WR' : Worst Realization + 'ADD' : Average Drawdown of uncompounded returns + 'UCI' : Ulcer Index of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded returns + 'EDaR' : Entropic Drawdown at Risk of uncompounded returns + 'MDD' : Maximum Drawdown of uncompounded returns + """, + choices=self.MEAN_RISK_CHOICES, + ) + parser.add_argument( + "-r", + "--risk-free-rate", + type=float, + dest="risk_free", + default=self.params["risk_free"] + if "risk_free" in self.params + else get_rf(), + help="""Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual""", + ) + parser.add_argument( + "-a", + "--alpha", + type=float, + default=self.params["significance_level"] + if "significance_level" in self.params + else 0.05, + dest="significance_level", + help="Significance level of CVaR, EVaR, CDaR and EDaR", + ) + parser.add_argument( + "-pi", + "--pie", + action="store_true", + dest="pie", + default=False, + help="Display a pie chart for weights", + ) + parser.add_argument( + "-hi", + "--hist", + action="store_true", + dest="hist", + default=False, + help="Display a histogram with risk measures", + ) + parser.add_argument( + "-dd", + "--drawdown", + action="store_true", + dest="dd", + default=False, + help="Display a drawdown chart with risk measures", + ) + parser.add_argument( + "-rc", + "--rc-chart", + action="store_true", + dest="rc_chart", + default=False, + help="Display a risk contribution chart for assets", + ) + parser.add_argument( + "-he", + "--heat", + action="store_true", + dest="heat", + default=False, + help="Display a heatmap of correlation matrix with dendrogram", + ) + if other_args: + if "-" not in other_args[0]: + other_args.insert(0, "-pf") + + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + if len(self.tickers) < 2: + console.print( + "Please have at least 2 loaded tickers to calculate weights.\n" + ) + return + + portfolios = ns_parser.portfolios + stocks = [] + for i in portfolios: + stocks += list(self.portfolios[i].keys()) + stocks = list(set(stocks)) + stocks.sort() + + _, stock_returns = optimizer_model.get_equal_weights( + stocks=stocks, + period=ns_parser.historic_period, + start=ns_parser.start_period, + end=ns_parser.end_period, + log_returns=ns_parser.log_returns, + freq=ns_parser.return_frequency, + maxnan=ns_parser.max_nan, + threshold=ns_parser.threshold_value, + method=ns_parser.nan_fill_method, + value=1, + ) + + categories = ns_parser.categories + + for i in portfolios: + weights = self.portfolios[i] + weights = dict( + sorted(weights.items(), key=lambda x: x[1], reverse=True) + ) + stocks = list(weights.keys()) + optimizer_view.additional_plots( + weights=weights, + stock_returns=stock_returns[stocks], + category=None, + title_opt=i, + freq=ns_parser.return_frequency, + risk_measure=ns_parser.risk_measure.lower(), + risk_free_rate=ns_parser.risk_free, + alpha=ns_parser.significance_level, + a_sim=100, + beta=ns_parser.significance_level, + b_sim=100, + pie=ns_parser.pie, + hist=ns_parser.hist, + dd=ns_parser.dd, + rc_chart=ns_parser.rc_chart, + heat=ns_parser.heat, + external_axes=None, + ) + if ns_parser.pie or ns_parser.heat or ns_parser.rc_chart: + for category in categories: + filtered_categories = dict( + filter( + lambda elem: elem[0] in stocks, + self.categories[category].items(), + ) + ) + optimizer_view.additional_plots( + weights=weights, + stock_returns=stock_returns[stocks], + category=filtered_categories, + title_opt=category + " - " + i, + freq=ns_parser.return_frequency, + risk_measure=ns_parser.risk_measure.lower(), + risk_free_rate=ns_parser.risk_free, + alpha=ns_parser.significance_level, + a_sim=100, + beta=ns_parser.significance_level, + b_sim=100, + pie=ns_parser.pie, + hist=ns_parser.hist, + dd=ns_parser.dd, + rc_chart=ns_parser.rc_chart, + heat=ns_parser.heat, + external_axes=None, + ) + + @log_start_end(log=logger) + def call_equal(self, other_args: List[str]): + """Process equal command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="equal", + description="Returns an equally weighted portfolio", + ) + parser.add_argument( + "-p", + "--period", + default=self.params["historic_period"] + if "historic_period" in self.params + else "3y", + dest="historic_period", + help="""Period to get yfinance data from. + Possible frequency strings are: + 'd': means days, for example '252d' means 252 days + 'w': means weeks, for example '52w' means 52 weeks + 'mo': means months, for example '12mo' means 12 months + 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset""", + ) + parser.add_argument( + "-s", + "--start", + default=self.params["start_period"] + if "start_period" in self.params + else "", + dest="start_period", + help="""Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-e", + "--end", + default=self.params["end_period"] if "end_period" in self.params else "", + dest="end_period", + help="""End date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-lr", + "--log-returns", + action="store_true", + default=self.params["log_returns"] + if "log_returns" in self.params + else False, + dest="log_returns", + help="If use logarithmic or arithmetic returns to calculate returns", + ) + parser.add_argument( + "-f", + "--freq", + default=self.params["return_frequency"] + if "return_frequency" in self.params + else "d", + dest="return_frequency", + help="""Frequency used to calculate returns. Possible values are: + 'd': for daily returns + 'w': for weekly returns + 'm': for monthly returns + """, + choices=self.FREQ_CHOICES, + ) + parser.add_argument( + "-mn", + "--maxnan", + type=float, + default=self.params["max_nan"] if "max_nan" in self.params else 0.05, + dest="max_nan", + help="""Max percentage of nan values accepted per asset to be + considered in the optimization process""", + ) + parser.add_argument( + "-th", + "--threshold", + type=float, + default=self.params["threshold_value"] + if "threshold_value" in self.params + else 0.30, + dest="threshold_value", + help="""Value used to replace outliers that are higher to threshold + in absolute value""", + ) + parser.add_argument( + "-mt", + "--method", + default=self.params["nan_fill_method"] + if "nan_fill_method" in self.params + else "time", + dest="nan_fill_method", + help="""Method used to fill nan values in time series, by default time. + Possible values are: + 'linear': linear interpolation + 'time': linear interpolation based on time index + 'nearest': use nearest value to replace nan values + 'zero': spline of zeroth order + 'slinear': spline of first order + 'quadratic': spline of second order + 'cubic': spline of third order + 'barycentric': builds a polynomial that pass for all points""", + ) + parser.add_argument( + "-rm", + "--risk-measure", + default=self.params["risk_measure"] + if "risk_measure" in self.params + else "MV", + dest="risk_measure", + help="""Risk measure used to calculate indicators. Possible values are: + 'MV' : Variance + 'MAD' : Mean Absolute Deviation + 'MSV' : Semi Variance (Variance of negative returns) + 'FLPM' : First Lower Partial Moment + 'SLPM' : Second Lower Partial Moment + 'CVaR' : Conditional Value at Risk + 'EVaR' : Entropic Value at Risk + 'WR' : Worst Realization + 'ADD' : Average Drawdown of uncompounded returns + 'UCI' : Ulcer Index of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded returns + 'EDaR' : Entropic Drawdown at Risk of uncompounded returns + 'MDD' : Maximum Drawdown of uncompounded returns + """, + choices=self.MEAN_RISK_CHOICES, + ) + parser.add_argument( + "-r", + "--risk-free-rate", + type=float, + dest="risk_free", + default=self.params["risk_free"] + if "risk_free" in self.params + else get_rf(), + help="""Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual""", + ) + parser.add_argument( + "-a", + "--alpha", + type=float, + default=self.params["significance_level"] + if "significance_level" in self.params + else 0.05, + dest="significance_level", + help="Significance level of CVaR, EVaR, CDaR and EDaR", + ) + parser.add_argument( + "-v", + "--value", + default=self.params["long_allocation"] + if "long_allocation" in self.params + else 1, + type=float, + dest="long_allocation", + help="Amount to allocate to portfolio", + ) + parser.add_argument( + "--name", + type=str, + dest="name", + default="EQUAL_" + str(self.count), + help="Save portfolio with personalized or default name", + ) + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + if len(self.tickers) < 2: + console.print( + "Please have at least 2 loaded tickers to calculate weights.\n" + ) + return + + weights = optimizer_view.display_equal_weight( + stocks=self.tickers, + period=ns_parser.historic_period, + start=ns_parser.start_period, + end=ns_parser.end_period, + log_returns=ns_parser.log_returns, + freq=ns_parser.return_frequency, + maxnan=ns_parser.max_nan, + threshold=ns_parser.threshold_value, + method=ns_parser.nan_fill_method, + risk_measure=ns_parser.risk_measure.lower(), + risk_free_rate=ns_parser.risk_free, + alpha=ns_parser.significance_level, + value=ns_parser.long_allocation, + table=True, + ) + + self.portfolios[ns_parser.name.upper()] = weights + self.count += 1 + self.update_runtime_choices() + + @log_start_end(log=logger) + def call_mktcap(self, other_args: List[str]): + """Process mktcap command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="mktcap", + description="Returns a portfolio that is weighted based on Market Cap.", + ) + parser.add_argument( + "-p", + "--period", + default=self.params["historic_period"] + if "historic_period" in self.params + else "3y", + dest="historic_period", + help="""Period to get yfinance data from. + Possible frequency strings are: + 'd': means days, for example '252d' means 252 days + 'w': means weeks, for example '52w' means 52 weeks + 'mo': means months, for example '12mo' means 12 months + 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset""", + ) + parser.add_argument( + "-s", + "--start", + default=self.params["start_period"] + if "start_period" in self.params + else "", + dest="start_period", + help="""Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-e", + "--end", + default=self.params["end_period"] if "end_period" in self.params else "", + dest="end_period", + help="""End date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-lr", + "--log-returns", + action="store_true", + default=self.params["log_returns"] + if "log_returns" in self.params + else False, + dest="log_returns", + help="If use logarithmic or arithmetic returns to calculate returns", + ) + parser.add_argument( + "-f", + "--freq", + default=self.params["return_frequency"] + if "return_frequency" in self.params + else "d", + dest="return_frequency", + help="""Frequency used to calculate returns. Possible values are: + 'd': for daily returns + 'w': for weekly returns + 'm': for monthly returns + """, + choices=self.FREQ_CHOICES, + ) + parser.add_argument( + "-mn", + "--maxnan", + type=float, + default=self.params["max_nan"] if "max_nan" in self.params else 0.05, + dest="max_nan", + help="""Max percentage of nan values accepted per asset to be + considered in the optimization process""", + ) + parser.add_argument( + "-th", + "--threshold", + type=float, + default=self.params["threshold_value"] + if "threshold_value" in self.params + else 0.30, + dest="threshold_value", + help="""Value used to replace outliers that are higher to threshold + in absolute value""", + ) + parser.add_argument( + "-mt", + "--method", + default=self.params["nan_fill_method"] + if "nan_fill_method" in self.params + else "time", + dest="nan_fill_method", + help="""Method used to fill nan values in time series, by default time. + Possible values are: + 'linear': linear interpolation + 'time': linear interpolation based on time index + 'nearest': use nearest value to replace nan values + 'zero': spline of zeroth order + 'slinear': spline of first order + 'quadratic': spline of second order + 'cubic': spline of third order + 'barycentric': builds a polynomial that pass for all points""", + ) + parser.add_argument( + "-rm", + "--risk-measure", + default=self.params["risk_measure"] + if "risk_measure" in self.params + else "MV", + dest="risk_measure", + help="""Risk measure used to calculate indicators. Possible values are: + 'MV' : Variance + 'MAD' : Mean Absolute Deviation + 'MSV' : Semi Variance (Variance of negative returns) + 'FLPM' : First Lower Partial Moment + 'SLPM' : Second Lower Partial Moment + 'CVaR' : Conditional Value at Risk + 'EVaR' : Entropic Value at Risk + 'WR' : Worst Realization + 'ADD' : Average Drawdown of uncompounded returns + 'UCI' : Ulcer Index of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded returns + 'EDaR' : Entropic Drawdown at Risk of uncompounded returns + 'MDD' : Maximum Drawdown of uncompounded returns + """, + choices=self.MEAN_RISK_CHOICES, + ) + parser.add_argument( + "-r", + "--risk-free-rate", + type=float, + dest="risk_free", + default=self.params["risk_free"] + if "risk_free" in self.params + else get_rf(), + help="""Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual""", + ) + parser.add_argument( + "-a", + "--alpha", + type=float, + default=self.params["significance_level"] + if "significance_level" in self.params + else 0.05, + dest="significance_level", + help="Significance level of CVaR, EVaR, CDaR and EDaR", + ) + parser.add_argument( + "-v", + "--value", + default=self.params["long_allocation"] + if "long_allocation" in self.params + else 1, + type=float, + dest="long_allocation", + help="Amount to allocate to portfolio", + ) + parser.add_argument( + "--name", + type=str, + dest="name", + default="MKTCAP_" + str(self.count), + help="Save portfolio with personalized or default name", + ) + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + if len(self.tickers) < 2: + console.print( + "Please have at least 2 stocks selected to perform calculations." + ) + return + + weights = optimizer_view.display_property_weighting( + stocks=self.tickers, + period=ns_parser.historic_period, + start=ns_parser.start_period, + end=ns_parser.end_period, + log_returns=ns_parser.log_returns, + freq=ns_parser.return_frequency, + maxnan=ns_parser.max_nan, + threshold=ns_parser.threshold_value, + method=ns_parser.nan_fill_method, + s_property="marketCap", + risk_measure=ns_parser.risk_measure.lower(), + risk_free_rate=ns_parser.risk_free, + alpha=ns_parser.significance_level, + value=ns_parser.long_allocation, + table=True, + ) + + self.portfolios[ns_parser.name.upper()] = weights + self.count += 1 + self.update_runtime_choices() + + @log_start_end(log=logger) + def call_dividend(self, other_args: List[str]): + """Process dividend command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="dividend", + description="Returns a portfolio that is weighted based dividend yield.", + ) + parser.add_argument( + "-p", + "--period", + default=self.params["historic_period"] + if "historic_period" in self.params + else "3y", + dest="historic_period", + help="""Period to get yfinance data from. + Possible frequency strings are: + 'd': means days, for example '252d' means 252 days + 'w': means weeks, for example '52w' means 52 weeks + 'mo': means months, for example '12mo' means 12 months + 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset""", + ) + parser.add_argument( + "-s", + "--start", + default=self.params["start_period"] + if "start_period" in self.params + else "", + dest="start_period", + help="""Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-e", + "--end", + default=self.params["end_period"] if "end_period" in self.params else "", + dest="end_period", + help="""End date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-lr", + "--log-returns", + action="store_true", + default=self.params["log_returns"] + if "log_returns" in self.params + else False, + dest="log_returns", + help="If use logarithmic or arithmetic returns to calculate returns", + ) + parser.add_argument( + "-f", + "--freq", + default=self.params["return_frequency"] + if "return_frequency" in self.params + else "d", + dest="return_frequency", + help="""Frequency used to calculate returns. Possible values are: + 'd': for daily returns + 'w': for weekly returns + 'm': for monthly returns + """, + choices=self.FREQ_CHOICES, + ) + parser.add_argument( + "-mn", + "--maxnan", + type=float, + default=self.params["max_nan"] if "max_nan" in self.params else 0.05, + dest="max_nan", + help="""Max percentage of nan values accepted per asset to be + considered in the optimization process""", + ) + parser.add_argument( + "-th", + "--threshold", + type=float, + default=self.params["threshold_value"] + if "threshold_value" in self.params + else 0.30, + dest="threshold_value", + help="""Value used to replace outliers that are higher to threshold + in absolute value""", + ) + parser.add_argument( + "-mt", + "--method", + default=self.params["nan_fill_method"] + if "nan_fill_method" in self.params + else "time", + dest="nan_fill_method", + help="""Method used to fill nan values in time series, by default time. + Possible values are: + 'linear': linear interpolation + 'time': linear interpolation based on time index + 'nearest': use nearest value to replace nan values + 'zero': spline of zeroth order + 'slinear': spline of first order + 'quadratic': spline of second order + 'cubic': spline of third order + 'barycentric': builds a polynomial that pass for all points""", + ) + parser.add_argument( + "-rm", + "--risk-measure", + default=self.params["risk_measure"] + if "risk_measure" in self.params + else "MV", + dest="risk_measure", + help="""Risk measure used to calculate indicators. Possible values are: + 'MV' : Variance + 'MAD' : Mean Absolute Deviation + 'MSV' : Semi Variance (Variance of negative returns) + 'FLPM' : First Lower Partial Moment + 'SLPM' : Second Lower Partial Moment + 'CVaR' : Conditional Value at Risk + 'EVaR' : Entropic Value at Risk + 'WR' : Worst Realization + 'ADD' : Average Drawdown of uncompounded returns + 'UCI' : Ulcer Index of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded returns + 'EDaR' : Entropic Drawdown at Risk of uncompounded returns + 'MDD' : Maximum Drawdown of uncompounded returns + """, + choices=self.MEAN_RISK_CHOICES, + ) + parser.add_argument( + "-r", + "--risk-free-rate", + type=float, + dest="risk_free", + default=self.params["risk_free"] + if "risk_free" in self.params + else get_rf(), + help="""Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual""", + ) + parser.add_argument( + "-a", + "--alpha", + type=float, + default=self.params["significance_level"] + if "significance_level" in self.params + else 0.05, + dest="significance_level", + help="Significance level of CVaR, EVaR, CDaR and EDaR", + ) + parser.add_argument( + "-v", + "--value", + default=self.params["long_allocation"] + if "long_allocation" in self.params + else 1, + type=float, + dest="long_allocation", + help="Amount to allocate to portfolio", + ) + parser.add_argument( + "--name", + type=str, + dest="name", + default="DIVIDEND_" + str(self.count), + help="Save portfolio with personalized or default name", + ) + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + if len(self.tickers) < 2: + console.print( + "Please have at least 2 stocks selected to perform calculations." + ) + return + + weights = optimizer_view.display_property_weighting( + stocks=self.tickers, + period=ns_parser.historic_period, + start=ns_parser.start_period, + end=ns_parser.end_period, + log_returns=ns_parser.log_returns, + freq=ns_parser.return_frequency, + maxnan=ns_parser.max_nan, + threshold=ns_parser.threshold_value, + method=ns_parser.nan_fill_method, + s_property="dividendYield", + risk_measure=ns_parser.risk_measure.lower(), + risk_free_rate=ns_parser.risk_free, + alpha=ns_parser.significance_level, + value=ns_parser.long_allocation, + table=True, + ) + + self.portfolios[ns_parser.name.upper()] = weights + self.count += 1 + self.update_runtime_choices() + + @log_start_end(log=logger) + def call_property(self, other_args: List[str]): + """Process property command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="property", + description="Returns a portfolio that is weighted based on selected property.", + ) + parser.add_argument( + "-p", + "--period", + default=self.params["historic_period"] + if "historic_period" in self.params + else "3y", + dest="historic_period", + help="""Period to get yfinance data from. + Possible frequency strings are: + 'd': means days, for example '252d' means 252 days + 'w': means weeks, for example '52w' means 52 weeks + 'mo': means months, for example '12mo' means 12 months + 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset""", + ) + parser.add_argument( + "-s", + "--start", + default=self.params["start_period"] + if "start_period" in self.params + else "", + dest="start_period", + help="""Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-e", + "--end", + default=self.params["end_period"] if "end_period" in self.params else "", + dest="end_period", + help="""End date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-lr", + "--log-returns", + action="store_true", + default=self.params["log_returns"] + if "log_returns" in self.params + else False, + dest="log_returns", + help="If use logarithmic or arithmetic returns to calculate returns", + ) + parser.add_argument( + "-f", + "--freq", + default=self.params["return_frequency"] + if "return_frequency" in self.params + else "d", + dest="return_frequency", + help="""Frequency used to calculate returns. Possible values are: + 'd': for daily returns + 'w': for weekly returns + 'm': for monthly returns + """, + choices=self.FREQ_CHOICES, + ) + parser.add_argument( + "-mn", + "--maxnan", + type=float, + default=self.params["max_nan"] if "max_nan" in self.params else 0.05, + dest="max_nan", + help="""Max percentage of nan values accepted per asset to be + considered in the optimization process""", + ) + parser.add_argument( + "-th", + "--threshold", + type=float, + default=self.params["threshold_value"] + if "threshold_value" in self.params + else 0.30, + dest="threshold_value", + help="""Value used to replace outliers that are higher to threshold + in absolute value""", + ) + parser.add_argument( + "-mt", + "--method", + default=self.params["nan_fill_method"] + if "nan_fill_method" in self.params + else "time", + dest="nan_fill_method", + help="""Method used to fill nan values in time series, by default time. + Possible values are: + 'linear': linear interpolation + 'time': linear interpolation based on time index + 'nearest': use nearest value to replace nan values + 'zero': spline of zeroth order + 'slinear': spline of first order + 'quadratic': spline of second order + 'cubic': spline of third order + 'barycentric': builds a polynomial that pass for all points""", + ) + parser.add_argument( + "-pr", + "--property", + required=bool("-h" not in other_args), + type=optimizer_helper.check_valid_property_type, + dest="s_property", + choices=yahoo_finance_model.yf_info_choices, + help="""Property info to weight. Use one of yfinance info options.""", + ) + parser.add_argument( + "-rm", + "--risk-measure", + default=self.params["risk_measure"] + if "risk_measure" in self.params + else "MV", + dest="risk_measure", + help="""Risk measure used to calculate indicators. Possible values are: + 'MV' : Variance + 'MAD' : Mean Absolute Deviation + 'MSV' : Semi Variance (Variance of negative returns) + 'FLPM' : First Lower Partial Moment + 'SLPM' : Second Lower Partial Moment + 'CVaR' : Conditional Value at Risk + 'EVaR' : Entropic Value at Risk + 'WR' : Worst Realization + 'ADD' : Average Drawdown of uncompounded returns + 'UCI' : Ulcer Index of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded returns + 'EDaR' : Entropic Drawdown at Risk of uncompounded returns + 'MDD' : Maximum Drawdown of uncompounded returns + """, + choices=self.MEAN_RISK_CHOICES, + ) + parser.add_argument( + "-r", + "--risk-free-rate", + type=float, + dest="risk_free", + default=self.params["risk_free"] + if "risk_free" in self.params + else get_rf(), + help="""Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual""", + ) + parser.add_argument( + "-a", + "--alpha", + type=float, + default=self.params["significance_level"] + if "significance_level" in self.params + else 0.05, + dest="significance_level", + help="Significance level of CVaR, EVaR, CDaR and EDaR", + ) + parser.add_argument( + "-v", + "--value", + default=self.params["long_allocation"] + if "long_allocation" in self.params + else 1, + type=float, + dest="long_allocation", + help="Amount to allocate to portfolio", + ) + parser.add_argument( + "--name", + type=str, + dest="name", + default="PROPERTY_" + str(self.count), + help="Save portfolio with personalized or default name", + ) + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + if len(self.tickers) < 2: + console.print( + "Please have at least 2 stocks selected to perform calculations." + ) + return + + weights = optimizer_view.display_property_weighting( + stocks=self.tickers, + period=ns_parser.historic_period, + start=ns_parser.start_period, + end=ns_parser.end_period, + log_returns=ns_parser.log_returns, + freq=ns_parser.return_frequency, + maxnan=ns_parser.max_nan, + threshold=ns_parser.threshold_value, + method=ns_parser.nan_fill_method, + s_property=ns_parser.s_property, + risk_measure=ns_parser.risk_measure.lower(), + risk_free_rate=ns_parser.risk_free, + alpha=ns_parser.significance_level, + value=ns_parser.long_allocation, + table=True, + ) + + self.portfolios[ns_parser.name.upper()] = weights + self.count += 1 + self.update_runtime_choices() + + @log_start_end(log=logger) + def call_maxsharpe(self, other_args: List[str]): + """Process maxsharpe command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="maxsharpe", + description="Maximizes the portfolio's return/risk ratio", + ) + parser.add_argument( + "-p", + "--period", + default=self.params["historic_period"] + if "historic_period" in self.params + else "3y", + dest="historic_period", + help="""Period to get yfinance data from. + Possible frequency strings are: + 'd': means days, for example '252d' means 252 days + 'w': means weeks, for example '52w' means 52 weeks + 'mo': means months, for example '12mo' means 12 months + 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset""", + ) + parser.add_argument( + "-s", + "--start", + default=self.params["start_period"] + if "start_period" in self.params + else "", + dest="start_period", + help="""Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-e", + "--end", + default=self.params["end_period"] if "end_period" in self.params else "", + dest="end_period", + help="""End date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-lr", + "--log-returns", + action="store_true", + default=self.params["log_returns"] + if "log_returns" in self.params + else False, + dest="log_returns", + help="If use logarithmic or arithmetic returns to calculate returns", + ) + parser.add_argument( + "-f", + "--freq", + default=self.params["return_frequency"] + if "return_frequency" in self.params + else "d", + dest="return_frequency", + help="""Frequency used to calculate returns. Possible values are: + 'd': for daily returns + 'w': for weekly returns + 'm': for monthly returns + """, + choices=self.FREQ_CHOICES, + ) + parser.add_argument( + "-mn", + "--maxnan", + type=float, + default=self.params["max_nan"] if "max_nan" in self.params else 0.05, + dest="max_nan", + help="""Max percentage of nan values accepted per asset to be + considered in the optimization process""", + ) + parser.add_argument( + "-th", + "--threshold", + type=float, + default=self.params["threshold_value"] + if "threshold_value" in self.params + else 0.30, + dest="threshold_value", + help="""Value used to replace outliers that are higher to threshold + in absolute value""", + ) + parser.add_argument( + "-mt", + "--method", + default=self.params["nan_fill_method"] + if "nan_fill_method" in self.params + else "time", + dest="nan_fill_method", + help="""Method used to fill nan values in time series, by default time. + Possible values are: + 'linear': linear interpolation + 'time': linear interpolation based on time index + 'nearest': use nearest value to replace nan values + 'zero': spline of zeroth order + 'slinear': spline of first order + 'quadratic': spline of second order + 'cubic': spline of third order + 'barycentric': builds a polynomial that pass for all points""", + ) + parser.add_argument( + "-rm", + "--risk-measure", + default=self.params["risk_measure"] + if "risk_measure" in self.params + else "MV", + dest="risk_measure", + help="""Risk measure used to optimize the portfolio. Possible values are: + 'MV' : Variance + 'MAD' : Mean Absolute Deviation + 'MSV' : Semi Variance (Variance of negative returns) + 'FLPM' : First Lower Partial Moment + 'SLPM' : Second Lower Partial Moment + 'CVaR' : Conditional Value at Risk + 'EVaR' : Entropic Value at Risk + 'WR' : Worst Realization + 'ADD' : Average Drawdown of uncompounded returns + 'UCI' : Ulcer Index of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded returns + 'EDaR' : Entropic Drawdown at Risk of uncompounded returns + 'MDD' : Maximum Drawdown of uncompounded returns + """, + choices=self.MEAN_RISK_CHOICES, + ) + parser.add_argument( + "-r", + "--risk-free-rate", + type=float, + dest="risk_free", + default=self.params["risk_free"] + if "risk_free" in self.params + else get_rf(), + help="""Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual""", + ) + parser.add_argument( + "-a", + "--alpha", + type=float, + default=self.params["significance_level"] + if "significance_level" in self.params + else 0.05, + dest="significance_level", + help="Significance level of CVaR, EVaR, CDaR and EDaR", + ) + parser.add_argument( + "-tr", + "--target-return", + dest="target_return", + default=self.params["target_return"] + if "target_return" in self.params + else -1, + help="Constraint on minimum level of portfolio's return", + ) + parser.add_argument( + "-tk", + "--target-risk", + dest="target_risk", + default=self.params["target_risk"] if "target_risk" in self.params else -1, + help="Constraint on maximum level of portfolio's risk", + ) + parser.add_argument( + "-m", + "--mean", + default=self.params["expected_return"] + if "expected_return" in self.params + else "hist", + dest="expected_return", + help="Method used to estimate the expected return vector", + choices=self.MEAN_CHOICES, + ) + parser.add_argument( + "-cv", + "--covariance", + default=self.params["expected_return"] + if "expected_return" in self.params + else "hist", + dest="covariance", + help="""Method used to estimate covariance matrix. Possible values are + 'hist': historical method + 'ewma1': exponential weighted moving average with adjust=True + 'ewma2': exponential weighted moving average with adjust=False + 'ledoit': Ledoit and Wolf shrinkage method + 'oas': oracle shrinkage method + 'shrunk': scikit-learn shrunk method + 'gl': graphical lasso method + 'jlogo': j-logo covariance + 'fixed': takes average of eigenvalues above max Marchenko Pastour limit + 'spectral': makes zero eigenvalues above max Marchenko Pastour limit + 'shrink': Lopez de Prado's book shrinkage method + """, + choices=self.COVARIANCE_CHOICES, + ) + parser.add_argument( + "-de", + "--d-ewma", + type=float, + default=self.params["smoothing_factor_ewma"] + if "smoothing_factor_ewma" in self.params + else 0.94, + dest="smoothing_factor_ewma", + help="Smoothing factor for ewma estimators", + ) + parser.add_argument( + "-v", + "--value", + dest="long_allocation", + help="Amount to allocate to portfolio in long positions", + type=float, + default=self.params["long_allocation"] + if "long_allocation" in self.params + else 1, + ) + parser.add_argument( + "-vs", + "--value-short", + dest="short_allocation", + help="Amount to allocate to portfolio in short positions", + type=float, + default=self.params["short_allocation"] + if "short_allocation" in self.params + else 0.0, + ) + parser.add_argument( + "--name", + type=str, + dest="name", + default="MAXSHARPE_" + str(self.count), + help="Save portfolio with personalized or default name", + ) + subparsers = parser.add_subparsers( + title="sensitivity analysis command", help="sensitivity analysis" + ) + parser_update = subparsers.add_parser("sa", help="sensitivity analysis command") + + parser_dict = vars(parser) + for i in parser_dict["_actions"]: + data_dict = vars(i) + variables = list(data_dict.keys()) + if variables[0] == "option_strings" and data_dict["dest"] != "name": + if len(data_dict["option_strings"]) == 1: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + elif len(data_dict["option_strings"]) == 2: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + data_dict["option_strings"][1] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + + parser.add_argument( + "-ct", + "--categories", + dest="categories", + type=lambda s: [str(item).upper() for item in s.split(",")], + default=[], + help="Show selected categories", + ) + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + if len(self.tickers) < 2: + console.print( + "Please have at least 2 loaded tickers to calculate weights.\n" + ) + return + + table = True + if "historic_period_sa" in vars(ns_parser): + table = False + + weights = optimizer_view.display_max_sharpe( + stocks=self.tickers, + period=ns_parser.historic_period, + start=ns_parser.start_period, + end=ns_parser.end_period, + log_returns=ns_parser.log_returns, + freq=ns_parser.return_frequency, + maxnan=ns_parser.max_nan, + threshold=ns_parser.threshold_value, + method=ns_parser.nan_fill_method, + risk_measure=ns_parser.risk_measure.lower(), + risk_free_rate=ns_parser.risk_free, + alpha=ns_parser.significance_level, + target_return=ns_parser.target_return, + target_risk=ns_parser.target_risk, + mean=ns_parser.expected_return.lower(), + covariance=ns_parser.covariance.lower(), + d_ewma=ns_parser.smoothing_factor_ewma, + value=ns_parser.long_allocation, + value_short=ns_parser.short_allocation, + table=table, + ) + + self.portfolios[ns_parser.name.upper()] = weights + self.count += 1 + self.update_runtime_choices() + + if table is False: + weights_sa = optimizer_view.display_max_sharpe( + stocks=self.tickers, + period=ns_parser.historic_period_sa, + start=ns_parser.start_period_sa, + end=ns_parser.end_period_sa, + log_returns=ns_parser.log_returns_sa, + freq=ns_parser.return_frequency_sa, + maxnan=ns_parser.max_nan_sa, + threshold=ns_parser.threshold_value_sa, + method=ns_parser.nan_fill_method_sa, + risk_measure=ns_parser.risk_measure_sa.lower(), + risk_free_rate=ns_parser.risk_free_sa, + alpha=ns_parser.significance_level_sa, + target_return=ns_parser.target_return_sa, + target_risk=ns_parser.target_risk_sa, + mean=ns_parser.expected_return_sa.lower(), + covariance=ns_parser.covariance_sa.lower(), + d_ewma=ns_parser.smoothing_factor_ewma_sa, + value=ns_parser.long_allocation_sa, + value_short=ns_parser.short_allocation_sa, + table=table, + ) + + console.print("") + optimizer_view.display_weights_sa( + weights=weights, weights_sa=weights_sa + ) + + if not ns_parser.categories: + categories = ["ASSET_CLASS", "COUNTRY", "SECTOR", "INDUSTRY"] + else: + categories = ns_parser.categories + + for category in categories: + optimizer_view.display_categories_sa( + weights=weights, + weights_sa=weights_sa, + categories=self.categories, + column=category, + title="Category - " + category.title(), + ) + + @log_start_end(log=logger) + def call_minrisk(self, other_args: List[str]): + """Process minrisk command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="minrisk", + description="Minimizes portfolio's risk", + ) + parser.add_argument( + "-p", + "--period", + default=self.params["historic_period"] + if "historic_period" in self.params + else "3y", + dest="historic_period", + help="""Period to get yfinance data from. + Possible frequency strings are: + 'd': means days, for example '252d' means 252 days + 'w': means weeks, for example '52w' means 52 weeks + 'mo': means months, for example '12mo' means 12 months + 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset""", + ) + parser.add_argument( + "-s", + "--start", + default=self.params["start_period"] + if "start_period" in self.params + else "", + dest="start_period", + help="""Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-e", + "--end", + default=self.params["end_period"] if "end_period" in self.params else "", + dest="end_period", + help="""End date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-lr", + "--log-returns", + action="store_true", + default=self.params["log_returns"] + if "log_returns" in self.params + else False, + dest="log_returns", + help="If use logarithmic or arithmetic returns to calculate returns", + ) + parser.add_argument( + "-f", + "--freq", + default=self.params["return_frequency"] + if "return_frequency" in self.params + else "d", + dest="return_frequency", + help="""Frequency used to calculate returns. Possible values are: + 'd': for daily returns + 'w': for weekly returns + 'm': for monthly returns + """, + choices=self.FREQ_CHOICES, + ) + parser.add_argument( + "-mn", + "--maxnan", + type=float, + default=self.params["max_nan"] if "max_nan" in self.params else 0.05, + dest="max_nan", + help="""Max percentage of nan values accepted per asset to be + considered in the optimization process""", + ) + parser.add_argument( + "-th", + "--threshold", + type=float, + default=self.params["threshold_value"] + if "threshold_value" in self.params + else 0.30, + dest="threshold_value", + help="""Value used to replace outliers that are higher to threshold + in absolute value""", + ) + parser.add_argument( + "-mt", + "--method", + default=self.params["nan_fill_method"] + if "nan_fill_method" in self.params + else "time", + dest="nan_fill_method", + help="""Method used to fill nan values in time series, by default time. + Possible values are: + 'linear': linear interpolation + 'time': linear interpolation based on time index + 'nearest': use nearest value to replace nan values + 'zero': spline of zeroth order + 'slinear': spline of first order + 'quadratic': spline of second order + 'cubic': spline of third order + 'barycentric': builds a polynomial that pass for all points""", + ) + parser.add_argument( + "-rm", + "--risk-measure", + default=self.params["risk_measure"] + if "risk_measure" in self.params + else "MV", + dest="risk_measure", + help="""Risk measure used to optimize the portfolio. Possible values are: + 'MV' : Variance + 'MAD' : Mean Absolute Deviation + 'MSV' : Semi Variance (Variance of negative returns) + 'FLPM' : First Lower Partial Moment + 'SLPM' : Second Lower Partial Moment + 'CVaR' : Conditional Value at Risk + 'EVaR' : Entropic Value at Risk + 'WR' : Worst Realization + 'ADD' : Average Drawdown of uncompounded returns + 'UCI' : Ulcer Index of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded returns + 'EDaR' : Entropic Drawdown at Risk of uncompounded returns + 'MDD' : Maximum Drawdown of uncompounded returns + """, + choices=self.MEAN_RISK_CHOICES, + ) + parser.add_argument( + "-r", + "--risk-free-rate", + type=float, + dest="risk_free", + default=self.params["risk_free"] + if "risk_free" in self.params + else get_rf(), + help="""Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual""", + ) + parser.add_argument( + "-a", + "--alpha", + type=float, + default=self.params["significance_level"] + if "significance_level" in self.params + else 0.05, + dest="significance_level", + help="Significance level of CVaR, EVaR, CDaR and EDaR", + ) + parser.add_argument( + "-tr", + "--target-return", + dest="target_return", + default=self.params["target_return"] + if "target_return" in self.params + else -1, + help="Constraint on minimum level of portfolio's return", + ) + parser.add_argument( + "-tk", + "--target-risk", + dest="target_risk", + default=self.params["target_risk"] if "target_risk" in self.params else -1, + help="Constraint on maximum level of portfolio's risk", + ) + parser.add_argument( + "-m", + "--mean", + default=self.params["expected_return"] + if "expected_return" in self.params + else "hist", + dest="expected_return", + help="Method used to estimate expected returns vector", + choices=self.MEAN_CHOICES, + ) + parser.add_argument( + "-cv", + "--covariance", + default=self.params["covariance"] if "mean_ewma" in self.params else "hist", + dest="covariance", + help="""Method used to estimate covariance matrix. Possible values are + 'hist': historical method + 'ewma1': exponential weighted moving average with adjust=True + 'ewma2': exponential weighted moving average with adjust=False + 'ledoit': Ledoit and Wolf shrinkage method + 'oas': oracle shrinkage method + 'shrunk': scikit-learn shrunk method + 'gl': graphical lasso method + 'jlogo': j-logo covariance + 'fixed': takes average of eigenvalues above max Marchenko Pastour limit + 'spectral': makes zero eigenvalues above max Marchenko Pastour limit + 'shrink': Lopez de Prado's book shrinkage method + """, + choices=self.COVARIANCE_CHOICES, + ) + parser.add_argument( + "-de", + "--d-ewma", + type=float, + default=self.params["smoothing_factor_ewma"] + if "smoothing_factor_ewma" in self.params + else 0.94, + dest="smoothing_factor_ewma", + help="Smoothing factor for ewma estimators", + ) + parser.add_argument( + "-v", + "--value", + type=float, + default=self.params["long_allocation"] + if "long_allocation" in self.params + else 1, + dest="long_allocation", + help="Amount to allocate to portfolio in long positions", + ) + parser.add_argument( + "-vs", + "--value-short", + type=float, + default=self.params["short_allocation"] + if "short_allocation" in self.params + else 0.0, + dest="short_allocation", + help="Amount to allocate to portfolio in short positions", + ) + parser.add_argument( + "--name", + type=str, + dest="name", + default="MINRISK_" + str(self.count), + help="Save portfolio with personalized or default name", + ) + subparsers = parser.add_subparsers( + title="sensitivity analysis command", help="sensitivity analysis" + ) + parser_update = subparsers.add_parser("sa", help="sensitivity analysis command") + + parser_dict = vars(parser) + for i in parser_dict["_actions"]: + data_dict = vars(i) + variables = list(data_dict.keys()) + if variables[0] == "option_strings" and data_dict["dest"] != "name": + if len(data_dict["option_strings"]) == 1: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + elif len(data_dict["option_strings"]) == 2: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + data_dict["option_strings"][1] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + + parser.add_argument( + "-ct", + "--categories", + dest="categories", + type=lambda s: [str(item).upper() for item in s.split(",")], + default=[], + help="Show selected categories", + ) + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + if len(self.tickers) < 2: + console.print( + "Please have at least 2 loaded tickers to calculate weights.\n" + ) + return + + table = True + if "historic_period_sa" in vars(ns_parser): + table = False + + weights = optimizer_view.display_min_risk( + stocks=self.tickers, + period=ns_parser.historic_period, + start=ns_parser.start_period, + end=ns_parser.end_period, + log_returns=ns_parser.log_returns, + freq=ns_parser.return_frequency, + maxnan=ns_parser.max_nan, + threshold=ns_parser.threshold_value, + method=ns_parser.nan_fill_method, + risk_measure=ns_parser.risk_measure.lower(), + risk_free_rate=ns_parser.risk_free, + alpha=ns_parser.significance_level, + target_return=ns_parser.target_return, + target_risk=ns_parser.target_risk, + mean=ns_parser.expected_return.lower(), + covariance=ns_parser.covariance.lower(), + d_ewma=ns_parser.smoothing_factor_ewma, + value=ns_parser.long_allocation, + value_short=ns_parser.short_allocation, + table=table, + ) + + self.portfolios[ns_parser.name.upper()] = weights + self.count += 1 + self.update_runtime_choices() + + if table is False: + weights_sa = optimizer_view.display_min_risk( + stocks=self.tickers, + period=ns_parser.historic_period_sa, + start=ns_parser.start_period_sa, + end=ns_parser.end_period_sa, + log_returns=ns_parser.log_returns_sa, + freq=ns_parser.return_frequency_sa, + maxnan=ns_parser.max_nan_sa, + threshold=ns_parser.threshold_value_sa, + method=ns_parser.nan_fill_method_sa, + risk_measure=ns_parser.risk_measure_sa.lower(), + risk_free_rate=ns_parser.risk_free_sa, + alpha=ns_parser.significance_level_sa, + target_return=ns_parser.target_return_sa, + target_risk=ns_parser.target_risk_sa, + mean=ns_parser.expected_return_sa.lower(), + covariance=ns_parser.covariance_sa.lower(), + d_ewma=ns_parser.smoothing_factor_ewma_sa, + value=ns_parser.long_allocation_sa, + value_short=ns_parser.short_allocation_sa, + table=table, + ) + + console.print("") + optimizer_view.display_weights_sa( + weights=weights, weights_sa=weights_sa + ) + + if not ns_parser.categories: + categories = ["ASSET_CLASS", "COUNTRY", "SECTOR", "INDUSTRY"] + else: + categories = ns_parser.categories + + for category in categories: + optimizer_view.display_categories_sa( + weights=weights, + weights_sa=weights_sa, + categories=self.categories, + column=category, + title="Category - " + category.title(), + ) + + @log_start_end(log=logger) + def call_maxutil(self, other_args: List[str]): + """Process maxutil command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="maxutil", + description="Maximizes a risk averse utility function", + ) + parser.add_argument( + "-p", + "--period", + default=self.params["historic_period"] + if "historic_period" in self.params + else "3y", + dest="historic_period", + help="""Period to get yfinance data from. + Possible frequency strings are: + 'd': means days, for example '252d' means 252 days + 'w': means weeks, for example '52w' means 52 weeks + 'mo': means months, for example '12mo' means 12 months + 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset""", + ) + parser.add_argument( + "-s", + "--start", + default=self.params["start_period"] + if "start_period" in self.params + else "", + dest="start_period", + help="""Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-e", + "--end", + default=self.params["end_period"] if "end_period" in self.params else "", + dest="end_period", + help="""End date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-lr", + "--log-returns", + action="store_true", + default=self.params["log_returns"] + if "log_returns" in self.params + else False, + dest="log_returns", + help="If use logarithmic or arithmetic returns to calculate returns", + ) + parser.add_argument( + "-f", + "--freq", + default=self.params["return_frequency"] + if "return_frequency" in self.params + else "d", + dest="return_frequency", + help="""Frequency used to calculate returns. Possible values are: + 'd': for daily returns + 'w': for weekly returns + 'm': for monthly returns + """, + choices=self.FREQ_CHOICES, + ) + parser.add_argument( + "-mn", + "--maxnan", + type=float, + default=self.params["max_nan"] if "max_nan" in self.params else 0.05, + dest="max_nan", + help="""Max percentage of nan values accepted per asset to be + considered in the optimization process""", + ) + parser.add_argument( + "-th", + "--threshold", + type=float, + default=self.params["threshold_value"] + if "threshold_value" in self.params + else 0.30, + dest="threshold_value", + help="""Value used to replace outliers that are higher to threshold + in absolute value""", + ) + parser.add_argument( + "-mt", + "--method", + default=self.params["nan_fill_method"] + if "nan_fill_method" in self.params + else "time", + dest="nan_fill_method", + help="""Method used to fill nan values in time series, by default time. + Possible values are: + 'linear': linear interpolation + 'time': linear interpolation based on time index + 'nearest': use nearest value to replace nan values + 'zero': spline of zeroth order + 'slinear': spline of first order + 'quadratic': spline of second order + 'cubic': spline of third order + 'barycentric': builds a polynomial that pass for all points""", + ) + parser.add_argument( + "-rm", + "--risk-measure", + default=self.params["risk_measure"] + if "risk_measure" in self.params + else "MV", + dest="risk_measure", + help="""Risk measure used to optimize the portfolio. Possible values are: + 'MV' : Variance + 'MAD' : Mean Absolute Deviation + 'MSV' : Semi Variance (Variance of negative returns) + 'FLPM' : First Lower Partial Moment + 'SLPM' : Second Lower Partial Moment + 'CVaR' : Conditional Value at Risk + 'EVaR' : Entropic Value at Risk + 'WR' : Worst Realization + 'ADD' : Average Drawdown of uncompounded returns + 'UCI' : Ulcer Index of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded returns + 'EDaR' : Entropic Drawdown at Risk of uncompounded returns + 'MDD' : Maximum Drawdown of uncompounded returns + """, + choices=self.MEAN_RISK_CHOICES, + ) + parser.add_argument( + "-r", + "--risk-free-rate", + type=float, + dest="risk_free", + default=self.params["risk_free"] + if "risk_free" in self.params + else get_rf(), + help="""Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual""", + ) + parser.add_argument( + "-ra", + "--risk-aversion", + type=float, + dest="risk_aversion", + default=self.params["long_allocation"] + if "long_allocation" in self.params + else 1, + help="Risk aversion parameter", + ) + parser.add_argument( + "-a", + "--alpha", + type=float, + default=self.params["significance_level"] + if "significance_level" in self.params + else 0.05, + dest="significance_level", + help="Significance level of CVaR, EVaR, CDaR and EDaR", + ) + parser.add_argument( + "-tr", + "--target-return", + dest="target_return", + default=self.params["target_return"] + if "target_return" in self.params + else -1, + help="Constraint on minimum level of portfolio's return", + ) + parser.add_argument( + "-tk", + "--target-risk", + dest="target_risk", + default=self.params["target_risk"] if "target_risk" in self.params else -1, + help="Constraint on maximum level of portfolio's risk", + ) + parser.add_argument( + "-m", + "--mean", + default=self.params["expected_return"] + if "expected_return" in self.params + else "hist", + dest="expected_return", + help="Method used to estimate the expected return vector", + choices=self.MEAN_CHOICES, + ) + parser.add_argument( + "-cv", + "--covariance", + default=self.params["covariance"] + if "covariance" in self.params + else "hist", + dest="covariance", + help="""Method used to estimate covariance matrix. Possible values are + 'hist': historical method + 'ewma1': exponential weighted moving average with adjust=True + 'ewma2': exponential weighted moving average with adjust=False + 'ledoit': Ledoit and Wolf shrinkage method + 'oas': oracle shrinkage method + 'shrunk': scikit-learn shrunk method + 'gl': graphical lasso method + 'jlogo': j-logo covariance + 'fixed': takes average of eigenvalues above max Marchenko Pastour limit + 'spectral': makes zero eigenvalues above max Marchenko Pastour limit + 'shrink': Lopez de Prado's book shrinkage method + """, + choices=self.COVARIANCE_CHOICES, + ) + parser.add_argument( + "-de", + "--d-ewma", + type=float, + default=self.params["smoothing_factor_ewma"] + if "smoothing_factor_ewma" in self.params + else 0.94, + dest="smoothing_factor_ewma", + help="Smoothing factor for ewma estimators", + ) + parser.add_argument( + "-v", + "--value", + dest="long_allocation", + help="Amount to allocate to portfolio in long positions", + type=float, + default=self.params["long_allocation"] + if "long_allocation" in self.params + else 1, + ) + parser.add_argument( + "-vs", + "--value-short", + dest="short_allocation", + help="Amount to allocate to portfolio in short positions", + type=float, + default=self.params["short_allocation"] + if "short_allocation" in self.params + else 0.0, + ) + parser.add_argument( + "--name", + type=str, + dest="name", + default="MAXUTIL_" + str(self.count), + help="Save portfolio with personalized or default name", + ) + subparsers = parser.add_subparsers( + title="sensitivity analysis command", help="sensitivity analysis" + ) + parser_update = subparsers.add_parser("sa", help="sensitivity analysis command") + + parser_dict = vars(parser) + for i in parser_dict["_actions"]: + data_dict = vars(i) + variables = list(data_dict.keys()) + if variables[0] == "option_strings" and data_dict["dest"] != "name": + if len(data_dict["option_strings"]) == 1: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + elif len(data_dict["option_strings"]) == 2: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + data_dict["option_strings"][1] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + + parser.add_argument( + "-ct", + "--categories", + dest="categories", + type=lambda s: [str(item).upper() for item in s.split(",")], + default=[], + help="Show selected categories", + ) + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + if len(self.tickers) < 2: + console.print( + "Please have at least 2 loaded tickers to calculate weights.\n" + ) + return + + table = True + if "historic_period_sa" in vars(ns_parser): + table = False + + weights = optimizer_view.display_max_util( + stocks=self.tickers, + period=ns_parser.historic_period, + start=ns_parser.start_period, + end=ns_parser.end_period, + log_returns=ns_parser.log_returns, + freq=ns_parser.return_frequency, + maxnan=ns_parser.max_nan, + threshold=ns_parser.threshold_value, + method=ns_parser.nan_fill_method, + risk_measure=ns_parser.risk_measure.lower(), + risk_free_rate=ns_parser.risk_free, + risk_aversion=ns_parser.risk_aversion, + alpha=ns_parser.significance_level, + target_return=ns_parser.target_return, + target_risk=ns_parser.target_risk, + mean=ns_parser.expected_return.lower(), + covariance=ns_parser.covariance.lower(), + d_ewma=ns_parser.smoothing_factor_ewma, + value=ns_parser.long_allocation, + value_short=ns_parser.short_allocation, + table=table, + ) + + self.portfolios[ns_parser.name.upper()] = weights + self.count += 1 + self.update_runtime_choices() + + if table is False: + weights_sa = optimizer_view.display_max_util( + stocks=self.tickers, + period=ns_parser.historic_period_sa, + start=ns_parser.start_period_sa, + end=ns_parser.end_period_sa, + log_returns=ns_parser.log_returns_sa, + freq=ns_parser.return_frequency_sa, + maxnan=ns_parser.max_nan_sa, + threshold=ns_parser.threshold_value_sa, + method=ns_parser.nan_fill_method_sa, + risk_measure=ns_parser.risk_measure_sa.lower(), + risk_free_rate=ns_parser.risk_free_sa, + risk_aversion=ns_parser.risk_aversion_sa, + alpha=ns_parser.significance_level_sa, + target_return=ns_parser.target_return_sa, + target_risk=ns_parser.target_risk_sa, + mean=ns_parser.expected_return_sa.lower(), + covariance=ns_parser.covariance_sa.lower(), + d_ewma=ns_parser.smoothing_factor_ewma_sa, + value=ns_parser.long_allocation_sa, + value_short=ns_parser.short_allocation_sa, + table=table, + ) + + console.print("") + optimizer_view.display_weights_sa( + weights=weights, weights_sa=weights_sa + ) + + if not ns_parser.categories: + categories = ["ASSET_CLASS", "COUNTRY", "SECTOR", "INDUSTRY"] + else: + categories = ns_parser.categories + + for category in categories: + optimizer_view.display_categories_sa( + weights=weights, + weights_sa=weights_sa, + categories=self.categories, + column=category, + title="Category - " + category.title(), + ) + + @log_start_end(log=logger) + def call_maxret(self, other_args: List[str]): + """Process maxret command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="maxret", + description="Maximizes the portfolio's return ", + ) + parser.add_argument( + "-p", + "--period", + default=self.params["historic_period"] + if "historic_period" in self.params + else "3y", + dest="historic_period", + help="""Period to get yfinance data from. + Possible frequency strings are: + 'd': means days, for example '252d' means 252 days + 'w': means weeks, for example '52w' means 52 weeks + 'mo': means months, for example '12mo' means 12 months + 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset""", + ) + parser.add_argument( + "-s", + "--start", + default=self.params["start_period"] + if "start_period" in self.params + else "", + dest="start_period", + help="""Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-e", + "--end", + default=self.params["end_period"] if "end_period" in self.params else "", + dest="end_period", + help="""End date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-lr", + "--log-returns", + action="store_true", + default=self.params["log_returns"] + if "log_returns" in self.params + else False, + dest="log_returns", + help="If use logarithmic or arithmetic returns to calculate returns", + ) + parser.add_argument( + "-f", + "--freq", + default=self.params["return_frequency"] + if "return_frequency" in self.params + else "d", + dest="return_frequency", + help="""Frequency used to calculate returns. Possible values are: + 'd': for daily returns + 'w': for weekly returns + 'm': for monthly returns + """, + choices=self.FREQ_CHOICES, + ) + parser.add_argument( + "-mn", + "--maxnan", + type=float, + default=self.params["max_nan"] if "max_nan" in self.params else 0.05, + dest="max_nan", + help="""Max percentage of nan values accepted per asset to be + considered in the optimization process""", + ) + parser.add_argument( + "-th", + "--threshold", + type=float, + default=self.params["threshold_value"] + if "threshold_value" in self.params + else 0.30, + dest="threshold_value", + help="""Value used to replace outliers that are higher to threshold + in absolute value""", + ) + parser.add_argument( + "-mt", + "--method", + default=self.params["nan_fill_method"] + if "nan_fill_method" in self.params + else "time", + dest="nan_fill_method", + help="""Method used to fill nan values in time series, by default time. + Possible values are: + 'linear': linear interpolation + 'time': linear interpolation based on time index + 'nearest': use nearest value to replace nan values + 'zero': spline of zeroth order + 'slinear': spline of first order + 'quadratic': spline of second order + 'cubic': spline of third order + 'barycentric': builds a polynomial that pass for all points""", + ) + parser.add_argument( + "-rm", + "--risk-measure", + default=self.params["risk_measure"] + if "risk_measure" in self.params + else "MV", + dest="risk_measure", + help="""Risk measure used to optimize the portfolio. Possible values are: + 'MV' : Variance + 'MAD' : Mean Absolute Deviation + 'MSV' : Semi Variance (Variance of negative returns) + 'FLPM' : First Lower Partial Moment + 'SLPM' : Second Lower Partial Moment + 'CVaR' : Conditional Value at Risk + 'EVaR' : Entropic Value at Risk + 'WR' : Worst Realization + 'ADD' : Average Drawdown of uncompounded returns + 'UCI' : Ulcer Index of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded returns + 'EDaR' : Entropic Drawdown at Risk of uncompounded returns + 'MDD' : Maximum Drawdown of uncompounded returns + """, + choices=self.MEAN_RISK_CHOICES, + ) + parser.add_argument( + "-r", + "--risk-free-rate", + type=float, + dest="risk_free", + default=self.params["risk_free"] + if "risk_free" in self.params + else get_rf(), + help="""Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual""", + ) + parser.add_argument( + "-a", + "--alpha", + type=float, + default=self.params["significance_level"] + if "significance_level" in self.params + else 0.05, + dest="significance_level", + help="Significance level of CVaR, EVaR, CDaR and EDaR", + ) + parser.add_argument( + "-tr", + "--target-return", + dest="target_return", + default=self.params["target_return"] + if "target_return" in self.params + else -1, + help="Constraint on minimum level of portfolio's return", + ) + parser.add_argument( + "-tk", + "--target-risk", + dest="target_risk", + default=self.params["target_risk"] if "target_risk" in self.params else -1, + help="Constraint on maximum level of portfolio's risk", + ) + parser.add_argument( + "-m", + "--mean", + default=self.params["expected_return"] + if "expected_return" in self.params + else "hist", + dest="expected_return", + help="Method used to estimate the expected return vector", + choices=self.MEAN_CHOICES, + ) + parser.add_argument( + "-cv", + "--covariance", + default=self.params["covariance"] + if "covariance" in self.params + else "hist", + dest="covariance", + help="""Method used to estimate covariance matrix. Possible values are + 'hist': historical method + 'ewma1': exponential weighted moving average with adjust=True + 'ewma2': exponential weighted moving average with adjust=False + 'ledoit': Ledoit and Wolf shrinkage method + 'oas': oracle shrinkage method + 'shrunk': scikit-learn shrunk method + 'gl': graphical lasso method + 'jlogo': j-logo covariance + 'fixed': takes average of eigenvalues above max Marchenko Pastour limit + 'spectral': makes zero eigenvalues above max Marchenko Pastour limit + 'shrink': Lopez de Prado's book shrinkage method + """, + choices=self.COVARIANCE_CHOICES, + ) + parser.add_argument( + "-de", + "--d-ewma", + type=float, + default=self.params["smoothing_factor_ewma"] + if "smoothing_factor_ewma" in self.params + else 0.94, + dest="smoothing_factor_ewma", + help="Smoothing factor for ewma estimators", + ) + parser.add_argument( + "-v", + "--value", + dest="long_allocation", + help="Amount to allocate to portfolio in long positions", + type=float, + default=self.params["long_allocation"] + if "long_allocation" in self.params + else 1, + ) + parser.add_argument( + "-vs", + "--value-short", + dest="short_allocation", + help="Amount to allocate to portfolio in short positions", + type=float, + default=self.params["short_allocation"] + if "short_allocation" in self.params + else 0.0, + ) + parser.add_argument( + "--name", + type=str, + dest="name", + default="MAXRET_" + str(self.count), + help="Save portfolio with personalized or default name", + ) + subparsers = parser.add_subparsers( + title="sensitivity analysis command", help="sensitivity analysis" + ) + parser_update = subparsers.add_parser("sa", help="sensitivity analysis command") + + parser_dict = vars(parser) + for i in parser_dict["_actions"]: + data_dict = vars(i) + variables = list(data_dict.keys()) + if variables[0] == "option_strings" and data_dict["dest"] != "name": + if len(data_dict["option_strings"]) == 1: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + elif len(data_dict["option_strings"]) == 2: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + data_dict["option_strings"][1] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + + parser.add_argument( + "-ct", + "--categories", + dest="categories", + type=lambda s: [str(item).upper() for item in s.split(",")], + default=[], + help="Show selected categories", + ) + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + if len(self.tickers) < 2: + console.print( + "Please have at least 2 loaded tickers to calculate weights.\n" + ) + return + + table = True + if "historic_period_sa" in vars(ns_parser): + table = False + + weights = optimizer_view.display_max_ret( + stocks=self.tickers, + period=ns_parser.historic_period, + start=ns_parser.start_period, + end=ns_parser.end_period, + log_returns=ns_parser.log_returns, + freq=ns_parser.return_frequency, + maxnan=ns_parser.max_nan, + threshold=ns_parser.threshold_value, + method=ns_parser.nan_fill_method, + risk_measure=ns_parser.risk_measure.lower(), + risk_free_rate=ns_parser.risk_free, + alpha=ns_parser.significance_level, + target_return=ns_parser.target_return, + target_risk=ns_parser.target_risk, + mean=ns_parser.expected_return.lower(), + covariance=ns_parser.covariance.lower(), + d_ewma=ns_parser.smoothing_factor_ewma, + value=ns_parser.long_allocation, + value_short=ns_parser.short_allocation, + table=table, + ) + + self.portfolios[ns_parser.name.upper()] = weights + self.count += 1 + self.update_runtime_choices() + + if table is False: + weights_sa = optimizer_view.display_max_ret( + stocks=self.tickers, + period=ns_parser.historic_period_sa, + start=ns_parser.start_period_sa, + end=ns_parser.end_period_sa, + log_returns=ns_parser.log_returns_sa, + freq=ns_parser.return_frequency_sa, + maxnan=ns_parser.max_nan_sa, + threshold=ns_parser.threshold_value_sa, + method=ns_parser.nan_fill_method_sa, + risk_measure=ns_parser.risk_measure_sa.lower(), + risk_free_rate=ns_parser.risk_free_sa, + alpha=ns_parser.significance_level_sa, + target_return=ns_parser.target_return_sa, + target_risk=ns_parser.target_risk_sa, + mean=ns_parser.expected_return_sa.lower(), + covariance=ns_parser.covariance_sa.lower(), + d_ewma=ns_parser.smoothing_factor_ewma_sa, + value=ns_parser.long_allocation_sa, + value_short=ns_parser.short_allocation_sa, + table=table, + ) + + console.print("") + optimizer_view.display_weights_sa( + weights=weights, weights_sa=weights_sa + ) + + if not ns_parser.categories: + categories = ["ASSET_CLASS", "COUNTRY", "SECTOR", "INDUSTRY"] + else: + categories = ns_parser.categories + + for category in categories: + optimizer_view.display_categories_sa( + weights=weights, + weights_sa=weights_sa, + categories=self.categories, + column=category, + title="Category - " + category.title(), + ) + + @log_start_end(log=logger) + def call_maxdiv(self, other_args: List[str]): + """Process maxdiv command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="maxdiv", + description="Maximizes the portfolio's diversification ratio", + ) + parser.add_argument( + "-p", + "--period", + default=self.params["historic_period"] + if "historic_period" in self.params + else "3y", + dest="historic_period", + help="""Period to get yfinance data from. + Possible frequency strings are: + 'd': means days, for example '252d' means 252 days + 'w': means weeks, for example '52w' means 52 weeks + 'mo': means months, for example '12mo' means 12 months + 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset""", + ) + parser.add_argument( + "-s", + "--start", + default=self.params["start_period"] + if "start_period" in self.params + else "", + dest="start_period", + help="""Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-e", + "--end", + default=self.params["end_period"] if "end_period" in self.params else "", + dest="end_period", + help="""End date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-lr", + "--log-returns", + action="store_true", + default=self.params["log_returns"] + if "log_returns" in self.params + else False, + dest="log_returns", + help="If use logarithmic or arithmetic returns to calculate returns", + ) + parser.add_argument( + "-f", + "--freq", + default=self.params["return_frequency"] + if "return_frequency" in self.params + else "d", + dest="return_frequency", + help="""Frequency used to calculate returns. Possible values are: + 'd': for daily returns + 'w': for weekly returns + 'm': for monthly returns + """, + choices=self.FREQ_CHOICES, + ) + parser.add_argument( + "-mn", + "--maxnan", + type=float, + default=self.params["max_nan"] if "max_nan" in self.params else 0.05, + dest="max_nan", + help="""Max percentage of nan values accepted per asset to be + considered in the optimization process""", + ) + parser.add_argument( + "-th", + "--threshold", + type=float, + default=self.params["threshold_value"] + if "threshold_value" in self.params + else 0.30, + dest="threshold_value", + help="""Value used to replace outliers that are higher to threshold + in absolute value""", + ) + parser.add_argument( + "-mt", + "--method", + default=self.params["nan_fill_method"] + if "nan_fill_method" in self.params + else "time", + dest="nan_fill_method", + help="""Method used to fill nan values in time series, by default time. + Possible values are: + 'linear': linear interpolation + 'time': linear interpolation based on time index + 'nearest': use nearest value to replace nan values + 'zero': spline of zeroth order + 'slinear': spline of first order + 'quadratic': spline of second order + 'cubic': spline of third order + 'barycentric': builds a polynomial that pass for all points""", + ) + parser.add_argument( + "-cv", + "--covariance", + default=self.params["covariance"] + if "covariance" in self.params + else "hist", + dest="covariance", + help="""Method used to estimate covariance matrix. Possible values are + 'hist': historical method + 'ewma1': exponential weighted moving average with adjust=True + 'ewma2': exponential weighted moving average with adjust=False + 'ledoit': Ledoit and Wolf shrinkage method + 'oas': oracle shrinkage method + 'shrunk': scikit-learn shrunk method + 'gl': graphical lasso method + 'jlogo': j-logo covariance + 'fixed': takes average of eigenvalues above max Marchenko Pastour limit + 'spectral': makes zero eigenvalues above max Marchenko Pastour limit + 'shrink': Lopez de Prado's book shrinkage method + """, + choices=self.COVARIANCE_CHOICES, + ) + parser.add_argument( + "-de", + "--d-ewma", + type=float, + default=self.params["smoothing_factor_ewma"] + if "smoothing_factor_ewma" in self.params + else 0.94, + dest="smoothing_factor_ewma", + help="Smoothing factor for ewma estimators", + ) + parser.add_argument( + "-v", + "--value", + dest="long_allocation", + help="Amount to allocate to portfolio in long positions", + type=float, + default=self.params["long_allocation"] + if "long_allocation" in self.params + else 1, + ) + parser.add_argument( + "-vs", + "--value-short", + dest="short_allocation", + help="Amount to allocate to portfolio in short positions", + type=float, + default=self.params["short_allocation"] + if "short_allocation" in self.params + else 0.0, + ) + parser.add_argument( + "--name", + type=str, + dest="name", + default="MAXDIV_" + str(self.count), + help="Save portfolio with personalized or default name", + ) + subparsers = parser.add_subparsers( + title="sensitivity analysis command", help="sensitivity analysis" + ) + parser_update = subparsers.add_parser("sa", help="sensitivity analysis command") + + parser_dict = vars(parser) + for i in parser_dict["_actions"]: + data_dict = vars(i) + variables = list(data_dict.keys()) + if variables[0] == "option_strings" and data_dict["dest"] != "name": + if len(data_dict["option_strings"]) == 1: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + elif len(data_dict["option_strings"]) == 2: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + data_dict["option_strings"][1] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + + parser.add_argument( + "-ct", + "--categories", + dest="categories", + type=lambda s: [str(item).upper() for item in s.split(",")], + default=[], + help="Show selected categories", + ) + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + if len(self.tickers) < 2: + console.print( + "Please have at least 2 loaded tickers to calculate weights.\n" + ) + return + + table = True + if "historic_period_sa" in vars(ns_parser): + table = False + + weights = optimizer_view.display_max_div( + stocks=self.tickers, + period=ns_parser.historic_period, + start=ns_parser.start_period, + end=ns_parser.end_period, + log_returns=ns_parser.log_returns, + freq=ns_parser.return_frequency, + maxnan=ns_parser.max_nan, + threshold=ns_parser.threshold_value, + method=ns_parser.nan_fill_method, + covariance=ns_parser.covariance.lower(), + d_ewma=ns_parser.smoothing_factor_ewma, + value=ns_parser.long_allocation, + value_short=ns_parser.short_allocation, + table=table, + ) + + self.portfolios[ns_parser.name.upper()] = weights + self.count += 1 + self.update_runtime_choices() + + if table is False: + weights_sa = optimizer_view.display_max_div( + stocks=self.tickers, + period=ns_parser.historic_period_sa, + start=ns_parser.start_period_sa, + end=ns_parser.end_period_sa, + log_returns=ns_parser.log_returns_sa, + freq=ns_parser.return_frequency_sa, + maxnan=ns_parser.max_nan_sa, + threshold=ns_parser.threshold_value_sa, + method=ns_parser.nan_fill_method_sa, + covariance=ns_parser.covariance_sa.lower(), + d_ewma=ns_parser.smoothing_factor_ewma_sa, + value=ns_parser.long_allocation_sa, + value_short=ns_parser.short_allocation_sa, + table=table, + ) + + console.print("") + optimizer_view.display_weights_sa( + weights=weights, weights_sa=weights_sa + ) + + if not ns_parser.categories: + categories = ["ASSET_CLASS", "COUNTRY", "SECTOR", "INDUSTRY"] + else: + categories = ns_parser.categories + + for category in categories: + optimizer_view.display_categories_sa( + weights=weights, + weights_sa=weights_sa, + categories=self.categories, + column=category, + title="Category - " + category.title(), + ) + + @log_start_end(log=logger) + def call_maxdecorr(self, other_args: List[str]): + """Process maxdecorr command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="maxdecorr", + description="Maximizes the portfolio's decorrelation", + ) + parser.add_argument( + "-p", + "--period", + default=self.params["historic_period"] + if "historic_period" in self.params + else "3y", + dest="historic_period", + help="""Period to get yfinance data from. + Possible frequency strings are: + 'd': means days, for example '252d' means 252 days + 'w': means weeks, for example '52w' means 52 weeks + 'mo': means months, for example '12mo' means 12 months + 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset""", + ) + parser.add_argument( + "-s", + "--start", + default=self.params["start_period"] + if "start_period" in self.params + else "", + dest="start_period", + help="""Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-e", + "--end", + default=self.params["end_period"] if "end_period" in self.params else "", + dest="end_period", + help="""End date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-lr", + "--log-returns", + action="store_true", + default=self.params["log_returns"] + if "log_returns" in self.params + else False, + dest="log_returns", + help="If use logarithmic or arithmetic returns to calculate returns", + ) + parser.add_argument( + "-f", + "--freq", + default=self.params["return_frequency"] + if "return_frequency" in self.params + else "d", + dest="return_frequency", + help="""Frequency used to calculate returns. Possible values are: + 'd': for daily returns + 'w': for weekly returns + 'm': for monthly returns + """, + choices=self.FREQ_CHOICES, + ) + parser.add_argument( + "-mn", + "--maxnan", + type=float, + default=self.params["max_nan"] if "max_nan" in self.params else 0.05, + dest="max_nan", + help="""Max percentage of nan values accepted per asset to be + considered in the optimization process""", + ) + parser.add_argument( + "-th", + "--threshold", + type=float, + default=self.params["threshold_value"] + if "threshold_value" in self.params + else 0.30, + dest="threshold_value", + help="""Value used to replace outliers that are higher to threshold + in absolute value""", + ) + parser.add_argument( + "-mt", + "--method", + default=self.params["nan_fill_method"] + if "nan_fill_method" in self.params + else "time", + dest="nan_fill_method", + help="""Method used to fill nan values in time series, by default time. + Possible values are: + 'linear': linear interpolation + 'time': linear interpolation based on time index + 'nearest': use nearest value to replace nan values + 'zero': spline of zeroth order + 'slinear': spline of first order + 'quadratic': spline of second order + 'cubic': spline of third order + 'barycentric': builds a polynomial that pass for all points""", + ) + parser.add_argument( + "-cv", + "--covariance", + default=self.params["covariance"] + if "covariance" in self.params + else "hist", + dest="covariance", + help="""Method used to estimate covariance matrix. Possible values are + 'hist': historical method + 'ewma1': exponential weighted moving average with adjust=True + 'ewma2': exponential weighted moving average with adjust=False + 'ledoit': Ledoit and Wolf shrinkage method + 'oas': oracle shrinkage method + 'shrunk': scikit-learn shrunk method + 'gl': graphical lasso method + 'jlogo': j-logo covariance + 'fixed': takes average of eigenvalues above max Marchenko Pastour limit + 'spectral': makes zero eigenvalues above max Marchenko Pastour limit + 'shrink': Lopez de Prado's book shrinkage method + """, + choices=self.COVARIANCE_CHOICES, + ) + parser.add_argument( + "-de", + "--d-ewma", + type=float, + default=self.params["smoothing_factor_ewma"] + if "smoothing_factor_ewma" in self.params + else 0.94, + dest="smoothing_factor_ewma", + help="Smoothing factor for ewma estimators", + ) + parser.add_argument( + "-v", + "--value", + dest="long_allocation", + help="Amount to allocate to portfolio in long positions", + type=float, + default=self.params["long_allocation"] + if "long_allocation" in self.params + else 1, + ) + parser.add_argument( + "-vs", + "--value-short", + dest="short_allocation", + help="Amount to allocate to portfolio in short positions", + type=float, + default=self.params["short_allocation"] + if "short_allocation" in self.params + else 0.0, + ) + parser.add_argument( + "--name", + type=str, + dest="name", + default="MAXDECORR_" + str(self.count), + help="Save portfolio with personalized or default name", + ) + subparsers = parser.add_subparsers( + title="sensitivity analysis command", help="sensitivity analysis" + ) + parser_update = subparsers.add_parser("sa", help="sensitivity analysis command") + + parser_dict = vars(parser) + for i in parser_dict["_actions"]: + data_dict = vars(i) + variables = list(data_dict.keys()) + if variables[0] == "option_strings" and data_dict["dest"] != "name": + if len(data_dict["option_strings"]) == 1: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + elif len(data_dict["option_strings"]) == 2: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + data_dict["option_strings"][1] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + + parser.add_argument( + "-ct", + "--categories", + dest="categories", + type=lambda s: [str(item).upper() for item in s.split(",")], + default=[], + help="Show selected categories", + ) + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + if len(self.tickers) < 2: + console.print( + "Please have at least 2 loaded tickers to calculate weights.\n" + ) + return + + table = True + if "historic_period_sa" in vars(ns_parser): + table = False + + weights = optimizer_view.display_max_decorr( + stocks=self.tickers, + period=ns_parser.historic_period, + start=ns_parser.start_period, + end=ns_parser.end_period, + log_returns=ns_parser.log_returns, + freq=ns_parser.return_frequency, + maxnan=ns_parser.max_nan, + threshold=ns_parser.threshold_value, + method=ns_parser.nan_fill_method, + covariance=ns_parser.covariance.lower(), + d_ewma=ns_parser.smoothing_factor_ewma, + value=ns_parser.long_allocation, + value_short=ns_parser.short_allocation, + table=table, + ) + + self.portfolios[ns_parser.name.upper()] = weights + self.count += 1 + self.update_runtime_choices() + + if table is False: + weights_sa = optimizer_view.display_max_decorr( + stocks=self.tickers, + period=ns_parser.historic_period_sa, + start=ns_parser.start_period_sa, + end=ns_parser.end_period_sa, + log_returns=ns_parser.log_returns_sa, + freq=ns_parser.return_frequency_sa, + maxnan=ns_parser.max_nan_sa, + threshold=ns_parser.threshold_value_sa, + method=ns_parser.nan_fill_method_sa, + covariance=ns_parser.covariance_sa.lower(), + d_ewma=ns_parser.smoothing_factor_ewma_sa, + value=ns_parser.long_allocation_sa, + value_short=ns_parser.short_allocation_sa, + table=table, + ) + + console.print("") + optimizer_view.display_weights_sa( + weights=weights, weights_sa=weights_sa + ) + + if not ns_parser.categories: + categories = ["ASSET_CLASS", "COUNTRY", "SECTOR", "INDUSTRY"] + else: + categories = ns_parser.categories + + for category in categories: + optimizer_view.display_categories_sa( + weights=weights, + weights_sa=weights_sa, + categories=self.categories, + column=category, + title="Category - " + category.title(), + ) + + @log_start_end(log=logger) + def call_blacklitterman(self, other_args: List[str]): + """Process blacklitterman command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="blacklitterman", + description="Optimize portfolio using Black Litterman estimates", + ) + parser.add_argument( + "-p", + "--period", + default=self.params["historic_period"] + if "historic_period" in self.params + else "3y", + dest="historic_period", + help="""Period to get yfinance data from. + Possible frequency strings are: + 'd': means days, for example '252d' means 252 days + 'w': means weeks, for example '52w' means 52 weeks + 'mo': means months, for example '12mo' means 12 months + 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset""", + ) + parser.add_argument( + "-s", + "--start", + default=self.params["start_period"] + if "start_period" in self.params + else "", + dest="start_period", + help="""Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-e", + "--end", + default=self.params["end_period"] if "end_period" in self.params else "", + dest="end_period", + help="""End date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-lr", + "--log-returns", + action="store_true", + default=self.params["log_returns"] + if "log_returns" in self.params + else False, + dest="log_returns", + help="If use logarithmic or arithmetic returns to calculate returns", + ) + parser.add_argument( + "-f", + "--freq", + default=self.params["return_frequency"] + if "return_frequency" in self.params + else "d", + dest="return_frequency", + help="""Frequency used to calculate returns. Possible values are: + 'd': for daily returns + 'w': for weekly returns + 'm': for monthly returns + """, + choices=self.FREQ_CHOICES, + ) + parser.add_argument( + "-mn", + "--maxnan", + type=float, + default=self.params["max_nan"] if "max_nan" in self.params else 0.05, + dest="max_nan", + help="""Max percentage of nan values accepted per asset to be + considered in the optimization process""", + ) + parser.add_argument( + "-th", + "--threshold", + type=float, + default=self.params["threshold_value"] + if "threshold_value" in self.params + else 0.30, + dest="threshold_value", + help="""Value used to replace outliers that are higher to threshold + in absolute value""", + ) + parser.add_argument( + "-mt", + "--method", + default=self.params["nan_fill_method"] + if "nan_fill_method" in self.params + else "time", + dest="nan_fill_method", + help="""Method used to fill nan values in time series, by default time. + Possible values are: + 'linear': linear interpolation + 'time': linear interpolation based on time index + 'nearest': use nearest value to replace nan values + 'zero': spline of zeroth order + 'slinear': spline of first order + 'quadratic': spline of second order + 'cubic': spline of third order + 'barycentric': builds a polynomial that pass for all points""", + ) + parser.add_argument( + "-bm", + "--benchmark", + type=str, + default=None, + dest="benchmark", + help="portfolio name from current portfolio list", + ) + parser.add_argument( + "-o", + "--objective", + default=self.params["objective"] + if "objective" in self.params + else "Sharpe", + dest="objective", + help="Objective function used to optimize the portfolio", + choices=self.OBJECTIVE_CHOICES, + ) + parser.add_argument( + "-pv", + "--p-views", + type=lambda s: [ + [float(item) for item in row.split(",")] for row in s.split(";") + ], + default=self.params["p_views"] if "p_views" in self.params else None, + dest="p_views", + help="matrix P of analyst views", + ) + parser.add_argument( + "-qv", + "--q-views", + type=lambda s: [float(item) for item in s.split(",")], + default=self.params["q_views"] if "q_views" in self.params else None, + dest="q_views", + help="matrix Q of analyst views", + ) + parser.add_argument( + "-r", + "--risk-free-rate", + type=float, + dest="risk_free", + default=self.params["risk_free"] + if "risk_free" in self.params + else get_rf(), + help="""Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual""", + ) + parser.add_argument( + "-ra", + "--risk-aversion", + type=float, + dest="risk_aversion", + default=self.params["long_allocation"] + if "long_allocation" in self.params + else 1, + help="Risk aversion parameter", + ) + parser.add_argument( + "-d", + "--delta", + default=self.params["delta"] if "delta" in self.params else None, + dest="delta", + help="Risk aversion factor of Black Litterman model", + ) + parser.add_argument( + "-eq", + "--equilibrium", + action="store_true", + default=self.params["equilibrium"] + if "equilibrium" in self.params + else True, + dest="equilibrium", + help="""If True excess returns are based on equilibrium market portfolio, if False + excess returns are calculated as historical returns minus risk free rate. + """, + ) + parser.add_argument( + "-op", + "--optimize", + action="store_false", + default=self.params["optimize"] if "optimize" in self.params else True, + dest="optimize", + help="""If True Black Litterman estimates are used as inputs of mean variance model, + if False returns equilibrium weights from Black Litterman model + """, + ) + parser.add_argument( + "-v", + "--value", + type=float, + default=self.params["long_allocation"] + if "long_allocation" in self.params + else 1, + dest="long_allocation", + help="Amount to allocate to portfolio in long positions", + ) + parser.add_argument( + "-vs", + "--value-short", + type=float, + default=self.params["short_allocation"] + if "short_allocation" in self.params + else 0.0, + dest="short_allocation", + help="Amount to allocate to portfolio in short positions", + ) + parser.add_argument( + "--name", + type=str, + dest="name", + default="BL_" + str(self.count), + help="Save portfolio with personalized or default name", + ) + parser.add_argument( + "--file", + type=lambda s: s if s.endswith(".xlsx") or len(s) == 0 else s + ".xlsx", + dest="file", + default="", + help="Upload an Excel file with views for Black Litterman model", + ) + subparsers = parser.add_subparsers( + title="sensitivity analysis command", help="sensitivity analysis" + ) + parser_update = subparsers.add_parser("sa", help="sensitivity analysis command") + + parser_dict = vars(parser) + for i in parser_dict["_actions"]: + data_dict = vars(i) + variables = list(data_dict.keys()) + if variables[0] == "option_strings" and data_dict["dest"] not in [ + "name", + "benchmark", + ]: + if len(data_dict["option_strings"]) == 1: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + elif len(data_dict["option_strings"]) == 2: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + data_dict["option_strings"][1] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + + parser.add_argument( + "-ct", + "--categories", + dest="categories", + type=lambda s: [str(item).upper() for item in s.split(",")], + default=[], + help="Show selected categories", + ) + parser.add_argument( + "--download", + type=lambda s: s if s.endswith(".xlsx") or len(s) == 0 else s + ".xlsx", + dest="download", + default="", + help="Create a template to design Black Litterman model views", + ) + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + if len(self.tickers) < 2: + console.print( + "Please have at least 2 loaded tickers to calculate weights.\n" + ) + return + + if len(ns_parser.download) > 0: + file = os.path.abspath( + os.path.join( + self.DEFAULT_ALLOCATION_PATH, "..", "views", ns_parser.download + ) + ) + excel_model.excel_bl_views(file=file, stocks=self.tickers, n=1) + return + + if ns_parser.file: + excel_file = os.path.abspath( + os.path.join( + self.DEFAULT_ALLOCATION_PATH, "..", "views", ns_parser.file + ) + ) + p_views, q_views = excel_model.load_bl_views(excel_file=excel_file) + else: + p_views = ns_parser.p_views + q_views = ns_parser.q_views + + if ns_parser.benchmark is None: + benchmark = None + else: + benchmark = self.portfolios[ns_parser.benchmark.upper()] + + table = True + if "historic_period_sa" in vars(ns_parser): + table = False + + weights = optimizer_view.display_black_litterman( + stocks=self.tickers, + p_views=p_views, + q_views=q_views, + period=ns_parser.historic_period, + start=ns_parser.start_period, + end=ns_parser.end_period, + log_returns=ns_parser.log_returns, + freq=ns_parser.return_frequency, + maxnan=ns_parser.max_nan, + threshold=ns_parser.threshold_value, + method=ns_parser.nan_fill_method, + benchmark=benchmark, + objective=ns_parser.objective.lower(), + risk_free_rate=ns_parser.risk_free, + risk_aversion=ns_parser.risk_aversion, + delta=ns_parser.delta, + equilibrium=ns_parser.equilibrium, + optimize=ns_parser.optimize, + value=ns_parser.long_allocation, + value_short=ns_parser.short_allocation, + table=table, + ) + + self.portfolios[ns_parser.name.upper()] = weights + self.count += 1 + self.update_runtime_choices() + + if table is False: + if ns_parser.file_sa: + excel_file = os.path.abspath( + os.path.join( + self.DEFAULT_ALLOCATION_PATH, + "..", + "views", + ns_parser.file_sa, + ) + ) + p_views_sa, q_views_sa = excel_model.load_bl_views( + excel_file=excel_file + ) + else: + p_views_sa = ns_parser.p_views_sa + q_views_sa = ns_parser.q_views_sa + + weights_sa = optimizer_view.display_black_litterman( + stocks=self.tickers, + p_views=p_views_sa, + q_views=q_views_sa, + period=ns_parser.historic_period_sa, + start=ns_parser.start_period_sa, + end=ns_parser.end_period_sa, + log_returns=ns_parser.log_returns_sa, + freq=ns_parser.return_frequency_sa, + maxnan=ns_parser.max_nan_sa, + threshold=ns_parser.threshold_value_sa, + method=ns_parser.nan_fill_method_sa, + benchmark=benchmark, + objective=ns_parser.objective_sa.lower(), + risk_free_rate=ns_parser.risk_free_sa, + risk_aversion=ns_parser.risk_aversion_sa, + delta=ns_parser.delta_sa, + equilibrium=ns_parser.equilibrium_sa, + optimize=ns_parser.optimize_sa, + value=ns_parser.long_allocation_sa, + value_short=ns_parser.short_allocation_sa, + table=table, + ) + + console.print("") + optimizer_view.display_weights_sa( + weights=weights, weights_sa=weights_sa + ) + + if not ns_parser.categories: + categories = ["ASSET_CLASS", "COUNTRY", "SECTOR", "INDUSTRY"] + else: + categories = ns_parser.categories + + for category in categories: + optimizer_view.display_categories_sa( + weights=weights, + weights_sa=weights_sa, + categories=self.categories, + column=category, + title="Category - " + category.title(), + ) + + @log_start_end(log=logger) + def call_ef(self, other_args): + """Process ef command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="ef", + description="""This function plots random portfolios based on their + risk and returns and shows the efficient frontier.""", + ) + parser.add_argument( + "-p", + "--period", + default=self.params["historic_period"] + if "historic_period" in self.params + else "3y", + dest="historic_period", + help="""Period to get yfinance data from. + Possible frequency strings are: + 'd': means days, for example '252d' means 252 days + 'w': means weeks, for example '52w' means 52 weeks + 'mo': means months, for example '12mo' means 12 months + 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset""", + ) + parser.add_argument( + "-s", + "--start", + default=self.params["start_period"] + if "start_period" in self.params + else "", + dest="start_period", + help="""Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-e", + "--end", + default=self.params["end_period"] if "end_period" in self.params else "", + dest="end_period", + help="""End date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-lr", + "--log-returns", + action="store_true", + default=self.params["log_returns"] + if "log_returns" in self.params + else False, + dest="log_returns", + help="If use logarithmic or arithmetic returns to calculate returns", + ) + parser.add_argument( + "-f", + "--freq", + default=self.params["return_frequency"] + if "return_frequency" in self.params + else "d", + dest="return_frequency", + help="""Frequency used to calculate returns. Possible values are: + 'd': for daily returns + 'w': for weekly returns + 'm': for monthly returns + """, + choices=self.FREQ_CHOICES, + ) + parser.add_argument( + "-mn", + "--maxnan", + type=float, + default=self.params["max_nan"] if "max_nan" in self.params else 0.05, + dest="max_nan", + help="""Max percentage of nan values accepted per asset to be + considered in the optimization process""", + ) + parser.add_argument( + "-th", + "--threshold", + type=float, + default=self.params["threshold_value"] + if "threshold_value" in self.params + else 0.30, + dest="threshold_value", + help="""Value used to replace outliers that are higher to threshold + in absolute value""", + ) + parser.add_argument( + "-mt", + "--method", + default=self.params["nan_fill_method"] + if "nan_fill_method" in self.params + else "time", + dest="nan_fill_method", + help="""Method used to fill nan values in time series, by default time. + Possible values are: + 'linear': linear interpolation + 'time': linear interpolation based on time index + 'nearest': use nearest value to replace nan values + 'zero': spline of zeroth order + 'slinear': spline of first order + 'quadratic': spline of second order + 'cubic': spline of third order + 'barycentric': builds a polynomial that pass for all points""", + ) + parser.add_argument( + "-rm", + "--risk-measure", + default=self.params["risk_measure"] + if "risk_measure" in self.params + else "MV", + dest="risk_measure", + help="""Risk measure used to optimize the portfolio. Possible values are: + 'MV' : Variance + 'MAD' : Mean Absolute Deviation + 'MSV' : Semi Variance (Variance of negative returns) + 'FLPM' : First Lower Partial Moment + 'SLPM' : Second Lower Partial Moment + 'CVaR' : Conditional Value at Risk + 'EVaR' : Entropic Value at Risk + 'WR' : Worst Realization + 'ADD' : Average Drawdown of uncompounded returns + 'UCI' : Ulcer Index of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded returns + 'EDaR' : Entropic Drawdown at Risk of uncompounded returns + 'MDD' : Maximum Drawdown of uncompounded returns + """, + choices=self.MEAN_RISK_CHOICES, + ) + parser.add_argument( + "-r", + "--risk-free-rate", + type=float, + dest="risk_free", + default=self.params["risk_free"] + if "risk_free" in self.params + else get_rf(), + help="""Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual""", + ) + parser.add_argument( + "-a", + "--alpha", + type=float, + default=self.params["significance_level"] + if "significance_level" in self.params + else 0.05, + dest="significance_level", + help="Significance level of CVaR, EVaR, CDaR and EDaR", + ) + parser.add_argument( + "-v", + "--value", + dest="long_allocation", + help="Amount to allocate to portfolio in long positions", + type=float, + default=self.params["long_allocation"] + if "long_allocation" in self.params + else 1, + ) + parser.add_argument( + "-vs", + "--value-short", + dest="short_allocation", + help="Amount to allocate to portfolio in short positions", + type=float, + default=self.params["short_allocation"] + if "short_allocation" in self.params + else 0.0, + ) + if other_args and "-" not in other_args[0][0]: + other_args.insert(0, "-n") + parser.add_argument( + "-n", + "--number-portfolios", + default=self.params["amount_portfolios"] + if "amount_portfolios" in self.params + else 100, + type=check_non_negative, + dest="amount_portfolios", + help="Number of portfolios to simulate", + ) + parser.add_argument( + "-se", + "--seed", + default=self.params["random_seed"] if "random_seed" in self.params else 123, + type=check_non_negative, + dest="random_seed", + help="Seed used to generate random portfolios", + ) + parser.add_argument( + "-t", + "--tangency", + action="store_true", + dest="tangency", + default=self.params["tangency"] if "tangency" in self.params else False, + help="Adds the optimal line with the risk-free asset", + ) + ns_parser = parse_known_args_and_warn(parser, other_args) + + if ns_parser: + if len(self.tickers) < 2: + console.print( + "Please have at least 2 loaded tickers to calculate weights.\n" + ) + return + + optimizer_view.display_ef( + stocks=self.tickers, + period=ns_parser.historic_period, + start=ns_parser.start_period, + end=ns_parser.end_period, + log_returns=ns_parser.log_returns, + freq=ns_parser.return_frequency, + maxnan=ns_parser.max_nan, + threshold=ns_parser.threshold_value, + method=ns_parser.nan_fill_method, + risk_measure=ns_parser.risk_measure.lower(), + risk_free_rate=ns_parser.risk_free, + alpha=ns_parser.significance_level, + value=ns_parser.long_allocation, + value_short=ns_parser.short_allocation, + n_portfolios=ns_parser.amount_portfolios, + seed=ns_parser.random_seed, + tangency=ns_parser.tangency, + ) + + @log_start_end(log=logger) + def call_riskparity(self, other_args: List[str]): + """Process riskparity command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="riskparity", + description="""Build a risk parity portfolio based on risk + budgeting approach""", + ) + parser.add_argument( + "-p", + "--period", + default=self.params["historic_period"] + if "historic_period" in self.params + else "3y", + dest="historic_period", + help="""Period to get yfinance data from. + Possible frequency strings are: + 'd': means days, for example '252d' means 252 days + 'w': means weeks, for example '52w' means 52 weeks + 'mo': means months, for example '12mo' means 12 months + 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset""", + ) + parser.add_argument( + "-s", + "--start", + default=self.params["start_period"] + if "start_period" in self.params + else "", + dest="start_period", + help="""Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-e", + "--end", + default=self.params["end_period"] if "end_period" in self.params else "", + dest="end_period", + help="""End date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-lr", + "--log-returns", + action="store_true", + default=self.params["log_returns"] + if "log_returns" in self.params + else False, + dest="log_returns", + help="If use logarithmic or arithmetic returns to calculate returns", + ) + parser.add_argument( + "-f", + "--freq", + default=self.params["return_frequency"] + if "return_frequency" in self.params + else "d", + dest="return_frequency", + help="""Frequency used to calculate returns. Possible values are: + 'd': for daily returns + 'w': for weekly returns + 'm': for monthly returns + """, + choices=self.FREQ_CHOICES, + ) + parser.add_argument( + "-mn", + "--maxnan", + type=float, + default=self.params["max_nan"] if "max_nan" in self.params else 0.05, + dest="max_nan", + help="""Max percentage of nan values accepted per asset to be + considered in the optimization process. """, + ) + parser.add_argument( + "-th", + "--threshold", + type=float, + default=self.params["threshold_value"] + if "threshold_value" in self.params + else 0.30, + dest="threshold_value", + help="""Value used to replace outliers that are higher to threshold + in absolute value""", + ) + parser.add_argument( + "-mt", + "--method", + default=self.params["nan_fill_method"] + if "nan_fill_method" in self.params + else "time", + dest="nan_fill_method", + help="""Method used to fill nan values in time series, by default time. + Possible values are: + 'linear': linear interpolation + 'time': linear interpolation based on time index + 'nearest': use nearest value to replace nan values + 'zero': spline of zeroth order + 'slinear': spline of first order + 'quadratic': spline of second order + 'cubic': spline of third order + 'barycentric': builds a polynomial that pass for all points""", + ) + parser.add_argument( + "-rm", + "--risk-measure", + default=self.params["risk_measure"] + if "risk_measure" in self.params + else "MV", + dest="risk_measure", + help="""Risk measure used to optimize the portfolio. Possible values are: + 'MV' : Variance + 'MAD' : Mean Absolute Deviation + 'MSV' : Semi Variance (Variance of negative returns) + 'FLPM' : First Lower Partial Moment + 'SLPM' : Second Lower Partial Moment + 'CVaR' : Conditional Value at Risk + 'EVaR' : Entropic Value at Risk + 'UCI' : Ulcer Index of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded returns + 'EDaR' : Entropic Drawdown at Risk of uncompounded returns + """, + choices=self.RISK_PARITY_CHOICES, + ) + parser.add_argument( + "-rc", + "--risk-cont", + type=lambda s: [float(item) for item in s.split(",")], + default=self.params["risk_contribution"] + if "risk_contribution" in self.params + else None, + dest="risk_contribution", + help="vector of risk contribution constraint", + ) + parser.add_argument( + "-r", + "--risk-free-rate", + type=float, + dest="risk_free", + default=self.params["risk_free"] + if "risk_free" in self.params + else get_rf(), + help="""Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual""", + ) + parser.add_argument( + "-a", + "--alpha", + type=float, + default=self.params["significance_level"] + if "significance_level" in self.params + else 0.05, + dest="significance_level", + help="Significance level of CVaR, EVaR, CDaR and EDaR", + ) + parser.add_argument( + "-tr", + "--target-return", + dest="target_return", + default=self.params["target_return"] + if "target_return" in self.params + else -1, + help="Constraint on minimum level of portfolio's return", + ) + parser.add_argument( + "-de", + "--d-ewma", + type=float, + default=self.params["smoothing_factor_ewma"] + if "smoothing_factor_ewma" in self.params + else 0.94, + dest="smoothing_factor_ewma", + help="Smoothing factor for ewma estimators", + ) + parser.add_argument( + "-v", + "--value", + dest="long_allocation", + help="Amount to allocate to portfolio", + type=float, + default=self.params["long_allocation"] + if "long_allocation" in self.params + else 1, + ) + parser.add_argument( + "--name", + type=str, + dest="name", + default="RP_" + str(self.count), + help="Save portfolio with personalized or default name", + ) + subparsers = parser.add_subparsers( + title="sensitivity analysis command", help="sensitivity analysis" + ) + parser_update = subparsers.add_parser("sa", help="sensitivity analysis command") + + parser_dict = vars(parser) + for i in parser_dict["_actions"]: + data_dict = vars(i) + variables = list(data_dict.keys()) + if variables[0] == "option_strings" and data_dict["dest"] != "name": + if len(data_dict["option_strings"]) == 1: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + elif len(data_dict["option_strings"]) == 2: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + data_dict["option_strings"][1] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + + parser.add_argument( + "-ct", + "--categories", + dest="categories", + type=lambda s: [str(item).upper() for item in s.split(",")], + default=[], + help="Show selected categories", + ) + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + if len(self.tickers) < 2: + console.print( + "Please have at least 2 loaded tickers to calculate weights.\n" + ) + return + + table = True + if "historic_period_sa" in vars(ns_parser): + table = False + + weights = optimizer_view.display_risk_parity( + stocks=self.tickers, + period=ns_parser.historic_period, + start=ns_parser.start_period, + end=ns_parser.end_period, + log_returns=ns_parser.log_returns, + freq=ns_parser.return_frequency, + maxnan=ns_parser.max_nan, + threshold=ns_parser.threshold_value, + method=ns_parser.nan_fill_method, + risk_measure=ns_parser.risk_measure.lower(), + risk_cont=ns_parser.risk_contribution, + risk_free_rate=ns_parser.risk_free, + alpha=ns_parser.significance_level, + target_return=ns_parser.target_return, + value=ns_parser.long_allocation, + table=table, + ) + + self.portfolios[ns_parser.name.upper()] = weights + self.count += 1 + self.update_runtime_choices() + + if table is False: + weights_sa = optimizer_view.display_risk_parity( + stocks=self.tickers, + period=ns_parser.historic_period_sa, + start=ns_parser.start_period_sa, + end=ns_parser.end_period_sa, + log_returns=ns_parser.log_returns_sa, + freq=ns_parser.return_frequency_sa, + maxnan=ns_parser.max_nan_sa, + threshold=ns_parser.threshold_value_sa, + method=ns_parser.nan_fill_method_sa, + risk_measure=ns_parser.risk_measure_sa.lower(), + risk_cont=ns_parser.risk_contribution_sa, + risk_free_rate=ns_parser.risk_free_sa, + alpha=ns_parser.significance_level_sa, + target_return=ns_parser.target_return_sa, + value=ns_parser.long_allocation_sa, + table=table, + ) + + console.print("") + optimizer_view.display_weights_sa( + weights=weights, weights_sa=weights_sa + ) + + if not ns_parser.categories: + categories = ["ASSET_CLASS", "COUNTRY", "SECTOR", "INDUSTRY"] + else: + categories = ns_parser.categories + + for category in categories: + optimizer_view.display_categories_sa( + weights=weights, + weights_sa=weights_sa, + categories=self.categories, + column=category, + title="Category - " + category.title(), + ) + + @log_start_end(log=logger) + def call_relriskparity(self, other_args: List[str]): + """Process relriskparity command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="relriskparity", + description="""Build a relaxed risk parity portfolio based on + least squares approach""", + ) + parser.add_argument( + "-p", + "--period", + default=self.params["historic_period"] + if "historic_period" in self.params + else "3y", + dest="historic_period", + help="""Period to get yfinance data from. + Possible frequency strings are: + 'd': means days, for example '252d' means 252 days + 'w': means weeks, for example '52w' means 52 weeks + 'mo': means months, for example '12mo' means 12 months + 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset""", + ) + parser.add_argument( + "-s", + "--start", + default=self.params["start_period"] + if "start_period" in self.params + else "", + dest="start_period", + help="""Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-e", + "--end", + default=self.params["end_period"] if "end_period" in self.params else "", + dest="end_period", + help="""End date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-lr", + "--log-returns", + action="store_true", + default=self.params["log_returns"] + if "log_returns" in self.params + else False, + dest="log_returns", + help="If use logarithmic or arithmetic returns to calculate returns", + ) + parser.add_argument( + "-f", + "--freq", + default=self.params["return_frequency"] + if "return_frequency" in self.params + else "d", + dest="return_frequency", + help="""Frequency used to calculate returns. Possible values are: + 'd': for daily returns + 'w': for weekly returns + 'm': for monthly returns + """, + choices=self.FREQ_CHOICES, + ) + parser.add_argument( + "-mn", + "--maxnan", + type=float, + default=self.params["max_nan"] if "max_nan" in self.params else 0.05, + dest="max_nan", + help="""Max percentage of nan values accepted per asset to be + considered in the optimization process""", + ) + parser.add_argument( + "-th", + "--threshold", + type=float, + default=self.params["threshold_value"] + if "threshold_value" in self.params + else 0.30, + dest="threshold_value", + help="""Value used to replace outliers that are higher to threshold + in absolute value""", + ) + parser.add_argument( + "-mt", + "--method", + default=self.params["nan_fill_method"] + if "nan_fill_method" in self.params + else "time", + dest="nan_fill_method", + help="""Method used to fill nan values in time series, by default time. + Possible values are: + 'linear': linear interpolation + 'time': linear interpolation based on time index + 'nearest': use nearest value to replace nan values + 'zero': spline of zeroth order + 'slinear': spline of first order + 'quadratic': spline of second order + 'cubic': spline of third order + 'barycentric': builds a polynomial that pass for all points""", + ) + parser.add_argument( + "-ve", + "--version", + default=self.params["risk_parity_model"] + if "risk_parity_model" in self.params + else "A", + dest="risk_parity_model", + help="""version of relaxed risk parity model: Possible values are: + 'A': risk parity without regularization and penalization constraints + 'B': with regularization constraint but without penalization constraint + 'C': with regularization and penalization constraints""", + choices=self.REL_RISK_PARITY_CHOICES, + ) + parser.add_argument( + "-rc", + "--risk-cont", + type=lambda s: [float(item) for item in s.split(",")], + default=self.params["risk_contribution"] + if "risk_contribution" in self.params + else None, + dest="risk_contribution", + help="Vector of risk contribution constraints", + ) + parser.add_argument( + "-pf", + "--penal-factor", + type=float, + dest="penal_factor", + default=self.params["penal_factor"] if "penal_factor" in self.params else 1, + help="""The penalization factor of penalization constraints. Only + used with version 'C'.""", + ) + parser.add_argument( + "-tr", + "--target-return", + dest="target_return", + default=self.params["target_return"] + if "target_return" in self.params + else -1, + help="Constraint on minimum level of portfolio's return", + ) + parser.add_argument( + "-de", + "--d-ewma", + type=float, + default=self.params["smoothing_factor_ewma"] + if "smoothing_factor_ewma" in self.params + else 0.94, + dest="smoothing_factor_ewma", + help="Smoothing factor for ewma estimators", + ) + parser.add_argument( + "-v", + "--value", + dest="long_allocation", + help="Amount to allocate to portfolio", + type=float, + default=self.params["long_allocation"] + if "long_allocation" in self.params + else 1, + ) + parser.add_argument( + "--name", + type=str, + dest="name", + default="RRP_" + str(self.count), + help="Save portfolio with personalized or default name", + ) + subparsers = parser.add_subparsers( + title="sensitivity analysis command", help="sensitivity analysis" + ) + parser_update = subparsers.add_parser("sa", help="sensitivity analysis command") + + parser_dict = vars(parser) + for i in parser_dict["_actions"]: + data_dict = vars(i) + variables = list(data_dict.keys()) + if variables[0] == "option_strings" and data_dict["dest"] != "name": + if len(data_dict["option_strings"]) == 1: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + elif len(data_dict["option_strings"]) == 2: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + data_dict["option_strings"][1] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + + parser.add_argument( + "-ct", + "--categories", + dest="categories", + type=lambda s: [str(item).upper() for item in s.split(",")], + default=[], + help="Show selected categories", + ) + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + if len(self.tickers) < 2: + console.print( + "Please have at least 2 loaded tickers to calculate weights.\n" + ) + return + + table = True + if "historic_period_sa" in vars(ns_parser): + table = False + + weights = optimizer_view.display_rel_risk_parity( + stocks=self.tickers, + period=ns_parser.historic_period, + start=ns_parser.start_period, + end=ns_parser.end_period, + log_returns=ns_parser.log_returns, + freq=ns_parser.return_frequency, + maxnan=ns_parser.max_nan, + threshold=ns_parser.threshold_value, + method=ns_parser.nan_fill_method, + version=ns_parser.risk_parity_model, + risk_cont=ns_parser.risk_contribution, + penal_factor=ns_parser.penal_factor, + target_return=ns_parser.target_return, + d_ewma=ns_parser.smoothing_factor_ewma, + value=ns_parser.long_allocation, + table=table, + ) + + self.portfolios[ns_parser.name.upper()] = weights + self.count += 1 + self.update_runtime_choices() + + if table is False: + weights_sa = optimizer_view.display_rel_risk_parity( + stocks=self.tickers, + period=ns_parser.historic_period_sa, + start=ns_parser.start_period_sa, + end=ns_parser.end_period_sa, + log_returns=ns_parser.log_returns_sa, + freq=ns_parser.return_frequency_sa, + maxnan=ns_parser.max_nan_sa, + threshold=ns_parser.threshold_value_sa, + method=ns_parser.nan_fill_method_sa, + version=ns_parser.risk_parity_model_sa, + risk_cont=ns_parser.risk_contribution_sa, + penal_factor=ns_parser.penal_factor_sa, + target_return=ns_parser.target_return_sa, + d_ewma=ns_parser.smoothing_factor_ewma_sa, + value=ns_parser.long_allocation_sa, + table=table, + ) + + console.print("") + optimizer_view.display_weights_sa( + weights=weights, weights_sa=weights_sa + ) + + if not ns_parser.categories: + categories = ["ASSET_CLASS", "COUNTRY", "SECTOR", "INDUSTRY"] + else: + categories = ns_parser.categories + + for category in categories: + optimizer_view.display_categories_sa( + weights=weights, + weights_sa=weights_sa, + categories=self.categories, + column=category, + title="Category - " + category.title(), + ) + + @log_start_end(log=logger) + def call_hrp(self, other_args: List[str]): + """Process hierarchical risk parity command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="hrp", + description="Builds a hierarchical risk parity portfolio", + ) + parser.add_argument( + "-p", + "--period", + default=self.params["historic_period"] + if "historic_period" in self.params + else "3y", + dest="historic_period", + help="""Period to get yfinance data from. + Possible frequency strings are: + 'd': means days, for example '252d' means 252 days + 'w': means weeks, for example '52w' means 52 weeks + 'mo': means months, for example '12mo' means 12 months + 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset""", + ) + parser.add_argument( + "-s", + "--start", + default=self.params["start_period"] + if "start_period" in self.params + else "", + dest="start_period", + help="""Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-e", + "--end", + default=self.params["end_period"] if "end_period" in self.params else "", + dest="end_period", + help="""End date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-lr", + "--log-returns", + action="store_true", + default=self.params["log_returns"] + if "log_returns" in self.params + else False, + dest="log_returns", + help="If use logarithmic or arithmetic returns to calculate returns", + ) + parser.add_argument( + "-f", + "--freq", + default=self.params["return_frequency"] + if "return_frequency" in self.params + else "d", + dest="return_frequency", + help="""Frequency used to calculate returns. Possible values are: + 'd': for daily returns + 'w': for weekly returns + 'm': for monthly returns + """, + choices=self.FREQ_CHOICES, + ) + parser.add_argument( + "-mn", + "--maxnan", + type=float, + default=self.params["max_nan"] if "max_nan" in self.params else 0.05, + dest="max_nan", + help="""Max percentage of nan values accepted per asset to be + considered in the optimization process""", + ) + parser.add_argument( + "-th", + "--threshold", + type=float, + default=self.params["threshold_value"] + if "threshold_value" in self.params + else 0.30, + dest="threshold_value", + help="""Value used to replace outliers that are higher to threshold + in absolute value""", + ) + parser.add_argument( + "-mt", + "--method", + default=self.params["nan_fill_method"] + if "nan_fill_method" in self.params + else "time", + dest="nan_fill_method", + help="""Method used to fill nan values in time series, by default time. + Possible values are: + 'linear': linear interpolation + 'time': linear interpolation based on time index + 'nearest': use nearest value to replace nan values + 'zero': spline of zeroth order + 'slinear': spline of first order + 'quadratic': spline of second order + 'cubic': spline of third order + 'barycentric': builds a polynomial that pass for all points""", + ) + parser.add_argument( + "-cd", + "--codependence", + default=self.params["co_dependence"] + if "co_dependence" in self.params + else "pearson", + dest="co_dependence", + help="""The codependence or similarity matrix used to build the + distance metric and clusters. Possible values are: + 'pearson': pearson correlation matrix + 'spearman': spearman correlation matrix + 'abs_pearson': absolute value of pearson correlation matrix + 'abs_spearman': absolute value of spearman correlation matrix + 'distance': distance correlation matrix + 'mutual_info': mutual information codependence matrix + 'tail': tail index codependence matrix""", + choices=self.CODEPENDENCE_CHOICES, + ) + parser.add_argument( + "-cv", + "--covariance", + default=self.params["covariance"] + if "covariance" in self.params + else "hist", + dest="covariance", + help="""Method used to estimate covariance matrix. Possible values are + 'hist': historical method + 'ewma1': exponential weighted moving average with adjust=True + 'ewma2': exponential weighted moving average with adjust=False + 'ledoit': Ledoit and Wolf shrinkage method + 'oas': oracle shrinkage method + 'shrunk': scikit-learn shrunk method + 'gl': graphical lasso method + 'jlogo': j-logo covariance + 'fixed': takes average of eigenvalues above max Marchenko Pastour limit + 'spectral': makes zero eigenvalues above max Marchenko Pastour limit + 'shrink': Lopez de Prado's book shrinkage method + """, + choices=self.COVARIANCE_CHOICES, + ) + parser.add_argument( + "-rm", + "--risk-measure", + default=self.params["risk_measure"] + if "risk_measure" in self.params + else "MV", + dest="risk_measure", + help="""Risk measure used to optimize the portfolio. Possible values are: + 'MV' : Variance + 'MAD' : Mean Absolute Deviation + 'GMD' : Gini Mean Difference + 'MSV' : Semi Variance (Variance of negative returns) + 'FLPM' : First Lower Partial Moment + 'SLPM' : Second Lower Partial Moment + 'VaR' : Value at Risk + 'CVaR' : Conditional Value at Risk + 'TG' : Tail Gini + 'EVaR' : Entropic Value at Risk + 'WR' : Worst Realization + 'RG' : Range + 'CVRG' : CVaR Range + 'TGRG' : Tail Gini Range + 'ADD' : Average Drawdown of uncompounded returns + 'UCI' : Ulcer Index of uncompounded returns + 'DaR' : Drawdown at Risk of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded returns + 'EDaR' : Entropic Drawdown at Risk of uncompounded returns + 'MDD' : Maximum Drawdown of uncompounded returns + 'ADD_Rel' : Average Drawdown of compounded returns + 'UCI_Rel' : Ulcer Index of compounded returns + 'DaR_Rel' : Drawdown at Risk of compounded returns + 'CDaR_Rel' : Conditional Drawdown at Risk of compounded returns + 'EDaR_Rel' : Entropic Drawdown at Risk of compounded returns + 'MDD_Rel' : Maximum Drawdown of compounded returns + """, + choices=self.HCP_CHOICES, + ) + parser.add_argument( + "-r", + "--risk-free-rate", + type=float, + dest="risk_free", + default=self.params["risk_free"] + if "risk_free" in self.params + else get_rf(), + help="""Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual""", + ) + parser.add_argument( + "-a", + "--alpha", + type=float, + default=self.params["significance_level"] + if "significance_level" in self.params + else 0.05, + dest="significance_level", + help="""Significance level of VaR, CVaR, EVaR, DaR, CDaR, EDaR and + Tail Gini of losses""", + ) + parser.add_argument( + "-as", + "--a-sim", + type=int, + default=self.params["cvar_simulations_losses"] + if "cvar_simulations_losses" in self.params + else 100, + dest="cvar_simulations_losses", + help="""Number of CVaRs used to approximate Tail Gini of losses. + The default is 100""", + ) + parser.add_argument( + "-b", + "--beta", + type=float, + default=self.params["cvar_significance"] + if "cvar_significance" in self.params + else None, + dest="cvar_significance", + help="""Significance level of CVaR and Tail Gini of gains. If + empty it duplicates alpha""", + ) + parser.add_argument( + "-bs", + "--b-sim", + type=int, + default=self.params["cvar_simulations_gains"] + if "cvar_simulations_gains" in self.params + else None, + dest="cvar_simulations_gains", + help="""Number of CVaRs used to approximate Tail Gini of gains. + If empty it duplicates a_sim value""", + ) + parser.add_argument( + "-lk", + "--linkage", + default=self.params["linkage"] if "linkage" in self.params else "single", + dest="linkage", + help="Linkage method of hierarchical clustering", + choices=self.LINKAGE_CHOICES, + ) + parser.add_argument( + "-k", + type=int, + default=self.params["amount_clusters"] + if "amount_clusters" in self.params + else None, + dest="amount_clusters", + help="Number of clusters specified in advance", + ) + parser.add_argument( + "-mk", + "--max-k", + type=int, + default=self.params["max_clusters"] + if "max_clusters" in self.params + else 10, + dest="max_clusters", + help="""Max number of clusters used by the two difference gap + statistic to find the optimal number of clusters. If k is + empty this value is used""", + ) + parser.add_argument( + "-bi", + "--bins-info", + default=self.params["amount_bins"] + if "amount_bins" in self.params + else "KN", + dest="amount_bins", + help="Number of bins used to calculate the variation of information", + ) + parser.add_argument( + "-at", + "--alpha-tail", + type=float, + default=self.params["alpha_tail"] if "alpha_tail" in self.params else 0.05, + dest="alpha_tail", + help="""Significance level for lower tail dependence index, only + used when when codependence value is 'tail' """, + ) + parser.add_argument( + "-lo", + "--leaf-order", + default=self.params["leaf_order"] if "leaf_order" in self.params else True, + dest="leaf_order", + help="""Indicates if the cluster are ordered so that the distance + between successive leaves is minimal""", + ) + parser.add_argument( + "-de", + "--d-ewma", + type=float, + default=self.params["smoothing_factor_ewma"] + if "smoothing_factor_ewma" in self.params + else 0.94, + dest="smoothing_factor_ewma", + help="Smoothing factor for ewma estimators", + ) + parser.add_argument( + "-v", + "--value", + type=float, + default=self.params["long_allocation"] + if "long_allocation" in self.params + else 1, + dest="long_allocation", + help="Amount to allocate to portfolio", + ) + parser.add_argument( + "--name", + type=str, + dest="name", + default="HRP_" + str(self.count), + help="Save portfolio with personalized or default name", + ) + subparsers = parser.add_subparsers( + title="sensitivity analysis command", help="sensitivity analysis" + ) + parser_update = subparsers.add_parser("sa", help="sensitivity analysis command") + + parser_dict = vars(parser) + for i in parser_dict["_actions"]: + data_dict = vars(i) + variables = list(data_dict.keys()) + if variables[0] == "option_strings" and data_dict["dest"] != "name": + if len(data_dict["option_strings"]) == 1: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + elif len(data_dict["option_strings"]) == 2: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + data_dict["option_strings"][1] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + + parser.add_argument( + "-ct", + "--categories", + dest="categories", + type=lambda s: [str(item).upper() for item in s.split(",")], + default=[], + help="Show selected categories", + ) + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + if len(self.tickers) < 2: + console.print( + "Please have at least 2 loaded tickers to calculate weights.\n" + ) + return + + table = True + if "historic_period_sa" in vars(ns_parser): + table = False + + weights = optimizer_view.display_hrp( + stocks=self.tickers, + period=ns_parser.historic_period, + start=ns_parser.start_period, + end=ns_parser.end_period, + log_returns=ns_parser.log_returns, + freq=ns_parser.return_frequency, + maxnan=ns_parser.max_nan, + threshold=ns_parser.threshold_value, + method=ns_parser.nan_fill_method, + codependence=ns_parser.co_dependence.lower(), + covariance=ns_parser.covariance.lower(), + risk_measure=ns_parser.risk_measure.lower(), + risk_free_rate=ns_parser.risk_free, + alpha=ns_parser.significance_level, + a_sim=ns_parser.cvar_simulations_losses, + beta=ns_parser.cvar_significance, + b_sim=ns_parser.cvar_simulations_gains, + linkage=ns_parser.linkage.lower(), + k=ns_parser.amount_clusters, + max_k=ns_parser.max_clusters, + bins_info=ns_parser.amount_bins.upper(), + alpha_tail=ns_parser.alpha_tail, + leaf_order=ns_parser.leaf_order, + d_ewma=ns_parser.smoothing_factor_ewma, + value=ns_parser.long_allocation, + table=table, + ) + + self.portfolios[ns_parser.name.upper()] = weights + self.count += 1 + self.update_runtime_choices() + + if table is False: + weights_sa = optimizer_view.display_hrp( + stocks=self.tickers, + period=ns_parser.historic_period_sa, + start=ns_parser.start_period_sa, + end=ns_parser.end_period_sa, + log_returns=ns_parser.log_returns_sa, + freq=ns_parser.return_frequency_sa, + maxnan=ns_parser.max_nan_sa, + threshold=ns_parser.threshold_value_sa, + method=ns_parser.nan_fill_method_sa, + codependence=ns_parser.co_dependence_sa.lower(), + covariance=ns_parser.covariance_sa.lower(), + risk_measure=ns_parser.risk_measure_sa.lower(), + risk_free_rate=ns_parser.risk_free_sa, + alpha=ns_parser.significance_level_sa, + a_sim=ns_parser.cvar_simulations_losses_sa, + beta=ns_parser.cvar_significance_sa, + b_sim=ns_parser.cvar_simulations_gains_sa, + linkage=ns_parser.linkage_sa.lower(), + k=ns_parser.amount_clusters_sa, + max_k=ns_parser.max_clusters_sa, + bins_info=ns_parser.amount_bins_sa.upper(), + alpha_tail=ns_parser.alpha_tail_sa, + leaf_order=ns_parser.leaf_order_sa, + d_ewma=ns_parser.smoothing_factor_ewma_sa, + value=ns_parser.long_allocation_sa, + table=table, + ) + + console.print("") + optimizer_view.display_weights_sa( + weights=weights, weights_sa=weights_sa + ) + + if not ns_parser.categories: + categories = ["ASSET_CLASS", "COUNTRY", "SECTOR", "INDUSTRY"] + else: + categories = ns_parser.categories + + for category in categories: + optimizer_view.display_categories_sa( + weights=weights, + weights_sa=weights_sa, + categories=self.categories, + column=category, + title="Category - " + category.title(), + ) + + @log_start_end(log=logger) + def call_herc(self, other_args: List[str]): + """Process hierarchical equal risk contribution command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="herc", + description="Builds a hierarchical equal risk contribution portfolio", + ) + parser.add_argument( + "-p", + "--period", + default=self.params["historic_period"] + if "historic_period" in self.params + else "3y", + dest="historic_period", + help="""Period to get yfinance data from. + Possible frequency strings are: + 'd': means days, for example '252d' means 252 days + 'w': means weeks, for example '52w' means 52 weeks + 'mo': means months, for example '12mo' means 12 months + 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset""", + ) + parser.add_argument( + "-s", + "--start", + default=self.params["start_period"] + if "start_period" in self.params + else "", + dest="start_period", + help="""Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-e", + "--end", + default=self.params["end_period"] if "end_period" in self.params else "", + dest="end_period", + help="""End date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-lr", + "--log-returns", + action="store_true", + default=self.params["log_returns"] + if "log_returns" in self.params + else False, + dest="log_returns", + help="If use logarithmic or arithmetic returns to calculate returns", + ) + parser.add_argument( + "-f", + "--freq", + default=self.params["return_frequency"] + if "return_frequency" in self.params + else "d", + dest="return_frequency", + help="""Frequency used to calculate returns. Possible values are: + 'd': for daily returns + 'w': for weekly returns + 'm': for monthly returns + """, + choices=self.FREQ_CHOICES, + ) + parser.add_argument( + "-mn", + "--maxnan", + type=float, + default=self.params["max_nan"] if "max_nan" in self.params else 0.05, + dest="max_nan", + help="""Max percentage of nan values accepted per asset to be + considered in the optimization process""", + ) + parser.add_argument( + "-th", + "--threshold", + type=float, + default=self.params["threshold_value"] + if "threshold_value" in self.params + else 0.30, + dest="threshold_value", + help="""Value used to replace outliers that are higher to threshold + in absolute value""", + ) + parser.add_argument( + "-mt", + "--method", + default=self.params["nan_fill_method"] + if "nan_fill_method" in self.params + else "time", + dest="nan_fill_method", + help="""Method used to fill nan values in time series, by default time. + Possible values are: + 'linear': linear interpolation + 'time': linear interpolation based on time index + 'nearest': use nearest value to replace nan values + 'zero': spline of zeroth order + 'slinear': spline of first order + 'quadratic': spline of second order + 'cubic': spline of third order + 'barycentric': builds a polynomial that pass for all points""", + ) + parser.add_argument( + "-cd", + "--codependence", + default="pearson", + dest="co_dependence", + help="""The codependence or similarity matrix used to build the + distance metric and clusters. Possible values are: + 'pearson': pearson correlation matrix + 'spearman': spearman correlation matrix + 'abs_pearson': absolute value of pearson correlation matrix + 'abs_spearman': absolute value of spearman correlation matrix + 'distance': distance correlation matrix + 'mutual_info': mutual information codependence matrix + 'tail': tail index codependence matrix""", + choices=self.CODEPENDENCE_CHOICES, + ) + parser.add_argument( + "-cv", + "--covariance", + default=self.params["covariance"] + if "covariance" in self.params + else "hist", + dest="covariance", + help="""Method used to estimate covariance matrix. Possible values are + 'hist': historical method + 'ewma1': exponential weighted moving average with adjust=True + 'ewma2': exponential weighted moving average with adjust=False + 'ledoit': Ledoit and Wolf shrinkage method + 'oas': oracle shrinkage method + 'shrunk': scikit-learn shrunk method + 'gl': graphical lasso method + 'jlogo': j-logo covariance + 'fixed': takes average of eigenvalues above max Marchenko Pastour limit + 'spectral': makes zero eigenvalues above max Marchenko Pastour limit + 'shrink': Lopez de Prado's book shrinkage method + """, + choices=self.COVARIANCE_CHOICES, + ) + parser.add_argument( + "-rm", + "--risk-measure", + default=self.params["risk_measure"] + if "risk_measure" in self.params + else "MV", + dest="risk_measure", + help="""Risk measure used to optimize the portfolio. Possible values are: + 'MV' : Variance + 'MAD' : Mean Absolute Deviation + 'GMD' : Gini Mean Difference + 'MSV' : Semi Variance (Variance of negative returns) + 'FLPM' : First Lower Partial Moment + 'SLPM' : Second Lower Partial Moment + 'VaR' : Value at Risk + 'CVaR' : Conditional Value at Risk + 'TG' : Tail Gini + 'EVaR' : Entropic Value at Risk + 'WR' : Worst Realization + 'RG' : Range + 'CVRG' : CVaR Range + 'TGRG' : Tail Gini Range + 'ADD' : Average Drawdown of uncompounded returns + 'UCI' : Ulcer Index of uncompounded returns + 'DaR' : Drawdown at Risk of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded returns + 'EDaR' : Entropic Drawdown at Risk of uncompounded returns + 'MDD' : Maximum Drawdown of uncompounded returns + 'ADD_Rel' : Average Drawdown of compounded returns + 'UCI_Rel' : Ulcer Index of compounded returns + 'DaR_Rel' : Drawdown at Risk of compounded returns + 'CDaR_Rel' : Conditional Drawdown at Risk of compounded returns + 'EDaR_Rel' : Entropic Drawdown at Risk of compounded returns + 'MDD_Rel' : Maximum Drawdown of compounded returns + """, + choices=self.HCP_CHOICES, + ) + parser.add_argument( + "-r", + "--risk-free-rate", + type=float, + dest="risk_free", + default=self.params["risk_free"] + if "risk_free" in self.params + else get_rf(), + help="""Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual""", + ) + parser.add_argument( + "-a", + "--alpha", + type=float, + default=self.params["significance_level"] + if "significance_level" in self.params + else 0.05, + dest="significance_level", + help="""Significance level of VaR, CVaR, EVaR, DaR, CDaR, EDaR and + Tail Gini of losses""", + ) + parser.add_argument( + "-as", + "--a-sim", + type=int, + default=self.params["cvar_simulations_losses"] + if "cvar_simulations_losses" in self.params + else 100, + dest="cvar_simulations_losses", + help="""Number of CVaRs used to approximate Tail Gini of losses. + The default is 100""", + ) + parser.add_argument( + "-b", + "--beta", + type=float, + default=self.params["cvar_significance"] + if "cvar_significance" in self.params + else None, + dest="cvar_significance", + help="""Significance level of CVaR and Tail Gini of gains. If + empty it duplicates alpha""", + ) + parser.add_argument( + "-bs", + "--b-sim", + type=int, + default=self.params["cvar_simulations_gains"] + if "cvar_simulations_gains" in self.params + else None, + dest="cvar_simulations_gains", + help="""Number of CVaRs used to approximate Tail Gini of gains. + If empty it duplicates a_sim value""", + ) + parser.add_argument( + "-lk", + "--linkage", + default=self.params["linkage"] if "linkage" in self.params else "single", + dest="linkage", + help="Linkage method of hierarchical clustering", + choices=self.LINKAGE_CHOICES, + ) + parser.add_argument( + "-k", + type=int, + default=self.params["amount_clusters"] + if "amount_clusters" in self.params + else None, + dest="amount_clusters", + help="Number of clusters specified in advance", + ) + parser.add_argument( + "-mk", + "--max-k", + type=int, + default=self.params["max_clusters"] + if "max_clusters" in self.params + else 10, + dest="max_clusters", + help="""Max number of clusters used by the two difference gap + statistic to find the optimal number of clusters. If k is + empty this value is used""", + ) + parser.add_argument( + "-bi", + "--bins-info", + default=self.params["amount_bins"] + if "amount_bins" in self.params + else "KN", + dest="amount_bins", + help="Number of bins used to calculate the variation of information", + ) + parser.add_argument( + "-at", + "--alpha-tail", + type=float, + default=self.params["alpha_tail"] if "alpha_tail" in self.params else 0.05, + dest="alpha_tail", + help="""Significance level for lower tail dependence index, only + used when when codependence value is 'tail' """, + ) + parser.add_argument( + "-lo", + "--leaf-order", + default=self.params["leaf_order"] if "leaf_order" in self.params else True, + dest="leaf_order", + help="""Indicates if the cluster are ordered so that the distance + between successive leaves is minimal""", + ) + parser.add_argument( + "-de", + "--d-ewma", + type=float, + default=self.params["smoothing_factor_ewma"] + if "smoothing_factor_ewma" in self.params + else 0.94, + dest="smoothing_factor_ewma", + help="Smoothing factor for ewma estimators", + ) + parser.add_argument( + "-v", + "--value", + type=float, + default=self.params["long_allocation"] + if "long_allocation" in self.params + else 1, + dest="long_allocation", + help="Amount to allocate to portfolio", + ) + parser.add_argument( + "--name", + type=str, + dest="name", + default="HERC_" + str(self.count), + help="Save portfolio with personalized or default name", + ) + subparsers = parser.add_subparsers( + title="sensitivity analysis command", help="sensitivity analysis" + ) + parser_update = subparsers.add_parser("sa", help="sensitivity analysis command") + + parser_dict = vars(parser) + for i in parser_dict["_actions"]: + data_dict = vars(i) + variables = list(data_dict.keys()) + if variables[0] == "option_strings" and data_dict["dest"] != "name": + if len(data_dict["option_strings"]) == 1: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + elif len(data_dict["option_strings"]) == 2: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + data_dict["option_strings"][1] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + + parser.add_argument( + "-ct", + "--categories", + dest="categories", + type=lambda s: [str(item).upper() for item in s.split(",")], + default=[], + help="Show selected categories", + ) + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + if len(self.tickers) < 2: + console.print( + "Please have at least 2 loaded tickers to calculate weights.\n" + ) + return + + table = True + if "historic_period_sa" in vars(ns_parser): + table = False + + weights = optimizer_view.display_herc( + stocks=self.tickers, + period=ns_parser.historic_period, + start=ns_parser.start_period, + end=ns_parser.end_period, + log_returns=ns_parser.log_returns, + freq=ns_parser.return_frequency, + maxnan=ns_parser.max_nan, + threshold=ns_parser.threshold_value, + method=ns_parser.nan_fill_method, + codependence=ns_parser.co_dependence.lower(), + covariance=ns_parser.covariance.lower(), + risk_measure=ns_parser.risk_measure.lower(), + risk_free_rate=ns_parser.risk_free, + alpha=ns_parser.significance_level, + a_sim=ns_parser.cvar_simulations_losses, + beta=ns_parser.cvar_significance, + b_sim=ns_parser.cvar_simulations_gains, + linkage=ns_parser.linkage.lower(), + k=ns_parser.amount_clusters, + max_k=ns_parser.max_clusters, + bins_info=ns_parser.amount_bins.upper(), + alpha_tail=ns_parser.alpha_tail, + leaf_order=ns_parser.leaf_order, + d_ewma=ns_parser.smoothing_factor_ewma, + value=ns_parser.long_allocation, + table=table, + ) + + self.portfolios[ns_parser.name.upper()] = weights + self.count += 1 + self.update_runtime_choices() + + if table is False: + weights_sa = optimizer_view.display_herc( + stocks=self.tickers, + period=ns_parser.historic_period_sa, + start=ns_parser.start_period_sa, + end=ns_parser.end_period_sa, + log_returns=ns_parser.log_returns_sa, + freq=ns_parser.return_frequency_sa, + maxnan=ns_parser.max_nan_sa, + threshold=ns_parser.threshold_value_sa, + method=ns_parser.nan_fill_method_sa, + codependence=ns_parser.co_dependence_sa.lower(), + covariance=ns_parser.covariance_sa.lower(), + risk_measure=ns_parser.risk_measure_sa.lower(), + risk_free_rate=ns_parser.risk_free_sa, + alpha=ns_parser.significance_level_sa, + a_sim=ns_parser.cvar_simulations_losses_sa, + beta=ns_parser.cvar_significance_sa, + b_sim=ns_parser.cvar_simulations_gains_sa, + linkage=ns_parser.linkage_sa.lower(), + k=ns_parser.amount_clusters_sa, + max_k=ns_parser.max_clusters_sa, + bins_info=ns_parser.amount_bins_sa.upper(), + alpha_tail=ns_parser.alpha_tail_sa, + leaf_order=ns_parser.leaf_order_sa, + d_ewma=ns_parser.smoothing_factor_ewma_sa, + value=ns_parser.long_allocation_sa, + table=table, + ) + + console.print("") + optimizer_view.display_weights_sa( + weights=weights, weights_sa=weights_sa + ) + + if not ns_parser.categories: + categories = ["ASSET_CLASS", "COUNTRY", "SECTOR", "INDUSTRY"] + else: + categories = ns_parser.categories + + for category in categories: + optimizer_view.display_categories_sa( + weights=weights, + weights_sa=weights_sa, + categories=self.categories, + column=category, + title="Category - " + category.title(), + ) + + @log_start_end(log=logger) + def call_nco(self, other_args: List[str]): + """Process nested clustered optimization command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="nco", + description="Builds a nested clustered optimization portfolio", + ) + parser.add_argument( + "-p", + "--period", + default=self.params["historic_period"] + if "historic_period" in self.params + else "3y", + dest="historic_period", + help="""Period to get yfinance data from. + Possible frequency strings are: + 'd': means days, for example '252d' means 252 days + 'w': means weeks, for example '52w' means 52 weeks + 'mo': means months, for example '12mo' means 12 months + 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset""", + ) + parser.add_argument( + "-s", + "--start", + default=self.params["start_period"] + if "start_period" in self.params + else "", + dest="start_period", + help="""Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-e", + "--end", + default=self.params["end_period"] if "end_period" in self.params else "", + dest="end_period", + help="""End date to get yfinance data from. Must be in + 'YYYY-MM-DD' format""", + ) + parser.add_argument( + "-lr", + "--log-returns", + action="store_true", + default=self.params["log_returns"] + if "log_returns" in self.params + else False, + dest="log_returns", + help="If use logarithmic or arithmetic returns to calculate returns", + ) + parser.add_argument( + "-f", + "--freq", + default=self.params["return_frequency"] + if "return_frequency" in self.params + else "d", + dest="return_frequency", + help="""Frequency used to calculate returns. Possible values are: + 'd': for daily returns + 'w': for weekly returns + 'm': for monthly returns + """, + choices=self.FREQ_CHOICES, + ) + parser.add_argument( + "-mn", + "--maxnan", + type=float, + default=self.params["max_nan"] if "max_nan" in self.params else 0.05, + dest="max_nan", + help="""Max percentage of nan values accepted per asset to be + considered in the optimization process""", + ) + parser.add_argument( + "-th", + "--threshold", + type=float, + default=self.params["threshold_value"] + if "threshold_value" in self.params + else 0.30, + dest="threshold_value", + help="""Value used to replace outliers that are higher to threshold + in absolute value""", + ) + parser.add_argument( + "-mt", + "--method", + default=self.params["nan_fill_method"] + if "nan_fill_method" in self.params + else "time", + dest="nan_fill_method", + help="""Method used to fill nan values in time series, by default time. + Possible values are: + 'linear': linear interpolation + 'time': linear interpolation based on time index + 'nearest': use nearest value to replace nan values + 'zero': spline of zeroth order + 'slinear': spline of first order + 'quadratic': spline of second order + 'cubic': spline of third order + 'barycentric': builds a polynomial that pass for all points""", + ) + parser.add_argument( + "-cd", + "--codependence", + default=self.params["co_dependence"] + if "co_dependence" in self.params + else "pearson", + dest="co_dependence", + help="""The codependence or similarity matrix used to build the + distance metric and clusters. Possible values are: + 'pearson': pearson correlation matrix + 'spearman': spearman correlation matrix + 'abs_pearson': absolute value of pearson correlation matrix + 'abs_spearman': absolute value of spearman correlation matrix + 'distance': distance correlation matrix + 'mutual_info': mutual information codependence matrix + 'tail': tail index codependence matrix""", + choices=self.CODEPENDENCE_CHOICES, + ) + parser.add_argument( + "-cv", + "--covariance", + default=self.params["covariance"] + if "covariance" in self.params + else "hist", + dest="covariance", + help="""Method used to estimate covariance matrix. Possible values are + 'hist': historical method + 'ewma1': exponential weighted moving average with adjust=True + 'ewma2': exponential weighted moving average with adjust=False + 'ledoit': Ledoit and Wolf shrinkage method + 'oas': oracle shrinkage method + 'shrunk': scikit-learn shrunk method + 'gl': graphical lasso method + 'jlogo': j-logo covariance + 'fixed': takes average of eigenvalues above max Marchenko Pastour limit + 'spectral': makes zero eigenvalues above max Marchenko Pastour limit + 'shrink': Lopez de Prado's book shrinkage method + """, + choices=self.COVARIANCE_CHOICES, + ) + parser.add_argument( + "-o", + "--objective", + default=self.params["objective"] + if "objective" in self.params + else "MinRisk", + dest="objective", + help="Objective function used to optimize the portfolio", + choices=self.NCO_OBJECTIVE_CHOICES, + ) + parser.add_argument( + "-rm", + "--risk-measure", + default=self.params["risk_measure"] + if "risk_measure" in self.params + else "MV", + dest="risk_measure", + help="""Risk measure used to optimize the portfolio. Possible values are: + 'MV' : Variance + 'MAD' : Mean Absolute Deviation + 'MSV' : Semi Variance (Variance of negative returns) + 'FLPM' : First Lower Partial Moment + 'SLPM' : Second Lower Partial Moment + 'CVaR' : Conditional Value at Risk + 'EVaR' : Entropic Value at Risk + 'WR' : Worst Realization + 'ADD' : Average Drawdown of uncompounded returns + 'UCI' : Ulcer Index of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded returns + 'EDaR' : Entropic Drawdown at Risk of uncompounded returns + 'MDD' : Maximum Drawdown of uncompounded returns + """, + choices=self.MEAN_RISK_CHOICES, + ) + parser.add_argument( + "-r", + "--risk-free-rate", + type=float, + dest="risk_free", + default=self.params["risk_free"] + if "risk_free" in self.params + else get_rf(), + help="""Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual""", + ) + parser.add_argument( + "-ra", + "--risk-aversion", + type=float, + dest="risk_aversion", + default=self.params["long_allocation"] + if "long_allocation" in self.params + else 1, + help="Risk aversion parameter", + ) + parser.add_argument( + "-a", + "--alpha", + type=float, + default=self.params["significance_level"] + if "significance_level" in self.params + else 0.05, + dest="significance_level", + help="Significance level of CVaR, EVaR, CDaR and EDaR", + ) + parser.add_argument( + "-lk", + "--linkage", + default=self.params["linkage"] if "linkage" in self.params else "single", + dest="linkage", + help="Linkage method of hierarchical clustering", + choices=self.LINKAGE_CHOICES, + ) + parser.add_argument( + "-k", + type=int, + default=self.params["amount_clusters"] + if "amount_clusters" in self.params + else None, + dest="amount_clusters", + help="Number of clusters specified in advance", + ) + parser.add_argument( + "-mk", + "--max-k", + type=int, + default=self.params["max_clusters"] + if "max_clusters" in self.params + else 10, + dest="max_clusters", + help="""Max number of clusters used by the two difference gap + statistic to find the optimal number of clusters. If k is + empty this value is used""", + ) + parser.add_argument( + "-bi", + "--bins-info", + default=self.params["amount_bins"] + if "amount_bins" in self.params + else "KN", + dest="amount_bins", + help="Number of bins used to calculate the variation of information", + ) + parser.add_argument( + "-at", + "--alpha-tail", + type=float, + default=self.params["alpha_tail"] if "alpha_tail" in self.params else 0.05, + dest="alpha_tail", + help="""Significance level for lower tail dependence index, only + used when when codependence value is 'tail' """, + ) + parser.add_argument( + "-lo", + "--leaf-order", + action="store_true", + default=self.params["leaf_order"] if "leaf_order" in self.params else True, + dest="leaf_order", + help="""indicates if the cluster are ordered so that the distance + between successive leaves is minimal""", + ) + parser.add_argument( + "-de", + "--d-ewma", + type=float, + default=self.params["smoothing_factor_ewma"] + if "smoothing_factor_ewma" in self.params + else 0.94, + dest="smoothing_factor_ewma", + help="Smoothing factor for ewma estimators", + ) + parser.add_argument( + "-v", + "--value", + dest="long_allocation", + help="Amount to allocate to portfolio", + type=float, + default=self.params["long_allocation"] + if "long_allocation" in self.params + else 1, + ) + parser.add_argument( + "--name", + type=str, + dest="name", + default="NCO_" + str(self.count), + help="Save portfolio with personalized or default name", + ) + subparsers = parser.add_subparsers( + title="sensitivity analysis command", help="sensitivity analysis" + ) + parser_update = subparsers.add_parser("sa", help="sensitivity analysis command") + + parser_dict = vars(parser) + for i in parser_dict["_actions"]: + data_dict = vars(i) + variables = list(data_dict.keys()) + if variables[0] == "option_strings" and data_dict["dest"] != "name": + if len(data_dict["option_strings"]) == 1: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + elif len(data_dict["option_strings"]) == 2: + parser_update.add_argument( + data_dict["option_strings"][0] + "-sa", + data_dict["option_strings"][1] + "-sa", + type=data_dict["type"], + default=data_dict["default"], + dest=data_dict["dest"] + "_sa", + choices=data_dict["choices"], + help=data_dict["help"], + ) + + parser.add_argument( + "-ct", + "--categories", + dest="categories", + type=lambda s: [str(item).upper() for item in s.split(",")], + default=[], + help="Show selected categories", + ) + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + if len(self.tickers) < 2: + console.print( + "Please have at least 2 loaded tickers to calculate weights.\n" + ) + return + + table = True + if "historic_period_sa" in vars(ns_parser): + table = False + + weights = optimizer_view.display_nco( + stocks=self.tickers, + period=ns_parser.historic_period, + start=ns_parser.start_period, + end=ns_parser.end_period, + log_returns=ns_parser.log_returns, + freq=ns_parser.return_frequency, + maxnan=ns_parser.max_nan, + threshold=ns_parser.threshold_value, + method=ns_parser.nan_fill_method, + codependence=ns_parser.co_dependence.lower(), + covariance=ns_parser.covariance.lower(), + objective=ns_parser.objective.lower(), + risk_measure=ns_parser.risk_measure.lower(), + risk_free_rate=ns_parser.risk_free, + risk_aversion=ns_parser.risk_aversion, + alpha=ns_parser.significance_level, + linkage=ns_parser.linkage.lower(), + k=ns_parser.amount_clusters, + max_k=ns_parser.max_clusters, + bins_info=ns_parser.amount_bins.upper(), + alpha_tail=ns_parser.alpha_tail, + leaf_order=ns_parser.leaf_order, + d_ewma=ns_parser.smoothing_factor_ewma, + value=ns_parser.long_allocation, + table=table, + ) + + self.portfolios[ns_parser.name.upper()] = weights + self.count += 1 + self.update_runtime_choices() + + if table is False: + weights_sa = optimizer_view.display_nco( + stocks=self.tickers, + period=ns_parser.historic_period_sa, + start=ns_parser.start_period_sa, + end=ns_parser.end_period_sa, + log_returns=ns_parser.log_returns_sa, + freq=ns_parser.return_frequency_sa, + maxnan=ns_parser.max_nan_sa, + threshold=ns_parser.threshold_value_sa, + method=ns_parser.nan_fill_method_sa, + codependence=ns_parser.co_dependence_sa.lower(), + covariance=ns_parser.covariance_sa.lower(), + objective=ns_parser.objective_sa.lower(), + risk_measure=ns_parser.risk_measure_sa.lower(), + risk_free_rate=ns_parser.risk_free_sa, + risk_aversion=ns_parser.risk_aversion_sa, + alpha=ns_parser.significance_level_sa, + linkage=ns_parser.linkage_sa.lower(), + k=ns_parser.amount_clusters_sa, + max_k=ns_parser.max_clusters_sa, + bins_info=ns_parser.amount_bins_sa.upper(), + alpha_tail=ns_parser.alpha_tail_sa, + leaf_order=ns_parser.leaf_order_sa, + d_ewma=ns_parser.smoothing_factor_ewma_sa, + value=ns_parser.long_allocation_sa, + table=table, + ) + + console.print("") + optimizer_view.display_weights_sa( + weights=weights, weights_sa=weights_sa + ) + + if not ns_parser.categories: + categories = ["ASSET_CLASS", "COUNTRY", "SECTOR", "INDUSTRY"] + else: + categories = ns_parser.categories + + for category in categories: + optimizer_view.display_categories_sa( + weights=weights, + weights_sa=weights_sa, + categories=self.categories, + column=category, + title="Category - " + category.title(), + ) diff --git a/openbb_terminal/portfolio/portfolio_optimization/yahoo_finance_model.py b/openbb_terminal/portfolio/portfolio_optimization/yahoo_finance_model.py index c32d5243155..40c407bd486 100644 --- a/openbb_terminal/portfolio/portfolio_optimization/yahoo_finance_model.py +++ b/openbb_terminal/portfolio/portfolio_optimization/yahoo_finance_model.py @@ -2,18 +2,121 @@ __docformat__ = "numpy" import logging +import os +import tempfile +from calendar import monthrange +from datetime import date from typing import List +import numpy as np import pandas as pd import yfinance as yf +from dateutil.relativedelta import relativedelta, FR from openbb_terminal.decorators import log_start_end logger = logging.getLogger(__name__) +# pylint: disable=R0912, E1101 + +yf_info_choices = [ + "previousClose", + "regularMarketOpen", + "twoHundredDayAverage", + "trailingAnnualDividendYield", + "payoutRatio", + "volume24Hr", + "regularMarketDayHigh", + "navPrice", + "averageDailyVolume10Day", + "totalAssets", + "regularMarketPreviousClose", + "fiftyDayAverage", + "trailingAnnualDividendRate", + "open", + "toCurrency", + "averageVolume10days", + "expireDate", + "yield", + "algorithm", + "dividendRate", + "exDividendDate", + "beta", + "circulatingSupply", + "regularMarketDayLow", + "priceHint", + "currency", + "trailingPE", + "regularMarketVolume", + "lastMarket", + "maxSupply", + "openInterest", + "marketCap", + "volumeAllCurrencies", + "strikePrice", + "averageVolume", + "priceToSalesTrailing12Months", + "dayLow", + "ask", + "ytdReturn", + "askSize", + "volume", + "fiftyTwoWeekHigh", + "forwardPE", + "fromCurrency", + "fiveYearAvgDividendYield", + "fiftyTwoWeekLow", + "bid", + "dividendYield", + "bidSize", + "dayHigh", + "annualHoldingsTurnover", + "enterpriseToRevenue", + "beta3Year", + "profitMargins", + "enterpriseToEbitda", + "52WeekChange", + "morningStarRiskRating", + "forwardEps", + "revenueQuarterlyGrowth", + "sharesOutstanding", + "fundInceptionDate", + "annualReportExpenseRatio", + "bookValue", + "sharesShort", + "sharesPercentSharesOut", + "heldPercentInstitutions", + "netIncomeToCommon", + "trailingEps", + "lastDividendValue", + "SandP52WeekChange", + "priceToBook", + "heldPercentInsiders", + "shortRatio", + "sharesShortPreviousMonthDate", + "floatShares", + "enterpriseValue", + "fundFamily", + "threeYearAverageReturn", + "lastSplitFactor", + "legalType", + "lastDividendDate", + "morningStarOverallRating", + "earningsQuarterlyGrowth", + "pegRatio", + "lastCapGain", + "shortPercentOfFloat", + "sharesShortPriorMonth", + "impliedSharesOutstanding", + "fiveYearAverageReturn", + "regularMarketPrice", +] + @log_start_end(log=logger) -def process_stocks(list_of_stocks: List[str], period: str = "3mo") -> pd.DataFrame: +def process_stocks( + list_of_stocks: List[str], period: str = "3mo", start: str = "", end: str = "" +) -> pd.DataFrame: """Get adjusted closing price for each stock in the list Parameters @@ -21,7 +124,12 @@ def process_stocks(list_of_stocks: List[str], period: str = "3mo") -> pd.DataFra list_of_stocks: List[str] List of tickers to get historical data for period: str - Period to get data from yfinance + Period to get data from yfinance, personalized + start: str + If not using period, start date string (YYYY-MM-DD) + end: str + If not using period, end date string (YYYY-MM-DD). If empty use last + weekday. Returns ------- @@ -29,10 +137,239 @@ def process_stocks(list_of_stocks: List[str], period: str = "3mo") -> pd.DataFra DataFrame containing daily (adjusted) close prices for each stock in list """ - stock_prices = yf.download( - list_of_stocks, period=period, progress=False, group_by="ticker" - ) - stock_closes = pd.DataFrame(index=stock_prices.index) - for stock in list_of_stocks: - stock_closes[stock] = stock_prices[stock]["Adj Close"] + period_choices = [ + "1d", + "5d", + "1mo", + "3mo", + "6mo", + "1y", + "2y", + "5y", + "10y", + "ytd", + "max", + ] + + directory = "gst_temp_files" + parent_dir = tempfile.gettempdir() + path = os.path.join(parent_dir, directory) + + if os.path.isdir(path) is False: + os.mkdir(path) + + stock_closes = None + + if start != "": + if end == "": + end_ = date.today() + else: + end_ = date.fromisoformat(end) + + # Check if end date is on weekend + if end_.weekday() >= 5: + end_ = end_ + relativedelta(weekday=FR(-1)) + + end = end_.strftime("%Y-%m-%d") + + # Creating temporal file name + name = os.path.join(path, "Stocks " + start + " to " + end + ".pkl") + + # Checking if exist + if os.path.exists(name): + stock_closes_0 = pd.read_pickle(name) + list_of_stocks_0 = list(set(list_of_stocks) - set(stock_closes_0.columns)) + else: + stock_closes_0 = None + list_of_stocks_0 = list_of_stocks + + # Download assets that are not in temporal file + if list_of_stocks_0 == []: + stock_closes = stock_closes_0.copy() + else: + stock_prices = yf.download( + list_of_stocks_0, + start=start, + end=end, + progress=False, + group_by="ticker", + ) + + else: + if period in period_choices: + # Setting temporal file name + name = os.path.join( + path, + "Stocks " + period + " " + date.today().strftime("%Y-%m-%d") + ".pkl", + ) + + # Creating if exist + if os.path.exists(name): + stock_closes_0 = pd.read_pickle(name) + list_of_stocks_0 = list( + set(list_of_stocks) - set(stock_closes_0.columns) + ) + else: + stock_closes_0 = None + list_of_stocks_0 = list_of_stocks + + # Download assets that are not in temporal file + if list_of_stocks_0 == []: + stock_closes = stock_closes_0.copy() + else: + stock_prices = yf.download( + list_of_stocks_0, period=period, progress=False, group_by="ticker" + ) + + else: + end_ = date.today() + if end_.weekday() >= 5: + end_ = end_ + relativedelta(weekday=FR(-1)) + if period.find("d") >= 1: + days = int(period[:-1]) + start_ = end_ - relativedelta(days=days) + elif period.find("w") >= 1: + weeks = int(period[:-1]) + start_ = end_ - relativedelta(weeks=weeks) + elif period.find("mo") >= 1: + months = int(period[:-2]) + start_ = end_ - relativedelta(months=months) + elif period.find("y") >= 1: + years = int(period[:-1]) + start_ = end_ - relativedelta(years=years) + else: + # console.print( + # "Please use an adequate period." + # ) + return None + + start = start_.strftime("%Y-%m-%d") + end = end_.strftime("%Y-%m-%d") + + # Creating temporal file name + name = os.path.join(path, "Stocks " + start + " to " + end + ".pkl") + + # Checking if temporal file exists + if os.path.exists(name): + stock_closes_0 = pd.read_pickle(name) + list_of_stocks_0 = list( + set(list_of_stocks) - set(stock_closes_0.columns) + ) + else: + stock_closes_0 = None + list_of_stocks_0 = list_of_stocks + + # Download assets that are not in temporal file + if list_of_stocks_0 == []: + stock_closes = stock_closes_0.copy() + else: + stock_prices = yf.download( + list_of_stocks_0, + start=start, + end=end, + progress=False, + group_by="ticker", + ) + + if stock_closes is None: + if len(list_of_stocks_0) == 1: + stock_closes = stock_prices.loc[:, ["Adj Close"]] + stock_closes.columns = list_of_stocks_0 + else: + stock_closes = stock_prices.loc[:, (slice(None), "Adj Close")] + stock_closes.columns = stock_closes.columns.get_level_values(0) + + if list_of_stocks_0 != []: + stock_closes = pd.concat([stock_closes, stock_closes_0], axis=1) + stock_closes.to_pickle(name) + + stock_closes = stock_closes[list_of_stocks] + return stock_closes + + +@log_start_end(log=logger) +def process_returns( + stock_prices: pd.DataFrame, + log_returns: bool = False, + freq: str = "D", + maxnan: float = 0.05, + threshold: float = 0, + method: str = "time", +) -> pd.DataFrame: + """Process stock prices to calculate returns and delete outliers + + Parameters + ---------- + stock_prices: pd.DataFrame + DataFrame of stock prices + log_returns: bool + If True calculate log returns, else arithmetic returns. Default value + is False + freq: str or int + The frequency used to calculate returns. Default value is 'D'. Possible + values are: + - 'D' for daily returns. + - 'W' for weekly returns. + - 'M' for monthly returns. + + maxnan: str or float + Max percentage of nan values accepted per asset to be included in + returns + threshold: str or float + Value used to replace outliers that are higher to threshold in daily returns. + method: str + Method used to fill nan values. Default value is 'time'. For more information see + `interpolate `_. + + Returns + ------- + stock_returns: DataFrame + DataFrame containing daily (adjusted) close prices for each stock in list + """ + + # Interpolate nan values + stock_returns = stock_prices.copy() + stock_returns.interpolate(method=method, axis=0, inplace=True) + + # Select stocks with low number of nans + selected_stocks = np.isnan(stock_returns).sum(axis=0) + selected_stocks = np.where(selected_stocks <= maxnan * stock_returns.shape[0])[0] + stock_returns = stock_returns.iloc[:, selected_stocks] + + # Replace values above and below threshold + if threshold > 0: + stock_returns = stock_returns.pct_change() + stock_returns.mask(stock_returns > threshold, threshold, inplace=True) + stock_returns.mask(stock_returns < -threshold, -threshold, inplace=True) + + s = stock_returns.isna().idxmin().tolist() + j = 0 + for i in s: + stock_returns.iloc[stock_returns.index.get_loc(i) - 1, j] = 0 + j += 1 + + stock_returns = stock_returns + 1 + stock_returns = stock_returns.cumprod() + + # Change the frequency of the data + if freq.upper() == "D": + pass + elif freq.upper() in ["W", "M"]: + last_day = stock_returns.index[-1] + stock_returns = stock_returns.resample(freq).last() + if freq.upper() == ["W"]: + if last_day.weekday() < 4: + stock_returns = stock_returns.iloc[:-1, :] + if freq.upper() == ["M"]: + if monthrange(last_day.year, last_day.month)[1] - last_day.day <= 5: + stock_returns = stock_returns.iloc[:-1, :] + + # Calculate returns + if log_returns is True: + stock_returns = np.log(stock_returns) + stock_returns = stock_returns.diff().dropna() + else: + stock_returns = stock_returns.pct_change().dropna() + + return stock_returns diff --git a/poetry.lock b/poetry.lock index 5ffc913a6ce..480a281e0f0 100644 --- a/poetry.lock +++ b/poetry.lock @@ -104,6 +104,21 @@ category = "main" optional = false python-versions = "*" +[[package]] +name = "arch" +version = "5.2.0" +description = "ARCH for Python" +category = "main" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +numpy = ">=1.17" +pandas = ">=1.0" +property-cached = ">=1.6.4" +scipy = ">=1.3" +statsmodels = ">=0.11" + [[package]] name = "argon2-cffi" version = "21.3.0" @@ -179,6 +194,27 @@ lazy-object-proxy = ">=1.4.0" typing-extensions = {version = ">=3.10", markers = "python_version < \"3.10\""} wrapt = ">=1.11,<2" +[[package]] +name = "astropy" +version = "5.0.4" +description = "Astronomy and astrophysics core library" +category = "main" +optional = false +python-versions = ">=3.8" + +[package.dependencies] +numpy = ">=1.18" +packaging = ">=19.0" +pyerfa = ">=2.0" +PyYAML = ">=3.13" + +[package.extras] +all = ["scipy (>=1.3)", "matplotlib (>=3.1,!=3.4.0)", "certifi", "dask", "h5py", "pyarrow (>=5.0.0)", "beautifulsoup4", "html5lib", "bleach", "pandas", "sortedcontainers", "pytz", "jplephem", "mpmath", "asdf (>=2.9.2)", "bottleneck", "ipython (>=4.2)", "pytest (>=7.0)", "typing-extensions (>=3.10.0.1)"] +docs = ["sphinx (<4)", "sphinx-astropy (>=1.6)", "pytest (>=7.0)", "scipy (>=1.3)", "matplotlib (>=3.1,!=3.4.0)", "sphinx-changelog (>=1.1.0)", "Jinja2 (<3.1)"] +recommended = ["scipy (>=1.3)", "matplotlib (>=3.1,!=3.4.0)"] +test = ["pytest (>=7.0)", "pytest-doctestplus (>=0.12)", "pytest-astropy-header (>=0.2.1)", "pytest-astropy (>=0.9)", "pytest-xdist"] +test_all = ["pytest (>=7.0)", "pytest-doctestplus (>=0.12)", "pytest-astropy-header (>=0.2.1)", "pytest-astropy (>=0.9)", "pytest-xdist", "objgraph", "ipython (>=4.2)", "coverage", "skyfield (>=1.20)", "sgp4 (>=2.3)"] + [[package]] name = "asttokens" version = "2.0.5" @@ -2111,6 +2147,21 @@ category = "main" optional = false python-versions = ">=3.5" +[[package]] +name = "networkx" +version = "2.8" +description = "Python package for creating and manipulating graphs and networks" +category = "main" +optional = false +python-versions = ">=3.8" + +[package.extras] +default = ["numpy (>=1.19)", "scipy (>=1.8)", "matplotlib (>=3.4)", "pandas (>=1.3)"] +developer = ["pre-commit (>=2.18)", "mypy (>=0.942)"] +doc = ["sphinx (>=4.5)", "pydata-sphinx-theme (>=0.8.1)", "sphinx-gallery (>=0.10)", "numpydoc (>=1.2)", "pillow (>=9.1)", "nb2plots (>=0.6)", "texext (>=0.6.6)"] +extra = ["lxml (>=4.6)", "pygraphviz (>=1.9)", "pydot (>=1.4.2)", "sympy (>=1.10)"] +test = ["pytest (>=7.1)", "pytest-cov (>=3.0)", "codecov (>=2.1)"] + [[package]] name = "nodeenv" version = "1.6.0" @@ -2718,6 +2769,21 @@ typing-extensions = ">=3.7.4.3" dotenv = ["python-dotenv (>=0.10.4)"] email = ["email-validator (>=1.0.3)"] +[[package]] +name = "pyerfa" +version = "2.0.0.1" +description = "Python bindings for ERFA" +category = "main" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +numpy = ">=1.17" + +[package.extras] +docs = ["sphinx-astropy (>=1.3)"] +test = ["pytest", "pytest-doctestplus (>=0.7)"] + [[package]] name = "pyex" version = "0.5.0" @@ -3356,6 +3422,27 @@ pygments = ">=2.6.0,<3.0.0" [package.extras] jupyter = ["ipywidgets (>=7.5.1,<8.0.0)"] +[[package]] +name = "riskfolio-lib" +version = "3.1.1" +description = "Portfolio Optimization and Quantitative Strategic Asset Allocation in Python" +category = "main" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +arch = ">=4.15" +astropy = ">=4.3.1" +cvxpy = ">=1.0.25" +matplotlib = ">=3.3.0" +networkx = ">=2.5.1" +numpy = ">=1.17.0" +pandas = ">=1.0.0" +scikit-learn = ">=0.22.0" +scipy = ">=1.0.1" +statsmodels = ">=0.10.1" +xlsxwriter = ">=1.3.7" + [[package]] name = "robin-stocks" version = "2.1.0" @@ -4454,6 +4541,14 @@ python-versions = ">=3.7.0" [package.dependencies] h11 = ">=0.9.0,<1" +[[package]] +name = "xlsxwriter" +version = "3.0.3" +description = "A Python module for creating Excel XLSX files." +category = "main" +optional = false +python-versions = ">=3.4" + [[package]] name = "yarl" version = "1.7.2" @@ -4515,7 +4610,7 @@ prediction = ["tensorflow"] [metadata] lock-version = "1.1" python-versions = "^3.8,<3.10" -content-hash = "2345d9d5b2d65ab5b131f5a38f6264ee13ea4c6c3145ec492f7a10fecce28902" +content-hash = "ac9d9fb58b8e0435ed6cd04eb19dbcd12a84a0680eb590b766632d4bbfe875dc" [metadata.files] absl-py = [ @@ -4624,6 +4719,31 @@ appnope = [ {file = "appnope-0.1.3-py2.py3-none-any.whl", hash = "sha256:265a455292d0bd8a72453494fa24df5a11eb18373a60c7c0430889f22548605e"}, {file = "appnope-0.1.3.tar.gz", hash = "sha256:02bd91c4de869fbb1e1c50aafc4098827a7a54ab2f39d9dcba6c9547ed920e24"}, ] +arch = [ + {file = "arch-5.2.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:7ee91f1acb4a57a8252d0dfbf0f32c32affda00bcbefda16abd8c8d8eb3f3376"}, + {file = "arch-5.2.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:98cb7980e6b6770d1e424fbf8647e63b1cf5d629f42e67c6fc041c5221309a52"}, + {file = "arch-5.2.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:462a53f360d153567005509976b5662e928f3b60d5d1b11735e1d36d837e37b7"}, + {file = "arch-5.2.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1d68d28c1557b098bce918b2e51c11708789ff6089e92374cf2b2e5b88392a80"}, + {file = "arch-5.2.0-cp310-cp310-win_amd64.whl", hash = "sha256:747d7a76ce9c71dead86211c33be1607ecc89a34e1367a279cd62ce80066724f"}, + {file = "arch-5.2.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:8ff2713842e5957e78fd80ad70459c6673bab1b28768e09c6ca3ea01ec2f1330"}, + {file = "arch-5.2.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8a88fe23045febd1ca4dc04ce889b86af12ac4a50a20cb3937384fe58abc4de5"}, + {file = "arch-5.2.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:df5eccc7c856b24f5f5e6a1483985395c11b885c61592572ed4270da849fe3dc"}, + {file = "arch-5.2.0-cp37-cp37m-win32.whl", hash = "sha256:dc71da6266bb43e1e1b2e5e05901def9bacab275634706875c95b1fefa6d0a9a"}, + {file = "arch-5.2.0-cp37-cp37m-win_amd64.whl", hash = "sha256:06fab3d54c20975a79250d600733d737804f7ec7a888836d38d2128ee40cdc25"}, + {file = "arch-5.2.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:62063cb61d0fbcdbd5245b0892558501fcf1ad420acbcd94f3a96443ee0c95c8"}, + {file = "arch-5.2.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:4a9763a2387157f091161ed5415965c0c3aca68c6df730a00951a4d62e1a49a9"}, + {file = "arch-5.2.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:331cfa3e58e5f5917604307638418f5278a64d3654cae175bfb4401533db0752"}, + {file = "arch-5.2.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:be21cc3ffbcc31f2fccd3ea76ff480929e0e5a21434f0dbf8544fc6ba440ba7d"}, + {file = "arch-5.2.0-cp38-cp38-win32.whl", hash = "sha256:decbd0c2c66c6244c50bbca2d6f3b321294ec616b3764d9e8bbfd6853f5f6c5c"}, + {file = "arch-5.2.0-cp38-cp38-win_amd64.whl", hash = "sha256:202b94282048caf4dcd72d8273ca4c03c9b02c7f5bc759b1be292ff8933b5f22"}, + {file = "arch-5.2.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:d2bd9a110023193095c81586840b188b6144aa5e70d2794f8e57223f7a468c9a"}, + {file = "arch-5.2.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:7b9881d99e26a669f7dc9eec709567fa029518b8cdb52bd6c30c10a50a6e4b20"}, + {file = "arch-5.2.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5ab0b59cfd019687d029c5cd9c2b09179b2ac5135fd0ed46e3ae81fcbd705f6f"}, + {file = "arch-5.2.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7c9512f097b4db724d56f5a21ef23fd779162bda25c2d87f592d765b4cfd5fef"}, + {file = "arch-5.2.0-cp39-cp39-win32.whl", hash = "sha256:e994e119b5466d63e47a61d6324ae460777b8d5519ee6095f98b480dd633cbb7"}, + {file = "arch-5.2.0-cp39-cp39-win_amd64.whl", hash = "sha256:e5bb8c72af1a5e90c890d01d01ed8c2a00bfd81c944592b6374eff61df9ede85"}, + {file = "arch-5.2.0.tar.gz", hash = "sha256:2dfd1b5f62b72625b8ed430ae0a3e011bbe24b9147c0164bc9e48bf5202dc6ab"}, +] argon2-cffi = [ {file = "argon2-cffi-21.3.0.tar.gz", hash = "sha256:d384164d944190a7dd7ef22c6aa3ff197da12962bd04b17f64d4e93d934dba5b"}, {file = "argon2_cffi-21.3.0-py3-none-any.whl", hash = "sha256:8c976986f2c5c0e5000919e6de187906cfd81fb1c72bf9d88c01177e77da7f80"}, @@ -4667,6 +4787,26 @@ astroid = [ {file = "astroid-2.11.3-py3-none-any.whl", hash = "sha256:f1af57483cd17e963b2eddce8361e00fc593d1520fe19948488e94ff6476bd71"}, {file = "astroid-2.11.3.tar.gz", hash = "sha256:4e5ba10571e197785e312966ea5efb2f5783176d4c1a73fa922d474ae2be59f7"}, ] +astropy = [ + {file = "astropy-5.0.4-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:89690dc5a0b81be16cc2db2a565f9a5b01901cb29124e9c96a60b8115359d425"}, + {file = "astropy-5.0.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:37f8a52a091f9f652e1389453eab727e1546153b6bfe29e88c3095ba2abc97e1"}, + {file = "astropy-5.0.4-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:64e6fbd475f7ddf79b8a11017c5ef06e8a067d0ceb1385f1bfb9c6b6f6d15734"}, + {file = "astropy-5.0.4-cp310-cp310-win32.whl", hash = "sha256:90be582e150b42a32ea166d3d622e42a489ec354890dcdefcbd6f1e6013f7fa5"}, + {file = "astropy-5.0.4-cp310-cp310-win_amd64.whl", hash = "sha256:304e83dfb7235e2aa3d889b6b90a5b8032acaa887be01d77cd74a2856e6c5eef"}, + {file = "astropy-5.0.4-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:87416b21419f7718b6ceeaa5df31550ecd3b93937af77e5df1743f4cf4d5deba"}, + {file = "astropy-5.0.4-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:60dbda630ad1ba552c387f54898e733a09f0a8482eb1e855f222ec1e93445639"}, + {file = "astropy-5.0.4-cp38-cp38-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:c8ff2e6a3d58e26b9950d39a4496ab4092982a1c83b551c05309776eb585804f"}, + {file = "astropy-5.0.4-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:3ba320708b175ff87d9bbaba43104a98dfd8f2764b5e0ae40a86e27f25046fad"}, + {file = "astropy-5.0.4-cp38-cp38-win32.whl", hash = "sha256:b3a97c8aec1b6e84f17710c004b9b3bc3dff8d036736c051b882f63e1c79fe25"}, + {file = "astropy-5.0.4-cp38-cp38-win_amd64.whl", hash = "sha256:9c584d41a8bc3446aa7dc24102dfdf6247d488dbecd1f1dc433ed2c5f8101279"}, + {file = "astropy-5.0.4-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:6f69a07773d5114c83152aa6bd20d88858534960c45d211312e65f5e1ad14f60"}, + {file = "astropy-5.0.4-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:50d8c58a232b34cb969186418b4b6314a22f25dc8a7ac6ea306f115316b07932"}, + {file = "astropy-5.0.4-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:fdcf04de88946068a1abbb4ea8664dee8b7cd221ca547d00cf10fc9db76de3ce"}, + {file = "astropy-5.0.4-cp39-cp39-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:18c916417803273bfb6cfc56c7d9dca37fefa9d05c259d29346d3040e51184a6"}, + {file = "astropy-5.0.4-cp39-cp39-win32.whl", hash = "sha256:3a23ca012799969deebe1e64b72c3095c90e6861d8a2e8c989382b333d418aca"}, + {file = "astropy-5.0.4-cp39-cp39-win_amd64.whl", hash = "sha256:d2b2e1f23f5cf91a9067028ec09d8d4daf67c2027707563c47e10ed9009fefd5"}, + {file = "astropy-5.0.4.tar.gz", hash = "sha256:001184f1a9c3f526a363883ce28efb9cbf076df3d151ca3e131509a248f0dfb9"}, +] asttokens = [ {file = "asttokens-2.0.5-py2.py3-none-any.whl", hash = "sha256:0844691e88552595a6f4a4281a9f7f79b8dd45ca4ccea82e5e05b4bbdb76705c"}, {file = "asttokens-2.0.5.tar.gz", hash = "sha256:9a54c114f02c7a9480d56550932546a3f1fe71d8a02f1bc7ccd0ee3ee35cf4d5"}, @@ -5924,6 +6064,10 @@ nest-asyncio = [ {file = "nest_asyncio-1.5.5-py3-none-any.whl", hash = "sha256:b98e3ec1b246135e4642eceffa5a6c23a3ab12c82ff816a92c612d68205813b2"}, {file = "nest_asyncio-1.5.5.tar.gz", hash = "sha256:e442291cd942698be619823a17a86a5759eabe1f8613084790de189fe9e16d65"}, ] +networkx = [ + {file = "networkx-2.8-py3-none-any.whl", hash = "sha256:1a1e8fe052cc1b4e0339b998f6795099562a264a13a5af7a32cad45ab9d4e126"}, + {file = "networkx-2.8.tar.gz", hash = "sha256:4a52cf66aed221955420e11b3e2e05ca44196b4829aab9576d4d439212b0a14f"}, +] nodeenv = [ {file = "nodeenv-1.6.0-py2.py3-none-any.whl", hash = "sha256:621e6b7076565ddcacd2db0294c0381e01fd28945ab36bcf00f41c5daf63bef7"}, {file = "nodeenv-1.6.0.tar.gz", hash = "sha256:3ef13ff90291ba2a4a7a4ff9a979b63ffdd00a464dbe04acf0ea6471517a4c2b"}, @@ -6324,6 +6468,37 @@ pydantic = [ {file = "pydantic-1.8.2-py3-none-any.whl", hash = "sha256:fec866a0b59f372b7e776f2d7308511784dace622e0992a0b59ea3ccee0ae833"}, {file = "pydantic-1.8.2.tar.gz", hash = "sha256:26464e57ccaafe72b7ad156fdaa4e9b9ef051f69e175dbbb463283000c05ab7b"}, ] +pyerfa = [ + {file = "pyerfa-2.0.0.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:278832de7803f2fb0ef4b14263200f98dfdb3eaa78dc63835d93796fd8fc42c6"}, + {file = "pyerfa-2.0.0.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:629248cebc8626a52e80f69d4e2f30cc6e751f57803f5ba7ec99edd09785d181"}, + {file = "pyerfa-2.0.0.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:3285d95dfe398a931a633da961f6f1c0b8690f2a3b1c510a4efe639f784cd9c7"}, + {file = "pyerfa-2.0.0.1-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:177f50f0e8354f1a7115c2d4784668b365f1cc2f2c7d1e2f4ddf354160559b32"}, + {file = "pyerfa-2.0.0.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:041939a7554a98b72885904ffddd8882567191bee62358727679448480174c31"}, + {file = "pyerfa-2.0.0.1-cp310-cp310-win32.whl", hash = "sha256:f9e149bc3d423ae891f6587c1383fd471ae07744b88152e66b5e9f64a8bc9006"}, + {file = "pyerfa-2.0.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:f00dc4fc48a16eb39fd0121f2f06c03ee762b79a207cc5b0bc17d94191b51302"}, + {file = "pyerfa-2.0.0.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:1ba3668e1e181a678ce788d23a4f8666aabd8518f77fdde5157ba4744bc73d4a"}, + {file = "pyerfa-2.0.0.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b8f08f6e6d75a261bb92b707bea19eba2e46a8fcbfb499b789f3eb0d0352ea00"}, + {file = "pyerfa-2.0.0.1-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:da89304d6b25ac056e470f44f85770b04c9674eced07a7f93b5eb0ce1edaabd9"}, + {file = "pyerfa-2.0.0.1-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:36738ba75e7a69e0ea6a7e96a5d33a852816427e7e94e7089c188ef920b02669"}, + {file = "pyerfa-2.0.0.1-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:5c077aed4ccd585c1fe2f96ada8edb66e9d27b4ae8ff13ea2783283b298ba0c6"}, + {file = "pyerfa-2.0.0.1-cp37-cp37m-win32.whl", hash = "sha256:0833f8ebba9f84a19a04ee5ca5aa90be75729abfbb8328e7a6d89ed1b04e058c"}, + {file = "pyerfa-2.0.0.1-cp37-cp37m-win_amd64.whl", hash = "sha256:e86c08c9c0b75e448818473c6d709e3887a439c05a1aa34042d26774251422b7"}, + {file = "pyerfa-2.0.0.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:b935fa9d10dfd7206760859236640c835aa652609c0ae8a6584593324eb6f318"}, + {file = "pyerfa-2.0.0.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:67711a748821c5d91f7a8907b9125094dfc3e5ab6a6b7ad8e207fd6afbe6b37f"}, + {file = "pyerfa-2.0.0.1-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:d2c10838241aaf17279468dcc731cb2c09bfb7dd7b340c0f527fd70c7c9e53d1"}, + {file = "pyerfa-2.0.0.1-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:37249e1e2b378d1f56e9379e4bb8f2cf87645c160a8a3e92166a1b7bb7ad7ea6"}, + {file = "pyerfa-2.0.0.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:f76fb4b64a87da2af9d0b6b79cc25e1ecc5b4143b2b3c8c9f10b221748c5db4d"}, + {file = "pyerfa-2.0.0.1-cp38-cp38-win32.whl", hash = "sha256:486e672c52bf58eab61140968660ac7fb3b756116b53c26c334ae95dadd943ee"}, + {file = "pyerfa-2.0.0.1-cp38-cp38-win_amd64.whl", hash = "sha256:d603f1e8123f98a0593433aa6dad4ba03f0b0ceef4cb3e96f9a69aa7ab8d5c61"}, + {file = "pyerfa-2.0.0.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:ef5590b2075c50395b958f102988e519e339d96509dfdca0360f26dde94c47e7"}, + {file = "pyerfa-2.0.0.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c7ca8c98842f1ae10c1fbcea0e03a41ddc13456da88da2dc9b8335a8c414d7a3"}, + {file = "pyerfa-2.0.0.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:d3e7dedce1d7e4e044f6f81d192b1f6b373c8ad6716aa8721ec6d3cf4d36f5f3"}, + {file = "pyerfa-2.0.0.1-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:690116a6026ee84ce5fec794c9e21bdc8c0ac8345d6722323810181486745068"}, + {file = "pyerfa-2.0.0.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:da5ee24eaf5e5f841f36885ea16461800b7bea11df5b657bcff85d7a7f51d2d8"}, + {file = "pyerfa-2.0.0.1-cp39-cp39-win32.whl", hash = "sha256:7895b7e6f3bc36442d1969bf3bda5a4c3b661be7a5a468798369cbd5d81023d8"}, + {file = "pyerfa-2.0.0.1-cp39-cp39-win_amd64.whl", hash = "sha256:63a83c35cea8c5d50d53c18089f1e625c0ffc59a7a5b8d44e0f1b3ec5288f183"}, + {file = "pyerfa-2.0.0.1.tar.gz", hash = "sha256:2fd4637ffe2c1e6ede7482c13f583ba7c73119d78bef90175448ce506a0ede30"}, +] pyex = [ {file = "pyEX-0.5.0-py2.py3-none-any.whl", hash = "sha256:8860b8eb9c15d91e5f552786fbe8f8ecd46c4c4931e5cb82ba41187eb603f742"}, {file = "pyEX-0.5.0.tar.gz", hash = "sha256:e85c392733aec3717b00d05640bd7efcfc87bf949064a7f31112293fe395c27e"}, @@ -6881,6 +7056,10 @@ rich = [ {file = "rich-10.16.2-py3-none-any.whl", hash = "sha256:c59d73bd804c90f747c8d7b1d023b88f2a9ac2454224a4aeaf959b21eeb42d03"}, {file = "rich-10.16.2.tar.gz", hash = "sha256:720974689960e06c2efdb54327f8bf0cdbdf4eae4ad73b6c94213cad405c371b"}, ] +riskfolio-lib = [ + {file = "Riskfolio-Lib-3.1.1.tar.gz", hash = "sha256:5c56d52f85e28bad712bdb2f9c3556b41aa973daa1ad2c1e9441bf604f164344"}, + {file = "Riskfolio_Lib-3.1.1-py3-none-any.whl", hash = "sha256:847891d434ee5ed36cbfcb994093c7ebd18ef0d3a0983b2aec3ba627e50ca3d7"}, +] robin-stocks = [ {file = "robin_stocks-2.1.0-py3-none-any.whl", hash = "sha256:f746640e08d138fda2e1da42444e2881c3fb1ce43485f332e5079a42b0a78d57"}, {file = "robin_stocks-2.1.0.tar.gz", hash = "sha256:3d6b1d97ecf3191897d09c9dc430b57c6183a38d4c66a64f9c62a8f015bb0ae9"}, @@ -7543,6 +7722,10 @@ wsproto = [ {file = "wsproto-1.1.0-py3-none-any.whl", hash = "sha256:2218cb57952d90b9fca325c0dcfb08c3bda93e8fd8070b0a17f048e2e47a521b"}, {file = "wsproto-1.1.0.tar.gz", hash = "sha256:a2e56bfd5c7cd83c1369d83b5feccd6d37798b74872866e62616e0ecf111bda8"}, ] +xlsxwriter = [ + {file = "XlsxWriter-3.0.3-py3-none-any.whl", hash = "sha256:df0aefe5137478d206847eccf9f114715e42aaea077e6a48d0e8a2152e983010"}, + {file = "XlsxWriter-3.0.3.tar.gz", hash = "sha256:e89f4a1d2fa2c9ea15cde77de95cd3fd8b0345d0efb3964623f395c8c4988b7f"}, +] yarl = [ {file = "yarl-1.7.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:f2a8508f7350512434e41065684076f640ecce176d262a7d54f0da41d99c5a95"}, {file = "yarl-1.7.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:da6df107b9ccfe52d3a48165e48d72db0eca3e3029b5b8cb4fe6ee3cb870ba8b"}, diff --git a/portfolio/allocation/.gitkeep b/portfolio/allocation/.gitkeep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/portfolio/allocation/50_30_10_10_Portfolio.xlsx b/portfolio/allocation/50_30_10_10_Portfolio.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..cd39d7299f00b59361d7e5e90aaea4cc52713fe9 GIT binary patch literal 17970 zcmeIab95$qvo;)SVrydCwmES!aWb)O+qP}n$;7tpiEY2x`#k5}`s#O7=ky=l z_r1EWT76en{i?dEu3J_T7z7yr3;+TE001ALbmWCH7!Uve9Si^f2>=2}UC_$X-oVmc zThYbZz)q9K*}@zz7X*kb8vy9@`v2Yj2Wy}_URn~E9zO8G_d|DBskH=0C|@1U6I)5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M@lCc;7+OVo8GOAbukdKSuNuVAD{DTS?Oc_Fyf zpfT$pRR;UQcV4*5@{SOS)K+18{!y4o4qEmglHppzqGG%1;Wpz48tFQeHk;f!f6h_W ziz65PdP~6KhOsr&%X&%6JcMp>Mr}&|2QZN-d+&Vv2Vqhhn=Q@kF2On*C3e`DjBo9x z;Sm7RO`i6yT!yp>KNeu(iOLD&>$w*Y+N7R-Qs~*kZKD=b8&5wuEIQA!x0}<0tO3dR zD(NLoFw9yf=NfDl)7<2%=|es~I10@0)wOcl0yVWV!UwpDmvx6@bhRGM7?nGx-LQKD ztMUOpDjjA5N@unJYqky}2*S21+r9@}69+S*6E3%xG zi#913j?J9KhR%aqZLgtJ&#T#i21$vTc5VpP}r zhRTwZNb;bGpiRBT(1m2q!IaW|xbW9`Y z4X4}^O;!iYJ=Y$(|53<3&s~|V>UIX|9BPftY+;&|vo42iE^g1}6NxQPD-d!jmG?5X zKwT<`cM|Dii7!S-m@nVg!}0UHr@_)WU|J5Fb3UX#KPjBr1-eYN6@e`~BBnJPJS{>QBzZKmVD;e^)O4`}hxk zEg>uU?*jgv%>LiNKaSm>O@+Tv+kXfCJHhwwz+a!Nj{i5^_jftJ6FC2p^zE~j^&6e@ zcku7zvA@7@pIov}@LyE2-=V*AQ2v4fBm5WicSg$Z5`Je7{3RjmbH?dkcm5w-g5Rb5 zJ{t9xlv|uXrTji9^}B$7Z|?pD2LP}m0r-EmdViPl@7>M6OKBzr0Qiqy=kM@;??n9_ zF8Nt)`oHjh^`(AC|K0%j3y(YU4{dg{`5FWfj_?eAODVBl>h($ literal 0 HcmV?d00001 diff --git a/portfolio/allocation/60_40_Portfolio.xlsx b/portfolio/allocation/60_40_Portfolio.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..bc503fbb0f8f29d87e84e787ceb00b10035369e2 GIT binary patch literal 17533 zcmeHvWpEtn&aNqDW@ct~%*>9NnVA{Kl$a@IW=PD;5VK=uW@cu*-raNV?&j=Qx9;!n z^i)mPRQIF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RCuwf&PuoeB!}n&V7or)tU)x8AL8X#VB!B!)74tHaJDzkR`~B8_Z@)StMp? zV)bWNH4dPmPmqxBww+oi|fZ}SDmf zhFYLk0S4}RAa)_Tc@c9ub)bCW^<8Mu%4=Vro$0f~G^5;B7)ykX0?Rs#`i4M{L36t1 zk=3sTMA$O8F13U@N;N3xT+EY6$R5J5YN_5dfX?#n^IHs{CaB$`BoosJ=4%=Fbca8RWx;ZZbnRFYX?&FwHUV9;;mlb2sSh$6tsCQ^c}JrVoM(f zN|(?}W{ut#i~n$z4zn)^Lq*Y&0PF@{||2|keB|ufWOa0{~P$*zVn@a`-2|(ofY~O z`1e`SzXEsP-;wY?Pmca7=hs=lKPAb&H;n%>8Tc#s*J-3b!BFqRN$=o4XOn(~{yN|A zC-f5W59qJc4!=tHwW94Z>&awSfRuAJ}W&K~qRbKkT UySw~028#eR@$PYn0>AzGKaFj3l>h($ literal 0 HcmV?d00001 diff --git a/portfolio/allocation/Fixed_Income_Portfolio.xlsx b/portfolio/allocation/Fixed_Income_Portfolio.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..234c22aeb67c6a58ab17dcc5b7ee0f52232f5da0 GIT binary patch literal 16638 zcmeIZV{~O}vo;*7W81c^4m-AO+qTuQI<{>)9ou%&v7I-2pYyzXKmF`?eB=9l&ipaw zSYyts##;BR>#kZ?Rmn;KgCGNd0YCr%01yC_j=WHX0s;V_g8={_0YCt02-;XX8d*E) zD7x7iIcU+kT3O=ff&h_c0|0$K|G&ro;1wuOkdgpqfDgX#|IquX)LMcol&=Bjjjbfx zVY3=$jmy1b#?8@ z)(Vdj2PM*io{eC^Z^y#Jo5o#*q&qMTh&7E^AVDG5w1u+3@O3LuZA=^C zIiNzywU;$;P3%bd9n5op$JV@-MV6;j@?oS7rp5l6=wLu2GQz!U7&h6CwGLBqPGSbaZ)mU^w7Z<-(Ew8 zALiG;!wX2beErr&py=%@wg%S_l}C)V-bIEDuZS4{Eb7zY{W`L`&K-3!OmM%$Tpodl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px3x%l__A13(aB>&UEf6fg58~De$_mgY;+XV6N!2g`1{5x>}^Zx_>&r_AZ+xdM? z?k`I+pStVcrsjSJ|30bn7Z~zWWb_ICYi{Rv=KzpJ2rH}IdG+rQud0B=M9|HnS=?^gb^b@_KIf+PR{ z|JBI+9sZwProY1%$o>ZZpPtk2=-QJ9 z|H+R2h5c+c(ENP?|A{O8-PV6{Y=5`4MfZ1G|1aYzCkgr)E`N-O!UIfyMqK?L?GJ$e E2UR@x8UO$Q literal 0 HcmV?d00001 diff --git a/portfolio/allocation/SP_500_Portfolio.xlsx b/portfolio/allocation/SP_500_Portfolio.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..7ba0a3d4e3510587ff78559302e88354430b7e90 GIT binary patch literal 44809 zcmeEtWmBACvnKBD65QP-xVr`hcXtB8-CYxcLy$mVaQEPDgS!TIciBnavsJsb=O3Kq z!$8#xUEO_O(tSUmrU(s#0|5tt0099(0RbF&W{QG@fFOW_fWU@8fYO(Ac5<_Hax>QS z{%rZhkk!l4fxG|)iarkl3jF#1|Mfq(1LY~oiqISw5$7TAro({NQc|g(`se{40BYU# zO2um+zvK+N=kpxpil|xE=?;fQ>T3~a+HV;K742o~6ov8mn7?jyG%?(`dB=z^ul)F0 zF>t>k$+QsUVcLti@Cb`!3RPj7^iM$&Phk})GN?Cg;?8r3Z+_PuGs1k|Yf(~QoBgn} z|vnPSqQu}Nvnu`*NMsK^un(nVC=oW zLqn+jUj%Lduv6WD-%$ed6B$fkV^>RuFKn!TU;jUG{|B@6|0uoutFme@J4(d4+)L!p z{oGm-hJ>Q0xLg~BWnb! zL8?a2iior)7k79@TGvz=m-4MXOpm$Sxw{Nm1#fzfjzq??=8}BH;SDO8nM4-t668Nqr3%DU@j50#K}5*nu!5!Fq6c}L$SvjP`Viw{vnqdqE~OlRN@eKE6M zs`MLjptyY`0%+KLw5>MFbrqoWHnwo+x|Yi7#D4W-QOO?qM9Gcyz&R;9NRxLPs8`Q@ zIhy0$$A{QkHgqu@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A3A~nr{Y0C}N#mU1( z-^~f>xi#4@_SkraD*>51HjReD$2V`TKpog_0o^S-6lz61bs4#w%u6d@@E`XjQ@L*O zhqtqHA+D_O?O8%1MobGvor}j?U;7_hnl+zaF7K;6-L~dD*vXzy%(GdRA-q(sR@uvr z>Pj0f`nvnG+%WjvYK3$#vA=WWy>FR9@PhLDY%BbDu zGBz+aF}8yK(AZjkZ+xx4H;GhZr4&bnI@_>{*7tt*gsV10`IY*R_|4vKBpwNRCSrKc z>t2Jb8|Yc4;qx%bPFMl~aj!wUOMEF!QUtaD>wOgX*igaa>&zIcfH_ejQ=W4!3ml=> z<)q&?2KI2wbSJR+hs9<->@anc@;#c4FCnFn7D3!oIxQQt^vBxbwFxL2xc(31mGs@j>_Kj~nW~4p$E#VIZ9xLEQN}2Vg-`C51f`8;_;tg3 zCPlm3cQ3GCsU-;9a*N|$i&EhyE;7_9tB61YBa6lBb?gD~*E;-HUB?njN79tKv}aSn zDxr2-g1Id^w?6l}r10T&ie}0eD z1yiT~cYF=OYN{F0p#*@EBlN^!kRXe?G&-S@>KV21kl= "3.6" anyio==3.5.0; python_full_version >= "3.6.2" and python_version >= "3.7" appnope==0.1.3; platform_system == "Darwin" and python_version >= "3.8" and sys_platform == "darwin" and python_full_version >= "3.6.2" +arch==5.2.0; python_version >= "3.7" argon2-cffi-bindings==21.2.0; python_version >= "3.7" argon2-cffi==21.3.0; python_version >= "3.7" ascii-magic==1.6; python_version >= "3.5" astor==0.7.1; python_full_version >= "3.7.1" and python_full_version < "4.0.0" and python_version >= "3.8" astroid==2.11.3; python_full_version >= "3.6.2" +astropy==5.0.4; python_version >= "3.8" asttokens==2.0.5; python_full_version >= "3.6.2" and python_version >= "3.8" astunparse==1.6.3 async-generator==1.10; python_version >= "3.7" and python_version < "4.0" @@ -148,6 +150,7 @@ nbclient==0.5.13; python_full_version >= "3.7.0" and python_version >= "3.7" nbconvert==6.5.0; python_version >= "3.7" nbformat==5.3.0; python_full_version >= "3.7.0" and python_version >= "3.7" nest-asyncio==1.5.5; python_full_version >= "3.7.0" and python_version >= "3.7" +networkx==2.8; python_version >= "3.8" nodeenv==1.6.0; python_version >= "3.7" notebook-shim==0.1.0; python_version >= "3.7" notebook==6.4.11; python_version >= "3.7" @@ -195,6 +198,7 @@ pyasn1==0.4.8; python_version >= "3.6" and python_full_version < "3.0.0" and pyt pycodestyle==2.7.0; python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.5.0" pycoingecko==2.2.0 pycparser==2.21; python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.4.0" +pyerfa==2.0.0.1; python_version >= "3.8" pyex==0.5.0 pyflakes==2.3.1; python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.5.0" pygments==2.12.0; python_version >= "3.6" @@ -226,7 +230,7 @@ pytz==2022.1; python_full_version >= "3.7.1" and python_version >= "3.8" and pyt pyupgrade==2.32.0; python_version >= "3.7" pywin32==303; sys_platform == "win32" and platform_python_implementation != "PyPy" and python_version >= "3.7" and python_full_version >= "3.7.0" pywinpty==2.0.5; os_name == "nt" and python_version >= "3.7" -pyyaml==6.0; python_version >= "3.7" +pyyaml==6.0; python_version >= "3.8" pyzmq==22.3.0; python_full_version >= "3.7.0" and python_version >= "3.7" qdldl==0.1.5.post2; python_full_version >= "3.6.1" and python_full_version < "4.0.0" and python_version >= "3.7" qtconsole==5.3.0; python_version >= "3.7" @@ -238,6 +242,7 @@ reportlab==3.6.9; python_version >= "3.7" and python_version < "4" requests-oauthlib==1.3.1; python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.4.0" and python_version >= "3.6" requests==2.27.1; (python_version >= "2.7" and python_full_version < "3.0.0") or (python_full_version >= "3.6.0") rich==10.16.2; python_full_version >= "3.6.2" and python_full_version < "4.0.0" +riskfolio-lib==3.1.1; python_version >= "3.7" robin-stocks==2.1.0; python_version >= "3" rsa==4.8; python_version >= "3.6" and python_version < "4" and (python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version >= "3.6") scikit-learn==1.0.2; python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version >= "3.7" @@ -322,6 +327,7 @@ werkzeug==2.1.1; python_version >= "3.7" widgetsnbextension==3.6.0 wrapt==1.14.0; python_full_version >= "3.7.1" and python_full_version < "4.0.0" and (python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.5.0") and (python_version >= "3.5" and python_full_version < "3.0.0" or python_full_version >= "3.5.0" and python_version >= "3.5") and python_version >= "3.8" wsproto==1.1.0; python_version >= "3.7" and python_version < "4.0" and python_full_version >= "3.7.0" +xlsxwriter==3.0.3; python_version >= "3.7" yarl==1.7.2; python_version >= "3.6" yfinance==0.1.70 zipp==3.8.0; python_version < "3.10" and python_version >= "3.7" diff --git a/requirements.txt b/requirements.txt index f415c546e57..4d6181fd626 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,20 +5,19 @@ alpha-vantage==2.3.1 ansiwrap==0.8.4; python_version >= "3.6" anyio==3.5.0; python_full_version >= "3.6.2" and python_version >= "3.7" appnope==0.1.3; platform_system == "Darwin" and python_version >= "3.8" and sys_platform == "darwin" and python_full_version >= "3.6.2" +arch==5.2.0; python_version >= "3.7" argon2-cffi-bindings==21.2.0; python_version >= "3.7" argon2-cffi==21.3.0; python_version >= "3.7" ascii-magic==1.6; python_version >= "3.5" astor==0.7.1; python_full_version >= "3.7.1" and python_full_version < "4.0.0" and python_version >= "3.8" -astroid==2.11.3; python_full_version >= "3.6.2" +astropy==5.0.4; python_version >= "3.8" asttokens==2.0.5; python_full_version >= "3.6.2" and python_version >= "3.8" async-generator==1.10; python_version >= "3.7" and python_version < "4.0" async-timeout==4.0.2; python_version >= "3.6" -atomicwrites==1.4.0; python_version >= "3.7" and python_full_version < "3.0.0" and sys_platform == "win32" or sys_platform == "win32" and python_version >= "3.7" and python_full_version >= "3.4.0" attrs==21.4.0; python_full_version >= "3.7.0" and python_version >= "3.7" and python_version < "4.0" and (python_version >= "3.7" and python_full_version < "3.0.0" and python_version < "4.0" or python_version >= "3.7" and python_version < "4.0" and python_full_version >= "3.5.0") babel==2.10.1; python_version >= "3.7" backcall==0.2.0; python_full_version >= "3.6.2" and python_version >= "3.8" backports.zoneinfo==0.2.1; python_version < "3.9" and python_version >= "3.6" and (python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version >= "3.6") -bandit==1.7.4; python_version >= "3.7" beartype==0.7.1; python_version >= "3.8" and python_version < "4.0" and python_full_version >= "3.6.0" beautifulsoup4==4.11.1; python_full_version >= "3.6.0" and python_version >= "3.7" black==22.1.0; python_full_version >= "3.6.2" @@ -27,14 +26,11 @@ bs4==0.0.1 bt==0.2.9; (python_version >= "2.7" and python_full_version < "3.0.0") or (python_full_version >= "3.6.0") certifi==2021.10.8; python_full_version >= "3.7.1" and python_version < "4" and python_version >= "3.8" and python_full_version < "4.0.0" and (python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.6.0") and (python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version >= "3.7") cffi==1.15.0; python_version >= "3.7" -cfgv==3.3.1; python_full_version >= "3.6.1" and python_version >= "3.7" charset-normalizer==2.0.12; python_full_version >= "3.7.1" and python_version >= "3.8" and python_version < "4.0" and python_full_version < "4.0.0" and (python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.6.0") and (python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version >= "3.7") click==8.0.1; python_version >= "3.6" -codespell==2.1.0; python_version >= "3.5" -colorama==0.4.4; python_full_version >= "3.6.2" and python_full_version < "4.0.0" and (python_version >= "3.5" and python_full_version < "3.0.0" or python_full_version >= "3.5.0" and python_version >= "3.5") and platform_system == "Windows" and python_version >= "3.8" and (python_version >= "3.6" and python_full_version < "3.0.0" and sys_platform == "win32" or sys_platform == "win32" and python_version >= "3.6" and python_full_version >= "3.5.0") and sys_platform == "win32" and (python_version >= "3.7" and python_full_version < "3.0.0" and sys_platform == "win32" or sys_platform == "win32" and python_version >= "3.7" and python_full_version >= "3.5.0") and (python_version >= "3.7" and python_full_version < "3.0.0" and platform_system == "Windows" or platform_system == "Windows" and python_version >= "3.7" and python_full_version >= "3.5.0") and (python_version >= "3.6" and python_full_version < "3.0.0" and platform_system == "Windows" or python_full_version >= "3.5.0" and platform_system == "Windows" and python_version >= "3.6") +colorama==0.4.4; python_full_version >= "3.6.2" and python_full_version < "4.0.0" and (python_version >= "3.5" and python_full_version < "3.0.0" or python_full_version >= "3.5.0" and python_version >= "3.5") and platform_system == "Windows" and python_version >= "3.8" and (python_version >= "3.7" and python_full_version < "3.0.0" and sys_platform == "win32" or sys_platform == "win32" and python_version >= "3.7" and python_full_version >= "3.5.0") and (python_version >= "3.6" and python_full_version < "3.0.0" and platform_system == "Windows" or python_full_version >= "3.5.0" and platform_system == "Windows" and python_version >= "3.6") and sys_platform == "win32" commonmark==0.9.1; python_full_version >= "3.6.2" and python_full_version < "4.0.0" convertdate==2.4.0; python_version >= "3.7" and python_version < "4" -coverage==6.3.2; python_version >= "3.7" cryptography==36.0.2; python_version >= "3.7" and python_full_version < "3.0.0" and python_version < "4.0" or python_full_version >= "3.6.0" and python_version < "4" and python_version >= "3.7" cssselect==1.1.0; python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.4.0" cvxpy==1.2.0; python_full_version >= "3.6.1" and python_full_version < "4.0.0" and python_version >= "3.7" @@ -48,8 +44,6 @@ defusedxml==0.7.1; python_version >= "3.7" and python_full_version < "3.0.0" or degiro-connector==2.0.19; python_full_version >= "3.7.1" and python_full_version < "4.0.0" deprecation==2.1.0 detecta==0.0.5; python_version >= "3.6" -dill==0.3.4; python_full_version >= "3.6.2" -distlib==0.3.4; python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.5.0" and python_version >= "3.7" dnspython==2.2.1; python_version >= "3.6" and python_version < "4.0" docutils==0.16; python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.5.0" and python_version >= "3.7" ecos==2.0.10; python_full_version >= "3.6.1" and python_full_version < "4.0.0" and python_version >= "3.7" @@ -60,12 +54,10 @@ executing==0.8.3; python_full_version >= "3.6.2" and python_version >= "3.8" fastjsonschema==2.15.3; python_full_version >= "3.7.0" and python_version >= "3.7" fear-greed-index==0.1.4; python_version >= "3.7" ffn==0.3.6; python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" -filelock==3.6.0; python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.5.0" and python_version >= "3.7" financedatabase==1.0.2 finnhub-python==2.4.13 finviz==1.4.4 finvizfinance==0.14.0; python_version >= "3.5" -flake8==3.9.2; (python_version >= "2.7" and python_full_version < "3.0.0") or (python_full_version >= "3.5.0") fonttools==4.33.3; python_version >= "3.7" formulaic==0.3.3; python_full_version >= "3.7.1" and python_full_version < "4.0.0" and python_version >= "3.8" fred==3.1 @@ -80,12 +72,10 @@ grpcio==1.45.0; python_full_version >= "3.7.1" and python_full_version < "4.0.0" h11==0.13.0; python_version >= "3.7" and python_version < "4.0" and python_full_version >= "3.7.0" hijri-converter==2.2.3; python_version >= "3.6" holidays==0.11.3.1; python_version >= "3.6" -identify==2.4.12; python_version >= "3.7" idna==3.3; python_full_version >= "3.7.1" and python_version >= "3.8" and python_version < "4" and python_full_version < "4.0.0" and (python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.6.0") and (python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version >= "3.7") imagesize==1.3.0; python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.4.0" and python_version >= "3.7" importlib-metadata==4.11.3; python_version < "3.10" and python_version >= "3.7" inflection==0.5.1; python_version >= "3.6" -iniconfig==1.1.1; python_version >= "3.7" interface-meta==1.3.0; python_version >= "3.8" and python_version < "4.0" and python_full_version >= "3.7.1" and python_full_version < "4.0.0" investpy==1.0.8; python_version >= "3.7" ipykernel==6.13.0; python_version >= "3.7" @@ -94,7 +84,6 @@ ipython-genutils==0.2.0; python_version >= "3.7" ipython==8.2.0; python_full_version >= "3.6.2" and python_version >= "3.8" ipywidgets==7.7.0 iso8601==0.1.16 -isort==5.10.1; python_full_version >= "3.6.2" and python_version < "4.0" jedi==0.18.1; python_full_version >= "3.6.2" and python_version >= "3.8" jinja2==3.0.3; python_version >= "3.6" joblib==1.1.0; python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version >= "3.7" @@ -111,31 +100,25 @@ jupyterlab-widgets==1.1.0; python_version >= "3.6" jupyterlab==3.3.4; python_version >= "3.7" kiwisolver==1.4.2; python_version >= "3.7" korean-lunar-calendar==0.2.1; python_version >= "3.7" and python_full_version >= "3.7.0" -lazy-object-proxy==1.7.1; python_version >= "3.6" and python_full_version >= "3.6.2" linearmodels==4.26; python_version >= "3.8" lxml==4.8.0; python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version >= "3.7" m2r2==0.2.8; python_version >= "3.7" -markdown-it-py==1.1.0; python_version >= "3.6" and python_version < "4.0" markupsafe==2.1.1; python_version >= "3.7" matplotlib-inline==0.1.3; python_full_version >= "3.6.2" and python_version >= "3.8" matplotlib==3.5.1; python_version >= "3.7" -mccabe==0.6.1; python_full_version >= "3.6.2" -mdit-py-plugins==0.2.8; python_version >= "3.6" and python_version < "4.0" mistune==0.8.4; python_version >= "3.7" -mock==4.0.3; python_version >= "3.6" more-itertools==8.12.0; python_version >= "3.6" mplfinance==0.12.8b9 multidict==6.0.2; python_version >= "3.7" multitasking==0.0.10 mypy-extensions==0.4.3; python_version >= "3.8" and python_full_version >= "3.6.2" mypy==0.930; python_version >= "3.6" -myst-parser==0.15.2; python_version >= "3.6" nbclassic==0.3.7; python_version >= "3.7" nbclient==0.5.13; python_full_version >= "3.7.0" and python_version >= "3.7" nbconvert==6.5.0; python_version >= "3.7" nbformat==5.3.0; python_full_version >= "3.7.0" and python_version >= "3.7" nest-asyncio==1.5.5; python_full_version >= "3.7.0" and python_version >= "3.7" -nodeenv==1.6.0; python_version >= "3.7" +networkx==2.8; python_version >= "3.8" notebook-shim==0.1.0; python_version >= "3.7" notebook==6.4.11; python_version >= "3.7" numpy==1.21.2; python_version >= "3.7" and python_version < "3.11" @@ -155,17 +138,14 @@ papermill==2.3.4; python_version >= "3.6" parso==0.8.3; python_full_version >= "3.6.2" and python_version >= "3.8" pathspec==0.9.0; python_full_version >= "3.6.2" patsy==0.5.2; python_version >= "3.8" -pbr==5.8.1; python_version >= "3.7" pexpect==4.8.0; sys_platform != "win32" and python_version >= "3.8" and python_full_version >= "3.6.2" pickleshare==0.7.5; python_full_version >= "3.6.2" and python_version >= "3.8" pillow==9.1.0; python_version >= "3.7" and python_version < "4" -platformdirs==2.5.2; python_version >= "3.7" and python_full_version >= "3.6.2" and (python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.5.0" and python_version >= "3.7") +platformdirs==2.5.2; python_version >= "3.7" and python_full_version >= "3.6.2" plotly==5.7.0; python_version >= "3.6" -pluggy==1.0.0; python_version >= "3.7" pmdarima==1.8.5; python_version >= "3.7" praw==7.5.0; python_version >= "3.6" and python_version < "4.0" prawcore==2.3.0; python_version >= "3.6" and python_version < "4.0" -pre-commit==2.18.1; python_version >= "3.7" prometheus-client==0.14.1; python_version >= "3.7" prompt-toolkit==3.0.29; python_full_version >= "3.6.2" property-cached==1.6.4; python_version >= "3.8" @@ -174,16 +154,14 @@ psaw==0.0.12; python_version >= "3" psutil==5.9.0; python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.4.0" and python_version >= "3.7" ptyprocess==0.7.0; os_name != "nt" and python_version >= "3.8" and sys_platform != "win32" and python_full_version >= "3.6.2" pure-eval==0.2.2; python_full_version >= "3.6.2" and python_version >= "3.8" -py==1.11.0; python_full_version >= "3.7.0" and python_version >= "3.7" and implementation_name == "pypy" +py==1.11.0; implementation_name == "pypy" and python_version >= "3.7" and python_full_version >= "3.7.0" pyally==1.1.2 -pycodestyle==2.7.0; python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.5.0" pycoingecko==2.2.0 pycparser==2.21; python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.4.0" +pyerfa==2.0.0.1; python_version >= "3.8" pyex==0.5.0 -pyflakes==2.3.1; python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.5.0" pygments==2.12.0; python_version >= "3.6" pyhdfe==0.1.0; python_version >= "3.8" -pylint==2.13.7; python_full_version >= "3.6.2" pyluach==1.4.1; python_version >= "3.7" and python_full_version >= "3.7.0" pymeeus==0.5.11; python_version >= "3.7" and python_version < "4" pymongo==3.11.0; (python_version >= "2.7" and python_full_version < "3.0.0") or (python_full_version >= "3.4.0") @@ -196,10 +174,6 @@ pyportfolioopt==1.5.2; python_full_version >= "3.6.1" and python_full_version < pyprind==2.11.3; python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" pyrsistent==0.18.1; python_version >= "3.7" pysocks==1.7.1; python_version >= "3.7" and python_full_version < "3.0.0" and python_version < "4.0" or python_full_version >= "3.6.0" and python_version < "4" and python_version >= "3.7" -pytest-cov==3.0.0; python_version >= "3.6" -pytest-mock==3.7.0; python_version >= "3.7" -pytest-recording==0.12.0; python_version >= "3.5" -pytest==6.2.5; python_version >= "3.6" python-binance==1.0.16 python-coinmarketcap==0.2 python-dateutil==2.8.2; python_full_version >= "3.7.1" and python_version >= "3.8" and python_full_version < "4.0.0" and (python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.3.0" and python_version >= "3.7") and (python_version >= "3.5" and python_full_version < "3.0.0" or python_full_version >= "3.3.0" and python_version >= "3.5") @@ -207,10 +181,9 @@ python-dotenv==0.19.2; python_version >= "3.5" pytrends==4.8.0 pytz-deprecation-shim==0.1.0.post0; python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version >= "3.6" pytz==2022.1; python_full_version >= "3.7.1" and python_version >= "3.8" and python_full_version < "4.0.0" -pyupgrade==2.32.0; python_version >= "3.7" pywin32==303; sys_platform == "win32" and platform_python_implementation != "PyPy" and python_version >= "3.7" and python_full_version >= "3.7.0" pywinpty==2.0.5; os_name == "nt" and python_version >= "3.7" -pyyaml==6.0; python_version >= "3.7" +pyyaml==6.0; python_version >= "3.8" pyzmq==22.3.0; python_full_version >= "3.7.0" and python_version >= "3.7" qdldl==0.1.5.post2; python_full_version >= "3.6.1" and python_full_version < "4.0.0" and python_version >= "3.7" qtconsole==5.3.0; python_version >= "3.7" @@ -222,6 +195,7 @@ reportlab==3.6.9; python_version >= "3.7" and python_version < "4" requests-oauthlib==1.3.1; python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.4.0" requests==2.27.1; (python_version >= "2.7" and python_full_version < "3.0.0") or (python_full_version >= "3.6.0") rich==10.16.2; python_full_version >= "3.6.2" and python_full_version < "4.0.0" +riskfolio-lib==3.1.1; python_version >= "3.7" robin-stocks==2.1.0; python_version >= "3" scikit-learn==1.0.2; python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version >= "3.7" scipy==1.8.0; python_version >= "3.8" and python_version < "3.11" and python_full_version >= "3.7.1" and python_full_version < "4.0.0" and (python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.6.0") and (python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version >= "3.7") @@ -232,7 +206,7 @@ selenium==4.1.3; python_version >= "3.7" and python_version < "4.0" send2trash==1.8.0; python_version >= "3.7" sentiment-investor==2.1.0; python_version >= "3.8" and python_version < "4.0" setuptools-scm==6.4.2; python_version >= "3.8" -six==1.16.0; python_full_version >= "3.7.1" and python_version >= "3.8" and python_full_version < "4.0.0" and (python_version >= "3.8" and python_full_version < "3.0.0" or python_full_version >= "3.3.0" and python_version >= "3.8") and (python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.3.0") and (python_version >= "3.5" and python_full_version < "3.0.0" or python_full_version >= "3.3.0" and python_version >= "3.5") and (python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.5.0" and python_version >= "3.7") and (python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.3.0" and python_version >= "3.7") +six==1.16.0; python_full_version >= "3.7.1" and python_version >= "3.8" and python_full_version < "4.0.0" and (python_version >= "3.8" and python_full_version < "3.0.0" or python_full_version >= "3.3.0" and python_version >= "3.8") and (python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.3.0") and (python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.3.0" and python_version >= "3.7") smmap==5.0.0; python_version >= "3.7" sniffio==1.2.0; python_version >= "3.7" and python_version < "4.0" and python_full_version >= "3.6.2" snowballstemmer==2.2.0; python_version >= "3.7" @@ -251,7 +225,6 @@ squarify==0.4.3 sseclient==0.0.27 stack-data==0.2.0; python_full_version >= "3.6.2" and python_version >= "3.8" statsmodels==0.13.2; python_version >= "3.7" -stevedore==3.5.0; python_version >= "3.7" tabulate==0.8.9; python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" temporal-cache==0.1.4 tenacity==8.0.1; python_version >= "3.6" @@ -260,9 +233,7 @@ textwrap3==0.9.2; python_version >= "3.6" thepassiveinvestor==1.0.10 threadpoolctl==3.1.0; python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version >= "3.7" tinycss2==1.1.1; python_version >= "3.7" -tokenize-rt==4.2.1; python_full_version >= "3.6.2" and python_version >= "3.7" -toml==0.10.2; python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.3.0" and python_version >= "3.7" -tomli==2.0.1; python_version >= "3.8" and python_full_version >= "3.6.2" and python_version < "3.11" +tomli==2.0.1; python_version >= "3.8" and python_full_version >= "3.6.2" toolz==0.11.2; python_version >= "3.7" and python_full_version >= "3.7.0" tornado==6.1; python_full_version >= "3.7.0" and python_version >= "3.7" tqdm==4.64.0; python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.4.0" and python_version >= "3.6" @@ -270,13 +241,6 @@ tradingview-ta==3.2.10; python_version >= "3.6" traitlets==5.1.1; python_full_version >= "3.7.0" and python_version >= "3.8" trio-websocket==0.9.2; python_version >= "3.7" and python_version < "4.0" trio==0.20.0; python_version >= "3.7" and python_version < "4.0" -types-python-dateutil==2.8.12 -types-pytz==2021.3.6 -types-pyyaml==6.0.7 -types-requests==2.27.20 -types-setuptools==57.4.14 -types-six==1.16.15 -types-urllib3==1.26.13 typing-extensions==4.2.0; python_version < "3.10" and python_full_version >= "3.6.2" and python_version >= "3.7" tzdata==2022.1; platform_system == "Windows" and python_version >= "3.6" and (python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version >= "3.6") tzlocal==4.2; python_version >= "3.6" @@ -287,16 +251,15 @@ urllib3==1.26.9; python_full_version >= "3.7.1" and python_version < "4" and pyt user-agent==0.1.10 vadersentiment==3.3.2 valinvest==0.0.2; python_version >= "3.6" -vcrpy==4.1.1; python_version >= "3.5" -virtualenv==20.14.1; python_version >= "3.7" and python_full_version < "3.0.0" or python_full_version >= "3.5.0" and python_version >= "3.7" voila==0.3.5; python_version >= "3.7" wcwidth==0.2.5; python_full_version >= "3.6.2" and python_version >= "3.8" webencodings==0.5.1; python_version >= "3.7" websocket-client==1.3.2; python_version >= "3.8" and python_version < "4.0" websockets==10.3; python_version >= "3.7" widgetsnbextension==3.6.0 -wrapt==1.14.0; python_full_version >= "3.7.1" and python_full_version < "4.0.0" and (python_version >= "3.5" and python_full_version < "3.0.0" or python_full_version >= "3.5.0" and python_version >= "3.5") and python_version >= "3.8" +wrapt==1.14.0; python_full_version >= "3.7.1" and python_full_version < "4.0.0" and python_version >= "3.8" wsproto==1.1.0; python_version >= "3.7" and python_version < "4.0" and python_full_version >= "3.7.0" +xlsxwriter==3.0.3; python_version >= "3.7" yarl==1.7.2; python_version >= "3.6" yfinance==0.1.70 zipp==3.8.0; python_version < "3.10" and python_version >= "3.7" diff --git a/tests/openbb_terminal/portfolio/portfolio_optimization/test_po_controller.py b/tests/openbb_terminal/portfolio/portfolio_optimization/test_po_controller.py index 7c2b0fdce31..b1027026d5d 100644 --- a/tests/openbb_terminal/portfolio/portfolio_optimization/test_po_controller.py +++ b/tests/openbb_terminal/portfolio/portfolio_optimization/test_po_controller.py @@ -191,24 +191,17 @@ def test_call_func_expect_queue(expected_queue, func, queue): @pytest.mark.parametrize( "tested_func, other_args, mocked_func, called_args, called_kwargs", [ - ( - "call_select", - [], - "PortfolioOptimizationController.add_stocks", - [], - dict(), - ), ( "call_add", [], - "PortfolioOptimizationController.add_stocks", + "PortfolioOptimizationController.call_add", [], dict(), ), ( "call_rmv", [], - "PortfolioOptimizationController.rmv_stocks", + "PortfolioOptimizationController.call_rmv", [], dict(), ), @@ -248,30 +241,9 @@ def test_call_func_expect_queue(expected_queue, func, queue): dict(), ), ( - "call_minvol", + "call_minrisk", [], - "optimizer_view.display_min_volatility", - [], - dict(), - ), - ( - "call_maxquadutil", - [], - "optimizer_view.display_max_quadratic_utility", - [], - dict(), - ), - ( - "call_effrisk", - [], - "optimizer_view.display_efficient_risk", - [], - dict(), - ), - ( - "call_effret", - [], - "optimizer_view.display_efficient_return", + "optimizer_view.display_min_risk", [], dict(), ), @@ -283,23 +255,16 @@ def test_call_func_expect_queue(expected_queue, func, queue): dict(), ), ( - "call_yolo", + "call_add", [], - "", + "PortfolioOptimizationController.call_add", [], dict(), ), ( - "add_stocks", + "call_rmv", [], - "", - [], - dict(), - ), - ( - "rmv_stocks", - [], - "", + "PortfolioOptimizationController.call_rmv", [], dict(), ), diff --git a/tests/openbb_terminal/portfolio/portfolio_optimization/txt/test_po_controller/test_print_help.txt b/tests/openbb_terminal/portfolio/portfolio_optimization/txt/test_po_controller/test_print_help.txt index 487c056cc86..94397de3e03 100644 --- a/tests/openbb_terminal/portfolio/portfolio_optimization/txt/test_po_controller/test_print_help.txt +++ b/tests/openbb_terminal/portfolio/portfolio_optimization/txt/test_po_controller/test_print_help.txt @@ -1,22 +1,43 @@ - select select list of tickers to be optimized - add add tickers to the list of the tickers to be optimized - rmv remove tickers from the list of the tickers to be optimized +Parameter file: + + file select portfolio parameter file +> params specify and show portfolio risk parameters + load load tickers and categories from .xlsx or .csv file Tickers: None +Categories: None +Portfolios: None -Optimization: - equal equally weighted - mktcap weighted according to market cap (property marketCap) - dividend weighted according to dividend yield (property dividendYield) - property weight according to selected info property + add add tickers to the list of the tickers to be optimized + rmv remove tickers from the list of the tickers to be optimized + show show selected portfolios and categories from the list of saved portfolios + rpf remove portfolios from the list of saved portfolios + plot plot selected charts from the list of saved portfolios -Mean Variance Optimization: - maxsharpe optimizes for maximal Sharpe ratio (a.k.a the tangency portfolio - minvol optimizes for minimum volatility - maxquadutil maximises the quadratic utility, given some risk aversion - effret maximises return for a given target risk - effrisk minimises risk for a given target return +Mean Risk Optimization: + maxsharpe maximal Sharpe ratio portfolio (a.k.a the tangency portfolio) + minrisk minimum risk portfolio + maxutil maximal risk averse utility function, given some risk + aversion parameter + maxret maximal return portfolio + maxdiv maximum diversification portfolio + maxdecorr maximum decorrelation portfolio + blacklitterman black litterman portfolio + ef show the efficient frontier - ef show the efficient frontier +Risk Parity Optimization: + riskparity risk parity portfolio using risk budgeting approach + relriskparity relaxed risk parity using least squares approach + +Hierarchical Clustering Models: + hrp hierarchical risk parity + herc hierarchical equal risk contribution + nco nested clustering optimization + +Other Optimization Techniques: + equal equally weighted + mktcap weighted according to market cap (property marketCap) + dividend weighted according to dividend yield (property dividendYield) + property weight according to selected info property diff --git a/website/content/terminal/portfolio/po/_index.md b/website/content/terminal/portfolio/po/_index.md new file mode 100644 index 00000000000..407539f4df3 --- /dev/null +++ b/website/content/terminal/portfolio/po/_index.md @@ -0,0 +1,52 @@ +--- +geekdocCollapseSection: true +--- + +The terminal has incorporated Riskfolio-Lib. Refer to the documentation here: + +```text +Parameter file: + + file select portfolio parameter file +> params specify and show portfolio risk parameters + load load tickers and categories from .xlsx or .csv file + +Portfolio Optimization: + add add tickers to the list of the tickers to be optimized + rmv remove tickers from the list of the tickers to be optimized + show show selected portfolios and categories from the list of saved portfolios + rpf remove portfolios from the list of saved portfolios + plot plot selected charts from the list of saved portfolios + +Tickers: BLL, CLX, CSCO, DE, HD, IBM, MAS, MTB, OKE, PCG, RCL, SCHW, SYY, VZ, XRAY +Categories: ASSET_CLASS, SECTOR, INDUSTRY, COUNTRY, CURRENT_INVESTED_AMOUNT, CURRENCY +Portfolios: MINRISK_0, MAXSHARPE_1 + +Mean Risk Optimization: + maxsharpe maximal Sharpe ratio portfolio (a.k.a the tangency portfolio) + minrisk minimum risk portfolio + maxutil maximal risk averse utility function, given some risk + aversion parameter + maxret maximal return portfolio + maxdiv maximum diversification portfolio + maxdecorr maximum decorrelation portfolio + blacklitterman black litterman portfolio + ef show the efficient frontier + +Risk Parity Optimization: + riskparity risk parity portfolio using risk budgeting approach + relriskparity relaxed risk parity using least squares approach + +Hierarchical Clustering Models: + hrp hierarchical risk parity + herc hierarchical equal risk contribution + nco nested clustering optimization + +Other Optimization Techniques: + equal equally weighted + mktcap weighted according to market cap (property marketCap) + dividend weighted according to dividend yield (property dividendYield) + property weight according to selected info property +``` + +{{< toc-tree >}} \ No newline at end of file diff --git a/website/content/terminal/portfolio/portfolio_optimization/add/_index.md b/website/content/terminal/portfolio/po/add/_index.md similarity index 100% rename from website/content/terminal/portfolio/portfolio_optimization/add/_index.md rename to website/content/terminal/portfolio/po/add/_index.md diff --git a/website/content/terminal/portfolio/po/blacklitterman/_index.md b/website/content/terminal/portfolio/po/blacklitterman/_index.md new file mode 100644 index 00000000000..95aacf458a2 --- /dev/null +++ b/website/content/terminal/portfolio/po/blacklitterman/_index.md @@ -0,0 +1,135 @@ +``` +usage: blacklitterman [-p PERIOD] [-s START] [-e END] [-lr] [-f {d,w,m}] + [-mn MAXNAN] [-th THRESHOLD] [-mt METHOD] + [-bm BENCHMARK] [-o {MinRisk,Utility,Sharpe,MaxRet}] + [-pv P_VIEWS] [-qv Q_VIEWS] [-r RISK_FREE_RATE] + [-ra RISK_AVERSION] [-d DELTA] [-eq] [-op] [-v VALUE] + [-vs VALUE_SHORT] [--name NAME] [-h] +``` + +The Black-Litterman (BL) Model is an analytical tool used by portfolio managers to optimize asset allocation within an investor’s risk tolerance and market views. Global investors, such as pension funds and insurance companies, need to decide how to allocate their investments across different asset classes and countries. The BL model starts from a neutral position using modern portfolio theory (MPT), and then takes additional input from investors' views to determine how the ultimate asset allocation should deviate from the initial portfolio weights. It then undergoes a process of mean-variance optimization (MVO) to maximize expected return given one's objective risk tolerance. + +``` +optional arguments: + -p PERIOD, --period PERIOD + Period to get yfinance data from. Possible frequency + strings are: 'd': means days, for example '252d' means + 252 days 'w': means weeks, for example '52w' means 52 + weeks 'mo': means months, for example '12mo' means 12 + months 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset + (default: 3y) + -s START, --start START + Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format (default: ) + -e END, --end END End date to get yfinance data from. Must be in 'YYYY- + MM-DD' format (default: ) + -lr, --log-returns If use logarithmic or arithmetic returns to calculate + returns (default: False) + -f {d,w,m}, --freq {d,w,m} + Frequency used to calculate returns. Possible values + are: 'd': for daily returns 'w': for weekly returns + 'm': for monthly returns (default: d) + -mn MAXNAN, --maxnan MAXNAN + Max percentage of nan values accepted per asset to be + considered in the optimization process (default: 0.05) + -th THRESHOLD, --threshold THRESHOLD + Value used to replace outliers that are higher to + threshold in absolute value (default: 0.3) + -mt METHOD, --method METHOD + Method used to fill nan values in time series, by + default time. Possible values are: linear: linear + interpolation time: linear interpolation based on time + index nearest: use nearest value to replace nan values + zero: spline of zeroth order slinear: spline of first + order quadratic: spline of second order cubic: spline + of third order barycentric: builds a polynomial that + pass for all points (default: time) + -bm BENCHMARK, --benchmark BENCHMARK + portfolio name from current portfolio list (default: + None) + -o {MinRisk,Utility,Sharpe,MaxRet}, --objective {MinRisk,Utility,Sharpe,MaxRet} + Objective function used to optimize the portfolio + (default: MinRisk) + -pv P_VIEWS, --p-views P_VIEWS + matrix P of views (default: None) + -qv Q_VIEWS, --q-views Q_VIEWS + matrix Q of views (default: None) + -r RISK_FREE_RATE, --risk-free-rate RISK_FREE_RATE + Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual (default: 0.00329) + -ra RISK_AVERSION, --risk-aversion RISK_AVERSION + Risk aversion parameter (default: 1.0) + -d DELTA, --delta DELTA + Risk aversion factor of Black Litterman model + (default: None) + -eq, --equilibrium If True excess returns are based on equilibrium market + portfolio, if False excess returns are calculated as + historical returns minus risk free rate. (default: + True) + -op, --optimize If True Black Litterman estimates are used as inputs + of mean variance model, if False returns equilibrium + weights from Black Litterman model (default: True) + -v VALUE, --value VALUE + Amount to allocate to portfolio in long positions + (default: 1.0) + -vs VALUE_SHORT, --value-short VALUE_SHORT + Amount to allocate to portfolio in short positions + (default: 0.0) + --name NAME Save portfolio with personalized or default name + (default: BL_3) + -h, --help show this help message (default: False) +``` + +Example: + +First we need to build a benchmark portfolio: + +``` +2022 Apr 26, 01:25 (🦋) /portfolio/po/ $ add AAPL,MSFT,JP,BA +2022 Apr 26, 01:26 (🦋) /portfolio/po/ $ maxsharpe + + [3 Years] Maximal return/risk ratio portfolio using volatility as risk measure + + Weights +┏━━━━━━┳━━━━━━━━━━┓ +┃ ┃ Value ┃ +┡━━━━━━╇━━━━━━━━━━┩ +│ AAPL │ 100.00 % │ +├──────┼──────────┤ +│ BA │ 0.00 % │ +├──────┼──────────┤ +│ JP │ 0.00 % │ +├──────┼──────────┤ +│ MSFT │ 0.00 % │ +└──────┴──────────┘ +Annual (by 252) expected return: 45.46% +Annual (by √252) volatility: 34.16% +Sharpe ratio: 1.3209 +``` + +Then we add our views to the benchmark portfolio: + +``` +2022 Apr 26, 01:27 (🦋) /portfolio/po/ $ blacklitterman -bm maxsharpe_0 -pv 0,1, +0,0;1,0,0,0;0,0,0,1 -qv 0.1,0.1,0.05 -o Sharpe + + [3 Years] Black Litterman portfolio + + Weights +┏━━━━━━┳━━━━━━━━━━┓ +┃ ┃ Value ┃ +┡━━━━━━╇━━━━━━━━━━┩ +│ AAPL │ 70.30 % │ +├──────┼──────────┤ +│ BA │ 18.55 % │ +├──────┼──────────┤ +│ JP │ 0.01 % │ +├──────┼──────────┤ +│ MSFT │ 11.14 % │ +└──────┴──────────┘ +Annual (by 252) expected return: 33.94% +Annual (by √252) volatility: 32.80% +Sharpe ratio: 1.0346 +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/dividend/_index.md b/website/content/terminal/portfolio/po/dividend/_index.md new file mode 100644 index 00000000000..78bcc0410cb --- /dev/null +++ b/website/content/terminal/portfolio/po/dividend/_index.md @@ -0,0 +1,105 @@ +``` +usage: dividend [-p HISTORIC_PERIOD] [-s START_PERIOD] [-e END_PERIOD] [-lr] + [-f {d,w,m}] [-mn MAX_NAN] [-th THRESHOLD_VALUE] + [-mt NAN_FILL_METHOD] + [-rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD}] + [-r RISK_FREE] [-a SIGNIFICANCE_LEVEL] [-v LONG_ALLOCATION] + [--name NAME] [-h] +``` + +Returns a portfolio that is weighted based dividend yield. + +``` +optional arguments: + -p HISTORIC_PERIOD, --period HISTORIC_PERIOD + Period to get yfinance data from. Possible frequency + strings are: 'd': means days, for example '252d' means + 252 days 'w': means weeks, for example '52w' means 52 + weeks 'mo': means months, for example '12mo' means 12 + months 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset + (default: 3y) + -s START_PERIOD, --start START_PERIOD + Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format (default: ) + -e END_PERIOD, --end END_PERIOD + End date to get yfinance data from. Must be in 'YYYY- + MM-DD' format (default: ) + -lr, --log-returns If use logarithmic or arithmetic returns to calculate + returns (default: False) + -f {d,w,m}, --freq {d,w,m} + Frequency used to calculate returns. Possible values + are: 'd': for daily returns 'w': for weekly returns + 'm': for monthly returns (default: d) + -mn MAX_NAN, --maxnan MAX_NAN + Max percentage of nan values accepted per asset to be + considered in the optimization process (default: 0.05) + -th THRESHOLD_VALUE, --threshold THRESHOLD_VALUE + Value used to replace outliers that are higher to + threshold in absolute value (default: 0.3) + -mt NAN_FILL_METHOD, --method NAN_FILL_METHOD + Method used to fill nan values in time series, by + default time. Possible values are: 'linear': linear + interpolation 'time': linear interpolation based on + time index 'nearest': use nearest value to replace nan + values 'zero': spline of zeroth order 'slinear': + spline of first order 'quadratic': spline of second + order 'cubic': spline of third order 'barycentric': + builds a polynomial that pass for all points (default: + time) + -rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD}, --risk-measure {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD} + Risk measure used to calculate indicators. Possible + values are: 'MV' : Variance 'MAD' : Mean Absolute + Deviation 'MSV' : Semi Variance (Variance of negative + returns) 'FLPM' : First Lower Partial Moment 'SLPM' : + Second Lower Partial Moment 'CVaR' : Conditional Value + at Risk 'EVaR' : Entropic Value at Risk 'WR' : Worst + Realization 'ADD' : Average Drawdown of uncompounded + returns 'UCI' : Ulcer Index of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded + returns 'EDaR' : Entropic Drawdown at Risk of + uncompounded returns 'MDD' : Maximum Drawdown of + uncompounded returns (default: MV) + -r RISK_FREE, --risk-free-rate RISK_FREE + Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual (default: 0.00329) + -a SIGNIFICANCE_LEVEL, --alpha SIGNIFICANCE_LEVEL + Significance level of CVaR, EVaR, CDaR and EDaR + (default: 0.05) + -v LONG_ALLOCATION, --value LONG_ALLOCATION + Amount to allocate to portfolio (default: 1) + --name NAME Save portfolio with personalized or default name + (default: DIVIDEND_0) + -h, --help show this help message (default: False) +``` + +Example: +``` +2022 Apr 05, 14:55 (🦋) /portfolio/po/ $ dividend + + [3 Years] Weighted Portfolio based on dividendYield + + Weights +┏━━━━━━┳━━━━━━━━━┓ +┃ ┃ Value ┃ +┡━━━━━━╇━━━━━━━━━┩ +│ AAPL │ 8.48 % │ +├──────┼─────────┤ +│ AMZN │ 0.0 % │ +├──────┼─────────┤ +│ BA │ 0.0 % │ +├──────┼─────────┤ +│ FB │ 0.0 % │ +├──────┼─────────┤ +│ MSFT │ 13.58 % │ +├──────┼─────────┤ +│ T │ 77.92 % │ +├──────┼─────────┤ +│ TSLA │ 0.0 % │ +└──────┴─────────┘ + +Annual (by 252) expected return: 10.30% +Annual (by √252) volatility: 24.10% +Sharpe ratio: 0.4198 +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/ef/_index.md b/website/content/terminal/portfolio/po/ef/_index.md new file mode 100644 index 00000000000..fc1ed6f286f --- /dev/null +++ b/website/content/terminal/portfolio/po/ef/_index.md @@ -0,0 +1,61 @@ +``` +usage: ef [-p PERIOD] [-s START] [-e END] [-lr] [-f {d,w,m}] [-mn MAXNAN] + [-th THRESHOLD] [-mt METHOD] + [-rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD}] + [-r RISK_FREE_RATE] [-a ALPHA] [-v VALUE] [-vs VALUE_SHORT] + [-n N_PORTFOLIOS] [-se SEED] [-t] [-h] +``` + +This function plots random portfolios based on their risk and returns and +shows the efficient frontier of selected risk measure. + +``` +optional arguments: + -p PERIOD, --period PERIOD + Period to get yfinance data from (default: 3y) + -s START, --start START + Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format (default: ) + -e END, --end END End date to get yfinance data from (default: ) + -lr, --log-returns If use logarithmic or arithmetic returns to calculate + returns (default: False) + -f {d,w,m}, --freq {d,w,m} + Frequency used to calculate returns (default: d) + -mn MAXNAN, --maxnan MAXNAN + Max percentage of nan values accepted per asset to be + considered in the optimization process (default: 0.05) + -th THRESHOLD, --threshold THRESHOLD + Value used to replace outliers that are higher to + threshold in absolute value (default: 0.3) + -mt METHOD, --method METHOD + Method used to fill nan values (default: time) + -rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD}, --risk-measure {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD} + Risk measure used to optimize the portfolio (default: + MV) + -r RISK_FREE_RATE, --risk-free-rate RISK_FREE_RATE + Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual (default: 0.00185) + -a ALPHA, --alpha ALPHA + Significance level of CVaR, EVaR, CDaR and EDaR + (default: 0.05) + -v VALUE, --value VALUE + Amount to allocate to portfolio in long positions + (default: 1.0) + -vs VALUE_SHORT, --value-short VALUE_SHORT + Amount to allocate to portfolio in short positions + (default: 0.0) + -n N_PORTFOLIOS, --number-portfolios N_PORTFOLIOS + Number of portfolios to simulate (default: 100) + -se SEED, --seed SEED + Seed used to generate random portfolios (default: 123) + -t, --tangency Adds the optimal line with the risk-free asset + (default: False) + -h, --help show this help message (default: False) +``` + +Example: +``` +2022 Apr 05, 15:03 (🦋) /portfolio/po/ $ ef +``` +![Frontier](https://user-images.githubusercontent.com/61527316/161860003-e8b8ae93-ce8c-4e06-bad2-59c100f09325.png) + diff --git a/website/content/terminal/portfolio/po/equal/_index.md b/website/content/terminal/portfolio/po/equal/_index.md new file mode 100644 index 00000000000..288762aa26d --- /dev/null +++ b/website/content/terminal/portfolio/po/equal/_index.md @@ -0,0 +1,105 @@ +``` +usage: equal [-p HISTORIC_PERIOD] [-s START_PERIOD] [-e END_PERIOD] [-lr] + [-f {d,w,m}] [-mn MAX_NAN] [-th THRESHOLD_VALUE] + [-mt NAN_FILL_METHOD] + [-rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD}] + [-r RISK_FREE] [-a SIGNIFICANCE_LEVEL] [-v LONG_ALLOCATION] + [--name NAME] [-h] +``` + +Returns an equally weighted portfolio. + +``` +optional arguments: + -p HISTORIC_PERIOD, --period HISTORIC_PERIOD + Period to get yfinance data from. Possible frequency + strings are: 'd': means days, for example '252d' means + 252 days 'w': means weeks, for example '52w' means 52 + weeks 'mo': means months, for example '12mo' means 12 + months 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset + (default: 3y) + -s START_PERIOD, --start START_PERIOD + Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format (default: ) + -e END_PERIOD, --end END_PERIOD + End date to get yfinance data from. Must be in 'YYYY- + MM-DD' format (default: ) + -lr, --log-returns If use logarithmic or arithmetic returns to calculate + returns (default: False) + -f {d,w,m}, --freq {d,w,m} + Frequency used to calculate returns. Possible values + are: 'd': for daily returns 'w': for weekly returns + 'm': for monthly returns (default: d) + -mn MAX_NAN, --maxnan MAX_NAN + Max percentage of nan values accepted per asset to be + considered in the optimization process (default: 0.05) + -th THRESHOLD_VALUE, --threshold THRESHOLD_VALUE + Value used to replace outliers that are higher to + threshold in absolute value (default: 0.3) + -mt NAN_FILL_METHOD, --method NAN_FILL_METHOD + Method used to fill nan values in time series, by + default time. Possible values are: 'linear': linear + interpolation 'time': linear interpolation based on + time index 'nearest': use nearest value to replace nan + values 'zero': spline of zeroth order 'slinear': + spline of first order 'quadratic': spline of second + order 'cubic': spline of third order 'barycentric': + builds a polynomial that pass for all points (default: + time) + -rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD}, --risk-measure {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD} + Risk measure used to optimize the portfolio. Possible + values are: 'MV' : Variance 'MAD' : Mean Absolute + Deviation 'MSV' : Semi Variance (Variance of negative + returns) 'FLPM' : First Lower Partial Moment 'SLPM' : + Second Lower Partial Moment 'CVaR' : Conditional Value + at Risk 'EVaR' : Entropic Value at Risk 'WR' : Worst + Realization 'ADD' : Average Drawdown of uncompounded + returns 'UCI' : Ulcer Index of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded + returns 'EDaR' : Entropic Drawdown at Risk of + uncompounded returns 'MDD' : Maximum Drawdown of + uncompounded returns (default: MV) + -r RISK_FREE, --risk-free-rate RISK_FREE + Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual (default: 0.00329) + -a SIGNIFICANCE_LEVEL, --alpha SIGNIFICANCE_LEVEL + Significance level of CVaR, EVaR, CDaR and EDaR + (default: 0.05) + -v LONG_ALLOCATION, --value LONG_ALLOCATION + Amount to allocate to portfolio (default: 1) + --name NAME Save portfolio with personalized or default name + (default: EQUAL_0) + -h, --help show this help message (default: False) +``` + +Example: +``` +2022 Apr 05, 14:52 (🦋) /portfolio/po/ $ equal + + [3 Years] Equally Weighted Portfolio + + Weights +┏━━━━━━┳━━━━━━━━━┓ +┃ ┃ Value ┃ +┡━━━━━━╇━━━━━━━━━┩ +│ AAPL │ 14.28 % │ +├──────┼─────────┤ +│ AMZN │ 14.28 % │ +├──────┼─────────┤ +│ BA │ 14.28 % │ +├──────┼─────────┤ +│ FB │ 14.28 % │ +├──────┼─────────┤ +│ MSFT │ 14.28 % │ +├──────┼─────────┤ +│ T │ 14.28 % │ +├──────┼─────────┤ +│ TSLA │ 14.28 % │ +└──────┴─────────┘ + +Annual (by 252) expected return: 35.70% +Annual (by √252) volatility: 29.50% +Sharpe ratio: 1.2041 +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/file/_index.md b/website/content/terminal/portfolio/po/file/_index.md new file mode 100644 index 00000000000..c790483545b --- /dev/null +++ b/website/content/terminal/portfolio/po/file/_index.md @@ -0,0 +1,34 @@ +``` +usage: file -f FILE [FILE ...] [-h] +``` + +Select parameter file to use. + +Optional arguments: +``` +optional arguments: + -f FILE [FILE ...], --file FILE [FILE ...] + Parameter file to be used (default: None) + -h, --help show this help message (default: False) +``` + +``` +2022 May 02, 06:51 (🦋) /portfolio/po/ $ file OpenBB_Parameters_Template v1.0.0.xlsx +Parameters: + historic_period : 3y + log_returns : 0 + return_frequency : d + max_nan : 0.05 + threshold_value : 0.3 + nan_fill_method : time + risk_free : 0.003 + significance_level : 0.05 + risk_measure : MV + target_return : -1 + target_risk : -1 + expected_return : hist + covariance : hist + smoothing_factor_ewma : 0.94 + long_allocation : 1 + short_allocation : 0 +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/herc/_index.md b/website/content/terminal/portfolio/po/herc/_index.md new file mode 100644 index 00000000000..d95d2c1cd86 --- /dev/null +++ b/website/content/terminal/portfolio/po/herc/_index.md @@ -0,0 +1,178 @@ +``` +usage: herc [-p HISTORIC_PERIOD] [-s START_PERIOD] [-e END_PERIOD] [-lr] + [-f {d,w,m}] [-mn MAX_NAN] [-th THRESHOLD_VALUE] + [-mt NAN_FILL_METHOD] + [-cd {pearson,spearman,abs_pearson,abs_spearman,distance,mutual_info,tail}] + [-cv {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink}] + [-rm {MV,MAD,GMD,MSV,VaR,CVaR,TG,EVaR,RG,CVRG,TGRG,WR,FLPM,SLPM,MDD,ADD,DaR,CDaR,EDaR,UCI,MDD_Rel,ADD_Rel,DaR_Rel,CDaR_Rel,EDaR_Rel,UCI_Rel}] + [-r RISK_FREE] [-a SIGNIFICANCE_LEVEL] + [-as CVAR_SIMULATIONS_LOSSES] [-b CVAR_SIGNIFICANCE] + [-bs CVAR_SIMULATIONS_GAINS] + [-lk {single,complete,average,weighted,centroid,median,ward,dbht}] + [-k AMOUNT_CLUSTERS] [-mk MAX_CLUSTERS] [-bi AMOUNT_BINS] + [-at ALPHA_TAIL] [-lo LEAF_ORDER] [-de SMOOTHING_FACTOR_EWMA] + [-v LONG_ALLOCATION] [--name NAME] [-h] +``` + +In a risk budgeting portfolio, the risk contribution from each component is equal to the budget of risk defined by the portfolio manager. Maillard, Roncalli, and Teiletche ([source](https://investresolve.com/portfolio-optimization-simple-optimal-methods/#ref-Maillard2008)) described the Equal Risk Contribution optimization, which is satisfied when all assets contribute the same volatility to the portfolio (equal risk budgeting). It has been shown that the Equal Risk Contribution portfolio is a compelling balance between the objectives of the equal weight and Minimum Variance portfolios. It is also a close cousin to the Inverse Volatility portfolio, except that it is less vulnerable to the case where assets have vastly different correlations. + +``` +optional arguments: + -p HISTORIC_PERIOD, --period HISTORIC_PERIOD + Period to get yfinance data from. Possible frequency + strings are: 'd': means days, for example '252d' means + 252 days 'w': means weeks, for example '52w' means 52 + weeks 'mo': means months, for example '12mo' means 12 + months 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset + (default: 3y) + -s START_PERIOD, --start START_PERIOD + Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format (default: ) + -e END_PERIOD, --end END_PERIOD + End date to get yfinance data from. Must be in 'YYYY- + MM-DD' format (default: ) + -lr, --log-returns If use logarithmic or arithmetic returns to calculate + returns (default: False) + -f {d,w,m}, --freq {d,w,m} + Frequency used to calculate returns. Possible values + are: 'd': for daily returns 'w': for weekly returns + 'm': for monthly returns (default: d) + -mn MAX_NAN, --maxnan MAX_NAN + Max percentage of nan values accepted per asset to be + considered in the optimization process (default: 0.05) + -th THRESHOLD_VALUE, --threshold THRESHOLD_VALUE + Value used to replace outliers that are higher to + threshold in absolute value (default: 0.3) + -mt NAN_FILL_METHOD, --method NAN_FILL_METHOD + Method used to fill nan values in time series, by + default time. Possible values are: 'linear': linear + interpolation 'time': linear interpolation based on + time index 'nearest': use nearest value to replace nan + values 'zero': spline of zeroth order 'slinear': + spline of first order 'quadratic': spline of second + order 'cubic': spline of third order 'barycentric': + builds a polynomial that pass for all points (default: + time) + -cd {pearson,spearman,abs_pearson,abs_spearman,distance,mutual_info,tail}, --codependence {pearson,spearman,abs_pearson,abs_spearman,distance,mutual_info,tail} + The codependence or similarity matrix used to build + the distance metric and clusters. Possible values are: + 'pearson': pearson correlation matrix 'spearman': + spearman correlation matrix 'abs_pearson': absolute + value of pearson correlation matrix 'abs_spearman': + absolute value of spearman correlation matrix + 'distance': distance correlation matrix 'mutual_info': + mutual information codependence matrix 'tail': tail + index codependence matrix (default: pearson) + -cv {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink}, --covariance {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink} + Method used to estimate covariance matrix. Possible + values are 'hist': historical method 'ewma1': + exponential weighted moving average with adjust=True + 'ewma2': exponential weighted moving average with + adjust=False 'ledoit': Ledoit and Wolf shrinkage + method 'oas': oracle shrinkage method 'shrunk': + scikit-learn shrunk method 'gl': graphical lasso + method 'jlogo': j-logo covariance 'fixed': takes + average of eigenvalues above max Marchenko Pastour + limit 'spectral': makes zero eigenvalues above max + Marchenko Pastour limit 'shrink': Lopez de Prado's + book shrinkage method (default: hist) + -rm {MV,MAD,GMD,MSV,VaR,CVaR,TG,EVaR,RG,CVRG,TGRG,WR,FLPM,SLPM,MDD,ADD,DaR,CDaR,EDaR,UCI,MDD_Rel,ADD_Rel,DaR_Rel,CDaR_Rel,EDaR_Rel,UCI_Rel}, --risk-measure {MV,MAD,GMD,MSV,VaR,CVaR,TG,EVaR,RG,CVRG,TGRG,WR,FLPM,SLPM,MDD,ADD,DaR,CDaR,EDaR,UCI,MDD_Rel,ADD_Rel,DaR_Rel,CDaR_Rel,EDaR_Rel,UCI_Rel} + Risk measure used to optimize the portfolio. Possible + values are: 'MV' : Variance 'MAD' : Mean Absolute + Deviation 'GMD' : Gini Mean Difference 'MSV' : Semi + Variance (Variance of negative returns) 'FLPM' : First + Lower Partial Moment 'SLPM' : Second Lower Partial + Moment 'VaR' : Value at Risk 'CVaR' : Conditional + Value at Risk 'TG' : Tail Gini 'EVaR' : Entropic Value + at Risk 'WR' : Worst Realization 'RG' : Range 'CVRG' : + CVaR Range 'TGRG' : Tail Gini Range 'ADD' : Average + Drawdown of uncompounded returns 'UCI' : Ulcer Index + of uncompounded returns 'DaR' : Drawdown at Risk of + uncompounded returns 'CDaR' : Conditional Drawdown at + Risk of uncompounded returns 'EDaR' : Entropic + Drawdown at Risk of uncompounded returns 'MDD' : + Maximum Drawdown of uncompounded returns 'ADD_Rel' : + Average Drawdown of compounded returns 'UCI_Rel' : + Ulcer Index of compounded returns 'DaR_Rel' : Drawdown + at Risk of compounded returns 'CDaR_Rel' : Conditional + Drawdown at Risk of compounded returns 'EDaR_Rel' : + Entropic Drawdown at Risk of compounded returns + 'MDD_Rel' : Maximum Drawdown of compounded returns + (default: MV) + -r RISK_FREE, --risk-free-rate RISK_FREE + Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual (default: 0.00329) + -a SIGNIFICANCE_LEVEL, --alpha SIGNIFICANCE_LEVEL + Significance level of VaR, CVaR, EVaR, DaR, CDaR, EDaR + and Tail Gini of losses (default: 0.05) + -as CVAR_SIMULATIONS_LOSSES, --a-sim CVAR_SIMULATIONS_LOSSES + Number of CVaRs used to approximate Tail Gini of + losses. The default is 100 (default: 100) + -b CVAR_SIGNIFICANCE, --beta CVAR_SIGNIFICANCE + Significance level of CVaR and Tail Gini of gains. If + empty it duplicates alpha (default: None) + -bs CVAR_SIMULATIONS_GAINS, --b-sim CVAR_SIMULATIONS_GAINS + Number of CVaRs used to approximate Tail Gini of + gains. If empty it duplicates a_sim value (default: + None) + -lk {single,complete,average,weighted,centroid,median,ward,dbht}, --linkage {single,complete,average,weighted,centroid,median,ward,dbht} + Linkage method of hierarchical clustering (default: + single) + -k AMOUNT_CLUSTERS Number of clusters specified in advance (default: + None) + -mk MAX_CLUSTERS, --max-k MAX_CLUSTERS + Max number of clusters used by the two difference gap + statistic to find the optimal number of clusters. If k + is empty this value is used (default: 10) + -bi AMOUNT_BINS, --bins-info AMOUNT_BINS + Number of bins used to calculate the variation of + information (default: KN) + -at ALPHA_TAIL, --alpha-tail ALPHA_TAIL + Significance level for lower tail dependence index, + only used when when codependence value is 'tail' + (default: 0.05) + -lo LEAF_ORDER, --leaf-order LEAF_ORDER + Indicates if the cluster are ordered so that the + distance between successive leaves is minimal + (default: True) + -de SMOOTHING_FACTOR_EWMA, --d-ewma SMOOTHING_FACTOR_EWMA + Smoothing factor for ewma estimators (default: 0.94) + -v LONG_ALLOCATION, --value LONG_ALLOCATION + Amount to allocate to portfolio (default: 1) + --name NAME Save portfolio with personalized or default name + (default: HERC_0) + -h, --help show this help message (default: False) +``` + +Example: +``` +2022 Apr 05, 14:40 (🦋) /portfolio/po/ $ herc + + [3 Years] Hierarchical equal risk contribution portfolio using pearson +codependence,single linkage and volatility as risk measure + + Weights +┏━━━━━━┳━━━━━━━━━┓ +┃ ┃ Value ┃ +┡━━━━━━╇━━━━━━━━━┩ +│ AAPL │ 10.78 % │ +├──────┼─────────┤ +│ AMZN │ 12.64 % │ +├──────┼─────────┤ +│ BA │ 9.12 % │ +├──────┼─────────┤ +│ FB │ 8.08 % │ +├──────┼─────────┤ +│ MSFT │ 12.86 % │ +├──────┼─────────┤ +│ T │ 43.83 % │ +├──────┼─────────┤ +│ TSLA │ 2.66 % │ +└──────┴─────────┘ + +Annual (by 252) expected return: 18.09% +Annual (by √252) volatility: 24.19% +Sharpe ratio: 0.7401 +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/hrp/_index.md b/website/content/terminal/portfolio/po/hrp/_index.md new file mode 100644 index 00000000000..bdd26604526 --- /dev/null +++ b/website/content/terminal/portfolio/po/hrp/_index.md @@ -0,0 +1,178 @@ +``` +usage: hrp [-p HISTORIC_PERIOD] [-s START_PERIOD] [-e END_PERIOD] [-lr] + [-f {d,w,m}] [-mn MAX_NAN] [-th THRESHOLD_VALUE] + [-mt NAN_FILL_METHOD] + [-cd {pearson,spearman,abs_pearson,abs_spearman,distance,mutual_info,tail}] + [-cv {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink}] + [-rm {MV,MAD,GMD,MSV,VaR,CVaR,TG,EVaR,RG,CVRG,TGRG,WR,FLPM,SLPM,MDD,ADD,DaR,CDaR,EDaR,UCI,MDD_Rel,ADD_Rel,DaR_Rel,CDaR_Rel,EDaR_Rel,UCI_Rel}] + [-r RISK_FREE] [-a SIGNIFICANCE_LEVEL] + [-as CVAR_SIMULATIONS_LOSSES] [-b CVAR_SIGNIFICANCE] + [-bs CVAR_SIMULATIONS_GAINS] + [-lk {single,complete,average,weighted,centroid,median,ward,dbht}] + [-k AMOUNT_CLUSTERS] [-mk MAX_CLUSTERS] [-bi AMOUNT_BINS] + [-at ALPHA_TAIL] [-lo LEAF_ORDER] [-de SMOOTHING_FACTOR_EWMA] + [-v LONG_ALLOCATION] [--name NAME] [-h] +``` + +This Hierarchical Risk Parity (HRP) method uses the information contained in the covariance matrix without requiring its inversion or positive definiteness. In fact, HRP can compute a portfolio based on a singular covariance matrix—an impossible feat for quadratic optimizers. HRP starts by reorganizing the covariance matrix to place similar investments together. Then, it employs an inverse-variance weighting allocation based on the number of assets with no further use of the clustering. + +``` +optional arguments: + -p HISTORIC_PERIOD, --period HISTORIC_PERIOD + Period to get yfinance data from. Possible frequency + strings are: 'd': means days, for example '252d' means + 252 days 'w': means weeks, for example '52w' means 52 + weeks 'mo': means months, for example '12mo' means 12 + months 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset + (default: 3y) + -s START_PERIOD, --start START_PERIOD + Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format (default: ) + -e END_PERIOD, --end END_PERIOD + End date to get yfinance data from. Must be in 'YYYY- + MM-DD' format (default: ) + -lr, --log-returns If use logarithmic or arithmetic returns to calculate + returns (default: False) + -f {d,w,m}, --freq {d,w,m} + Frequency used to calculate returns. Possible values + are: 'd': for daily returns 'w': for weekly returns + 'm': for monthly returns (default: d) + -mn MAX_NAN, --maxnan MAX_NAN + Max percentage of nan values accepted per asset to be + considered in the optimization process (default: 0.05) + -th THRESHOLD_VALUE, --threshold THRESHOLD_VALUE + Value used to replace outliers that are higher to + threshold in absolute value (default: 0.3) + -mt NAN_FILL_METHOD, --method NAN_FILL_METHOD + Method used to fill nan values in time series, by + default time. Possible values are: 'linear': linear + interpolation 'time': linear interpolation based on + time index 'nearest': use nearest value to replace nan + values 'zero': spline of zeroth order 'slinear': + spline of first order 'quadratic': spline of second + order 'cubic': spline of third order 'barycentric': + builds a polynomial that pass for all points (default: + time) + -cd {pearson,spearman,abs_pearson,abs_spearman,distance,mutual_info,tail}, --codependence {pearson,spearman,abs_pearson,abs_spearman,distance,mutual_info,tail} + The codependence or similarity matrix used to build + the distance metric and clusters. Possible values are: + 'pearson': pearson correlation matrix 'spearman': + spearman correlation matrix 'abs_pearson': absolute + value of pearson correlation matrix 'abs_spearman': + absolute value of spearman correlation matrix + 'distance': distance correlation matrix 'mutual_info': + mutual information codependence matrix 'tail': tail + index codependence matrix (default: pearson) + -cv {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink}, --covariance {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink} + Method used to estimate covariance matrix. Possible + values are 'hist': historical method 'ewma1': + exponential weighted moving average with adjust=True + 'ewma2': exponential weighted moving average with + adjust=False 'ledoit': Ledoit and Wolf shrinkage + method 'oas': oracle shrinkage method 'shrunk': + scikit-learn shrunk method 'gl': graphical lasso + method 'jlogo': j-logo covariance 'fixed': takes + average of eigenvalues above max Marchenko Pastour + limit 'spectral': makes zero eigenvalues above max + Marchenko Pastour limit 'shrink': Lopez de Prado's + book shrinkage method (default: hist) + -rm {MV,MAD,GMD,MSV,VaR,CVaR,TG,EVaR,RG,CVRG,TGRG,WR,FLPM,SLPM,MDD,ADD,DaR,CDaR,EDaR,UCI,MDD_Rel,ADD_Rel,DaR_Rel,CDaR_Rel,EDaR_Rel,UCI_Rel}, --risk-measure {MV,MAD,GMD,MSV,VaR,CVaR,TG,EVaR,RG,CVRG,TGRG,WR,FLPM,SLPM,MDD,ADD,DaR,CDaR,EDaR,UCI,MDD_Rel,ADD_Rel,DaR_Rel,CDaR_Rel,EDaR_Rel,UCI_Rel} + Risk measure used to optimize the portfolio. Possible + values are: 'MV' : Variance 'MAD' : Mean Absolute + Deviation 'GMD' : Gini Mean Difference 'MSV' : Semi + Variance (Variance of negative returns) 'FLPM' : First + Lower Partial Moment 'SLPM' : Second Lower Partial + Moment 'VaR' : Value at Risk 'CVaR' : Conditional + Value at Risk 'TG' : Tail Gini 'EVaR' : Entropic Value + at Risk 'WR' : Worst Realization 'RG' : Range 'CVRG' : + CVaR Range 'TGRG' : Tail Gini Range 'ADD' : Average + Drawdown of uncompounded returns 'UCI' : Ulcer Index + of uncompounded returns 'DaR' : Drawdown at Risk of + uncompounded returns 'CDaR' : Conditional Drawdown at + Risk of uncompounded returns 'EDaR' : Entropic + Drawdown at Risk of uncompounded returns 'MDD' : + Maximum Drawdown of uncompounded returns 'ADD_Rel' : + Average Drawdown of compounded returns 'UCI_Rel' : + Ulcer Index of compounded returns 'DaR_Rel' : Drawdown + at Risk of compounded returns 'CDaR_Rel' : Conditional + Drawdown at Risk of compounded returns 'EDaR_Rel' : + Entropic Drawdown at Risk of compounded returns + 'MDD_Rel' : Maximum Drawdown of compounded returns + (default: MV) + -r RISK_FREE, --risk-free-rate RISK_FREE + Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual (default: 0.00329) + -a SIGNIFICANCE_LEVEL, --alpha SIGNIFICANCE_LEVEL + Significance level of VaR, CVaR, EVaR, DaR, CDaR, EDaR + and Tail Gini of losses (default: 0.05) + -as CVAR_SIMULATIONS_LOSSES, --a-sim CVAR_SIMULATIONS_LOSSES + Number of CVaRs used to approximate Tail Gini of + losses. The default is 100 (default: 100) + -b CVAR_SIGNIFICANCE, --beta CVAR_SIGNIFICANCE + Significance level of CVaR and Tail Gini of gains. If + empty it duplicates alpha (default: None) + -bs CVAR_SIMULATIONS_GAINS, --b-sim CVAR_SIMULATIONS_GAINS + Number of CVaRs used to approximate Tail Gini of + gains. If empty it duplicates a_sim value (default: + None) + -lk {single,complete,average,weighted,centroid,median,ward,dbht}, --linkage {single,complete,average,weighted,centroid,median,ward,dbht} + Linkage method of hierarchical clustering (default: + single) + -k AMOUNT_CLUSTERS Number of clusters specified in advance (default: + None) + -mk MAX_CLUSTERS, --max-k MAX_CLUSTERS + Max number of clusters used by the two difference gap + statistic to find the optimal number of clusters. If k + is empty this value is used (default: 10) + -bi AMOUNT_BINS, --bins-info AMOUNT_BINS + Number of bins used to calculate the variation of + information (default: KN) + -at ALPHA_TAIL, --alpha-tail ALPHA_TAIL + Significance level for lower tail dependence index, + only used when when codependence value is 'tail' + (default: 0.05) + -lo LEAF_ORDER, --leaf-order LEAF_ORDER + Indicates if the cluster are ordered so that the + distance between successive leaves is minimal + (default: True) + -de SMOOTHING_FACTOR_EWMA, --d-ewma SMOOTHING_FACTOR_EWMA + Smoothing factor for ewma estimators (default: 0.94) + -v LONG_ALLOCATION, --value LONG_ALLOCATION + Amount to allocate to portfolio (default: 1) + --name NAME Save portfolio with personalized or default name + (default: HRP_0) + -h, --help show this help message (default: False) +``` + +Example: +``` +2022 Apr 05, 14:20 (🦋) /portfolio/po/ $ hrp + + [3 Years] Hierarchical risk parity portfolio using pearson codependence, +single linkage and volatility as risk measure + + Weights +┏━━━━━━┳━━━━━━━━━┓ +┃ ┃ Value ┃ +┡━━━━━━╇━━━━━━━━━┩ +│ AAPL │ 13.74 % │ +├──────┼─────────┤ +│ AMZN │ 17.97 % │ +├──────┼─────────┤ +│ BA │ 5.74 % │ +├──────┼─────────┤ +│ FB │ 10.29 % │ +├──────┼─────────┤ +│ MSFT │ 18.28 % │ +├──────┼─────────┤ +│ T │ 27.57 % │ +├──────┼─────────┤ +│ TSLA │ 6.37 % │ +└──────┴─────────┘ + +Annual (by 252) expected return: 28.03% +Annual (by √252) volatility: 25.35% +Sharpe ratio: 1.0982 +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/load/_index.md b/website/content/terminal/portfolio/po/load/_index.md new file mode 100644 index 00000000000..c14a3114333 --- /dev/null +++ b/website/content/terminal/portfolio/po/load/_index.md @@ -0,0 +1,14 @@ +``` +usage: load -f FILE [FILE ...] [-h] +``` + +Load file with stocks tickers and categories. + +``` +2022 Apr 26, 01:35 (🦋) /portfolio/po/ $ load -f allocation.xlsx +2022 Apr 26, 02:15 (🦋) /portfolio/po/ $ show + +Current Portfolios: None + +Current Categories: ASSET_CLASS, SECTOR, INDUSTRY, COUNTRY, CURRENT_INVESTED_AMOUNT, CURRENCY +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/maxdecorr/_index.md b/website/content/terminal/portfolio/po/maxdecorr/_index.md new file mode 100644 index 00000000000..b040ae00790 --- /dev/null +++ b/website/content/terminal/portfolio/po/maxdecorr/_index.md @@ -0,0 +1,106 @@ +``` +usage: maxdecorr [-p HISTORIC_PERIOD] [-s START_PERIOD] [-e END_PERIOD] [-lr] + [-f {d,w,m}] [-mn MAX_NAN] [-th THRESHOLD_VALUE] + [-mt NAN_FILL_METHOD] + [-cv {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink}] + [-de SMOOTHING_FACTOR_EWMA] [-v LONG_ALLOCATION] + [-vs SHORT_ALLOCATION] [--name NAME] [-h] +``` + +Maximum Decorrelation described by Christoffersen et al. ([source](https://investresolve.com/portfolio-optimization-simple-optimal-methods/#ref-Christoff2010)) is closely related to Minimum Variance and Maximum Diversification, but applies to the case where an investor believes all assets have similar returns and volatility, but heterogeneous correlations. It is a Minimum Variance optimization that is performed on the correlation matrix rather than the covariance matrix. + +Interestingly, when the weights derived from the Maximum Decorrelation optimization are divided through by their respective volatilities and re-standardized so they sum to 1, we retrieve the Maximum Diversification weights. Thus, the portfolio weights that maximize decorrelation will also maximize the Diversification Ratio when all assets have equal volatility and maximize the Sharpe ratio when all assets have equal risks and returns. + +``` +optional arguments: + -p HISTORIC_PERIOD, --period HISTORIC_PERIOD + Period to get yfinance data from. Possible frequency + strings are: 'd': means days, for example '252d' means + 252 days 'w': means weeks, for example '52w' means 52 + weeks 'mo': means months, for example '12mo' means 12 + months 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset + (default: 3y) + -s START_PERIOD, --start START_PERIOD + Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format (default: ) + -e END_PERIOD, --end END_PERIOD + End date to get yfinance data from. Must be in 'YYYY- + MM-DD' format (default: ) + -lr, --log-returns If use logarithmic or arithmetic returns to calculate + returns (default: False) + -f {d,w,m}, --freq {d,w,m} + Frequency used to calculate returns. Possible values + are: 'd': for daily returns 'w': for weekly returns + 'm': for monthly returns (default: d) + -mn MAX_NAN, --maxnan MAX_NAN + Max percentage of nan values accepted per asset to be + considered in the optimization process (default: 0.05) + -th THRESHOLD_VALUE, --threshold THRESHOLD_VALUE + Value used to replace outliers that are higher to + threshold in absolute value (default: 0.3) + -mt NAN_FILL_METHOD, --method NAN_FILL_METHOD + Method used to fill nan values in time series, by + default time. Possible values are: 'linear': linear + interpolation 'time': linear interpolation based on + time index 'nearest': use nearest value to replace nan + values 'zero': spline of zeroth order 'slinear': + spline of first order 'quadratic': spline of second + order 'cubic': spline of third order 'barycentric': + builds a polynomial that pass for all points (default: + time) + -cv {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink}, --covariance {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink} + Method used to estimate covariance matrix. Possible + values are 'hist': historical method 'ewma1': + exponential weighted moving average with adjust=True + 'ewma2': exponential weighted moving average with + adjust=False 'ledoit': Ledoit and Wolf shrinkage + method 'oas': oracle shrinkage method 'shrunk': + scikit-learn shrunk method 'gl': graphical lasso + method 'jlogo': j-logo covariance 'fixed': takes + average of eigenvalues above max Marchenko Pastour + limit 'spectral': makes zero eigenvalues above max + Marchenko Pastour limit 'shrink': Lopez de Prado's + book shrinkage method (default: hist) + -de SMOOTHING_FACTOR_EWMA, --d-ewma SMOOTHING_FACTOR_EWMA + Smoothing factor for ewma estimators (default: 0.94) + -v LONG_ALLOCATION, --value LONG_ALLOCATION + Amount to allocate to portfolio in long positions + (default: 1) + -vs SHORT_ALLOCATION, --value-short SHORT_ALLOCATION + Amount to allocate to portfolio in short positions + (default: 0.0) + --name NAME Save portfolio with personalized or default name + (default: MAXDECORR_0) + -h, --help show this help message (default: False) +``` + +Example: +``` +2022 Apr 05, 14:15 (🦋) /portfolio/po/ $ maxdecorr + + [3 Years] Display a maximal decorrelation portfolio + Weights +┏━━━━━━┳━━━━━━━━━┓ +┃ ┃ Value ┃ +┡━━━━━━╇━━━━━━━━━┩ +│ AAPL │ 0.0 % │ +├──────┼─────────┤ +│ AMZN │ 18.49 % │ +├──────┼─────────┤ +│ BA │ 17.29 % │ +├──────┼─────────┤ +│ FB │ 12.33 % │ +├──────┼─────────┤ +│ MSFT │ 0.0 % │ +├──────┼─────────┤ +│ T │ 27.37 % │ +├──────┼─────────┤ +│ TSLA │ 24.50 % │ +└──────┴─────────┘ + +Annual (by 252) expected return: 36.58% +Annual (by √252) volatility: 31.17% +Sharpe ratio: 1.1735 +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/maxdiv/_index.md b/website/content/terminal/portfolio/po/maxdiv/_index.md new file mode 100644 index 00000000000..6ab240368eb --- /dev/null +++ b/website/content/terminal/portfolio/po/maxdiv/_index.md @@ -0,0 +1,105 @@ +``` +usage: maxdiv [-p HISTORIC_PERIOD] [-s START_PERIOD] [-e END_PERIOD] [-lr] + [-f {d,w,m}] [-mn MAX_NAN] [-th THRESHOLD_VALUE] + [-mt NAN_FILL_METHOD] + [-cv {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink}] + [-de SMOOTHING_FACTOR_EWMA] [-v LONG_ALLOCATION] + [-vs SHORT_ALLOCATION] [--name NAME] [-h] +``` + +Choueifaty and Coignard ([source](https://investresolve.com/portfolio-optimization-simple-optimal-methods/#ref-Choueifaty2008)) proposed that markets are risk-efficient, such that investments will produce returns in proportion to their total risk, as measured by volatility. This differs from CAPM, which assumes returns are proportional to non-diversifiable (i.e. systematic) risk. The Diversification Ratio, which is to be maximized, quantifies the degree to which the portfolio risk can be minimized through strategic placement of weights on diversifying (imperfectly correlated) assets. + +``` +optional arguments: + -p HISTORIC_PERIOD, --period HISTORIC_PERIOD + Period to get yfinance data from. Possible frequency + strings are: 'd': means days, for example '252d' means + 252 days 'w': means weeks, for example '52w' means 52 + weeks 'mo': means months, for example '12mo' means 12 + months 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset + (default: 3y) + -s START_PERIOD, --start START_PERIOD + Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format (default: ) + -e END_PERIOD, --end END_PERIOD + End date to get yfinance data from. Must be in 'YYYY- + MM-DD' format (default: ) + -lr, --log-returns If use logarithmic or arithmetic returns to calculate + returns (default: False) + -f {d,w,m}, --freq {d,w,m} + Frequency used to calculate returns. Possible values + are: 'd': for daily returns 'w': for weekly returns + 'm': for monthly returns (default: d) + -mn MAX_NAN, --maxnan MAX_NAN + Max percentage of nan values accepted per asset to be + considered in the optimization process (default: 0.05) + -th THRESHOLD_VALUE, --threshold THRESHOLD_VALUE + Value used to replace outliers that are higher to + threshold in absolute value (default: 0.3) + -mt NAN_FILL_METHOD, --method NAN_FILL_METHOD + Method used to fill nan values in time series, by + default time. Possible values are: 'linear': linear + interpolation 'time': linear interpolation based on + time index 'nearest': use nearest value to replace nan + values 'zero': spline of zeroth order 'slinear': + spline of first order 'quadratic': spline of second + order 'cubic': spline of third order 'barycentric': + builds a polynomial that pass for all points (default: + time) + -cv {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink}, --covariance {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink} + Method used to estimate covariance matrix. Possible + values are 'hist': historical method 'ewma1': + exponential weighted moving average with adjust=True + 'ewma2': exponential weighted moving average with + adjust=False 'ledoit': Ledoit and Wolf shrinkage + method 'oas': oracle shrinkage method 'shrunk': + scikit-learn shrunk method 'gl': graphical lasso + method 'jlogo': j-logo covariance 'fixed': takes + average of eigenvalues above max Marchenko Pastour + limit 'spectral': makes zero eigenvalues above max + Marchenko Pastour limit 'shrink': Lopez de Prado's + book shrinkage method (default: hist) + -de SMOOTHING_FACTOR_EWMA, --d-ewma SMOOTHING_FACTOR_EWMA + Smoothing factor for ewma estimators (default: 0.94) + -v LONG_ALLOCATION, --value LONG_ALLOCATION + Amount to allocate to portfolio in long positions + (default: 1) + -vs SHORT_ALLOCATION, --value-short SHORT_ALLOCATION + Amount to allocate to portfolio in short positions + (default: 0.0) + --name NAME Save portfolio with personalized or default name + (default: MAXDIV_0) + -h, --help show this help message (default: False) +``` + +Example: +``` +2022 Apr 05, 14:18 (🦋) /portfolio/po/ $ maxdiv + + [3 Years] Display a maximal diversification portfolio + + Weights +┏━━━━━━┳━━━━━━━━━┓ +┃ ┃ Value ┃ +┡━━━━━━╇━━━━━━━━━┩ +│ AAPL │ 0.0 % │ +├──────┼─────────┤ +│ AMZN │ 22.62 % │ +├──────┼─────────┤ +│ BA │ 11.53 % │ +├──────┼─────────┤ +│ FB │ 12.06 % │ +├──────┼─────────┤ +│ MSFT │ 0.0 % │ +├──────┼─────────┤ +│ T │ 40.01 % │ +├──────┼─────────┤ +│ TSLA │ 13.75 % │ +└──────┴─────────┘ + +Annual (by 252) expected return: 24.68% +Annual (by √252) volatility: 26.16% +Sharpe ratio: 0.9435 +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/maxret/_index.md b/website/content/terminal/portfolio/po/maxret/_index.md new file mode 100644 index 00000000000..5f34ff1431f --- /dev/null +++ b/website/content/terminal/portfolio/po/maxret/_index.md @@ -0,0 +1,135 @@ +``` +usage: maxret [-p HISTORIC_PERIOD] [-s START_PERIOD] [-e END_PERIOD] [-lr] + [-f {d,w,m}] [-mn MAX_NAN] [-th THRESHOLD_VALUE] + [-mt NAN_FILL_METHOD] + [-rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD}] + [-r RISK_FREE] [-a SIGNIFICANCE_LEVEL] [-tr TARGET_RETURN] + [-tk TARGET_RISK] [-m {hist,ewma1,ewma2}] + [-cv {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink}] + [-de SMOOTHING_FACTOR_EWMA] [-v LONG_ALLOCATION] + [-vs SHORT_ALLOCATION] [--name NAME] [-h] +``` + +Maximizes the return of portfolio. + +``` +optional arguments: + -p HISTORIC_PERIOD, --period HISTORIC_PERIOD + Period to get yfinance data from. Possible frequency + strings are: 'd': means days, for example '252d' means + 252 days 'w': means weeks, for example '52w' means 52 + weeks 'mo': means months, for example '12mo' means 12 + months 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset + (default: 3y) + -s START_PERIOD, --start START_PERIOD + Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format (default: ) + -e END_PERIOD, --end END_PERIOD + End date to get yfinance data from. Must be in 'YYYY- + MM-DD' format (default: ) + -lr, --log-returns If use logarithmic or arithmetic returns to calculate + returns (default: False) + -f {d,w,m}, --freq {d,w,m} + Frequency used to calculate returns. Possible values + are: 'd': for daily returns 'w': for weekly returns + 'm': for monthly returns (default: d) + -mn MAX_NAN, --maxnan MAX_NAN + Max percentage of nan values accepted per asset to be + considered in the optimization process (default: 0.05) + -th THRESHOLD_VALUE, --threshold THRESHOLD_VALUE + Value used to replace outliers that are higher to + threshold in absolute value (default: 0.3) + -mt NAN_FILL_METHOD, --method NAN_FILL_METHOD + Method used to fill nan values in time series, by + default time. Possible values are: 'linear': linear + interpolation 'time': linear interpolation based on + time index 'nearest': use nearest value to replace nan + values 'zero': spline of zeroth order 'slinear': + spline of first order 'quadratic': spline of second + order 'cubic': spline of third order 'barycentric': + builds a polynomial that pass for all points (default: + time) + -rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD}, --risk-measure {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD} + Risk measure used to optimize the portfolio. Possible + values are: 'MV' : Variance 'MAD' : Mean Absolute + Deviation 'MSV' : Semi Variance (Variance of negative + returns) 'FLPM' : First Lower Partial Moment 'SLPM' : + Second Lower Partial Moment 'CVaR' : Conditional Value + at Risk 'EVaR' : Entropic Value at Risk 'WR' : Worst + Realization 'ADD' : Average Drawdown of uncompounded + returns 'UCI' : Ulcer Index of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded + returns 'EDaR' : Entropic Drawdown at Risk of + uncompounded returns 'MDD' : Maximum Drawdown of + uncompounded returns (default: MV) + -r RISK_FREE, --risk-free-rate RISK_FREE + Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual (default: 0.00329) + -a SIGNIFICANCE_LEVEL, --alpha SIGNIFICANCE_LEVEL + Significance level of CVaR, EVaR, CDaR and EDaR + (default: 0.05) + -tr TARGET_RETURN, --target-return TARGET_RETURN + Constraint on minimum level of portfolio's return + (default: -1) + -tk TARGET_RISK, --target-risk TARGET_RISK + Constraint on maximum level of portfolio's risk + (default: -1) + -m {hist,ewma1,ewma2}, --mean {hist,ewma1,ewma2} + Method used to estimate the expected return vector + (default: hist) + -cv {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink}, --covariance {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink} + Method used to estimate covariance matrix. Possible + values are 'hist': historical method 'ewma1': + exponential weighted moving average with adjust=True + 'ewma2': exponential weighted moving average with + adjust=False 'ledoit': Ledoit and Wolf shrinkage + method 'oas': oracle shrinkage method 'shrunk': + scikit-learn shrunk method 'gl': graphical lasso + method 'jlogo': j-logo covariance 'fixed': takes + average of eigenvalues above max Marchenko Pastour + limit 'spectral': makes zero eigenvalues above max + Marchenko Pastour limit 'shrink': Lopez de Prado's + book shrinkage method (default: hist) + -de SMOOTHING_FACTOR_EWMA, --d-ewma SMOOTHING_FACTOR_EWMA + Smoothing factor for ewma estimators (default: 0.94) + -v LONG_ALLOCATION, --value LONG_ALLOCATION + Amount to allocate to portfolio in long positions + (default: 1) + -vs SHORT_ALLOCATION, --value-short SHORT_ALLOCATION + Amount to allocate to portfolio in short positions + (default: 0.0) + --name NAME Save portfolio with personalized or default name + (default: MAXRET_0) + -h, --help show this help message (default: False) +``` + +Example: +``` + [3 Years] Maximal return portfolio using +volatility as risk measure + + Weights +┏━━━━━━┳━━━━━━━━━┓ +┃ ┃ Value ┃ +┡━━━━━━╇━━━━━━━━━┩ +│ AAPL │ 0.0 % │ +├──────┼─────────┤ +│ AMZN │ 0.0 % │ +├──────┼─────────┤ +│ BA │ 0.0 % │ +├──────┼─────────┤ +│ FB │ 0.0 % │ +├──────┼─────────┤ +│ MSFT │ 0.0 % │ +├──────┼─────────┤ +│ T │ 0.0 % │ +├──────┼─────────┤ +│ TSLA │ 100.0 % │ +└──────┴─────────┘ + +Annual (by 252) expected return: 124.85% +Annual (by √252) volatility: 68.44% +Sharpe ratio: 1.8215 +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/maxsharpe/_index.md b/website/content/terminal/portfolio/po/maxsharpe/_index.md new file mode 100644 index 00000000000..6ff823c3a8c --- /dev/null +++ b/website/content/terminal/portfolio/po/maxsharpe/_index.md @@ -0,0 +1,144 @@ +``` +usage: maxsharpe [-p HISTORIC_PERIOD] [-s START_PERIOD] [-e END_PERIOD] [-lr] + [-f {d,w,m}] [-mn MAX_NAN] [-th THRESHOLD_VALUE] + [-mt NAN_FILL_METHOD] + [-rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD}] + [-r RISK_FREE] [-a SIGNIFICANCE_LEVEL] [-tr TARGET_RETURN] + [-tk TARGET_RISK] [-m {hist,ewma1,ewma2}] + [-cv {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink}] + [-de SMOOTHING_FACTOR_EWMA] [-v LONG_ALLOCATION] + [-vs SHORT_ALLOCATION] [--name NAME] [-h] +``` + +Maximizes the Risk-Adjusted Return Ratio. The Sharpe ratio is one of the most widely used methods for calculating risk-adjusted return. Modern Portfolio Theory (MPT) states that adding assets to a diversified portfolio that has low correlations can decrease portfolio risk without sacrificing returns. Adding diversification should increase the Sharpe ratio compared to similar portfolios with a lower level of diversification. For this to be true, investors must also accept the assumption that risk is equal to volatility, which is not unreasonable but may be too narrow to be applied to all investments. Post-Modern Portfolio Theory (PMPT) allows to extend the concept of Sharpe ratio to other risk measures like conditional value at risk or conditional drawdown at risk to consider downside risk aversion. + +The Risk-Adjusted Return Ratio is calculated as follows: + +1. Subtract the risk-free rate from the return of the portfolio. The risk-free rate could be a U.S. Treasury rate or yield, such as the one-year or two-year Treasury yield. + +2. Divide the result by the selected risk measure of the portfolio’s excess return. + +The Risk-Adjusted Return Ratio can also help explain whether a portfolio's excess returns are due to smart investment decisions or a result of too much risk. +``` +optional arguments: + -p HISTORIC_PERIOD, --period HISTORIC_PERIOD + Period to get yfinance data from. Possible frequency + strings are: 'd': means days, for example '252d' means + 252 days 'w': means weeks, for example '52w' means 52 + weeks 'mo': means months, for example '12mo' means 12 + months 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset + (default: 3y) + -s START_PERIOD, --start START_PERIOD + Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format (default: ) + -e END_PERIOD, --end END_PERIOD + End date to get yfinance data from. Must be in 'YYYY- + MM-DD' format (default: ) + -lr, --log-returns If use logarithmic or arithmetic returns to calculate + returns (default: False) + -f {d,w,m}, --freq {d,w,m} + Frequency used to calculate returns. Possible values + are: 'd': for daily returns 'w': for weekly returns + 'm': for monthly returns (default: d) + -mn MAX_NAN, --maxnan MAX_NAN + Max percentage of nan values accepted per asset to be + considered in the optimization process (default: 0.05) + -th THRESHOLD_VALUE, --threshold THRESHOLD_VALUE + Value used to replace outliers that are higher to + threshold in absolute value (default: 0.3) + -mt NAN_FILL_METHOD, --method NAN_FILL_METHOD + Method used to fill nan values in time series, by + default time. Possible values are: 'linear': linear + interpolation 'time': linear interpolation based on + time index 'nearest': use nearest value to replace nan + values 'zero': spline of zeroth order 'slinear': + spline of first order 'quadratic': spline of second + order 'cubic': spline of third order 'barycentric': + builds a polynomial that pass for all points (default: + time) + -rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD}, --risk-measure {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD} + Risk measure used to optimize the portfolio. Possible + values are: 'MV' : Variance 'MAD' : Mean Absolute + Deviation 'MSV' : Semi Variance (Variance of negative + returns) 'FLPM' : First Lower Partial Moment 'SLPM' : + Second Lower Partial Moment 'CVaR' : Conditional Value + at Risk 'EVaR' : Entropic Value at Risk 'WR' : Worst + Realization 'ADD' : Average Drawdown of uncompounded + returns 'UCI' : Ulcer Index of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded + returns 'EDaR' : Entropic Drawdown at Risk of + uncompounded returns 'MDD' : Maximum Drawdown of + uncompounded returns (default: MV) + -r RISK_FREE, --risk-free-rate RISK_FREE + Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual (default: 0.00329) + -a SIGNIFICANCE_LEVEL, --alpha SIGNIFICANCE_LEVEL + Significance level of CVaR, EVaR, CDaR and EDaR + (default: 0.05) + -tr TARGET_RETURN, --target-return TARGET_RETURN + Constraint on minimum level of portfolio's return + (default: -1) + -tk TARGET_RISK, --target-risk TARGET_RISK + Constraint on maximum level of portfolio's risk + (default: -1) + -m {hist,ewma1,ewma2}, --mean {hist,ewma1,ewma2} + Method used to estimate the expected return vector + (default: hist) + -cv {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink}, --covariance {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink} + Method used to estimate covariance matrix. Possible + values are 'hist': historical method 'ewma1': + exponential weighted moving average with adjust=True + 'ewma2': exponential weighted moving average with + adjust=False 'ledoit': Ledoit and Wolf shrinkage + method 'oas': oracle shrinkage method 'shrunk': + scikit-learn shrunk method 'gl': graphical lasso + method 'jlogo': j-logo covariance 'fixed': takes + average of eigenvalues above max Marchenko Pastour + limit 'spectral': makes zero eigenvalues above max + Marchenko Pastour limit 'shrink': Lopez de Prado's + book shrinkage method (default: hist) + -de SMOOTHING_FACTOR_EWMA, --d-ewma SMOOTHING_FACTOR_EWMA + Smoothing factor for ewma estimators (default: 0.94) + -v LONG_ALLOCATION, --value LONG_ALLOCATION + Amount to allocate to portfolio in long positions + (default: 1) + -vs SHORT_ALLOCATION, --value-short SHORT_ALLOCATION + Amount to allocate to portfolio in short positions + (default: 0.0) + --name NAME Save portfolio with personalized or default name + (default: MAXSHARPE_0) + -h, --help show this help message (default: False) +``` + +Example: +``` +2022 Apr 05, 13:52 (🦋) /portfolio/po/ $ maxsharpe --pie + + [3 Years] Display a maximal return/risk ratio portfolio using +volatility as risk measure + + Weights +┏━━━━━━┳━━━━━━━━━┓ +┃ ┃ Value ┃ +┡━━━━━━╇━━━━━━━━━┩ +│ AAPL │ 51.47 % │ +├──────┼─────────┤ +│ AMZN │ 0.0 % │ +├──────┼─────────┤ +│ BA │ 0.0 % │ +├──────┼─────────┤ +│ FB │ 0.0 % │ +├──────┼─────────┤ +│ MSFT │ 0.0 % │ +├──────┼─────────┤ +│ T │ 0.0 % │ +├──────┼─────────┤ +│ TSLA │ 48.52 % │ +└──────┴─────────┘ + +Annual (by 252) expected return: 86.15% +Annual (by √252) volatility: 44.22% +Sharpe ratio: 1.9441 +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/maxutil/_index.md b/website/content/terminal/portfolio/po/maxutil/_index.md new file mode 100644 index 00000000000..a0bef51ec1a --- /dev/null +++ b/website/content/terminal/portfolio/po/maxutil/_index.md @@ -0,0 +1,139 @@ +``` +usage: maxutil [-p HISTORIC_PERIOD] [-s START_PERIOD] [-e END_PERIOD] [-lr] + [-f {d,w,m}] [-mn MAX_NAN] [-th THRESHOLD_VALUE] + [-mt NAN_FILL_METHOD] + [-rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD}] + [-r RISK_FREE] [-ra RISK_AVERSION] [-a SIGNIFICANCE_LEVEL] + [-tr TARGET_RETURN] [-tk TARGET_RISK] [-m {hist,ewma1,ewma2}] + [-cv {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink}] + [-de SMOOTHING_FACTOR_EWMA] [-v LONG_ALLOCATION] + [-vs SHORT_ALLOCATION] [--name NAME] [-h] +``` + +In financial economics, the risk averse utility function is the most frequently used to describe investor behaviour. In Modern Portfolio Theory (MPT), the quadratic utility function based on variance is used to model investor preferences. However, in recent years, Post-Modern Portfolio Theory (PMPT) introduces linear risk averse utility functions based on post-modern risk measures like conditional value at risk or conditional drawdown at risk in order to model downside risk aversion. + +``` +optional arguments: + -p HISTORIC_PERIOD, --period HISTORIC_PERIOD + Period to get yfinance data from. Possible frequency + strings are: 'd': means days, for example '252d' means + 252 days 'w': means weeks, for example '52w' means 52 + weeks 'mo': means months, for example '12mo' means 12 + months 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset + (default: 3y) + -s START_PERIOD, --start START_PERIOD + Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format (default: ) + -e END_PERIOD, --end END_PERIOD + End date to get yfinance data from. Must be in 'YYYY- + MM-DD' format (default: ) + -lr, --log-returns If use logarithmic or arithmetic returns to calculate + returns (default: False) + -f {d,w,m}, --freq {d,w,m} + Frequency used to calculate returns. Possible values + are: 'd': for daily returns 'w': for weekly returns + 'm': for monthly returns (default: d) + -mn MAX_NAN, --maxnan MAX_NAN + Max percentage of nan values accepted per asset to be + considered in the optimization process (default: 0.05) + -th THRESHOLD_VALUE, --threshold THRESHOLD_VALUE + Value used to replace outliers that are higher to + threshold in absolute value (default: 0.3) + -mt NAN_FILL_METHOD, --method NAN_FILL_METHOD + Method used to fill nan values in time series, by + default time. Possible values are: 'linear': linear + interpolation 'time': linear interpolation based on + time index 'nearest': use nearest value to replace nan + values 'zero': spline of zeroth order 'slinear': + spline of first order 'quadratic': spline of second + order 'cubic': spline of third order 'barycentric': + builds a polynomial that pass for all points (default: + time) + -rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD}, --risk-measure {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD} + Risk measure used to optimize the portfolio. Possible + values are: 'MV' : Variance 'MAD' : Mean Absolute + Deviation 'MSV' : Semi Variance (Variance of negative + returns) 'FLPM' : First Lower Partial Moment 'SLPM' : + Second Lower Partial Moment 'CVaR' : Conditional Value + at Risk 'EVaR' : Entropic Value at Risk 'WR' : Worst + Realization 'ADD' : Average Drawdown of uncompounded + returns 'UCI' : Ulcer Index of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded + returns 'EDaR' : Entropic Drawdown at Risk of + uncompounded returns 'MDD' : Maximum Drawdown of + uncompounded returns (default: MV) + -r RISK_FREE, --risk-free-rate RISK_FREE + Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual (default: 0.00329) + -ra RISK_AVERSION, --risk-aversion RISK_AVERSION + Risk aversion parameter (default: 1) + -a SIGNIFICANCE_LEVEL, --alpha SIGNIFICANCE_LEVEL + Significance level of CVaR, EVaR, CDaR and EDaR + (default: 0.05) + -tr TARGET_RETURN, --target-return TARGET_RETURN + Constraint on minimum level of portfolio's return + (default: -1) + -tk TARGET_RISK, --target-risk TARGET_RISK + Constraint on maximum level of portfolio's risk + (default: -1) + -m {hist,ewma1,ewma2}, --mean {hist,ewma1,ewma2} + Method used to estimate the expected return vector + (default: hist) + -cv {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink}, --covariance {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink} + Method used to estimate covariance matrix. Possible + values are 'hist': historical method 'ewma1': + exponential weighted moving average with adjust=True + 'ewma2': exponential weighted moving average with + adjust=False 'ledoit': Ledoit and Wolf shrinkage + method 'oas': oracle shrinkage method 'shrunk': + scikit-learn shrunk method 'gl': graphical lasso + method 'jlogo': j-logo covariance 'fixed': takes + average of eigenvalues above max Marchenko Pastour + limit 'spectral': makes zero eigenvalues above max + Marchenko Pastour limit 'shrink': Lopez de Prado's + book shrinkage method (default: hist) + -de SMOOTHING_FACTOR_EWMA, --d-ewma SMOOTHING_FACTOR_EWMA + Smoothing factor for ewma estimators (default: 0.94) + -v LONG_ALLOCATION, --value LONG_ALLOCATION + Amount to allocate to portfolio in long positions + (default: 1) + -vs SHORT_ALLOCATION, --value-short SHORT_ALLOCATION + Amount to allocate to portfolio in short positions + (default: 0.0) + --name NAME Save portfolio with personalized or default name + (default: MAXUTIL_0) + -h, --help show this help message (default: False) +``` + +Example: +``` +2022 Apr 05, 13:21 (🦋) /portfolio/po/ $ maxutil + + [3 Years] Display a maximal risk averse utility function + portfolio using volatility as risk measure + + Weights +┏━━━━━━┳━━━━━━━━━┓ +┃ ┃ Value ┃ +┡━━━━━━╇━━━━━━━━━┩ +│ AAPL │ 0.0 % │ +├──────┼─────────┤ +│ AMZN │ 0.0 % │ +├──────┼─────────┤ +│ BA │ 0.0 % │ +├──────┼─────────┤ +│ FB │ 0.0 % │ +├──────┼─────────┤ +│ MSFT │ 0.0 % │ +├──────┼─────────┤ +│ T │ 0.0 % │ +├──────┼─────────┤ +│ TSLA │ 100.0 % │ +└──────┴─────────┘ + +Annual (by 252) expected return: 124.85% +Annual (by √252) volatility: 68.44% +Sharpe ratio: 1.8215 +``` diff --git a/website/content/terminal/portfolio/po/minrisk/_index.md b/website/content/terminal/portfolio/po/minrisk/_index.md new file mode 100644 index 00000000000..49026cd3de4 --- /dev/null +++ b/website/content/terminal/portfolio/po/minrisk/_index.md @@ -0,0 +1,139 @@ +``` +usage: minrisk [-p HISTORIC_PERIOD] [-s START_PERIOD] [-e END_PERIOD] [-lr] + [-f {d,w,m}] [-mn MAX_NAN] [-th THRESHOLD_VALUE] + [-mt NAN_FILL_METHOD] + [-rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD}] + [-r RISK_FREE] [-a SIGNIFICANCE_LEVEL] [-tr TARGET_RETURN] + [-tk TARGET_RISK] [-m {hist,ewma1,ewma2}] + [-cv {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink}] + [-de SMOOTHING_FACTOR_EWMA] [-v LONG_ALLOCATION] + [-vs SHORT_ALLOCATION] [--name NAME] [-h] +``` + +If all investments have the same expected return independent of risk, investors seeking maximum returns for minimum risk should concentrate exclusively on minimizing risk. This is the explicit objective of the minimum variance portfolio. + +Haugen and Baker ([source](https://investresolve.com/portfolio-optimization-simple-optimal-methods/#ref-Haugen1991)) proposed dispensing with any relationship between risk and return, at least for equities. Their paper was one of the first to demonstrate that stock returns are not well explained by beta. In fact, they observed a negative relationship between returns and volatility. In the face of a spurious link between risk and return, Haugen and Baker suggested that a regularly reconstituted long-only Minimum Variance portfolio might dominate the capitalization weighted portfolio for stocks. + +``` +optional arguments: + -p HISTORIC_PERIOD, --period HISTORIC_PERIOD + Period to get yfinance data from. Possible frequency + strings are: 'd': means days, for example '252d' means + 252 days 'w': means weeks, for example '52w' means 52 + weeks 'mo': means months, for example '12mo' means 12 + months 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset + (default: 3y) + -s START_PERIOD, --start START_PERIOD + Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format (default: ) + -e END_PERIOD, --end END_PERIOD + End date to get yfinance data from. Must be in 'YYYY- + MM-DD' format (default: ) + -lr, --log-returns If use logarithmic or arithmetic returns to calculate + returns (default: False) + -f {d,w,m}, --freq {d,w,m} + Frequency used to calculate returns. Possible values + are: 'd': for daily returns 'w': for weekly returns + 'm': for monthly returns (default: d) + -mn MAX_NAN, --maxnan MAX_NAN + Max percentage of nan values accepted per asset to be + considered in the optimization process (default: 0.05) + -th THRESHOLD_VALUE, --threshold THRESHOLD_VALUE + Value used to replace outliers that are higher to + threshold in absolute value (default: 0.3) + -mt NAN_FILL_METHOD, --method NAN_FILL_METHOD + Method used to fill nan values in time series, by + default time. Possible values are: 'linear': linear + interpolation 'time': linear interpolation based on + time index 'nearest': use nearest value to replace nan + values 'zero': spline of zeroth order 'slinear': + spline of first order 'quadratic': spline of second + order 'cubic': spline of third order 'barycentric': + builds a polynomial that pass for all points (default: + time) + -rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD}, --risk-measure {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD} + Risk measure used to optimize the portfolio. Possible + values are: 'MV' : Variance 'MAD' : Mean Absolute + Deviation 'MSV' : Semi Variance (Variance of negative + returns) 'FLPM' : First Lower Partial Moment 'SLPM' : + Second Lower Partial Moment 'CVaR' : Conditional Value + at Risk 'EVaR' : Entropic Value at Risk 'WR' : Worst + Realization 'ADD' : Average Drawdown of uncompounded + returns 'UCI' : Ulcer Index of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded + returns 'EDaR' : Entropic Drawdown at Risk of + uncompounded returns 'MDD' : Maximum Drawdown of + uncompounded returns (default: MV) + -r RISK_FREE, --risk-free-rate RISK_FREE + Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual (default: 0.00329) + -a SIGNIFICANCE_LEVEL, --alpha SIGNIFICANCE_LEVEL + Significance level of CVaR, EVaR, CDaR and EDaR + (default: 0.05) + -tr TARGET_RETURN, --target-return TARGET_RETURN + Constraint on minimum level of portfolio's return + (default: -1) + -tk TARGET_RISK, --target-risk TARGET_RISK + Constraint on maximum level of portfolio's risk + (default: -1) + -m {hist,ewma1,ewma2}, --mean {hist,ewma1,ewma2} + Method used to estimate expected returns vector + (default: hist) + -cv {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink}, --covariance {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink} + Method used to estimate covariance matrix. Possible + values are 'hist': historical method 'ewma1': + exponential weighted moving average with adjust=True + 'ewma2': exponential weighted moving average with + adjust=False 'ledoit': Ledoit and Wolf shrinkage + method 'oas': oracle shrinkage method 'shrunk': + scikit-learn shrunk method 'gl': graphical lasso + method 'jlogo': j-logo covariance 'fixed': takes + average of eigenvalues above max Marchenko Pastour + limit 'spectral': makes zero eigenvalues above max + Marchenko Pastour limit 'shrink': Lopez de Prado's + book shrinkage method (default: hist) + -de SMOOTHING_FACTOR_EWMA, --d-ewma SMOOTHING_FACTOR_EWMA + Smoothing factor for ewma estimators (default: 0.94) + -v LONG_ALLOCATION, --value LONG_ALLOCATION + Amount to allocate to portfolio in long positions + (default: 1) + -vs SHORT_ALLOCATION, --value-short SHORT_ALLOCATION + Amount to allocate to portfolio in short positions + (default: 0.0) + --name NAME Save portfolio with personalized or default name + (default: MINRISK_0) + -h, --help show this help message (default: False) +``` + +Example: +``` +2022 Apr 05, 13:45 (🦋) /portfolio/po/ $ minrisk + + [3 Years] Display a minimum risk portfolio using +volatility as risk measure + + Weights +┏━━━━━━┳━━━━━━━━━┓ +┃ ┃ Value ┃ +┡━━━━━━╇━━━━━━━━━┩ +│ AAPL │ 0.0 % │ +├──────┼─────────┤ +│ AMZN │ 35.21 % │ +├──────┼─────────┤ +│ BA │ 0.0 % │ +├──────┼─────────┤ +│ FB │ 0.0 % │ +├──────┼─────────┤ +│ MSFT │ 5.86 % │ +├──────┼─────────┤ +│ T │ 58.92 % │ +├──────┼─────────┤ +│ TSLA │ 0.0 % │ +└──────┴─────────┘ + +Annual (by 252) expected return: 11.77% +Annual (by √252) volatility: 22.03% +Sharpe ratio: 0.5256 +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/mktcap/_index.md b/website/content/terminal/portfolio/po/mktcap/_index.md new file mode 100644 index 00000000000..7da31269826 --- /dev/null +++ b/website/content/terminal/portfolio/po/mktcap/_index.md @@ -0,0 +1,105 @@ +``` +usage: mktcap [-p HISTORIC_PERIOD] [-s START_PERIOD] [-e END_PERIOD] [-lr] + [-f {d,w,m}] [-mn MAX_NAN] [-th THRESHOLD_VALUE] + [-mt NAN_FILL_METHOD] + [-rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD}] + [-r RISK_FREE] [-a SIGNIFICANCE_LEVEL] [-v LONG_ALLOCATION] + [--name NAME] [-h] +``` + +Returns a portfolio that is weighted based on Market Cap. + +``` +optional arguments: + -p HISTORIC_PERIOD, --period HISTORIC_PERIOD + Period to get yfinance data from. Possible frequency + strings are: 'd': means days, for example '252d' means + 252 days 'w': means weeks, for example '52w' means 52 + weeks 'mo': means months, for example '12mo' means 12 + months 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset + (default: 3y) + -s START_PERIOD, --start START_PERIOD + Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format (default: ) + -e END_PERIOD, --end END_PERIOD + End date to get yfinance data from. Must be in 'YYYY- + MM-DD' format (default: ) + -lr, --log-returns If use logarithmic or arithmetic returns to calculate + returns (default: False) + -f {d,w,m}, --freq {d,w,m} + Frequency used to calculate returns. Possible values + are: 'd': for daily returns 'w': for weekly returns + 'm': for monthly returns (default: d) + -mn MAX_NAN, --maxnan MAX_NAN + Max percentage of nan values accepted per asset to be + considered in the optimization process (default: 0.05) + -th THRESHOLD_VALUE, --threshold THRESHOLD_VALUE + Value used to replace outliers that are higher to + threshold in absolute value (default: 0.3) + -mt NAN_FILL_METHOD, --method NAN_FILL_METHOD + Method used to fill nan values in time series, by + default time. Possible values are: 'linear': linear + interpolation 'time': linear interpolation based on + time index 'nearest': use nearest value to replace nan + values 'zero': spline of zeroth order 'slinear': + spline of first order 'quadratic': spline of second + order 'cubic': spline of third order 'barycentric': + builds a polynomial that pass for all points (default: + time) + -rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD}, --risk-measure {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD} + Risk measure used to calculate indicators. Possible + values are: 'MV' : Variance 'MAD' : Mean Absolute + Deviation 'MSV' : Semi Variance (Variance of negative + returns) 'FLPM' : First Lower Partial Moment 'SLPM' : + Second Lower Partial Moment 'CVaR' : Conditional Value + at Risk 'EVaR' : Entropic Value at Risk 'WR' : Worst + Realization 'ADD' : Average Drawdown of uncompounded + returns 'UCI' : Ulcer Index of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded + returns 'EDaR' : Entropic Drawdown at Risk of + uncompounded returns 'MDD' : Maximum Drawdown of + uncompounded returns (default: MV) + -r RISK_FREE, --risk-free-rate RISK_FREE + Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual (default: 0.00329) + -a SIGNIFICANCE_LEVEL, --alpha SIGNIFICANCE_LEVEL + Significance level of CVaR, EVaR, CDaR and EDaR + (default: 0.05) + -v LONG_ALLOCATION, --value LONG_ALLOCATION + Amount to allocate to portfolio (default: 1) + --name NAME Save portfolio with personalized or default name + (default: MKTCAP_0) + -h, --help show this help message (default: False) +``` + +Example: +``` +2022 Apr 05, 14:53 (🦋) /portfolio/po/ $ mktcap + + [3 Years] Weighted Portfolio based on marketCap + + Weights +┏━━━━━━┳━━━━━━━━━┓ +┃ ┃ Value ┃ +┡━━━━━━╇━━━━━━━━━┩ +│ AAPL │ 32.03 % │ +├──────┼─────────┤ +│ AMZN │ 18.73 % │ +├──────┼─────────┤ +│ BA │ 1.21 % │ +├──────┼─────────┤ +│ FB │ 7.10 % │ +├──────┼─────────┤ +│ MSFT │ 26.20 % │ +├──────┼─────────┤ +│ T │ 1.92 % │ +├──────┼─────────┤ +│ TSLA │ 12.79 % │ +└──────┴─────────┘ + +Annual (by 252) expected return: 47.78% +Annual (by √252) volatility: 30.44% +Sharpe ratio: 1.5636 +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/nco/_index.md b/website/content/terminal/portfolio/po/nco/_index.md new file mode 100644 index 00000000000..850c300cd46 --- /dev/null +++ b/website/content/terminal/portfolio/po/nco/_index.md @@ -0,0 +1,161 @@ +``` +usage: nco [-p HISTORIC_PERIOD] [-s START_PERIOD] [-e END_PERIOD] [-lr] + [-f {d,w,m}] [-mn MAX_NAN] [-th THRESHOLD_VALUE] + [-mt NAN_FILL_METHOD] + [-cd {pearson,spearman,abs_pearson,abs_spearman,distance,mutual_info,tail}] + [-cv {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink}] + [-o {MinRisk,Utility,Sharpe,ERC}] + [-rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD}] + [-r RISK_FREE] [-ra RISK_AVERSION] [-a SIGNIFICANCE_LEVEL] + [-lk {single,complete,average,weighted,centroid,median,ward,dbht}] + [-k AMOUNT_CLUSTERS] [-mk MAX_CLUSTERS] [-bi AMOUNT_BINS] + [-at ALPHA_TAIL] [-lo] [-de SMOOTHING_FACTOR_EWMA] + [-v LONG_ALLOCATION] [--name NAME] [-h] +``` + +Convex optimization solutions tend to be unstable, to the point of entirely offsetting the benefits of optimization. For example, in the context of financial applications, it is known that portfolios optimized in-sample often underperform the naïve (equal weights) allocation out-of-sample. This instability can be traced back to two sources: (i) noise in the input variables; and (ii) signal structure that magnifies the estimation errors in the input variables. The paper by Lopez de Prado ([source](https://papers.ssrn.com/sol3/papers.cfm?abstract_id=3469961)) introduces the nested clustered optimization algorithm (NCO), a method that tackles both sources of instability. + +``` +optional arguments: + -p HISTORIC_PERIOD, --period HISTORIC_PERIOD + Period to get yfinance data from. Possible frequency + strings are: 'd': means days, for example '252d' means + 252 days 'w': means weeks, for example '52w' means 52 + weeks 'mo': means months, for example '12mo' means 12 + months 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset + (default: 3y) + -s START_PERIOD, --start START_PERIOD + Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format (default: ) + -e END_PERIOD, --end END_PERIOD + End date to get yfinance data from. Must be in 'YYYY- + MM-DD' format (default: ) + -lr, --log-returns If use logarithmic or arithmetic returns to calculate + returns (default: False) + -f {d,w,m}, --freq {d,w,m} + Frequency used to calculate returns. Possible values + are: 'd': for daily returns 'w': for weekly returns + 'm': for monthly returns (default: d) + -mn MAX_NAN, --maxnan MAX_NAN + Max percentage of nan values accepted per asset to be + considered in the optimization process (default: 0.05) + -th THRESHOLD_VALUE, --threshold THRESHOLD_VALUE + Value used to replace outliers that are higher to + threshold in absolute value (default: 0.3) + -mt NAN_FILL_METHOD, --method NAN_FILL_METHOD + Method used to fill nan values in time series, by + default time. Possible values are: 'linear': linear + interpolation 'time': linear interpolation based on + time index 'nearest': use nearest value to replace nan + values 'zero': spline of zeroth order 'slinear': + spline of first order 'quadratic': spline of second + order 'cubic': spline of third order 'barycentric': + builds a polynomial that pass for all points (default: + time) + -cd {pearson,spearman,abs_pearson,abs_spearman,distance,mutual_info,tail}, --codependence {pearson,spearman,abs_pearson,abs_spearman,distance,mutual_info,tail} + The codependence or similarity matrix used to build + the distance metric and clusters. Possible values are: + 'pearson': pearson correlation matrix 'spearman': + spearman correlation matrix 'abs_pearson': absolute + value of pearson correlation matrix 'abs_spearman': + absolute value of spearman correlation matrix + 'distance': distance correlation matrix 'mutual_info': + mutual information codependence matrix 'tail': tail + index codependence matrix (default: pearson) + -cv {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink}, --covariance {hist,ewma1,ewma2,ledoit,oas,shrunk,gl,jlogo,fixed,spectral,shrink} + Method used to estimate covariance matrix. Possible + values are 'hist': historical method 'ewma1': + exponential weighted moving average with adjust=True + 'ewma2': exponential weighted moving average with + adjust=False 'ledoit': Ledoit and Wolf shrinkage + method 'oas': oracle shrinkage method 'shrunk': + scikit-learn shrunk method 'gl': graphical lasso + method 'jlogo': j-logo covariance 'fixed': takes + average of eigenvalues above max Marchenko Pastour + limit 'spectral': makes zero eigenvalues above max + Marchenko Pastour limit 'shrink': Lopez de Prado's + book shrinkage method (default: hist) + -o {MinRisk,Utility,Sharpe,ERC}, --objective {MinRisk,Utility,Sharpe,ERC} + Objective function used to optimize the portfolio + (default: MinRisk) + -rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD}, --risk-measure {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD} + Risk measure used to optimize the portfolio. Possible + values are: 'MV' : Variance 'MAD' : Mean Absolute + Deviation 'MSV' : Semi Variance (Variance of negative + returns) 'FLPM' : First Lower Partial Moment 'SLPM' : + Second Lower Partial Moment 'CVaR' : Conditional Value + at Risk 'EVaR' : Entropic Value at Risk 'WR' : Worst + Realization 'ADD' : Average Drawdown of uncompounded + returns 'UCI' : Ulcer Index of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded + returns 'EDaR' : Entropic Drawdown at Risk of + uncompounded returns 'MDD' : Maximum Drawdown of + uncompounded returns (default: MV) + -r RISK_FREE, --risk-free-rate RISK_FREE + Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual (default: 0.00329) + -ra RISK_AVERSION, --risk-aversion RISK_AVERSION + Risk aversion parameter (default: 1) + -a SIGNIFICANCE_LEVEL, --alpha SIGNIFICANCE_LEVEL + Significance level of CVaR, EVaR, CDaR and EDaR + (default: 0.05) + -lk {single,complete,average,weighted,centroid,median,ward,dbht}, --linkage {single,complete,average,weighted,centroid,median,ward,dbht} + Linkage method of hierarchical clustering (default: + single) + -k AMOUNT_CLUSTERS Number of clusters specified in advance (default: + None) + -mk MAX_CLUSTERS, --max-k MAX_CLUSTERS + Max number of clusters used by the two difference gap + statistic to find the optimal number of clusters. If k + is empty this value is used (default: 10) + -bi AMOUNT_BINS, --bins-info AMOUNT_BINS + Number of bins used to calculate the variation of + information (default: KN) + -at ALPHA_TAIL, --alpha-tail ALPHA_TAIL + Significance level for lower tail dependence index, + only used when when codependence value is 'tail' + (default: 0.05) + -lo, --leaf-order indicates if the cluster are ordered so that the + distance between successive leaves is minimal + (default: True) + -de SMOOTHING_FACTOR_EWMA, --d-ewma SMOOTHING_FACTOR_EWMA + Smoothing factor for ewma estimators (default: 0.94) + -v LONG_ALLOCATION, --value LONG_ALLOCATION + Amount to allocate to portfolio (default: 1) + --name NAME Save portfolio with personalized or default name + (default: NCO_0) + -h, --help show this help message (default: False) +``` + +Example: +``` +2022 Apr 05, 14:34 (🦋) /portfolio/po/ $ nco + + [3 Years] Nested clustered optimization using pearson codependence, +single linkage and volatility as risk measure + + Weights +┏━━━━━━┳━━━━━━━━━┓ +┃ ┃ Value ┃ +┡━━━━━━╇━━━━━━━━━┩ +│ AAPL │ 7.17 % │ +├──────┼─────────┤ +│ AMZN │ 19.33 % │ +├──────┼─────────┤ +│ BA │ 0.0 % │ +├──────┼─────────┤ +│ FB │ 0.53 % │ +├──────┼─────────┤ +│ MSFT │ 16.81 % │ +├──────┼─────────┤ +│ T │ 56.14 % │ +├──────┼─────────┤ +│ TSLA │ 0.0 % │ +└──────┴─────────┘ + +Annual (by 252) expected return: 15.58% +Annual (by √252) volatility: 22.42% +Sharpe ratio: 0.6868 +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/params/_index.md b/website/content/terminal/portfolio/po/params/_index.md new file mode 100644 index 00000000000..1fe1451bfdd --- /dev/null +++ b/website/content/terminal/portfolio/po/params/_index.md @@ -0,0 +1,43 @@ +--- +geekdocCollapseSection: true +--- + +This menu can be used to change the loaded parameters file and/or alter specific parameters currently set as default. +``` +╭──────────────────────────────────────────────────────────────────────────────────────────── Portfolio - Portfolio Optimization - Parameters ────────────────────────────────────────────────────────────────────────────────────────────╮ +│ │ +│ Portfolio Risk Parameters (.ini or .xlsx) │ +│ │ +│ Loaded file: OpenBB_Parameters_Template v1.0.0.xlsx │ +│ │ +│ file load portfolio risk parameters │ +│ save save portfolio risk parameters to specified file │ +│ │ +│ Model of interest: maxsharpe │ +│ │ +│ clear clear model of interest from filtered parameters │ +│ set set model of interest to filter parameters │ +│ arg set a different value for an argument │ +│ │ +│ Parameters: │ +│ historic_period : 3y │ +│ log_returns : 0 │ +│ return_frequency : d │ +│ max_nan : 0.05 │ +│ threshold_value : 0.3 │ +│ nan_fill_method : time │ +│ risk_free : 0.003 │ +│ significance_level : 0.05 │ +│ risk_measure : MV │ +│ target_return : -1 │ +│ target_risk : -1 │ +│ expected_return : hist │ +│ covariance : hist │ +│ smoothing_factor_ewma : 0.94 │ +│ long_allocation : 1 │ +│ short_allocation : 0 │ +│ │ +╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── OpenBB Terminal ─╯ +``` + +{{< toc-tree >}} \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/params/arg/_index.md b/website/content/terminal/portfolio/po/params/arg/_index.md new file mode 100644 index 00000000000..b5c4599ae79 --- /dev/null +++ b/website/content/terminal/portfolio/po/params/arg/_index.md @@ -0,0 +1,48 @@ +``` +usage: arg [-a ARGUMENT ARGUMENT] [-s] [-h] +``` + +Set a different value for one of the available arguments. + +``` +optional arguments: + -a ARGUMENT ARGUMENT, --argument ARGUMENT ARGUMENT + Set a value for an argument (default: None) + -s, --show_arguments Show the available arguments, the options and a description. (default: False) + -h, --help show this help message (default: False) +``` + +Example: +``` +2022 May 02, 05:53 (🦋) /portfolio/po/params/ $ arg historic_period 10y + +2022 May 02, 05:53 (🦋) /portfolio/po/params/ $ ? +╭──────────────────────────────────────────────────────────────────────────────────────────── Portfolio - Portfolio Optimization - Parameters ────────────────────────────────────────────────────────────────────────────────────────────╮ +│ │ +│ Portfolio Risk Parameters (.ini or .xlsx) │ +│ │ +│ Loaded file: OpenBB_Parameters_Template v1.0.0.xlsx │ +│ │ +│ file load portfolio risk parameters │ +│ save save portfolio risk parameters to specified file │ +│ │ +│ Model of interest: maxdecorr │ +│ │ +│ clear clear model of interest from filtered parameters │ +│ set set model of interest to filter parameters │ +│ arg set a different value for an argument │ +│ │ +│ Parameters: │ +│ historic_period : 10y │ +│ log_returns : 0 │ +│ return_frequency : d │ +│ max_nan : 0.05 │ +│ threshold_value : 0.3 │ +│ nan_fill_method : time │ +│ risk_free : 0.003 │ +│ significance_level : 0.05 │ +│ covariance : hist │ +│ long_allocation : 1 │ +│ │ +╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── OpenBB Terminal ─╯ +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/params/clear/_index.md b/website/content/terminal/portfolio/po/params/clear/_index.md new file mode 100644 index 00000000000..af27dd6774a --- /dev/null +++ b/website/content/terminal/portfolio/po/params/clear/_index.md @@ -0,0 +1,106 @@ +``` +usage: clear [-h] +``` + +Clear selected portfolio optimization models + +``` +optional arguments: + -h, --help show this help message (default: False) +``` + +Example: +``` +2022 May 02, 05:51 (🦋) /portfolio/po/params/ $ ? +╭──────────────────────────────────────────────────────────────────────────────────────────── Portfolio - Portfolio Optimization - Parameters ────────────────────────────────────────────────────────────────────────────────────────────╮ +│ │ +│ Portfolio Risk Parameters (.ini or .xlsx) │ +│ │ +│ Loaded file: OpenBB_Parameters_Template v1.0.0.xlsx │ +│ │ +│ file load portfolio risk parameters │ +│ save save portfolio risk parameters to specified file │ +│ │ +│ Model of interest: maxsharpe │ +│ │ +│ clear clear model of interest from filtered parameters │ +│ set set model of interest to filter parameters │ +│ arg set a different value for an argument │ +│ │ +│ Parameters: │ +│ historic_period : 3y │ +│ log_returns : 0 │ +│ return_frequency : d │ +│ max_nan : 0.05 │ +│ threshold_value : 0.3 │ +│ nan_fill_method : time │ +│ risk_free : 0.003 │ +│ significance_level : 0.05 │ +│ risk_measure : MV │ +│ target_return : -1 │ +│ target_risk : -1 │ +│ expected_return : hist │ +│ covariance : hist │ +│ smoothing_factor_ewma : 0.94 │ +│ long_allocation : 1 │ +│ short_allocation : 0 │ +│ │ +╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── OpenBB Terminal ─╯ +2022 May 02, 05:51 (🦋) /portfolio/po/params/ $ clear + +2022 May 02, 05:51 (🦋) /portfolio/po/params/ $ ? +╭──────────────────────────────────────────────────────────────────────────────────────────── Portfolio - Portfolio Optimization - Parameters ────────────────────────────────────────────────────────────────────────────────────────────╮ +│ │ +│ Portfolio Risk Parameters (.ini or .xlsx) │ +│ │ +│ Loaded file: OpenBB_Parameters_Template v1.0.0.xlsx │ +│ │ +│ file load portfolio risk parameters │ +│ save save portfolio risk parameters to specified file │ +│ │ +│ Model of interest: │ +│ │ +│ clear clear model of interest from filtered parameters │ +│ set set model of interest to filter parameters │ +│ arg set a different value for an argument │ +│ │ +│ Parameters: │ +│ historic_period : 3y │ +│ log_returns : 0 │ +│ return_frequency : d │ +│ max_nan : 0.05 │ +│ threshold_value : 0.3 │ +│ nan_fill_method : time │ +│ risk_free : 0.003 │ +│ significance_level : 0.05 │ +│ technique : maxsharpe │ +│ risk_measure : MV │ +│ target_return : -1 │ +│ target_risk : -1 │ +│ expected_return : hist │ +│ covariance : hist │ +│ smoothing_factor_ewma : 0.94 │ +│ long_allocation : 1 │ +│ short_allocation : 0 │ +│ risk_aversion : 1 │ +│ amount_portfolios : 100 │ +│ random_seed : 123 │ +│ tangency : 0 │ +│ risk_parity_model : A │ +│ penal_factor : 1 │ +│ equilibrium : 1 │ +│ optimize : 1 │ +│ co_dependence : pearson │ +│ cvar_simulations_losses : 100 │ +│ cvar_simulations_gains : 100 │ +│ cvar_significance : 0.05 │ +│ linkage : single │ +│ amount_clusters : 10 │ +│ max_clusters : 10 │ +│ amount_bins : KN │ +│ alpha_tail : 0.05 │ +│ leaf_order : 1 │ +│ objective : MinRisk │ +│ │ +╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── OpenBB Terminal ─╯ +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/params/file/_index.md b/website/content/terminal/portfolio/po/params/file/_index.md new file mode 100644 index 00000000000..993692a59a0 --- /dev/null +++ b/website/content/terminal/portfolio/po/params/file/_index.md @@ -0,0 +1,17 @@ +``` +usage: file -f FILE [FILE ...] [-h] +``` + +Load portfolio risk parameters (ini or xlsx) + +``` +optional arguments: + -f FILE [FILE ...], --file FILE [FILE ...] + Parameter file to be used (default: None) + -h, --help show this help message (default: False) +``` + +Example: +``` +2022 May 02, 05:47 (🦋) /portfolio/po/params/ $ file OpenBB_Parameters_Template v1.0.0.xlsx +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/params/save/_index.md b/website/content/terminal/portfolio/po/params/save/_index.md new file mode 100644 index 00000000000..116703bce2a --- /dev/null +++ b/website/content/terminal/portfolio/po/params/save/_index.md @@ -0,0 +1,16 @@ +``` +usage: save -f FILE [-h] +``` + +Save portfolio risk parameters (ini or xlsx) + +``` +optional arguments: + -f FILE, --file FILE Filename to be saved (default: None) + -h, --help show this help message (default: False) +``` + +Example: +``` +2022 May 02, 05:49 (🦋) /portfolio/po/params/ $ save OpenBB_Parameters_Template.ini -h +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/params/set/_index.md b/website/content/terminal/portfolio/po/params/set/_index.md new file mode 100644 index 00000000000..2c711ecdea2 --- /dev/null +++ b/website/content/terminal/portfolio/po/params/set/_index.md @@ -0,0 +1,48 @@ +``` +usage: set -m {maxsharpe,minrisk,maxutil,maxret,maxdiv,maxdecorr,ef,riskparity,relriskparity,hrp,herc,nco} [-h] +``` + +Select one of the portfolio optimization models + +``` +optional arguments: + -m {maxsharpe,minrisk,maxutil,maxret,maxdiv,maxdecorr,ef,riskparity,relriskparity,hrp,herc,nco}, --model {maxsharpe,minrisk,maxutil,maxret,maxdiv,maxdecorr,ef,riskparity,relriskparity,hrp,herc,nco} + Frequency used to calculate returns (default: None) + -h, --help show this help message (default: False) + +``` + +Example: +``` +2022 May 02, 05:51 (🦋) /portfolio/po/params/ $ set maxdecorr + +2022 May 02, 05:52 (🦋) /portfolio/po/params/ $ ? +╭──────────────────────────────────────────────────────────────────────────────────────────── Portfolio - Portfolio Optimization - Parameters ────────────────────────────────────────────────────────────────────────────────────────────╮ +│ │ +│ Portfolio Risk Parameters (.ini or .xlsx) │ +│ │ +│ Loaded file: OpenBB_Parameters_Template v1.0.0.xlsx │ +│ │ +│ file load portfolio risk parameters │ +│ save save portfolio risk parameters to specified file │ +│ │ +│ Model of interest: maxdecorr │ +│ │ +│ clear clear model of interest from filtered parameters │ +│ set set model of interest to filter parameters │ +│ arg set a different value for an argument │ +│ │ +│ Parameters: │ +│ historic_period : 3y │ +│ log_returns : 0 │ +│ return_frequency : d │ +│ max_nan : 0.05 │ +│ threshold_value : 0.3 │ +│ nan_fill_method : time │ +│ risk_free : 0.003 │ +│ significance_level : 0.05 │ +│ covariance : hist │ +│ long_allocation : 1 │ +│ │ +╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── OpenBB Terminal ─╯ +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/plot/_index.md b/website/content/terminal/portfolio/po/plot/_index.md new file mode 100644 index 00000000000..2d5778a9fea --- /dev/null +++ b/website/content/terminal/portfolio/po/plot/_index.md @@ -0,0 +1,89 @@ +``` +usage: plot [-pf PORTFOLIOS] [-ct CATEGORIES] [-p HISTORIC_PERIOD] + [-s START_PERIOD] [-e END_PERIOD] [-lr] [-f {d,w,m}] [-mn MAX_NAN] + [-th THRESHOLD_VALUE] [-mt NAN_FILL_METHOD] + [-rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD}] + [-r RISK_FREE] [-a SIGNIFICANCE_LEVEL] [-pi] [-hi] [-dd] [-rc] + [-he] [-h] +``` + +Plot selected charts for portfolios + +``` +optional arguments: + -pf PORTFOLIOS, --portfolios PORTFOLIOS + Selected portfolios that will be plotted (default: []) + -ct CATEGORIES, --categories CATEGORIES + Show selected categories (default: []) + -p HISTORIC_PERIOD, --period HISTORIC_PERIOD + Period to get yfinance data from. Possible frequency + strings are: 'd': means days, for example '252d' means + 252 days 'w': means weeks, for example '52w' means 52 + weeks 'mo': means months, for example '12mo' means 12 + months 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset + (default: 3y) + -s START_PERIOD, --start START_PERIOD + Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format (default: ) + -e END_PERIOD, --end END_PERIOD + End date to get yfinance data from. Must be in 'YYYY- + MM-DD' format (default: ) + -lr, --log-returns If use logarithmic or arithmetic returns to calculate + returns (default: False) + -f {d,w,m}, --freq {d,w,m} + Frequency used to calculate returns. Possible values + are: 'd': for daily returns 'w': for weekly returns + 'm': for monthly returns (default: d) + -mn MAX_NAN, --maxnan MAX_NAN + Max percentage of nan values accepted per asset to be + considered in the optimization process (default: 0.05) + -th THRESHOLD_VALUE, --threshold THRESHOLD_VALUE + Value used to replace outliers that are higher to + threshold in absolute value (default: 0.3) + -mt NAN_FILL_METHOD, --method NAN_FILL_METHOD + Method used to fill nan values in time series, by + default time. Possible values are: 'linear': linear + interpolation 'time': linear interpolation based on + time index 'nearest': use nearest value to replace nan + values 'zero': spline of zeroth order 'slinear': + spline of first order 'quadratic': spline of second + order 'cubic': spline of third order 'barycentric': + builds a polynomial that pass for all points (default: + time) + -rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD}, --risk-measure {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD} + Risk measure used to optimize the portfolio. Possible + values are: 'MV' : Variance 'MAD' : Mean Absolute + Deviation 'MSV' : Semi Variance (Variance of negative + returns) 'FLPM' : First Lower Partial Moment 'SLPM' : + Second Lower Partial Moment 'CVaR' : Conditional Value + at Risk 'EVaR' : Entropic Value at Risk 'WR' : Worst + Realization 'ADD' : Average Drawdown of uncompounded + returns 'UCI' : Ulcer Index of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded + returns 'EDaR' : Entropic Drawdown at Risk of + uncompounded returns 'MDD' : Maximum Drawdown of + uncompounded returns (default: MV) + -r RISK_FREE, --risk-free-rate RISK_FREE + Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual (default: 0.00329) + -a SIGNIFICANCE_LEVEL, --alpha SIGNIFICANCE_LEVEL + Significance level of CVaR, EVaR, CDaR and EDaR + (default: 0.05) + -pi, --pie Display a pie chart for weights (default: False) + -hi, --hist Display a histogram with risk measures (default: + False) + -dd, --drawdown Display a drawdown chart with risk measures (default: + False) + -rc, --rc-chart Display a risk contribution chart for assets (default: + False) + -he, --heat Display a heatmap of correlation matrix with + dendrogram (default: False) + -h, --help show this help message (default: False) +``` + +Example: +``` +2022 Apr 26, 02:19 (🦋) /portfolio/po/ $ plot -pf maxsharpe_0 -pi -hi -dd -rc -he +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/property/_index.md b/website/content/terminal/portfolio/po/property/_index.md new file mode 100644 index 00000000000..466399fbcd6 --- /dev/null +++ b/website/content/terminal/portfolio/po/property/_index.md @@ -0,0 +1,109 @@ +``` +usage: property [-p HISTORIC_PERIOD] [-s START_PERIOD] [-e END_PERIOD] [-lr] + [-f {d,w,m}] [-mn MAX_NAN] [-th THRESHOLD_VALUE] + [-mt NAN_FILL_METHOD] + [-pr {previousClose,regularMarketOpen,twoHundredDayAverage,trailingAnnualDividendYield,payoutRatio,volume24Hr,regularMarketDayHigh,navPrice,averageDailyVolume10Day,totalAssets,regularMarketPreviousClose,fiftyDayAverage,trailingAnnualDividendRate,open,toCurrency,averageVolume10days,expireDate,yield,algorithm,dividendRate,exDividendDate,beta,circulatingSupply,regularMarketDayLow,priceHint,currency,trailingPE,regularMarketVolume,lastMarket,maxSupply,openInterest,marketCap,volumeAllCurrencies,strikePrice,averageVolume,priceToSalesTrailing12Months,dayLow,ask,ytdReturn,askSize,volume,fiftyTwoWeekHigh,forwardPE,fromCurrency,fiveYearAvgDividendYield,fiftyTwoWeekLow,bid,dividendYield,bidSize,dayHigh,annualHoldingsTurnover,enterpriseToRevenue,beta3Year,profitMargins,enterpriseToEbitda,52WeekChange,morningStarRiskRating,forwardEps,revenueQuarterlyGrowth,sharesOutstanding,fundInceptionDate,annualReportExpenseRatio,bookValue,sharesShort,sharesPercentSharesOut,heldPercentInstitutions,netIncomeToCommon,trailingEps,lastDividendValue,SandP52WeekChange,priceToBook,heldPercentInsiders,shortRatio,sharesShortPreviousMonthDate,floatShares,enterpriseValue,fundFamily,threeYearAverageReturn,lastSplitFactor,legalType,lastDividendDate,morningStarOverallRating,earningsQuarterlyGrowth,pegRatio,lastCapGain,shortPercentOfFloat,sharesShortPriorMonth,impliedSharesOutstanding,fiveYearAverageReturn,regularMarketPrice}] + [-rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD}] + [-r RISK_FREE] [-a SIGNIFICANCE_LEVEL] [-v LONG_ALLOCATION] + [--name NAME] [-h] +``` + +Returns a portfolio that is weighted based on selected property. + +``` +optional arguments: + -p HISTORIC_PERIOD, --period HISTORIC_PERIOD + Period to get yfinance data from. Possible frequency + strings are: 'd': means days, for example '252d' means + 252 days 'w': means weeks, for example '52w' means 52 + weeks 'mo': means months, for example '12mo' means 12 + months 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset + (default: 3y) + -s START_PERIOD, --start START_PERIOD + Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format (default: ) + -e END_PERIOD, --end END_PERIOD + End date to get yfinance data from. Must be in 'YYYY- + MM-DD' format (default: ) + -lr, --log-returns If use logarithmic or arithmetic returns to calculate + returns (default: False) + -f {d,w,m}, --freq {d,w,m} + Frequency used to calculate returns. Possible values + are: 'd': for daily returns 'w': for weekly returns + 'm': for monthly returns (default: d) + -mn MAX_NAN, --maxnan MAX_NAN + Max percentage of nan values accepted per asset to be + considered in the optimization process (default: 0.05) + -th THRESHOLD_VALUE, --threshold THRESHOLD_VALUE + Value used to replace outliers that are higher to + threshold in absolute value (default: 0.3) + -mt NAN_FILL_METHOD, --method NAN_FILL_METHOD + Method used to fill nan values in time series, by + default time. Possible values are: 'linear': linear + interpolation 'time': linear interpolation based on + time index 'nearest': use nearest value to replace nan + values 'zero': spline of zeroth order 'slinear': + spline of first order 'quadratic': spline of second + order 'cubic': spline of third order 'barycentric': + builds a polynomial that pass for all points (default: + time) + -pr {previousClose,regularMarketOpen,twoHundredDayAverage,trailingAnnualDividendYield,payoutRatio,volume24Hr,regularMarketDayHigh,navPrice,averageDailyVolume10Day,totalAssets,regularMarketPreviousClose,fiftyDayAverage,trailingAnnualDividendRate,open,toCurrency,averageVolume10days,expireDate,yield,algorithm,dividendRate,exDividendDate,beta,circulatingSupply,regularMarketDayLow,priceHint,currency,trailingPE,regularMarketVolume,lastMarket,maxSupply,openInterest,marketCap,volumeAllCurrencies,strikePrice,averageVolume,priceToSalesTrailing12Months,dayLow,ask,ytdReturn,askSize,volume,fiftyTwoWeekHigh,forwardPE,fromCurrency,fiveYearAvgDividendYield,fiftyTwoWeekLow,bid,dividendYield,bidSize,dayHigh,annualHoldingsTurnover,enterpriseToRevenue,beta3Year,profitMargins,enterpriseToEbitda,52WeekChange,morningStarRiskRating,forwardEps,revenueQuarterlyGrowth,sharesOutstanding,fundInceptionDate,annualReportExpenseRatio,bookValue,sharesShort,sharesPercentSharesOut,heldPercentInstitutions,netIncomeToCommon,trailingEps,lastDividendValue,SandP52WeekChange,priceToBook,heldPercentInsiders,shortRatio,sharesShortPreviousMonthDate,floatShares,enterpriseValue,fundFamily,threeYearAverageReturn,lastSplitFactor,legalType,lastDividendDate,morningStarOverallRating,earningsQuarterlyGrowth,pegRatio,lastCapGain,shortPercentOfFloat,sharesShortPriorMonth,impliedSharesOutstanding,fiveYearAverageReturn,regularMarketPrice}, --property {previousClose,regularMarketOpen,twoHundredDayAverage,trailingAnnualDividendYield,payoutRatio,volume24Hr,regularMarketDayHigh,navPrice,averageDailyVolume10Day,totalAssets,regularMarketPreviousClose,fiftyDayAverage,trailingAnnualDividendRate,open,toCurrency,averageVolume10days,expireDate,yield,algorithm,dividendRate,exDividendDate,beta,circulatingSupply,regularMarketDayLow,priceHint,currency,trailingPE,regularMarketVolume,lastMarket,maxSupply,openInterest,marketCap,volumeAllCurrencies,strikePrice,averageVolume,priceToSalesTrailing12Months,dayLow,ask,ytdReturn,askSize,volume,fiftyTwoWeekHigh,forwardPE,fromCurrency,fiveYearAvgDividendYield,fiftyTwoWeekLow,bid,dividendYield,bidSize,dayHigh,annualHoldingsTurnover,enterpriseToRevenue,beta3Year,profitMargins,enterpriseToEbitda,52WeekChange,morningStarRiskRating,forwardEps,revenueQuarterlyGrowth,sharesOutstanding,fundInceptionDate,annualReportExpenseRatio,bookValue,sharesShort,sharesPercentSharesOut,heldPercentInstitutions,netIncomeToCommon,trailingEps,lastDividendValue,SandP52WeekChange,priceToBook,heldPercentInsiders,shortRatio,sharesShortPreviousMonthDate,floatShares,enterpriseValue,fundFamily,threeYearAverageReturn,lastSplitFactor,legalType,lastDividendDate,morningStarOverallRating,earningsQuarterlyGrowth,pegRatio,lastCapGain,shortPercentOfFloat,sharesShortPriorMonth,impliedSharesOutstanding,fiveYearAverageReturn,regularMarketPrice} + Property info to weight. Use one of yfinance info + options. (default: None) + -rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD}, --risk-measure {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,WR,ADD,UCI,CDaR,EDaR,MDD} + Risk measure used to optimize the portfolio. Possible + values are: 'MV' : Variance 'MAD' : Mean Absolute + Deviation 'MSV' : Semi Variance (Variance of negative + returns) 'FLPM' : First Lower Partial Moment 'SLPM' : + Second Lower Partial Moment 'CVaR' : Conditional Value + at Risk 'EVaR' : Entropic Value at Risk 'WR' : Worst + Realization 'ADD' : Average Drawdown of uncompounded + returns 'UCI' : Ulcer Index of uncompounded returns + 'CDaR' : Conditional Drawdown at Risk of uncompounded + returns 'EDaR' : Entropic Drawdown at Risk of + uncompounded returns 'MDD' : Maximum Drawdown of + uncompounded returns (default: MV) + -r RISK_FREE, --risk-free-rate RISK_FREE + Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual (default: 0.00329) + -a SIGNIFICANCE_LEVEL, --alpha SIGNIFICANCE_LEVEL + Significance level of CVaR, EVaR, CDaR and EDaR + (default: 0.05) + -v LONG_ALLOCATION, --value LONG_ALLOCATION + Amount to allocate to portfolio (default: 1) + --name NAME Save portfolio with personalized or default name + (default: PROPERTY_0) + -h, --help show this help message (default: False) +``` + +Example: +``` +2022 Apr 05, 15:02 (🦋) /portfolio/po/ $ property -pr trailingEps + + [3 Years] Weighted Portfolio based on trailingEps + + Weights +┏━━━━━━┳━━━━━━━━━┓ +┃ ┃ Value ┃ +┡━━━━━━╇━━━━━━━━━┩ +│ AAPL │ 6.36 % │ +├──────┼─────────┤ +│ AMZN │ 68.58 % │ +├──────┼─────────┤ +│ BA │ -7.56 % │ +├──────┼─────────┤ +│ FB │ 14.57 % │ +├──────┼─────────┤ +│ MSFT │ 9.93 % │ +├──────┼─────────┤ +│ T │ 2.92 % │ +├──────┼─────────┤ +│ TSLA │ 5.18 % │ +└──────┴─────────┘ + +Annual (by 252) expected return: 33.74% +Annual (by √252) volatility: 30.25% +Sharpe ratio: 1.1094 +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/relriskparity/_index.md b/website/content/terminal/portfolio/po/relriskparity/_index.md new file mode 100644 index 00000000000..0b3210cd963 --- /dev/null +++ b/website/content/terminal/portfolio/po/relriskparity/_index.md @@ -0,0 +1,104 @@ +``` +usage: relriskparity [-p HISTORIC_PERIOD] [-s START_PERIOD] [-e END_PERIOD] + [-lr] [-f {d,w,m}] [-mn MAX_NAN] [-th THRESHOLD_VALUE] + [-mt NAN_FILL_METHOD] [-ve {A,B,C}] + [-rc RISK_CONTRIBUTION] [-pf PENAL_FACTOR] + [-tr TARGET_RETURN] [-de SMOOTHING_FACTOR_EWMA] + [-v LONG_ALLOCATION] [--name NAME] [-h] +``` + +A relaxed risk parity optimization model controls the balance of risk parity violation against the total portfolio performance. Risk parity has been criticized as being overly conservative and it is improved by re-introducing the asset expected returns into the model and permitting the portfolio to violate the risk parity condition. The paper by Gambeta & Kwon ([source](https://www.mdpi.com/1911-8074/13/10/237/htm)) proposes the incorporation of an explicit target return goal with an intuitive target return approach into a second-order-cone model of a risk parity optimization. When the target return is greater than risk parity return, a violation to risk parity allocations occurs that is controlled using a computational construct to obtain near-risk parity portfolios to retain as much risk parity-like traits as possible. This model is used to demonstrate empirically that higher returns can be achieved than risk parity without the risk contributions deviating dramatically from the risk parity allocations. Furthermore, this study reveals that the relaxed risk parity model exhibits advantageous traits of robustness to expected returns, which should not deter the use of expected returns in risk parity model. + +``` +optional arguments: + -p HISTORIC_PERIOD, --period HISTORIC_PERIOD + Period to get yfinance data from. Possible frequency + strings are: 'd': means days, for example '252d' means + 252 days 'w': means weeks, for example '52w' means 52 + weeks 'mo': means months, for example '12mo' means 12 + months 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset + (default: 3y) + -s START_PERIOD, --start START_PERIOD + Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format (default: ) + -e END_PERIOD, --end END_PERIOD + End date to get yfinance data from. Must be in 'YYYY- + MM-DD' format (default: ) + -lr, --log-returns If use logarithmic or arithmetic returns to calculate + returns (default: False) + -f {d,w,m}, --freq {d,w,m} + Frequency used to calculate returns. Possible values + are: 'd': for daily returns 'w': for weekly returns + 'm': for monthly returns (default: d) + -mn MAX_NAN, --maxnan MAX_NAN + Max percentage of nan values accepted per asset to be + considered in the optimization process (default: 0.05) + -th THRESHOLD_VALUE, --threshold THRESHOLD_VALUE + Value used to replace outliers that are higher to + threshold in absolute value (default: 0.3) + -mt NAN_FILL_METHOD, --method NAN_FILL_METHOD + Method used to fill nan values in time series, by + default time. Possible values are: 'linear': linear + interpolation 'time': linear interpolation based on + time index 'nearest': use nearest value to replace nan + values 'zero': spline of zeroth order 'slinear': + spline of first order 'quadratic': spline of second + order 'cubic': spline of third order 'barycentric': + builds a polynomial that pass for all points (default: + time) + -ve {A,B,C}, --version {A,B,C} + version of relaxed risk parity model: Possible values + are: 'A': risk parity without regularization and + penalization constraints 'B': with regularization + constraint but without penalization constraint 'C': + with regularization and penalization constraints + (default: A) + -rc RISK_CONTRIBUTION, --risk-cont RISK_CONTRIBUTION + Vector of risk contribution constraints (default: + None) + -pf PENAL_FACTOR, --penal-factor PENAL_FACTOR + The penalization factor of penalization constraints. + Only used with version 'C'. (default: 1) + -tr TARGET_RETURN, --target-return TARGET_RETURN + Constraint on minimum level of portfolio's return + (default: -1) + -de SMOOTHING_FACTOR_EWMA, --d-ewma SMOOTHING_FACTOR_EWMA + Smoothing factor for ewma estimators (default: 0.94) + -v LONG_ALLOCATION, --value LONG_ALLOCATION + Amount to allocate to portfolio (default: 1) + --name NAME Save portfolio with personalized or default name + (default: RRP_0) + -h, --help show this help message (default: False) +``` + +Example: +``` +2022 Apr 05, 14:08 (🦋) /portfolio/po/ $ relriskparity + + [3 Years] Relaxed risk parity portfolio based on least squares approach + + Weights +┏━━━━━━┳━━━━━━━━━┓ +┃ ┃ Value ┃ +┡━━━━━━╇━━━━━━━━━┩ +│ AAPL │ 13.42 % │ +├──────┼─────────┤ +│ AMZN │ 16.51 % │ +├──────┼─────────┤ +│ BA │ 10.18 % │ +├──────┼─────────┤ +│ FB │ 12.83 % │ +├──────┼─────────┤ +│ MSFT │ 14.36 % │ +├──────┼─────────┤ +│ T │ 24.0 % │ +├──────┼─────────┤ +│ TSLA │ 8.68 % │ +└──────┴─────────┘ + +Annual (by 252) expected return: 28.99% +Annual (by √252) volatility: 26.60% +Sharpe ratio: 1.0899 +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/po/riskparity/_index.md b/website/content/terminal/portfolio/po/riskparity/_index.md new file mode 100644 index 00000000000..5f09a093a94 --- /dev/null +++ b/website/content/terminal/portfolio/po/riskparity/_index.md @@ -0,0 +1,120 @@ +``` +usage: riskparity [-p HISTORIC_PERIOD] [-s START_PERIOD] [-e END_PERIOD] [-lr] + [-f {d,w,m}] [-mn MAX_NAN] [-th THRESHOLD_VALUE] + [-mt NAN_FILL_METHOD] + [-rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,CDaR,EDaR,UCI}] + [-rc RISK_CONTRIBUTION] [-r RISK_FREE] + [-a SIGNIFICANCE_LEVEL] [-tr TARGET_RETURN] + [-de SMOOTHING_FACTOR_EWMA] [-v LONG_ALLOCATION] + [--name NAME] [-h] +``` + +Both the Minimum Variance and Maximum Diversification portfolios are mean-variance efficient under intuitive assumptions. Minimum Variance is efficient if assets have similar returns while Maximum Diversification is efficient if assets have similar Sharpe ratios. However, both methods have the drawback that they can be quite concentrated in a small number of assets. For example, the Minimum Variance portfolio will place disproportionate weight in the lowest volatility asset while the Maximum Diversification portfolio will concentrate in assets with high volatility and low covariance with the market. In fact, these optimizations may result in portfolios that hold just a small fraction of all available assets. + +There are situations where this may not be preferable. Concentrated portfolios also may not accommodate large amounts of capital without high market impact costs. In addition, concentrated portfolios are more susceptible to mis-estimation of volatilities or correlations. + +These issues prompted a search for heuristic optimizations that meet similar optimization objectives, but with less concentration. The equal weight and capitalization weighted portfolios are common examples of this, but there are other methods that are compelling under different assumptions. + +**Risk parity was developed to remove the uncertainty of estimated returns and to protect against losses associated with portfolio concentration. In essence what this means is that you want to prevent allocation a significant portion to just a couple of assets because Minimum Variance and Maximum Diversification say this is the best allocation.** + +``` +optional arguments: + -p HISTORIC_PERIOD, --period HISTORIC_PERIOD + Period to get yfinance data from. Possible frequency + strings are: 'd': means days, for example '252d' means + 252 days 'w': means weeks, for example '52w' means 52 + weeks 'mo': means months, for example '12mo' means 12 + months 'y': means years, for example '1y' means 1 year + 'ytd': downloads data from beginning of year to today + 'max': downloads all data available for each asset + (default: 3y) + -s START_PERIOD, --start START_PERIOD + Start date to get yfinance data from. Must be in + 'YYYY-MM-DD' format (default: ) + -e END_PERIOD, --end END_PERIOD + End date to get yfinance data from. Must be in 'YYYY- + MM-DD' format (default: ) + -lr, --log-returns If use logarithmic or arithmetic returns to calculate + returns (default: False) + -f {d,w,m}, --freq {d,w,m} + Frequency used to calculate returns. Possible values + are: 'd': for daily returns 'w': for weekly returns + 'm': for monthly returns (default: d) + -mn MAX_NAN, --maxnan MAX_NAN + Max percentage of nan values accepted per asset to be + considered in the optimization process. (default: + 0.05) + -th THRESHOLD_VALUE, --threshold THRESHOLD_VALUE + Value used to replace outliers that are higher to + threshold in absolute value (default: 0.3) + -mt NAN_FILL_METHOD, --method NAN_FILL_METHOD + Method used to fill nan values in time series, by + default time. Possible values are: 'linear': linear + interpolation 'time': linear interpolation based on + time index 'nearest': use nearest value to replace nan + values 'zero': spline of zeroth order 'slinear': + spline of first order 'quadratic': spline of second + order 'cubic': spline of third order 'barycentric': + builds a polynomial that pass for all points (default: + time) + -rm {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,CDaR,EDaR,UCI}, --risk-measure {MV,MAD,MSV,FLPM,SLPM,CVaR,EVaR,CDaR,EDaR,UCI} + Risk measure used to optimize the portfolio. Possible + values are: 'MV' : Variance 'MAD' : Mean Absolute + Deviation 'MSV' : Semi Variance (Variance of negative + returns) 'FLPM' : First Lower Partial Moment 'SLPM' : + Second Lower Partial Moment 'CVaR' : Conditional Value + at Risk 'EVaR' : Entropic Value at Risk 'UCI' : Ulcer + Index of uncompounded returns 'CDaR' : Conditional + Drawdown at Risk of uncompounded returns 'EDaR' : + Entropic Drawdown at Risk of uncompounded returns + (default: MV) + -rc RISK_CONTRIBUTION, --risk-cont RISK_CONTRIBUTION + vector of risk contribution constraint (default: None) + -r RISK_FREE, --risk-free-rate RISK_FREE + Risk-free rate of borrowing/lending. The period of the + risk-free rate must be annual (default: 0.00329) + -a SIGNIFICANCE_LEVEL, --alpha SIGNIFICANCE_LEVEL + Significance level of CVaR, EVaR, CDaR and EDaR + (default: 0.05) + -tr TARGET_RETURN, --target-return TARGET_RETURN + Constraint on minimum level of portfolio's return + (default: -1) + -de SMOOTHING_FACTOR_EWMA, --d-ewma SMOOTHING_FACTOR_EWMA + Smoothing factor for ewma estimators (default: 0.94) + -v LONG_ALLOCATION, --value LONG_ALLOCATION + Amount to allocate to portfolio (default: 1) + --name NAME Save portfolio with personalized or default name + (default: RP_8) + -h, --help show this help message (default: False) + ``` + +Example: +``` +2022 Apr 05, 14:45 (🦋) /portfolio/po/ $ riskparity + + [3 Years] Risk parity portfolio based on risk budgeting approach +using volatility as risk measure + + Weights +┏━━━━━━┳━━━━━━━━━┓ +┃ ┃ Value ┃ +┡━━━━━━╇━━━━━━━━━┩ +│ AAPL │ 13.42 % │ +├──────┼─────────┤ +│ AMZN │ 16.51 % │ +├──────┼─────────┤ +│ BA │ 10.18 % │ +├──────┼─────────┤ +│ FB │ 12.83 % │ +├──────┼─────────┤ +│ MSFT │ 14.36 % │ +├──────┼─────────┤ +│ T │ 24.00 % │ +├──────┼─────────┤ +│ TSLA │ 8.68 % │ +└──────┴─────────┘ + +Annual (by 252) expected return: 28.99% +Annual (by √252) volatility: 26.60% +Sharpe ratio: 1.0829 +``` \ No newline at end of file diff --git a/website/content/terminal/portfolio/portfolio_optimization/rmv/_index.md b/website/content/terminal/portfolio/po/rmv/_index.md similarity index 100% rename from website/content/terminal/portfolio/portfolio_optimization/rmv/_index.md rename to website/content/terminal/portfolio/po/rmv/_index.md diff --git a/website/content/terminal/portfolio/po/rpf/_index.md b/website/content/terminal/portfolio/po/rpf/_index.md new file mode 100644 index 00000000000..f6fdfcd40cc --- /dev/null +++ b/website/content/terminal/portfolio/po/rpf/_index.md @@ -0,0 +1,12 @@ +``` +usage: rpf [-pf PORTFOLIOS] [-h] +``` + +Remove one portfolio from saved portfolios. + +``` +optional arguments: + -pf PORTFOLIOS, --portfolios PORTFOLIOS + portfolios to be removed from the saved portfolios + -h, --help show this help message +``` diff --git a/website/content/terminal/portfolio/portfolio_optimization/select/_index.md b/website/content/terminal/portfolio/po/select/_index.md similarity index 100% rename from website/content/terminal/portfolio/portfolio_optimization/select/_index.md rename to website/content/terminal/portfolio/po/select/_index.md diff --git a/website/content/terminal/portfolio/po/show/_index.md b/website/content/terminal/portfolio/po/show/_index.md new file mode 100644 index 00000000000..3f2ce1d935b --- /dev/null +++ b/website/content/terminal/portfolio/po/show/_index.md @@ -0,0 +1,14 @@ +``` +usage: show [-pf PORTFOLIOS] [-ct CATEGORIES] [-h] +``` + +Show selected saved portfolios + +``` +optional arguments: + -pf PORTFOLIOS, --portfolios PORTFOLIOS + Show selected saved portfolios + -ct CATEGORIES, --categories CATEGORIES + Show selected categories + -h, --help show this help message +``` diff --git a/website/content/terminal/portfolio/portfolio_optimization/_index.md b/website/content/terminal/portfolio/portfolio_optimization/_index.md deleted file mode 100644 index bf4d8d0b8ec..00000000000 --- a/website/content/terminal/portfolio/portfolio_optimization/_index.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -geekdocCollapseSection: true ---- - -The terminal has incorporated PyPortfolioOpt. Refer to the documentation here: https://pyportfolioopt.readthedocs.io/en/latest/MeanVariance.html - -```text -Portfolio Optimization: - select select list of tickers to be optimized - add add tickers to the list of the tickers to be optimized - rmv remove tickers from the list of the tickers to be optimized - -Tickers: VT, QQQ, SPY - -Optimization: - equal equally weighted - mktcap weighted according to market cap (property marketCap) - dividend weighted according to dividend yield (property dividendYield) - property weight according to selected info property - -Mean Variance Optimization: - maxsharpe optimizes for maximal Sharpe ratio (a.k.a the tangency portfolio - minvol optimizes for minimum volatility - maxquadutil maximises the quadratic utility, given some risk aversion - effret maximises return for a given target risk - effrisk minimises risk for a given target return - - ef show the efficient frontier -``` - -{{< toc-tree >}} \ No newline at end of file diff --git a/website/content/terminal/portfolio/portfolio_optimization/dividend/_index.md b/website/content/terminal/portfolio/portfolio_optimization/dividend/_index.md deleted file mode 100644 index ff1c080cfdc..00000000000 --- a/website/content/terminal/portfolio/portfolio_optimization/dividend/_index.md +++ /dev/null @@ -1,38 +0,0 @@ -```text -usage: dividend [-v VALUE] [--pie] [-h] -``` - -Returns a portfolio that is weighted for optimaal dividend yield. - -``` -optional arguments: - -v VALUE, --value VALUE - Amount to allocate to portfolio (default: 1) - --pie Display a pie chart for weights (default: False) - -h, --help show this help message (default: False) -``` -``` -2022 Feb 14, 11:09 (✨) /portfolio/po/ $ select BNS.TO,TD.TO,NA.TO,CM.TO,RY.TO,BMO.TO - -2022 Feb 14, 11:09 (✨) /portfolio/po/ $ dividend - Weights -┌────────┬─────────┐ -│ │ Value │ -├────────┼─────────┤ -│ BNS.TO │ 19.74 % │ -├────────┼─────────┤ -│ BMO.TO │ 16.24 % │ -├────────┼─────────┤ -│ TD.TO │ 15.18 % │ -├────────┼─────────┤ -│ CM.TO │ 18.17 % │ -├────────┼─────────┤ -│ NA.TO │ 15.55 % │ -├────────┼─────────┤ -│ RY.TO │ 15.09 % │ -└────────┴─────────┘ -``` -``` -2022 Feb 14, 11:10 (✨) /portfolio/po/ $ dividend --pie -``` -![dividend](https://user-images.githubusercontent.com/46355364/153901511-ded4f3ab-77db-413e-8352-627205dec059.png) diff --git a/website/content/terminal/portfolio/portfolio_optimization/ef/_index.md b/website/content/terminal/portfolio/portfolio_optimization/ef/_index.md deleted file mode 100644 index 66df060b40c..00000000000 --- a/website/content/terminal/portfolio/portfolio_optimization/ef/_index.md +++ /dev/null @@ -1,26 +0,0 @@ -``` -usage: ef [-p {1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max}] [-n N_PORT] [-r] [-h] -``` - -This function plots random portfolios based on their risk and returns and shows the efficient frontier. - -See: https://pyportfolioopt.readthedocs.io/en/latest/GeneralEfficientFrontier.html - -``` -optional arguments: - -p {1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max}, --period {1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max} - period to get yfinance data from (default: 1y) - -n N_PORT, --number-portfolios N_PORT - number of portfolios to simulate (default: 300) - -r, --risk-free Adds the optimal line with the risk-free asset (default: False) - -h, --help show this help message (default: False) -``` - -Example: -``` -2022 Feb 14, 11:12 (✨) /portfolio/po/ $ ef -Expected annual return: 46.7% -Annual volatility: 10.7% -Sharpe Ratio: 4.36 -``` -![ef](https://user-images.githubusercontent.com/46355364/153901823-bca43498-43f8-40ae-8933-b6deb9d1086c.png) diff --git a/website/content/terminal/portfolio/portfolio_optimization/effret/_index.md b/website/content/terminal/portfolio/portfolio_optimization/effret/_index.md deleted file mode 100644 index 4b0aead8190..00000000000 --- a/website/content/terminal/portfolio/portfolio_optimization/effret/_index.md +++ /dev/null @@ -1,28 +0,0 @@ -``` -usage: effret [-p {1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max}] [-v VALUE] [-n] [--pie] [-t TARGET_RETURN] [-h] -``` - -Calculate the 'Markowitz portfolio', minimising volatility for a given target return. By combining assets with different expected returns and volatilities, one can decide on a mathematically optimal allocation. - -``` -optional arguments: - -p {1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max}, --period {1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max} - period to get yfinance data from (default: 1y) - -v VALUE, --value VALUE - Amount to allocate to portfolio (default: 1.0) - -n, --market-neutral whether the portfolio should be market neutral (weights sum to zero), defaults to False. Requires negative lower weight bound. (default: False) - --pie Display a pie chart for weights. Only if neutral flag is left False. (default: False) - -t TARGET_RETURN, --target-return TARGET_RETURN - the desired return of the resulting portfolio (default: 0.1) - -h, --help show this help message (default: False) -``` - -Example: -``` -2022 Feb 14, 11:14 (✨) /portfolio/po/ $ effret --pie - -Expected annual return: 42.9% -Annual volatility: 10.2% -Sharpe Ratio: 4.00 -``` -![effret](https://user-images.githubusercontent.com/46355364/153902203-c7a23b78-6211-4d2b-be06-6ed8f0b00143.png) diff --git a/website/content/terminal/portfolio/portfolio_optimization/effrisk/_index.md b/website/content/terminal/portfolio/portfolio_optimization/effrisk/_index.md deleted file mode 100644 index 451816e379f..00000000000 --- a/website/content/terminal/portfolio/portfolio_optimization/effrisk/_index.md +++ /dev/null @@ -1,19 +0,0 @@ -``` -usage: effrisk [-p {1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max}] [-v VALUE] [-n] [--pie] [-t TARGET_VOLATILITY] [-h] -``` - -Maximise return for a target risk. The resulting portfolio will have a volatility less than the target (but not guaranteed to be equal) - -``` -optional arguments: - -p {1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max}, --period {1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max} - period to get yfinance data from (default: 3mo) - -v VALUE, --value VALUE - Amount to allocate to portfolio (default: 1.0) - -n, --market-neutral whether the portfolio should be market neutral (weights sum to zero), defaults to False. Requires negative lower weight - bound. (default: False) - --pie Display a pie chart for weights. Only if neutral flag is left False. (default: False) - -t TARGET_VOLATILITY, --target-volatility TARGET_VOLATILITY - The desired maximum volatility of the resulting portfolio (default: 0.1) - -h, --help show this help message (default: False) -``` diff --git a/website/content/terminal/portfolio/portfolio_optimization/equal/_index.md b/website/content/terminal/portfolio/portfolio_optimization/equal/_index.md deleted file mode 100644 index 348cdfc6cd5..00000000000 --- a/website/content/terminal/portfolio/portfolio_optimization/equal/_index.md +++ /dev/null @@ -1,37 +0,0 @@ -``` -usage: equal [-v VALUE] [--pie] [-h] -``` - -Returns an equally weighted portfolio - -``` -optional arguments: - -v VALUE, --value VALUE - Amount to allocate to portfolio (default: 1) - --pie Display a pie chart for weights (default: False) - -h, --help show this help message (default: False) -``` - -Example: -``` -2022 Feb 14, 11:15 (✨) /portfolio/po/ $ equal --pie - - Weights -┌────────┬─────────┐ -│ │ Value │ -├────────┼─────────┤ -│ BNS.TO │ 16.66 % │ -├────────┼─────────┤ -│ BMO.TO │ 16.66 % │ -├────────┼─────────┤ -│ TD.TO │ 16.66 % │ -├────────┼─────────┤ -│ CM.TO │ 16.66 % │ -├────────┼─────────┤ -│ NA.TO │ 16.66 % │ -├────────┼─────────┤ -│ RY.TO │ 16.66 % │ -└────────┴─────────┘ -``` - -![equal](https://user-images.githubusercontent.com/46355364/153902518-74f2818f-b844-4b0b-925f-7255898b51f4.png) diff --git a/website/content/terminal/portfolio/portfolio_optimization/maxquadutil/_index.md b/website/content/terminal/portfolio/portfolio_optimization/maxquadutil/_index.md deleted file mode 100644 index 5984c87822f..00000000000 --- a/website/content/terminal/portfolio/portfolio_optimization/maxquadutil/_index.md +++ /dev/null @@ -1,45 +0,0 @@ -``` -usage: maxquadutil [-p {1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max}] [-v VALUE] [-n] [--pie] [-r RISK_AVERSION] [-h] -``` -In financial economics, the utility function most frequently used to describe investor behaviour is the quadratic utility function. Its popularity stems from the fact that, under the assumption of quadratic utility, mean-variance analysis is optimal. - -https://www.d42.com/portfolio/analysis/quadratic-utility - -``` -optional arguments: - -p {1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max}, --period {1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max} - period to get yfinance data from (default: 1y) - -v VALUE, --value VALUE - Amount to allocate to portfolio (default: 1.0) - -n, --market-neutral whether the portfolio should be market neutral (weights sum to zero), defaults to False. Requires negative lower weight bound. (default: False) - --pie Display a pie chart for weights. Only if neutral flag is left False. (default: False) - -r RISK_AVERSION, --risk-aversion RISK_AVERSION - risk aversion parameter (default: 1.0) - -h, --help show this help message (default: False) -``` - -Example: -``` -2022 Feb 14, 11:16 (✨) /portfolio/po/ $ maxquadutil -[1 Year] Weights that maximise quadratic utility with risk aversion: 1.0 - Weights -┌────────┬─────────┐ -│ │ Value │ -├────────┼─────────┤ -│ BNS.TO │ -0.00 % │ -├────────┼─────────┤ -│ BMO.TO │ 100.0 % │ -├────────┼─────────┤ -│ TD.TO │ 0.0 % │ -├────────┼─────────┤ -│ CM.TO │ -0.0 % │ -├────────┼─────────┤ -│ NA.TO │ 0.0 % │ -├────────┼─────────┤ -│ RY.TO │ -0.0 % │ -└────────┴─────────┘ - -Expected annual return: 57.5% -Annual volatility: 15.3% -Sharpe Ratio: 3.62 -``` diff --git a/website/content/terminal/portfolio/portfolio_optimization/maxsharpe/_index.md b/website/content/terminal/portfolio/portfolio_optimization/maxsharpe/_index.md deleted file mode 100644 index db2c13f3c48..00000000000 --- a/website/content/terminal/portfolio/portfolio_optimization/maxsharpe/_index.md +++ /dev/null @@ -1,35 +0,0 @@ -``` -usage: maxsharpe [-p {1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max}] [-v VALUE] [--pie] [-r RISK_FREE_RATE] [-h] -``` -The Sharpe ratio is one of the most widely used methods for calculating risk-adjusted return. Modern Portfolio Theory (MPT) states that adding assets to a diversified portfolio that has low correlations can decrease portfolio risk without sacrificing returns. Adding diversification should increase the Sharpe ratio compared to similar portfolios with a lower level of diversification. For this to be true, investors must also accept the assumption that risk is equal to volatility, which is not unreasonable but may be too narrow to be applied to all investments. - -The Sharpe Ratio is calculated as follows: - -1. Subtract the risk-free rate from the return of the portfolio. The risk-free rate could be a U.S. Treasury rate or yield, such as the one-year or two-year Treasury yield. - -2. Divide the result by the standard deviation of the portfolio’s excess return. The standard deviation helps to show how much the portfolio's return deviates from the expected return. The standard deviation also sheds light on the portfolio's volatility. - -The Sharpe ratio can also help explain whether a portfolio's excess returns are due to smart investment decisions or a result of too much risk. - -``` -optional arguments: - -p {1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max}, --period {1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max} - period to get yfinance data from (default: 1y) - -v VALUE, --value VALUE - Amount to allocate to portfolio (default: 1.0) - --pie Display a pie chart for weights (default: False) - -r RISK_FREE_RATE, --risk-free-rate RISK_FREE_RATE - Risk-free rate of borrowing/lending. The period of the risk-free rate should correspond to the frequency of expected returns. (default: 0.00103) - -h, --help show this help message (default: False) -``` - -Example: -``` -2022 Feb 14, 11:18 (✨) /portfolio/po/ $ maxsharpe --pie - -Expected annual return: 46.7% -Annual volatility: 10.7% -Sharpe Ratio: 4.38 -``` - -![maxsharpe](https://user-images.githubusercontent.com/46355364/153902930-c28759e5-c679-4e35-9a65-da70aa09e871.png) diff --git a/website/content/terminal/portfolio/portfolio_optimization/minvol/_index.md b/website/content/terminal/portfolio/portfolio_optimization/minvol/_index.md deleted file mode 100644 index 01dee7f5acc..00000000000 --- a/website/content/terminal/portfolio/portfolio_optimization/minvol/_index.md +++ /dev/null @@ -1,26 +0,0 @@ -``` -usage: minvol [-p {1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max}] [-v VALUE] [--pie] [-h] -``` - -Optimizes for minimum volatility - -``` -optional arguments: - -p {1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max}, --period {1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max} - period to get yfinance data from (default: 3mo) - -v VALUE, --value VALUE - Amount to allocate to portfolio (default: 1.0) - --pie Display a pie chart for weights (default: False) - -h, --help show this help message (default: False) -``` - -Example: -``` -2022 Feb 14, 11:19 (✨) /portfolio/po/ $ minvol --pie - -Expected annual return: 43.1% -Annual volatility: 10.2% -Sharpe Ratio: 4.03 -``` - -![minvol](https://user-images.githubusercontent.com/46355364/153903170-177a82b7-81d6-4c86-a43b-72ac238de62b.png) diff --git a/website/content/terminal/portfolio/portfolio_optimization/mktcap/_index.md b/website/content/terminal/portfolio/portfolio_optimization/mktcap/_index.md deleted file mode 100644 index bd6b9881cb1..00000000000 --- a/website/content/terminal/portfolio/portfolio_optimization/mktcap/_index.md +++ /dev/null @@ -1,36 +0,0 @@ -``` -usage: property [-p PROPERTY] [-v VALUE] [--pie] [-h] -``` - -Returns a portfolio that is weighted based on market cap. - -``` -optional arguments: - -v VALUE, --value VALUE - Amount to allocate to portfolio (default: 1) - --pie Display a pie chart for weights (default: False) - -h, --help show this help message (default: False) -``` - -Example: -``` -2022 Feb 14, 11:19 (✨) /portfolio/po/ $ mktcap - Weights -┌────────┬─────────┐ -│ │ Value │ -├────────┼─────────┤ -│ BNS.TO │ 15.70 % │ -├────────┼─────────┤ -│ BMO.TO │ 13.48 % │ -├────────┼─────────┤ -│ TD.TO │ 27.06 % │ -├────────┼─────────┤ -│ CM.TO │ 10.16 % │ -├────────┼─────────┤ -│ NA.TO │ 4.84 % │ -├────────┼─────────┤ -│ RY.TO │ 28.73 % │ -└────────┴───────── -``` - -![mktcap](https://user-images.githubusercontent.com/46355364/153903395-45f4b424-cab3-41ac-91ee-745eddff7e71.png) diff --git a/website/content/terminal/portfolio/portfolio_optimization/property/_index.md b/website/content/terminal/portfolio/portfolio_optimization/property/_index.md deleted file mode 100644 index f37657d54b8..00000000000 --- a/website/content/terminal/portfolio/portfolio_optimization/property/_index.md +++ /dev/null @@ -1,50 +0,0 @@ -``` -usage: property [-p PROPERTY] [-v VALUE] [--pie] [-h] -``` - -Suggests a weighting based on a targeted statistic. - -``` -optional arguments: - -p PROPERTY, --property PROPERTY - Property info to weigh. Use one of: previousClose, regularMarketOpen, twoHundredDayAverage, trailingAnnualDividendYield, - payoutRatio, volume24Hr, regularMarketDayHigh, navPrice, averageDailyVolume10Day, totalAssets, regularMarketPreviousClose, - fiftyDayAverage, trailingAnnualDividendRate, open, toCurrency, averageVolume10days, expireDate, yield, algorithm, - dividendRate, exDividendDate, beta, circulatingSupply, regularMarketDayLow, priceHint, currency, trailingPE, - regularMarketVolume, lastMarket, maxSupply, openInterest, marketCap, volumeAllCurrencies, strikePrice, averageVolume, - priceToSalesTrailing12Months, dayLow, ask, ytdReturn, askSize, volume, fiftyTwoWeekHigh, forwardPE, fromCurrency, - fiveYearAvgDividendYield, fiftyTwoWeekLow, bid, dividendYield, bidSize, dayHigh, annualHoldingsTurnover, enterpriseToRevenue, - beta3Year, profitMargins, enterpriseToEbitda, 52WeekChange, morningStarRiskRating, forwardEps, revenueQuarterlyGrowth, - sharesOutstanding, fundInceptionDate, annualReportExpenseRatio, bookValue, sharesShort, sharesPercentSharesOut, fundFamily, - lastFiscalYearEnd, heldPercentInstitutions, netIncomeToCommon, trailingEps, lastDividendValue, SandP52WeekChange, - priceToBook, heldPercentInsiders, shortRatio, sharesShortPreviousMonthDate, floatShares, enterpriseValue, - threeYearAverageReturn, lastSplitFactor, legalType, lastDividendDate, morningStarOverallRating, earningsQuarterlyGrowth, - pegRatio, lastCapGain, shortPercentOfFloat, sharesShortPriorMonth, impliedSharesOutstanding, fiveYearAverageReturn, and - regularMarketPrice. (default: None) - -v VALUE, --value VALUE - Amount to allocate to portfolio (default: 1) - --pie Display a pie chart for weights (default: False) - -h, --help show this help message (default: False) -``` -Example: -``` -2022 Feb 14, 11:22 (✨) /portfolio/po/ $ property -p trailingEps - Weights -┌────────┬─────────┐ -│ │ Value │ -├────────┼─────────┤ -│ BNS.TO │ 12.63 % │ -├────────┼─────────┤ -│ BMO.TO │ 18.99 % │ -├────────┼─────────┤ -│ TD.TO │ 12.66 % │ -├────────┼─────────┤ -│ CM.TO │ 22.85 % │ -├────────┼─────────┤ -│ NA.TO │ 14.70 % │ -├────────┼─────────┤ -│ RY.TO │ 18.14 % │ -└────────┴─────────┘ -``` - -![property](https://user-images.githubusercontent.com/46355364/153903858-80e67d54-e2f7-46cc-8958-201b198db9e2.png) diff --git a/website/data/menu/main.yml b/website/data/menu/main.yml index 4db0c66deac..ee36bc5d1fb 100755 --- a/website/data/menu/main.yml +++ b/website/data/menu/main.yml @@ -433,7 +433,7 @@ main: - name: vsurf ref: "/terminal/stocks/options/vsurf" - name: portfolio optimization - ref: "/terminal/portfolio/portfolio_optimization" + ref: "/terminal/portfolio/po" - name: parity ref: "/terminal/stocks/options/parity" - name: binom @@ -1154,34 +1154,71 @@ main: - name: holdings ref: "/terminal/portfolio/brokers/robinhood/holdings" - name: portfolio optimization - ref: "/terminal/portfolio/portfolio_optimization" + ref: "/terminal/portfolio/po" sub: - name: select - ref: "/terminal/portfolio/portfolio_optimization/select" + ref: "/terminal/portfolio/po/select" + - name: file + ref: "/terminal/portfolio/po/file" + - name: params + ref: "/terminal/portfolio/po/params" + sub: + - name: arg + ref: "/terminal/portfolio/po/params/arg" + - name: clear + ref: "/terminal/portfolio/po/params/clear" + - name: file + ref: "/terminal/portfolio/po/params/file" + - name: save + ref: "/terminal/portfolio/po/params/save" + - name: set + ref: "/terminal/portfolio/po/params/set" + - name: load + ref: "/terminal/portfolio/po/load" - name: add - ref: "/terminal/portfolio/portfolio_optimization/add" + ref: "/terminal/portfolio/po/add" - name: rmv - ref: "/terminal/portfolio/portfolio_optimization/rmv" + ref: "/terminal/portfolio/po/rmv" + - name: show + ref: "/terminal/portfolio/po/show" + - name: rpf + ref: "/terminal/portfolio/po/rpf" + - name: plot + ref: "/terminal/portfolio/po/plot" - name: equal - ref: "/terminal/portfolio/portfolio_optimization/equal" + ref: "/terminal/portfolio/po/equal" - name: mktcap - ref: "/terminal/portfolio/portfolio_optimization/mktcap" + ref: "/terminal/portfolio/po/mktcap" - name: dividend - ref: "/terminal/portfolio/portfolio_optimization/dividend" + ref: "/terminal/portfolio/po/dividend" - name: property - ref: "/terminal/portfolio/portfolio_optimization/property" - - name: maxhsarpe - ref: "/terminal/portfolio/portfolio_optimization/maxsharpe" - - name: minvol - ref: "/terminal/portfolio/portfolio_optimization/minvol" - - name: maxquadutil - ref: "/terminal/portfolio/portfolio_optimization/maxquadutil" - - name: effret - ref: "/terminal/portfolio/portfolio_optimization/effret" - - name: effrisk - ref: "/terminal/portfolio/portfolio_optimization/effrisk" + ref: "/terminal/portfolio/po/property" + - name: maxsharpe + ref: "/terminal/portfolio/po/maxsharpe" + - name: minrisk + ref: "/terminal/portfolio/po/minrisk" + - name: maxutil + ref: "/terminal/portfolio/po/maxutil" + - name: maxret + ref: "/terminal/portfolio/po/maxret" + - name: maxdiv + ref: "/terminal/portfolio/po/maxdiv" + - name: maxdecorr + ref: "/terminal/portfolio/po/maxdecorr" + - name: blacklitterman + ref: "/terminal/portfolio/po/blacklitterman" - name: ef - ref: "/terminal/portfolio/portfolio_optimization/ef" + ref: "/terminal/portfolio/po/ef" + - name: riskparity + ref: "/terminal/portfolio/po/riskparity" + - name: relriskparity + ref: "/terminal/portfolio/po/relriskparity" + - name: hrp + ref: "/terminal/portfolio/po/hrp" + - name: herc + ref: "/terminal/portfolio/po/herc" + - name: nco + ref: "/terminal/portfolio/po/nco" - name: load ref: "/terminal/portfolio/load" - name: save diff --git a/website/public/katex-38042a7abd.min.css b/website/public/katex-38042a7abd.min.css index 33390f2fc39..fee531639ed 100644 --- a/website/public/katex-38042a7abd.min.css +++ b/website/public/katex-38042a7abd.min.css @@ -1 +1,1105 @@ -@font-face{font-family:KaTeX_AMS;font-style:normal;font-weight:400;src:url(fonts/KaTeX_AMS-Regular.woff2) format("woff2"),url(fonts/KaTeX_AMS-Regular.woff) format("woff"),url(fonts/KaTeX_AMS-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Caligraphic;font-style:normal;font-weight:700;src:url(fonts/KaTeX_Caligraphic-Bold.woff2) format("woff2"),url(fonts/KaTeX_Caligraphic-Bold.woff) format("woff"),url(fonts/KaTeX_Caligraphic-Bold.ttf) format("truetype")}@font-face{font-family:KaTeX_Caligraphic;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Caligraphic-Regular.woff2) format("woff2"),url(fonts/KaTeX_Caligraphic-Regular.woff) format("woff"),url(fonts/KaTeX_Caligraphic-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Fraktur;font-style:normal;font-weight:700;src:url(fonts/KaTeX_Fraktur-Bold.woff2) format("woff2"),url(fonts/KaTeX_Fraktur-Bold.woff) format("woff"),url(fonts/KaTeX_Fraktur-Bold.ttf) format("truetype")}@font-face{font-family:KaTeX_Fraktur;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Fraktur-Regular.woff2) format("woff2"),url(fonts/KaTeX_Fraktur-Regular.woff) format("woff"),url(fonts/KaTeX_Fraktur-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:normal;font-weight:700;src:url(fonts/KaTeX_Main-Bold.woff2) format("woff2"),url(fonts/KaTeX_Main-Bold.woff) format("woff"),url(fonts/KaTeX_Main-Bold.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:italic;font-weight:700;src:url(fonts/KaTeX_Main-BoldItalic.woff2) format("woff2"),url(fonts/KaTeX_Main-BoldItalic.woff) format("woff"),url(fonts/KaTeX_Main-BoldItalic.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:italic;font-weight:400;src:url(fonts/KaTeX_Main-Italic.woff2) format("woff2"),url(fonts/KaTeX_Main-Italic.woff) format("woff"),url(fonts/KaTeX_Main-Italic.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Main-Regular.woff2) format("woff2"),url(fonts/KaTeX_Main-Regular.woff) format("woff"),url(fonts/KaTeX_Main-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Math;font-style:italic;font-weight:700;src:url(fonts/KaTeX_Math-BoldItalic.woff2) format("woff2"),url(fonts/KaTeX_Math-BoldItalic.woff) format("woff"),url(fonts/KaTeX_Math-BoldItalic.ttf) format("truetype")}@font-face{font-family:KaTeX_Math;font-style:italic;font-weight:400;src:url(fonts/KaTeX_Math-Italic.woff2) format("woff2"),url(fonts/KaTeX_Math-Italic.woff) format("woff"),url(fonts/KaTeX_Math-Italic.ttf) format("truetype")}@font-face{font-family:"KaTeX_SansSerif";font-style:normal;font-weight:700;src:url(fonts/KaTeX_SansSerif-Bold.woff2) format("woff2"),url(fonts/KaTeX_SansSerif-Bold.woff) format("woff"),url(fonts/KaTeX_SansSerif-Bold.ttf) format("truetype")}@font-face{font-family:"KaTeX_SansSerif";font-style:italic;font-weight:400;src:url(fonts/KaTeX_SansSerif-Italic.woff2) format("woff2"),url(fonts/KaTeX_SansSerif-Italic.woff) format("woff"),url(fonts/KaTeX_SansSerif-Italic.ttf) format("truetype")}@font-face{font-family:"KaTeX_SansSerif";font-style:normal;font-weight:400;src:url(fonts/KaTeX_SansSerif-Regular.woff2) format("woff2"),url(fonts/KaTeX_SansSerif-Regular.woff) format("woff"),url(fonts/KaTeX_SansSerif-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Script;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Script-Regular.woff2) format("woff2"),url(fonts/KaTeX_Script-Regular.woff) format("woff"),url(fonts/KaTeX_Script-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Size1;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Size1-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size1-Regular.woff) format("woff"),url(fonts/KaTeX_Size1-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Size2;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Size2-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size2-Regular.woff) format("woff"),url(fonts/KaTeX_Size2-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Size3;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Size3-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size3-Regular.woff) format("woff"),url(fonts/KaTeX_Size3-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Size4;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Size4-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size4-Regular.woff) format("woff"),url(fonts/KaTeX_Size4-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Typewriter;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Typewriter-Regular.woff2) format("woff2"),url(fonts/KaTeX_Typewriter-Regular.woff) format("woff"),url(fonts/KaTeX_Typewriter-Regular.ttf) format("truetype")}.katex{text-rendering:auto;font:normal 1.21em KaTeX_Main,Times New Roman,serif;line-height:1.2;text-indent:0}.katex *{-ms-high-contrast-adjust:none!important;border-color:currentColor}.katex .katex-version:after{content:"0.13.13"}.katex .katex-mathml{clip:rect(1px,1px,1px,1px);border:0;height:1px;overflow:hidden;padding:0;position:absolute;width:1px}.katex .katex-html>.newline{display:block}.katex .base{position:relative;white-space:nowrap;width:-webkit-min-content;width:-moz-min-content;width:min-content}.katex .base,.katex .strut{display:inline-block}.katex .textbf{font-weight:700}.katex .textit{font-style:italic}.katex .textrm{font-family:KaTeX_Main}.katex .textsf{font-family:KaTeX_SansSerif}.katex .texttt{font-family:KaTeX_Typewriter}.katex .mathnormal{font-family:KaTeX_Math;font-style:italic}.katex .mathit{font-family:KaTeX_Main;font-style:italic}.katex .mathrm{font-style:normal}.katex .mathbf{font-family:KaTeX_Main;font-weight:700}.katex .boldsymbol{font-family:KaTeX_Math;font-style:italic;font-weight:700}.katex .amsrm,.katex .mathbb,.katex .textbb{font-family:KaTeX_AMS}.katex .mathcal{font-family:KaTeX_Caligraphic}.katex .mathfrak,.katex .textfrak{font-family:KaTeX_Fraktur}.katex .mathtt{font-family:KaTeX_Typewriter}.katex .mathscr,.katex .textscr{font-family:KaTeX_Script}.katex .mathsf,.katex .textsf{font-family:KaTeX_SansSerif}.katex .mathboldsf,.katex .textboldsf{font-family:KaTeX_SansSerif;font-weight:700}.katex .mathitsf,.katex .textitsf{font-family:KaTeX_SansSerif;font-style:italic}.katex .mainrm{font-family:KaTeX_Main;font-style:normal}.katex .vlist-t{border-collapse:collapse;display:inline-table;table-layout:fixed}.katex .vlist-r{display:table-row}.katex .vlist{display:table-cell;position:relative;vertical-align:bottom}.katex .vlist>span{display:block;height:0;position:relative}.katex .vlist>span>span{display:inline-block}.katex .vlist>span>.pstrut{overflow:hidden;width:0}.katex .vlist-t2{margin-right:-2px}.katex .vlist-s{display:table-cell;font-size:1px;min-width:2px;vertical-align:bottom;width:2px}.katex .vbox{align-items:baseline;display:inline-flex;flex-direction:column}.katex .hbox{width:100%}.katex .hbox,.katex .thinbox{display:inline-flex;flex-direction:row}.katex .thinbox{max-width:0;width:0}.katex .msupsub{text-align:left}.katex .mfrac>span>span{text-align:center}.katex .mfrac .frac-line{border-bottom-style:solid;display:inline-block;width:100%}.katex .hdashline,.katex .hline,.katex .mfrac .frac-line,.katex .overline .overline-line,.katex .rule,.katex .underline .underline-line{min-height:1px}.katex .mspace{display:inline-block}.katex .clap,.katex .llap,.katex .rlap{position:relative;width:0}.katex .clap>.inner,.katex .llap>.inner,.katex .rlap>.inner{position:absolute}.katex .clap>.fix,.katex .llap>.fix,.katex .rlap>.fix{display:inline-block}.katex .llap>.inner{right:0}.katex .clap>.inner,.katex .rlap>.inner{left:0}.katex .clap>.inner>span{margin-left:-50%;margin-right:50%}.katex .rule{border:0 solid;display:inline-block;position:relative}.katex .hline,.katex .overline .overline-line,.katex .underline .underline-line{border-bottom-style:solid;display:inline-block;width:100%}.katex .hdashline{border-bottom-style:dashed;display:inline-block;width:100%}.katex .sqrt>.root{margin-left:.27777778em;margin-right:-.55555556em}.katex .fontsize-ensurer.reset-size1.size1,.katex .sizing.reset-size1.size1{font-size:1em}.katex .fontsize-ensurer.reset-size1.size2,.katex .sizing.reset-size1.size2{font-size:1.2em}.katex .fontsize-ensurer.reset-size1.size3,.katex .sizing.reset-size1.size3{font-size:1.4em}.katex .fontsize-ensurer.reset-size1.size4,.katex .sizing.reset-size1.size4{font-size:1.6em}.katex .fontsize-ensurer.reset-size1.size5,.katex .sizing.reset-size1.size5{font-size:1.8em}.katex .fontsize-ensurer.reset-size1.size6,.katex .sizing.reset-size1.size6{font-size:2em}.katex .fontsize-ensurer.reset-size1.size7,.katex .sizing.reset-size1.size7{font-size:2.4em}.katex .fontsize-ensurer.reset-size1.size8,.katex .sizing.reset-size1.size8{font-size:2.88em}.katex .fontsize-ensurer.reset-size1.size9,.katex .sizing.reset-size1.size9{font-size:3.456em}.katex .fontsize-ensurer.reset-size1.size10,.katex .sizing.reset-size1.size10{font-size:4.148em}.katex .fontsize-ensurer.reset-size1.size11,.katex .sizing.reset-size1.size11{font-size:4.976em}.katex .fontsize-ensurer.reset-size2.size1,.katex .sizing.reset-size2.size1{font-size:.83333333em}.katex .fontsize-ensurer.reset-size2.size2,.katex .sizing.reset-size2.size2{font-size:1em}.katex .fontsize-ensurer.reset-size2.size3,.katex .sizing.reset-size2.size3{font-size:1.16666667em}.katex .fontsize-ensurer.reset-size2.size4,.katex .sizing.reset-size2.size4{font-size:1.33333333em}.katex .fontsize-ensurer.reset-size2.size5,.katex .sizing.reset-size2.size5{font-size:1.5em}.katex .fontsize-ensurer.reset-size2.size6,.katex .sizing.reset-size2.size6{font-size:1.66666667em}.katex .fontsize-ensurer.reset-size2.size7,.katex .sizing.reset-size2.size7{font-size:2em}.katex .fontsize-ensurer.reset-size2.size8,.katex .sizing.reset-size2.size8{font-size:2.4em}.katex .fontsize-ensurer.reset-size2.size9,.katex .sizing.reset-size2.size9{font-size:2.88em}.katex .fontsize-ensurer.reset-size2.size10,.katex .sizing.reset-size2.size10{font-size:3.45666667em}.katex .fontsize-ensurer.reset-size2.size11,.katex .sizing.reset-size2.size11{font-size:4.14666667em}.katex .fontsize-ensurer.reset-size3.size1,.katex .sizing.reset-size3.size1{font-size:.71428571em}.katex .fontsize-ensurer.reset-size3.size2,.katex .sizing.reset-size3.size2{font-size:.85714286em}.katex .fontsize-ensurer.reset-size3.size3,.katex .sizing.reset-size3.size3{font-size:1em}.katex .fontsize-ensurer.reset-size3.size4,.katex .sizing.reset-size3.size4{font-size:1.14285714em}.katex .fontsize-ensurer.reset-size3.size5,.katex .sizing.reset-size3.size5{font-size:1.28571429em}.katex .fontsize-ensurer.reset-size3.size6,.katex .sizing.reset-size3.size6{font-size:1.42857143em}.katex .fontsize-ensurer.reset-size3.size7,.katex .sizing.reset-size3.size7{font-size:1.71428571em}.katex .fontsize-ensurer.reset-size3.size8,.katex .sizing.reset-size3.size8{font-size:2.05714286em}.katex .fontsize-ensurer.reset-size3.size9,.katex .sizing.reset-size3.size9{font-size:2.46857143em}.katex .fontsize-ensurer.reset-size3.size10,.katex .sizing.reset-size3.size10{font-size:2.96285714em}.katex .fontsize-ensurer.reset-size3.size11,.katex .sizing.reset-size3.size11{font-size:3.55428571em}.katex .fontsize-ensurer.reset-size4.size1,.katex .sizing.reset-size4.size1{font-size:.625em}.katex .fontsize-ensurer.reset-size4.size2,.katex .sizing.reset-size4.size2{font-size:.75em}.katex .fontsize-ensurer.reset-size4.size3,.katex .sizing.reset-size4.size3{font-size:.875em}.katex .fontsize-ensurer.reset-size4.size4,.katex .sizing.reset-size4.size4{font-size:1em}.katex .fontsize-ensurer.reset-size4.size5,.katex .sizing.reset-size4.size5{font-size:1.125em}.katex .fontsize-ensurer.reset-size4.size6,.katex .sizing.reset-size4.size6{font-size:1.25em}.katex .fontsize-ensurer.reset-size4.size7,.katex .sizing.reset-size4.size7{font-size:1.5em}.katex .fontsize-ensurer.reset-size4.size8,.katex .sizing.reset-size4.size8{font-size:1.8em}.katex .fontsize-ensurer.reset-size4.size9,.katex .sizing.reset-size4.size9{font-size:2.16em}.katex .fontsize-ensurer.reset-size4.size10,.katex .sizing.reset-size4.size10{font-size:2.5925em}.katex .fontsize-ensurer.reset-size4.size11,.katex .sizing.reset-size4.size11{font-size:3.11em}.katex .fontsize-ensurer.reset-size5.size1,.katex .sizing.reset-size5.size1{font-size:.55555556em}.katex .fontsize-ensurer.reset-size5.size2,.katex .sizing.reset-size5.size2{font-size:.66666667em}.katex .fontsize-ensurer.reset-size5.size3,.katex .sizing.reset-size5.size3{font-size:.77777778em}.katex .fontsize-ensurer.reset-size5.size4,.katex .sizing.reset-size5.size4{font-size:.88888889em}.katex .fontsize-ensurer.reset-size5.size5,.katex .sizing.reset-size5.size5{font-size:1em}.katex .fontsize-ensurer.reset-size5.size6,.katex .sizing.reset-size5.size6{font-size:1.11111111em}.katex .fontsize-ensurer.reset-size5.size7,.katex .sizing.reset-size5.size7{font-size:1.33333333em}.katex .fontsize-ensurer.reset-size5.size8,.katex .sizing.reset-size5.size8{font-size:1.6em}.katex .fontsize-ensurer.reset-size5.size9,.katex .sizing.reset-size5.size9{font-size:1.92em}.katex .fontsize-ensurer.reset-size5.size10,.katex .sizing.reset-size5.size10{font-size:2.30444444em}.katex .fontsize-ensurer.reset-size5.size11,.katex .sizing.reset-size5.size11{font-size:2.76444444em}.katex .fontsize-ensurer.reset-size6.size1,.katex .sizing.reset-size6.size1{font-size:.5em}.katex .fontsize-ensurer.reset-size6.size2,.katex .sizing.reset-size6.size2{font-size:.6em}.katex .fontsize-ensurer.reset-size6.size3,.katex .sizing.reset-size6.size3{font-size:.7em}.katex .fontsize-ensurer.reset-size6.size4,.katex .sizing.reset-size6.size4{font-size:.8em}.katex .fontsize-ensurer.reset-size6.size5,.katex .sizing.reset-size6.size5{font-size:.9em}.katex .fontsize-ensurer.reset-size6.size6,.katex .sizing.reset-size6.size6{font-size:1em}.katex .fontsize-ensurer.reset-size6.size7,.katex .sizing.reset-size6.size7{font-size:1.2em}.katex .fontsize-ensurer.reset-size6.size8,.katex .sizing.reset-size6.size8{font-size:1.44em}.katex .fontsize-ensurer.reset-size6.size9,.katex .sizing.reset-size6.size9{font-size:1.728em}.katex .fontsize-ensurer.reset-size6.size10,.katex .sizing.reset-size6.size10{font-size:2.074em}.katex .fontsize-ensurer.reset-size6.size11,.katex .sizing.reset-size6.size11{font-size:2.488em}.katex .fontsize-ensurer.reset-size7.size1,.katex .sizing.reset-size7.size1{font-size:.41666667em}.katex .fontsize-ensurer.reset-size7.size2,.katex .sizing.reset-size7.size2{font-size:.5em}.katex .fontsize-ensurer.reset-size7.size3,.katex .sizing.reset-size7.size3{font-size:.58333333em}.katex .fontsize-ensurer.reset-size7.size4,.katex .sizing.reset-size7.size4{font-size:.66666667em}.katex .fontsize-ensurer.reset-size7.size5,.katex .sizing.reset-size7.size5{font-size:.75em}.katex .fontsize-ensurer.reset-size7.size6,.katex .sizing.reset-size7.size6{font-size:.83333333em}.katex .fontsize-ensurer.reset-size7.size7,.katex .sizing.reset-size7.size7{font-size:1em}.katex .fontsize-ensurer.reset-size7.size8,.katex .sizing.reset-size7.size8{font-size:1.2em}.katex .fontsize-ensurer.reset-size7.size9,.katex .sizing.reset-size7.size9{font-size:1.44em}.katex .fontsize-ensurer.reset-size7.size10,.katex .sizing.reset-size7.size10{font-size:1.72833333em}.katex .fontsize-ensurer.reset-size7.size11,.katex .sizing.reset-size7.size11{font-size:2.07333333em}.katex .fontsize-ensurer.reset-size8.size1,.katex .sizing.reset-size8.size1{font-size:.34722222em}.katex .fontsize-ensurer.reset-size8.size2,.katex .sizing.reset-size8.size2{font-size:.41666667em}.katex .fontsize-ensurer.reset-size8.size3,.katex .sizing.reset-size8.size3{font-size:.48611111em}.katex .fontsize-ensurer.reset-size8.size4,.katex .sizing.reset-size8.size4{font-size:.55555556em}.katex .fontsize-ensurer.reset-size8.size5,.katex .sizing.reset-size8.size5{font-size:.625em}.katex .fontsize-ensurer.reset-size8.size6,.katex .sizing.reset-size8.size6{font-size:.69444444em}.katex .fontsize-ensurer.reset-size8.size7,.katex .sizing.reset-size8.size7{font-size:.83333333em}.katex .fontsize-ensurer.reset-size8.size8,.katex .sizing.reset-size8.size8{font-size:1em}.katex .fontsize-ensurer.reset-size8.size9,.katex .sizing.reset-size8.size9{font-size:1.2em}.katex .fontsize-ensurer.reset-size8.size10,.katex .sizing.reset-size8.size10{font-size:1.44027778em}.katex .fontsize-ensurer.reset-size8.size11,.katex .sizing.reset-size8.size11{font-size:1.72777778em}.katex .fontsize-ensurer.reset-size9.size1,.katex .sizing.reset-size9.size1{font-size:.28935185em}.katex .fontsize-ensurer.reset-size9.size2,.katex .sizing.reset-size9.size2{font-size:.34722222em}.katex .fontsize-ensurer.reset-size9.size3,.katex .sizing.reset-size9.size3{font-size:.40509259em}.katex .fontsize-ensurer.reset-size9.size4,.katex .sizing.reset-size9.size4{font-size:.46296296em}.katex .fontsize-ensurer.reset-size9.size5,.katex .sizing.reset-size9.size5{font-size:.52083333em}.katex .fontsize-ensurer.reset-size9.size6,.katex .sizing.reset-size9.size6{font-size:.5787037em}.katex .fontsize-ensurer.reset-size9.size7,.katex .sizing.reset-size9.size7{font-size:.69444444em}.katex .fontsize-ensurer.reset-size9.size8,.katex .sizing.reset-size9.size8{font-size:.83333333em}.katex .fontsize-ensurer.reset-size9.size9,.katex .sizing.reset-size9.size9{font-size:1em}.katex .fontsize-ensurer.reset-size9.size10,.katex .sizing.reset-size9.size10{font-size:1.20023148em}.katex .fontsize-ensurer.reset-size9.size11,.katex .sizing.reset-size9.size11{font-size:1.43981481em}.katex .fontsize-ensurer.reset-size10.size1,.katex .sizing.reset-size10.size1{font-size:.24108004em}.katex .fontsize-ensurer.reset-size10.size2,.katex .sizing.reset-size10.size2{font-size:.28929605em}.katex .fontsize-ensurer.reset-size10.size3,.katex .sizing.reset-size10.size3{font-size:.33751205em}.katex .fontsize-ensurer.reset-size10.size4,.katex .sizing.reset-size10.size4{font-size:.38572806em}.katex .fontsize-ensurer.reset-size10.size5,.katex .sizing.reset-size10.size5{font-size:.43394407em}.katex .fontsize-ensurer.reset-size10.size6,.katex .sizing.reset-size10.size6{font-size:.48216008em}.katex .fontsize-ensurer.reset-size10.size7,.katex .sizing.reset-size10.size7{font-size:.57859209em}.katex .fontsize-ensurer.reset-size10.size8,.katex .sizing.reset-size10.size8{font-size:.69431051em}.katex .fontsize-ensurer.reset-size10.size9,.katex .sizing.reset-size10.size9{font-size:.83317261em}.katex .fontsize-ensurer.reset-size10.size10,.katex .sizing.reset-size10.size10{font-size:1em}.katex .fontsize-ensurer.reset-size10.size11,.katex .sizing.reset-size10.size11{font-size:1.19961427em}.katex .fontsize-ensurer.reset-size11.size1,.katex .sizing.reset-size11.size1{font-size:.20096463em}.katex .fontsize-ensurer.reset-size11.size2,.katex .sizing.reset-size11.size2{font-size:.24115756em}.katex .fontsize-ensurer.reset-size11.size3,.katex .sizing.reset-size11.size3{font-size:.28135048em}.katex .fontsize-ensurer.reset-size11.size4,.katex .sizing.reset-size11.size4{font-size:.32154341em}.katex .fontsize-ensurer.reset-size11.size5,.katex .sizing.reset-size11.size5{font-size:.36173633em}.katex .fontsize-ensurer.reset-size11.size6,.katex .sizing.reset-size11.size6{font-size:.40192926em}.katex .fontsize-ensurer.reset-size11.size7,.katex .sizing.reset-size11.size7{font-size:.48231511em}.katex .fontsize-ensurer.reset-size11.size8,.katex .sizing.reset-size11.size8{font-size:.57877814em}.katex .fontsize-ensurer.reset-size11.size9,.katex .sizing.reset-size11.size9{font-size:.69453376em}.katex .fontsize-ensurer.reset-size11.size10,.katex .sizing.reset-size11.size10{font-size:.83360129em}.katex .fontsize-ensurer.reset-size11.size11,.katex .sizing.reset-size11.size11{font-size:1em}.katex .delimsizing.size1{font-family:KaTeX_Size1}.katex .delimsizing.size2{font-family:KaTeX_Size2}.katex .delimsizing.size3{font-family:KaTeX_Size3}.katex .delimsizing.size4{font-family:KaTeX_Size4}.katex .delimsizing.mult .delim-size1>span{font-family:KaTeX_Size1}.katex .delimsizing.mult .delim-size4>span{font-family:KaTeX_Size4}.katex .nulldelimiter{display:inline-block;width:.12em}.katex .delimcenter,.katex .op-symbol{position:relative}.katex .op-symbol.small-op{font-family:KaTeX_Size1}.katex .op-symbol.large-op{font-family:KaTeX_Size2}.katex .accent>.vlist-t,.katex .op-limits>.vlist-t{text-align:center}.katex .accent .accent-body{position:relative}.katex .accent .accent-body:not(.accent-full){width:0}.katex .overlay{display:block}.katex .mtable .vertical-separator{display:inline-block;min-width:1px}.katex .mtable .arraycolsep{display:inline-block}.katex .mtable .col-align-c>.vlist-t{text-align:center}.katex .mtable .col-align-l>.vlist-t{text-align:left}.katex .mtable .col-align-r>.vlist-t{text-align:right}.katex .svg-align{text-align:left}.katex svg{fill:currentColor;stroke:currentColor;fill-rule:nonzero;fill-opacity:1;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;display:block;height:inherit;position:absolute;width:100%}.katex svg path{stroke:none}.katex img{border-style:none;max-height:none;max-width:none;min-height:0;min-width:0}.katex .stretchy{display:block;overflow:hidden;position:relative;width:100%}.katex .stretchy:after,.katex .stretchy:before{content:""}.katex .hide-tail{overflow:hidden;position:relative;width:100%}.katex .halfarrow-left{left:0;overflow:hidden;position:absolute;width:50.2%}.katex .halfarrow-right{overflow:hidden;position:absolute;right:0;width:50.2%}.katex .brace-left{left:0;overflow:hidden;position:absolute;width:25.1%}.katex .brace-center{left:25%;overflow:hidden;position:absolute;width:50%}.katex .brace-right{overflow:hidden;position:absolute;right:0;width:25.1%}.katex .x-arrow-pad{padding:0 .5em}.katex .cd-arrow-pad{padding:0 .55556em 0 .27778em}.katex .mover,.katex .munder,.katex .x-arrow{text-align:center}.katex .boxpad{padding:0 .3em}.katex .fbox,.katex .fcolorbox{border:.04em solid;box-sizing:border-box}.katex .cancel-pad{padding:0 .2em}.katex .cancel-lap{margin-left:-.2em;margin-right:-.2em}.katex .sout{border-bottom-style:solid;border-bottom-width:.08em}.katex .angl{border-right:.049em solid;border-top:.049em solid;box-sizing:border-box;margin-right:.03889em}.katex .anglpad{padding:0 .03889em}.katex .eqn-num:before{content:"(" counter(katexEqnNo) ")";counter-increment:katexEqnNo}.katex .mml-eqn-num:before{content:"(" counter(mmlEqnNo) ")";counter-increment:mmlEqnNo}.katex .mtr-glue{width:50%}.katex .cd-vert-arrow{display:inline-block;position:relative}.katex .cd-label-left{display:inline-block;position:absolute;right:calc(50% + .3em);text-align:left}.katex .cd-label-right{display:inline-block;left:calc(50% + .3em);position:absolute;text-align:right}.katex-display{display:block;margin:1em 0;text-align:center}.katex-display>.katex{display:block;text-align:center;white-space:nowrap}.katex-display>.katex>.katex-html{display:block;position:relative}.katex-display>.katex>.katex-html>.tag{position:absolute;right:0}.katex-display.leqno>.katex>.katex-html>.tag{left:0;right:auto}.katex-display.fleqn>.katex{padding-left:2em;text-align:left}body{counter-reset:katexEqnNo mmlEqnNo} +@font-face { + font-family: KaTeX_AMS; + font-style: normal; + font-weight: 400; + src: url(fonts/KaTeX_AMS-Regular.woff2) format("woff2"), + url(fonts/KaTeX_AMS-Regular.woff) format("woff"), + url(fonts/KaTeX_AMS-Regular.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Caligraphic; + font-style: normal; + font-weight: 700; + src: url(fonts/KaTeX_Caligraphic-Bold.woff2) format("woff2"), + url(fonts/KaTeX_Caligraphic-Bold.woff) format("woff"), + url(fonts/KaTeX_Caligraphic-Bold.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Caligraphic; + font-style: normal; + font-weight: 400; + src: url(fonts/KaTeX_Caligraphic-Regular.woff2) format("woff2"), + url(fonts/KaTeX_Caligraphic-Regular.woff) format("woff"), + url(fonts/KaTeX_Caligraphic-Regular.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Fraktur; + font-style: normal; + font-weight: 700; + src: url(fonts/KaTeX_Fraktur-Bold.woff2) format("woff2"), + url(fonts/KaTeX_Fraktur-Bold.woff) format("woff"), + url(fonts/KaTeX_Fraktur-Bold.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Fraktur; + font-style: normal; + font-weight: 400; + src: url(fonts/KaTeX_Fraktur-Regular.woff2) format("woff2"), + url(fonts/KaTeX_Fraktur-Regular.woff) format("woff"), + url(fonts/KaTeX_Fraktur-Regular.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Main; + font-style: normal; + font-weight: 700; + src: url(fonts/KaTeX_Main-Bold.woff2) format("woff2"), + url(fonts/KaTeX_Main-Bold.woff) format("woff"), + url(fonts/KaTeX_Main-Bold.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Main; + font-style: italic; + font-weight: 700; + src: url(fonts/KaTeX_Main-BoldItalic.woff2) format("woff2"), + url(fonts/KaTeX_Main-BoldItalic.woff) format("woff"), + url(fonts/KaTeX_Main-BoldItalic.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Main; + font-style: italic; + font-weight: 400; + src: url(fonts/KaTeX_Main-Italic.woff2) format("woff2"), + url(fonts/KaTeX_Main-Italic.woff) format("woff"), + url(fonts/KaTeX_Main-Italic.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Main; + font-style: normal; + font-weight: 400; + src: url(fonts/KaTeX_Main-Regular.woff2) format("woff2"), + url(fonts/KaTeX_Main-Regular.woff) format("woff"), + url(fonts/KaTeX_Main-Regular.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Math; + font-style: italic; + font-weight: 700; + src: url(fonts/KaTeX_Math-BoldItalic.woff2) format("woff2"), + url(fonts/KaTeX_Math-BoldItalic.woff) format("woff"), + url(fonts/KaTeX_Math-BoldItalic.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Math; + font-style: italic; + font-weight: 400; + src: url(fonts/KaTeX_Math-Italic.woff2) format("woff2"), + url(fonts/KaTeX_Math-Italic.woff) format("woff"), + url(fonts/KaTeX_Math-Italic.ttf) format("truetype"); +} +@font-face { + font-family: "KaTeX_SansSerif"; + font-style: normal; + font-weight: 700; + src: url(fonts/KaTeX_SansSerif-Bold.woff2) format("woff2"), + url(fonts/KaTeX_SansSerif-Bold.woff) format("woff"), + url(fonts/KaTeX_SansSerif-Bold.ttf) format("truetype"); +} +@font-face { + font-family: "KaTeX_SansSerif"; + font-style: italic; + font-weight: 400; + src: url(fonts/KaTeX_SansSerif-Italic.woff2) format("woff2"), + url(fonts/KaTeX_SansSerif-Italic.woff) format("woff"), + url(fonts/KaTeX_SansSerif-Italic.ttf) format("truetype"); +} +@font-face { + font-family: "KaTeX_SansSerif"; + font-style: normal; + font-weight: 400; + src: url(fonts/KaTeX_SansSerif-Regular.woff2) format("woff2"), + url(fonts/KaTeX_SansSerif-Regular.woff) format("woff"), + url(fonts/KaTeX_SansSerif-Regular.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Script; + font-style: normal; + font-weight: 400; + src: url(fonts/KaTeX_Script-Regular.woff2) format("woff2"), + url(fonts/KaTeX_Script-Regular.woff) format("woff"), + url(fonts/KaTeX_Script-Regular.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Size1; + font-style: normal; + font-weight: 400; + src: url(fonts/KaTeX_Size1-Regular.woff2) format("woff2"), + url(fonts/KaTeX_Size1-Regular.woff) format("woff"), + url(fonts/KaTeX_Size1-Regular.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Size2; + font-style: normal; + font-weight: 400; + src: url(fonts/KaTeX_Size2-Regular.woff2) format("woff2"), + url(fonts/KaTeX_Size2-Regular.woff) format("woff"), + url(fonts/KaTeX_Size2-Regular.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Size3; + font-style: normal; + font-weight: 400; + src: url(fonts/KaTeX_Size3-Regular.woff2) format("woff2"), + url(fonts/KaTeX_Size3-Regular.woff) format("woff"), + url(fonts/KaTeX_Size3-Regular.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Size4; + font-style: normal; + font-weight: 400; + src: url(fonts/KaTeX_Size4-Regular.woff2) format("woff2"), + url(fonts/KaTeX_Size4-Regular.woff) format("woff"), + url(fonts/KaTeX_Size4-Regular.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Typewriter; + font-style: normal; + font-weight: 400; + src: url(fonts/KaTeX_Typewriter-Regular.woff2) format("woff2"), + url(fonts/KaTeX_Typewriter-Regular.woff) format("woff"), + url(fonts/KaTeX_Typewriter-Regular.ttf) format("truetype"); +} +.katex { + text-rendering: auto; + font: normal 1.21em KaTeX_Main, Times New Roman, serif; + line-height: 1.2; + text-indent: 0; +} +.katex * { + -ms-high-contrast-adjust: none !important; + border-color: currentColor; +} +.katex .katex-version:after { + content: "0.13.13"; +} +.katex .katex-mathml { + clip: rect(1px, 1px, 1px, 1px); + border: 0; + height: 1px; + overflow: hidden; + padding: 0; + position: absolute; + width: 1px; +} +.katex .katex-html > .newline { + display: block; +} +.katex .base { + position: relative; + white-space: nowrap; + width: -webkit-min-content; + width: -moz-min-content; + width: min-content; +} +.katex .base, +.katex .strut { + display: inline-block; +} +.katex .textbf { + font-weight: 700; +} +.katex .textit { + font-style: italic; +} +.katex .textrm { + font-family: KaTeX_Main; +} +.katex .textsf { + font-family: KaTeX_SansSerif; +} +.katex .texttt { + font-family: KaTeX_Typewriter; +} +.katex .mathnormal { + font-family: KaTeX_Math; + font-style: italic; +} +.katex .mathit { + font-family: KaTeX_Main; + font-style: italic; +} +.katex .mathrm { + font-style: normal; +} +.katex .mathbf { + font-family: KaTeX_Main; + font-weight: 700; +} +.katex .boldsymbol { + font-family: KaTeX_Math; + font-style: italic; + font-weight: 700; +} +.katex .amsrm, +.katex .mathbb, +.katex .textbb { + font-family: KaTeX_AMS; +} +.katex .mathcal { + font-family: KaTeX_Caligraphic; +} +.katex .mathfrak, +.katex .textfrak { + font-family: KaTeX_Fraktur; +} +.katex .mathtt { + font-family: KaTeX_Typewriter; +} +.katex .mathscr, +.katex .textscr { + font-family: KaTeX_Script; +} +.katex .mathsf, +.katex .textsf { + font-family: KaTeX_SansSerif; +} +.katex .mathboldsf, +.katex .textboldsf { + font-family: KaTeX_SansSerif; + font-weight: 700; +} +.katex .mathitsf, +.katex .textitsf { + font-family: KaTeX_SansSerif; + font-style: italic; +} +.katex .mainrm { + font-family: KaTeX_Main; + font-style: normal; +} +.katex .vlist-t { + border-collapse: collapse; + display: inline-table; + table-layout: fixed; +} +.katex .vlist-r { + display: table-row; +} +.katex .vlist { + display: table-cell; + position: relative; + vertical-align: bottom; +} +.katex .vlist > span { + display: block; + height: 0; + position: relative; +} +.katex .vlist > span > span { + display: inline-block; +} +.katex .vlist > span > .pstrut { + overflow: hidden; + width: 0; +} +.katex .vlist-t2 { + margin-right: -2px; +} +.katex .vlist-s { + display: table-cell; + font-size: 1px; + min-width: 2px; + vertical-align: bottom; + width: 2px; +} +.katex .vbox { + align-items: baseline; + display: inline-flex; + flex-direction: column; +} +.katex .hbox { + width: 100%; +} +.katex .hbox, +.katex .thinbox { + display: inline-flex; + flex-direction: row; +} +.katex .thinbox { + max-width: 0; + width: 0; +} +.katex .msupsub { + text-align: left; +} +.katex .mfrac > span > span { + text-align: center; +} +.katex .mfrac .frac-line { + border-bottom-style: solid; + display: inline-block; + width: 100%; +} +.katex .hdashline, +.katex .hline, +.katex .mfrac .frac-line, +.katex .overline .overline-line, +.katex .rule, +.katex .underline .underline-line { + min-height: 1px; +} +.katex .mspace { + display: inline-block; +} +.katex .clap, +.katex .llap, +.katex .rlap { + position: relative; + width: 0; +} +.katex .clap > .inner, +.katex .llap > .inner, +.katex .rlap > .inner { + position: absolute; +} +.katex .clap > .fix, +.katex .llap > .fix, +.katex .rlap > .fix { + display: inline-block; +} +.katex .llap > .inner { + right: 0; +} +.katex .clap > .inner, +.katex .rlap > .inner { + left: 0; +} +.katex .clap > .inner > span { + margin-left: -50%; + margin-right: 50%; +} +.katex .rule { + border: 0 solid; + display: inline-block; + position: relative; +} +.katex .hline, +.katex .overline .overline-line, +.katex .underline .underline-line { + border-bottom-style: solid; + display: inline-block; + width: 100%; +} +.katex .hdashline { + border-bottom-style: underline; + display: inline-block; + width: 100%; +} +.katex .sqrt > .root { + margin-left: 0.27777778em; + margin-right: -0.55555556em; +} +.katex .fontsize-ensurer.reset-size1.size1, +.katex .sizing.reset-size1.size1 { + font-size: 1em; +} +.katex .fontsize-ensurer.reset-size1.size2, +.katex .sizing.reset-size1.size2 { + font-size: 1.2em; +} +.katex .fontsize-ensurer.reset-size1.size3, +.katex .sizing.reset-size1.size3 { + font-size: 1.4em; +} +.katex .fontsize-ensurer.reset-size1.size4, +.katex .sizing.reset-size1.size4 { + font-size: 1.6em; +} +.katex .fontsize-ensurer.reset-size1.size5, +.katex .sizing.reset-size1.size5 { + font-size: 1.8em; +} +.katex .fontsize-ensurer.reset-size1.size6, +.katex .sizing.reset-size1.size6 { + font-size: 2em; +} +.katex .fontsize-ensurer.reset-size1.size7, +.katex .sizing.reset-size1.size7 { + font-size: 2.4em; +} +.katex .fontsize-ensurer.reset-size1.size8, +.katex .sizing.reset-size1.size8 { + font-size: 2.88em; +} +.katex .fontsize-ensurer.reset-size1.size9, +.katex .sizing.reset-size1.size9 { + font-size: 3.456em; +} +.katex .fontsize-ensurer.reset-size1.size10, +.katex .sizing.reset-size1.size10 { + font-size: 4.148em; +} +.katex .fontsize-ensurer.reset-size1.size11, +.katex .sizing.reset-size1.size11 { + font-size: 4.976em; +} +.katex .fontsize-ensurer.reset-size2.size1, +.katex .sizing.reset-size2.size1 { + font-size: 0.83333333em; +} +.katex .fontsize-ensurer.reset-size2.size2, +.katex .sizing.reset-size2.size2 { + font-size: 1em; +} +.katex .fontsize-ensurer.reset-size2.size3, +.katex .sizing.reset-size2.size3 { + font-size: 1.16666667em; +} +.katex .fontsize-ensurer.reset-size2.size4, +.katex .sizing.reset-size2.size4 { + font-size: 1.33333333em; +} +.katex .fontsize-ensurer.reset-size2.size5, +.katex .sizing.reset-size2.size5 { + font-size: 1.5em; +} +.katex .fontsize-ensurer.reset-size2.size6, +.katex .sizing.reset-size2.size6 { + font-size: 1.66666667em; +} +.katex .fontsize-ensurer.reset-size2.size7, +.katex .sizing.reset-size2.size7 { + font-size: 2em; +} +.katex .fontsize-ensurer.reset-size2.size8, +.katex .sizing.reset-size2.size8 { + font-size: 2.4em; +} +.katex .fontsize-ensurer.reset-size2.size9, +.katex .sizing.reset-size2.size9 { + font-size: 2.88em; +} +.katex .fontsize-ensurer.reset-size2.size10, +.katex .sizing.reset-size2.size10 { + font-size: 3.45666667em; +} +.katex .fontsize-ensurer.reset-size2.size11, +.katex .sizing.reset-size2.size11 { + font-size: 4.14666667em; +} +.katex .fontsize-ensurer.reset-size3.size1, +.katex .sizing.reset-size3.size1 { + font-size: 0.71428571em; +} +.katex .fontsize-ensurer.reset-size3.size2, +.katex .sizing.reset-size3.size2 { + font-size: 0.85714286em; +} +.katex .fontsize-ensurer.reset-size3.size3, +.katex .sizing.reset-size3.size3 { + font-size: 1em; +} +.katex .fontsize-ensurer.reset-size3.size4, +.katex .sizing.reset-size3.size4 { + font-size: 1.14285714em; +} +.katex .fontsize-ensurer.reset-size3.size5, +.katex .sizing.reset-size3.size5 { + font-size: 1.28571429em; +} +.katex .fontsize-ensurer.reset-size3.size6, +.katex .sizing.reset-size3.size6 { + font-size: 1.42857143em; +} +.katex .fontsize-ensurer.reset-size3.size7, +.katex .sizing.reset-size3.size7 { + font-size: 1.71428571em; +} +.katex .fontsize-ensurer.reset-size3.size8, +.katex .sizing.reset-size3.size8 { + font-size: 2.05714286em; +} +.katex .fontsize-ensurer.reset-size3.size9, +.katex .sizing.reset-size3.size9 { + font-size: 2.46857143em; +} +.katex .fontsize-ensurer.reset-size3.size10, +.katex .sizing.reset-size3.size10 { + font-size: 2.96285714em; +} +.katex .fontsize-ensurer.reset-size3.size11, +.katex .sizing.reset-size3.size11 { + font-size: 3.55428571em; +} +.katex .fontsize-ensurer.reset-size4.size1, +.katex .sizing.reset-size4.size1 { + font-size: 0.625em; +} +.katex .fontsize-ensurer.reset-size4.size2, +.katex .sizing.reset-size4.size2 { + font-size: 0.75em; +} +.katex .fontsize-ensurer.reset-size4.size3, +.katex .sizing.reset-size4.size3 { + font-size: 0.875em; +} +.katex .fontsize-ensurer.reset-size4.size4, +.katex .sizing.reset-size4.size4 { + font-size: 1em; +} +.katex .fontsize-ensurer.reset-size4.size5, +.katex .sizing.reset-size4.size5 { + font-size: 1.125em; +} +.katex .fontsize-ensurer.reset-size4.size6, +.katex .sizing.reset-size4.size6 { + font-size: 1.25em; +} +.katex .fontsize-ensurer.reset-size4.size7, +.katex .sizing.reset-size4.size7 { + font-size: 1.5em; +} +.katex .fontsize-ensurer.reset-size4.size8, +.katex .sizing.reset-size4.size8 { + font-size: 1.8em; +} +.katex .fontsize-ensurer.reset-size4.size9, +.katex .sizing.reset-size4.size9 { + font-size: 2.16em; +} +.katex .fontsize-ensurer.reset-size4.size10, +.katex .sizing.reset-size4.size10 { + font-size: 2.5925em; +} +.katex .fontsize-ensurer.reset-size4.size11, +.katex .sizing.reset-size4.size11 { + font-size: 3.11em; +} +.katex .fontsize-ensurer.reset-size5.size1, +.katex .sizing.reset-size5.size1 { + font-size: 0.55555556em; +} +.katex .fontsize-ensurer.reset-size5.size2, +.katex .sizing.reset-size5.size2 { + font-size: 0.66666667em; +} +.katex .fontsize-ensurer.reset-size5.size3, +.katex .sizing.reset-size5.size3 { + font-size: 0.77777778em; +} +.katex .fontsize-ensurer.reset-size5.size4, +.katex .sizing.reset-size5.size4 { + font-size: 0.88888889em; +} +.katex .fontsize-ensurer.reset-size5.size5, +.katex .sizing.reset-size5.size5 { + font-size: 1em; +} +.katex .fontsize-ensurer.reset-size5.size6, +.katex .sizing.reset-size5.size6 { + font-size: 1.11111111em; +} +.katex .fontsize-ensurer.reset-size5.size7, +.katex .sizing.reset-size5.size7 { + font-size: 1.33333333em; +} +.katex .fontsize-ensurer.reset-size5.size8, +.katex .sizing.reset-size5.size8 { + font-size: 1.6em; +} +.katex .fontsize-ensurer.reset-size5.size9, +.katex .sizing.reset-size5.size9 { + font-size: 1.92em; +} +.katex .fontsize-ensurer.reset-size5.size10, +.katex .sizing.reset-size5.size10 { + font-size: 2.30444444em; +} +.katex .fontsize-ensurer.reset-size5.size11, +.katex .sizing.reset-size5.size11 { + font-size: 2.76444444em; +} +.katex .fontsize-ensurer.reset-size6.size1, +.katex .sizing.reset-size6.size1 { + font-size: 0.5em; +} +.katex .fontsize-ensurer.reset-size6.size2, +.katex .sizing.reset-size6.size2 { + font-size: 0.6em; +} +.katex .fontsize-ensurer.reset-size6.size3, +.katex .sizing.reset-size6.size3 { + font-size: 0.7em; +} +.katex .fontsize-ensurer.reset-size6.size4, +.katex .sizing.reset-size6.size4 { + font-size: 0.8em; +} +.katex .fontsize-ensurer.reset-size6.size5, +.katex .sizing.reset-size6.size5 { + font-size: 0.9em; +} +.katex .fontsize-ensurer.reset-size6.size6, +.katex .sizing.reset-size6.size6 { + font-size: 1em; +} +.katex .fontsize-ensurer.reset-size6.size7, +.katex .sizing.reset-size6.size7 { + font-size: 1.2em; +} +.katex .fontsize-ensurer.reset-size6.size8, +.katex .sizing.reset-size6.size8 { + font-size: 1.44em; +} +.katex .fontsize-ensurer.reset-size6.size9, +.katex .sizing.reset-size6.size9 { + font-size: 1.728em; +} +.katex .fontsize-ensurer.reset-size6.size10, +.katex .sizing.reset-size6.size10 { + font-size: 2.074em; +} +.katex .fontsize-ensurer.reset-size6.size11, +.katex .sizing.reset-size6.size11 { + font-size: 2.488em; +} +.katex .fontsize-ensurer.reset-size7.size1, +.katex .sizing.reset-size7.size1 { + font-size: 0.41666667em; +} +.katex .fontsize-ensurer.reset-size7.size2, +.katex .sizing.reset-size7.size2 { + font-size: 0.5em; +} +.katex .fontsize-ensurer.reset-size7.size3, +.katex .sizing.reset-size7.size3 { + font-size: 0.58333333em; +} +.katex .fontsize-ensurer.reset-size7.size4, +.katex .sizing.reset-size7.size4 { + font-size: 0.66666667em; +} +.katex .fontsize-ensurer.reset-size7.size5, +.katex .sizing.reset-size7.size5 { + font-size: 0.75em; +} +.katex .fontsize-ensurer.reset-size7.size6, +.katex .sizing.reset-size7.size6 { + font-size: 0.83333333em; +} +.katex .fontsize-ensurer.reset-size7.size7, +.katex .sizing.reset-size7.size7 { + font-size: 1em; +} +.katex .fontsize-ensurer.reset-size7.size8, +.katex .sizing.reset-size7.size8 { + font-size: 1.2em; +} +.katex .fontsize-ensurer.reset-size7.size9, +.katex .sizing.reset-size7.size9 { + font-size: 1.44em; +} +.katex .fontsize-ensurer.reset-size7.size10, +.katex .sizing.reset-size7.size10 { + font-size: 1.72833333em; +} +.katex .fontsize-ensurer.reset-size7.size11, +.katex .sizing.reset-size7.size11 { + font-size: 2.07333333em; +} +.katex .fontsize-ensurer.reset-size8.size1, +.katex .sizing.reset-size8.size1 { + font-size: 0.34722222em; +} +.katex .fontsize-ensurer.reset-size8.size2, +.katex .sizing.reset-size8.size2 { + font-size: 0.41666667em; +} +.katex .fontsize-ensurer.reset-size8.size3, +.katex .sizing.reset-size8.size3 { + font-size: 0.48611111em; +} +.katex .fontsize-ensurer.reset-size8.size4, +.katex .sizing.reset-size8.size4 { + font-size: 0.55555556em; +} +.katex .fontsize-ensurer.reset-size8.size5, +.katex .sizing.reset-size8.size5 { + font-size: 0.625em; +} +.katex .fontsize-ensurer.reset-size8.size6, +.katex .sizing.reset-size8.size6 { + font-size: 0.69444444em; +} +.katex .fontsize-ensurer.reset-size8.size7, +.katex .sizing.reset-size8.size7 { + font-size: 0.83333333em; +} +.katex .fontsize-ensurer.reset-size8.size8, +.katex .sizing.reset-size8.size8 { + font-size: 1em; +} +.katex .fontsize-ensurer.reset-size8.size9, +.katex .sizing.reset-size8.size9 { + font-size: 1.2em; +} +.katex .fontsize-ensurer.reset-size8.size10, +.katex .sizing.reset-size8.size10 { + font-size: 1.44027778em; +} +.katex .fontsize-ensurer.reset-size8.size11, +.katex .sizing.reset-size8.size11 { + font-size: 1.72777778em; +} +.katex .fontsize-ensurer.reset-size9.size1, +.katex .sizing.reset-size9.size1 { + font-size: 0.28935185em; +} +.katex .fontsize-ensurer.reset-size9.size2, +.katex .sizing.reset-size9.size2 { + font-size: 0.34722222em; +} +.katex .fontsize-ensurer.reset-size9.size3, +.katex .sizing.reset-size9.size3 { + font-size: 0.40509259em; +} +.katex .fontsize-ensurer.reset-size9.size4, +.katex .sizing.reset-size9.size4 { + font-size: 0.46296296em; +} +.katex .fontsize-ensurer.reset-size9.size5, +.katex .sizing.reset-size9.size5 { + font-size: 0.52083333em; +} +.katex .fontsize-ensurer.reset-size9.size6, +.katex .sizing.reset-size9.size6 { + font-size: 0.5787037em; +} +.katex .fontsize-ensurer.reset-size9.size7, +.katex .sizing.reset-size9.size7 { + font-size: 0.69444444em; +} +.katex .fontsize-ensurer.reset-size9.size8, +.katex .sizing.reset-size9.size8 { + font-size: 0.83333333em; +} +.katex .fontsize-ensurer.reset-size9.size9, +.katex .sizing.reset-size9.size9 { + font-size: 1em; +} +.katex .fontsize-ensurer.reset-size9.size10, +.katex .sizing.reset-size9.size10 { + font-size: 1.20023148em; +} +.katex .fontsize-ensurer.reset-size9.size11, +.katex .sizing.reset-size9.size11 { + font-size: 1.43981481em; +} +.katex .fontsize-ensurer.reset-size10.size1, +.katex .sizing.reset-size10.size1 { + font-size: 0.24108004em; +} +.katex .fontsize-ensurer.reset-size10.size2, +.katex .sizing.reset-size10.size2 { + font-size: 0.28929605em; +} +.katex .fontsize-ensurer.reset-size10.size3, +.katex .sizing.reset-size10.size3 { + font-size: 0.33751205em; +} +.katex .fontsize-ensurer.reset-size10.size4, +.katex .sizing.reset-size10.size4 { + font-size: 0.38572806em; +} +.katex .fontsize-ensurer.reset-size10.size5, +.katex .sizing.reset-size10.size5 { + font-size: 0.43394407em; +} +.katex .fontsize-ensurer.reset-size10.size6, +.katex .sizing.reset-size10.size6 { + font-size: 0.48216008em; +} +.katex .fontsize-ensurer.reset-size10.size7, +.katex .sizing.reset-size10.size7 { + font-size: 0.57859209em; +} +.katex .fontsize-ensurer.reset-size10.size8, +.katex .sizing.reset-size10.size8 { + font-size: 0.69431051em; +} +.katex .fontsize-ensurer.reset-size10.size9, +.katex .sizing.reset-size10.size9 { + font-size: 0.83317261em; +} +.katex .fontsize-ensurer.reset-size10.size10, +.katex .sizing.reset-size10.size10 { + font-size: 1em; +} +.katex .fontsize-ensurer.reset-size10.size11, +.katex .sizing.reset-size10.size11 { + font-size: 1.19961427em; +} +.katex .fontsize-ensurer.reset-size11.size1, +.katex .sizing.reset-size11.size1 { + font-size: 0.20096463em; +} +.katex .fontsize-ensurer.reset-size11.size2, +.katex .sizing.reset-size11.size2 { + font-size: 0.24115756em; +} +.katex .fontsize-ensurer.reset-size11.size3, +.katex .sizing.reset-size11.size3 { + font-size: 0.28135048em; +} +.katex .fontsize-ensurer.reset-size11.size4, +.katex .sizing.reset-size11.size4 { + font-size: 0.32154341em; +} +.katex .fontsize-ensurer.reset-size11.size5, +.katex .sizing.reset-size11.size5 { + font-size: 0.36173633em; +} +.katex .fontsize-ensurer.reset-size11.size6, +.katex .sizing.reset-size11.size6 { + font-size: 0.40192926em; +} +.katex .fontsize-ensurer.reset-size11.size7, +.katex .sizing.reset-size11.size7 { + font-size: 0.48231511em; +} +.katex .fontsize-ensurer.reset-size11.size8, +.katex .sizing.reset-size11.size8 { + font-size: 0.57877814em; +} +.katex .fontsize-ensurer.reset-size11.size9, +.katex .sizing.reset-size11.size9 { + font-size: 0.69453376em; +} +.katex .fontsize-ensurer.reset-size11.size10, +.katex .sizing.reset-size11.size10 { + font-size: 0.83360129em; +} +.katex .fontsize-ensurer.reset-size11.size11, +.katex .sizing.reset-size11.size11 { + font-size: 1em; +} +.katex .delimsizing.size1 { + font-family: KaTeX_Size1; +} +.katex .delimsizing.size2 { + font-family: KaTeX_Size2; +} +.katex .delimsizing.size3 { + font-family: KaTeX_Size3; +} +.katex .delimsizing.size4 { + font-family: KaTeX_Size4; +} +.katex .delimsizing.mult .delim-size1 > span { + font-family: KaTeX_Size1; +} +.katex .delimsizing.mult .delim-size4 > span { + font-family: KaTeX_Size4; +} +.katex .nulldelimiter { + display: inline-block; + width: 0.12em; +} +.katex .delimcenter, +.katex .op-symbol { + position: relative; +} +.katex .op-symbol.small-op { + font-family: KaTeX_Size1; +} +.katex .op-symbol.large-op { + font-family: KaTeX_Size2; +} +.katex .accent > .vlist-t, +.katex .op-limits > .vlist-t { + text-align: center; +} +.katex .accent .accent-body { + position: relative; +} +.katex .accent .accent-body:not(.accent-full) { + width: 0; +} +.katex .overlay { + display: block; +} +.katex .mtable .vertical-separator { + display: inline-block; + min-width: 1px; +} +.katex .mtable .arraycolsep { + display: inline-block; +} +.katex .mtable .col-align-c > .vlist-t { + text-align: center; +} +.katex .mtable .col-align-l > .vlist-t { + text-align: left; +} +.katex .mtable .col-align-r > .vlist-t { + text-align: right; +} +.katex .svg-align { + text-align: left; +} +.katex svg { + fill: currentColor; + stroke: currentColor; + fill-rule: nonzero; + fill-opacity: 1; + stroke-width: 1; + stroke-linecap: butt; + stroke-linejoin: miter; + stroke-miterlimit: 4; + stroke-dasharray: none; + stroke-dashoffset: 0; + stroke-opacity: 1; + display: block; + height: inherit; + position: absolute; + width: 100%; +} +.katex svg path { + stroke: none; +} +.katex img { + border-style: none; + max-height: none; + max-width: none; + min-height: 0; + min-width: 0; +} +.katex .stretchy { + display: block; + overflow: hidden; + position: relative; + width: 100%; +} +.katex .stretchy:after, +.katex .stretchy:before { + content: ""; +} +.katex .hide-tail { + overflow: hidden; + position: relative; + width: 100%; +} +.katex .halfarrow-left { + left: 0; + overflow: hidden; + position: absolute; + width: 50.2%; +} +.katex .halfarrow-right { + overflow: hidden; + position: absolute; + right: 0; + width: 50.2%; +} +.katex .brace-left { + left: 0; + overflow: hidden; + position: absolute; + width: 25.1%; +} +.katex .brace-center { + left: 25%; + overflow: hidden; + position: absolute; + width: 50%; +} +.katex .brace-right { + overflow: hidden; + position: absolute; + right: 0; + width: 25.1%; +} +.katex .x-arrow-pad { + padding: 0 0.5em; +} +.katex .cd-arrow-pad { + padding: 0 0.55556em 0 0.27778em; +} +.katex .mover, +.katex .munder, +.katex .x-arrow { + text-align: center; +} +.katex .boxpad { + padding: 0 0.3em; +} +.katex .fbox, +.katex .fcolorbox { + border: 0.04em solid; + box-sizing: border-box; +} +.katex .cancel-pad { + padding: 0 0.2em; +} +.katex .cancel-lap { + margin-left: -0.2em; + margin-right: -0.2em; +} +.katex .sout { + border-bottom-style: solid; + border-bottom-width: 0.08em; +} +.katex .angl { + border-right: 0.049em solid; + border-top: 0.049em solid; + box-sizing: border-box; + margin-right: 0.03889em; +} +.katex .anglpad { + padding: 0 0.03889em; +} +.katex .eqn-num:before { + content: "(" counter(katexEqnNo) ")"; + counter-increment: katexEqnNo; +} +.katex .mml-eqn-num:before { + content: "(" counter(mmlEqnNo) ")"; + counter-increment: mmlEqnNo; +} +.katex .mtr-glue { + width: 50%; +} +.katex .cd-vert-arrow { + display: inline-block; + position: relative; +} +.katex .cd-label-left { + display: inline-block; + position: absolute; + right: calc(50% + 0.3em); + text-align: left; +} +.katex .cd-label-right { + display: inline-block; + left: calc(50% + 0.3em); + position: absolute; + text-align: right; +} +.katex-display { + display: block; + margin: 1em 0; + text-align: center; +} +.katex-display > .katex { + display: block; + text-align: center; + white-space: nowrap; +} +.katex-display > .katex > .katex-html { + display: block; + position: relative; +} +.katex-display > .katex > .katex-html > .tag { + position: absolute; + right: 0; +} +.katex-display.leqno > .katex > .katex-html > .tag { + left: 0; + right: auto; +} +.katex-display.fleqn > .katex { + padding-left: 2em; + text-align: left; +} +body { + counter-reset: katexEqnNo mmlEqnNo; +} diff --git a/website/public/katex-4ff918ea95.min.css b/website/public/katex-4ff918ea95.min.css index 9655d471f50..1c4412ce288 100644 --- a/website/public/katex-4ff918ea95.min.css +++ b/website/public/katex-4ff918ea95.min.css @@ -1 +1,1114 @@ -@font-face{font-family:KaTeX_AMS;font-style:normal;font-weight:400;src:url(fonts/KaTeX_AMS-Regular.woff2) format("woff2"),url(fonts/KaTeX_AMS-Regular.woff) format("woff"),url(fonts/KaTeX_AMS-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Caligraphic;font-style:normal;font-weight:700;src:url(fonts/KaTeX_Caligraphic-Bold.woff2) format("woff2"),url(fonts/KaTeX_Caligraphic-Bold.woff) format("woff"),url(fonts/KaTeX_Caligraphic-Bold.ttf) format("truetype")}@font-face{font-family:KaTeX_Caligraphic;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Caligraphic-Regular.woff2) format("woff2"),url(fonts/KaTeX_Caligraphic-Regular.woff) format("woff"),url(fonts/KaTeX_Caligraphic-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Fraktur;font-style:normal;font-weight:700;src:url(fonts/KaTeX_Fraktur-Bold.woff2) format("woff2"),url(fonts/KaTeX_Fraktur-Bold.woff) format("woff"),url(fonts/KaTeX_Fraktur-Bold.ttf) format("truetype")}@font-face{font-family:KaTeX_Fraktur;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Fraktur-Regular.woff2) format("woff2"),url(fonts/KaTeX_Fraktur-Regular.woff) format("woff"),url(fonts/KaTeX_Fraktur-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:normal;font-weight:700;src:url(fonts/KaTeX_Main-Bold.woff2) format("woff2"),url(fonts/KaTeX_Main-Bold.woff) format("woff"),url(fonts/KaTeX_Main-Bold.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:italic;font-weight:700;src:url(fonts/KaTeX_Main-BoldItalic.woff2) format("woff2"),url(fonts/KaTeX_Main-BoldItalic.woff) format("woff"),url(fonts/KaTeX_Main-BoldItalic.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:italic;font-weight:400;src:url(fonts/KaTeX_Main-Italic.woff2) format("woff2"),url(fonts/KaTeX_Main-Italic.woff) format("woff"),url(fonts/KaTeX_Main-Italic.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Main-Regular.woff2) format("woff2"),url(fonts/KaTeX_Main-Regular.woff) format("woff"),url(fonts/KaTeX_Main-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Math;font-style:italic;font-weight:700;src:url(fonts/KaTeX_Math-BoldItalic.woff2) format("woff2"),url(fonts/KaTeX_Math-BoldItalic.woff) format("woff"),url(fonts/KaTeX_Math-BoldItalic.ttf) format("truetype")}@font-face{font-family:KaTeX_Math;font-style:italic;font-weight:400;src:url(fonts/KaTeX_Math-Italic.woff2) format("woff2"),url(fonts/KaTeX_Math-Italic.woff) format("woff"),url(fonts/KaTeX_Math-Italic.ttf) format("truetype")}@font-face{font-family:"KaTeX_SansSerif";font-style:normal;font-weight:700;src:url(fonts/KaTeX_SansSerif-Bold.woff2) format("woff2"),url(fonts/KaTeX_SansSerif-Bold.woff) format("woff"),url(fonts/KaTeX_SansSerif-Bold.ttf) format("truetype")}@font-face{font-family:"KaTeX_SansSerif";font-style:italic;font-weight:400;src:url(fonts/KaTeX_SansSerif-Italic.woff2) format("woff2"),url(fonts/KaTeX_SansSerif-Italic.woff) format("woff"),url(fonts/KaTeX_SansSerif-Italic.ttf) format("truetype")}@font-face{font-family:"KaTeX_SansSerif";font-style:normal;font-weight:400;src:url(fonts/KaTeX_SansSerif-Regular.woff2) format("woff2"),url(fonts/KaTeX_SansSerif-Regular.woff) format("woff"),url(fonts/KaTeX_SansSerif-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Script;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Script-Regular.woff2) format("woff2"),url(fonts/KaTeX_Script-Regular.woff) format("woff"),url(fonts/KaTeX_Script-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Size1;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Size1-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size1-Regular.woff) format("woff"),url(fonts/KaTeX_Size1-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Size2;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Size2-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size2-Regular.woff) format("woff"),url(fonts/KaTeX_Size2-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Size3;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Size3-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size3-Regular.woff) format("woff"),url(fonts/KaTeX_Size3-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Size4;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Size4-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size4-Regular.woff) format("woff"),url(fonts/KaTeX_Size4-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Typewriter;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Typewriter-Regular.woff2) format("woff2"),url(fonts/KaTeX_Typewriter-Regular.woff) format("woff"),url(fonts/KaTeX_Typewriter-Regular.ttf) format("truetype")}.katex{font:normal 1.21em KaTeX_Main,Times New Roman,serif;line-height:1.2;text-indent:0;text-rendering:auto}.katex *{-ms-high-contrast-adjust:none!important;border-color:currentColor}.katex .katex-version:after{content:"0.13.11"}.katex .katex-mathml{clip:rect(1px,1px,1px,1px);border:0;height:1px;overflow:hidden;padding:0;position:absolute;width:1px}.katex .katex-html>.newline{display:block}.katex .base{position:relative;white-space:nowrap;width:-webkit-min-content;width:-moz-min-content;width:min-content}.katex .base,.katex .strut{display:inline-block}.katex .textbf{font-weight:700}.katex .textit{font-style:italic}.katex .textrm{font-family:KaTeX_Main}.katex .textsf{font-family:KaTeX_SansSerif}.katex .texttt{font-family:KaTeX_Typewriter}.katex .mathnormal{font-family:KaTeX_Math;font-style:italic}.katex .mathit{font-family:KaTeX_Main;font-style:italic}.katex .mathrm{font-style:normal}.katex .mathbf{font-family:KaTeX_Main;font-weight:700}.katex .boldsymbol{font-family:KaTeX_Math;font-style:italic;font-weight:700}.katex .amsrm,.katex .mathbb,.katex .textbb{font-family:KaTeX_AMS}.katex .mathcal{font-family:KaTeX_Caligraphic}.katex .mathfrak,.katex .textfrak{font-family:KaTeX_Fraktur}.katex .mathtt{font-family:KaTeX_Typewriter}.katex .mathscr,.katex .textscr{font-family:KaTeX_Script}.katex .mathsf,.katex .textsf{font-family:KaTeX_SansSerif}.katex .mathboldsf,.katex .textboldsf{font-family:KaTeX_SansSerif;font-weight:700}.katex .mathitsf,.katex .textitsf{font-family:KaTeX_SansSerif;font-style:italic}.katex .mainrm{font-family:KaTeX_Main;font-style:normal}.katex .vlist-t{border-collapse:collapse;display:inline-table;table-layout:fixed}.katex .vlist-r{display:table-row}.katex .vlist{display:table-cell;position:relative;vertical-align:bottom}.katex .vlist>span{display:block;height:0;position:relative}.katex .vlist>span>span{display:inline-block}.katex .vlist>span>.pstrut{overflow:hidden;width:0}.katex .vlist-t2{margin-right:-2px}.katex .vlist-s{display:table-cell;font-size:1px;min-width:2px;vertical-align:bottom;width:2px}.katex .vbox{-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-box-align:baseline;align-items:baseline;display:-webkit-inline-box;display:inline-flex;flex-direction:column}.katex .hbox{width:100%}.katex .hbox,.katex .thinbox{-webkit-box-orient:horizontal;-webkit-box-direction:normal;display:-webkit-inline-box;display:inline-flex;flex-direction:row}.katex .thinbox{max-width:0;width:0}.katex .msupsub{text-align:left}.katex .mfrac>span>span{text-align:center}.katex .mfrac .frac-line{border-bottom-style:solid;display:inline-block;width:100%}.katex .hdashline,.katex .hline,.katex .mfrac .frac-line,.katex .overline .overline-line,.katex .rule,.katex .underline .underline-line{min-height:1px}.katex .mspace{display:inline-block}.katex .clap,.katex .llap,.katex .rlap{position:relative;width:0}.katex .clap>.inner,.katex .llap>.inner,.katex .rlap>.inner{position:absolute}.katex .clap>.fix,.katex .llap>.fix,.katex .rlap>.fix{display:inline-block}.katex .llap>.inner{right:0}.katex .clap>.inner,.katex .rlap>.inner{left:0}.katex .clap>.inner>span{margin-left:-50%;margin-right:50%}.katex .rule{border:0 solid;display:inline-block;position:relative}.katex .hline,.katex .overline .overline-line,.katex .underline .underline-line{border-bottom-style:solid;display:inline-block;width:100%}.katex .hdashline{border-bottom-style:dashed;display:inline-block;width:100%}.katex .sqrt>.root{margin-left:.27777778em;margin-right:-.55555556em}.katex .fontsize-ensurer.reset-size1.size1,.katex .sizing.reset-size1.size1{font-size:1em}.katex .fontsize-ensurer.reset-size1.size2,.katex .sizing.reset-size1.size2{font-size:1.2em}.katex .fontsize-ensurer.reset-size1.size3,.katex .sizing.reset-size1.size3{font-size:1.4em}.katex .fontsize-ensurer.reset-size1.size4,.katex .sizing.reset-size1.size4{font-size:1.6em}.katex .fontsize-ensurer.reset-size1.size5,.katex .sizing.reset-size1.size5{font-size:1.8em}.katex .fontsize-ensurer.reset-size1.size6,.katex .sizing.reset-size1.size6{font-size:2em}.katex .fontsize-ensurer.reset-size1.size7,.katex .sizing.reset-size1.size7{font-size:2.4em}.katex .fontsize-ensurer.reset-size1.size8,.katex .sizing.reset-size1.size8{font-size:2.88em}.katex .fontsize-ensurer.reset-size1.size9,.katex .sizing.reset-size1.size9{font-size:3.456em}.katex .fontsize-ensurer.reset-size1.size10,.katex .sizing.reset-size1.size10{font-size:4.148em}.katex .fontsize-ensurer.reset-size1.size11,.katex .sizing.reset-size1.size11{font-size:4.976em}.katex .fontsize-ensurer.reset-size2.size1,.katex .sizing.reset-size2.size1{font-size:.83333333em}.katex .fontsize-ensurer.reset-size2.size2,.katex .sizing.reset-size2.size2{font-size:1em}.katex .fontsize-ensurer.reset-size2.size3,.katex .sizing.reset-size2.size3{font-size:1.16666667em}.katex .fontsize-ensurer.reset-size2.size4,.katex .sizing.reset-size2.size4{font-size:1.33333333em}.katex .fontsize-ensurer.reset-size2.size5,.katex .sizing.reset-size2.size5{font-size:1.5em}.katex .fontsize-ensurer.reset-size2.size6,.katex .sizing.reset-size2.size6{font-size:1.66666667em}.katex .fontsize-ensurer.reset-size2.size7,.katex .sizing.reset-size2.size7{font-size:2em}.katex .fontsize-ensurer.reset-size2.size8,.katex .sizing.reset-size2.size8{font-size:2.4em}.katex .fontsize-ensurer.reset-size2.size9,.katex .sizing.reset-size2.size9{font-size:2.88em}.katex .fontsize-ensurer.reset-size2.size10,.katex .sizing.reset-size2.size10{font-size:3.45666667em}.katex .fontsize-ensurer.reset-size2.size11,.katex .sizing.reset-size2.size11{font-size:4.14666667em}.katex .fontsize-ensurer.reset-size3.size1,.katex .sizing.reset-size3.size1{font-size:.71428571em}.katex .fontsize-ensurer.reset-size3.size2,.katex .sizing.reset-size3.size2{font-size:.85714286em}.katex .fontsize-ensurer.reset-size3.size3,.katex .sizing.reset-size3.size3{font-size:1em}.katex .fontsize-ensurer.reset-size3.size4,.katex .sizing.reset-size3.size4{font-size:1.14285714em}.katex .fontsize-ensurer.reset-size3.size5,.katex .sizing.reset-size3.size5{font-size:1.28571429em}.katex .fontsize-ensurer.reset-size3.size6,.katex .sizing.reset-size3.size6{font-size:1.42857143em}.katex .fontsize-ensurer.reset-size3.size7,.katex .sizing.reset-size3.size7{font-size:1.71428571em}.katex .fontsize-ensurer.reset-size3.size8,.katex .sizing.reset-size3.size8{font-size:2.05714286em}.katex .fontsize-ensurer.reset-size3.size9,.katex .sizing.reset-size3.size9{font-size:2.46857143em}.katex .fontsize-ensurer.reset-size3.size10,.katex .sizing.reset-size3.size10{font-size:2.96285714em}.katex .fontsize-ensurer.reset-size3.size11,.katex .sizing.reset-size3.size11{font-size:3.55428571em}.katex .fontsize-ensurer.reset-size4.size1,.katex .sizing.reset-size4.size1{font-size:.625em}.katex .fontsize-ensurer.reset-size4.size2,.katex .sizing.reset-size4.size2{font-size:.75em}.katex .fontsize-ensurer.reset-size4.size3,.katex .sizing.reset-size4.size3{font-size:.875em}.katex .fontsize-ensurer.reset-size4.size4,.katex .sizing.reset-size4.size4{font-size:1em}.katex .fontsize-ensurer.reset-size4.size5,.katex .sizing.reset-size4.size5{font-size:1.125em}.katex .fontsize-ensurer.reset-size4.size6,.katex .sizing.reset-size4.size6{font-size:1.25em}.katex .fontsize-ensurer.reset-size4.size7,.katex .sizing.reset-size4.size7{font-size:1.5em}.katex .fontsize-ensurer.reset-size4.size8,.katex .sizing.reset-size4.size8{font-size:1.8em}.katex .fontsize-ensurer.reset-size4.size9,.katex .sizing.reset-size4.size9{font-size:2.16em}.katex .fontsize-ensurer.reset-size4.size10,.katex .sizing.reset-size4.size10{font-size:2.5925em}.katex .fontsize-ensurer.reset-size4.size11,.katex .sizing.reset-size4.size11{font-size:3.11em}.katex .fontsize-ensurer.reset-size5.size1,.katex .sizing.reset-size5.size1{font-size:.55555556em}.katex .fontsize-ensurer.reset-size5.size2,.katex .sizing.reset-size5.size2{font-size:.66666667em}.katex .fontsize-ensurer.reset-size5.size3,.katex .sizing.reset-size5.size3{font-size:.77777778em}.katex .fontsize-ensurer.reset-size5.size4,.katex .sizing.reset-size5.size4{font-size:.88888889em}.katex .fontsize-ensurer.reset-size5.size5,.katex .sizing.reset-size5.size5{font-size:1em}.katex .fontsize-ensurer.reset-size5.size6,.katex .sizing.reset-size5.size6{font-size:1.11111111em}.katex .fontsize-ensurer.reset-size5.size7,.katex .sizing.reset-size5.size7{font-size:1.33333333em}.katex .fontsize-ensurer.reset-size5.size8,.katex .sizing.reset-size5.size8{font-size:1.6em}.katex .fontsize-ensurer.reset-size5.size9,.katex .sizing.reset-size5.size9{font-size:1.92em}.katex .fontsize-ensurer.reset-size5.size10,.katex .sizing.reset-size5.size10{font-size:2.30444444em}.katex .fontsize-ensurer.reset-size5.size11,.katex .sizing.reset-size5.size11{font-size:2.76444444em}.katex .fontsize-ensurer.reset-size6.size1,.katex .sizing.reset-size6.size1{font-size:.5em}.katex .fontsize-ensurer.reset-size6.size2,.katex .sizing.reset-size6.size2{font-size:.6em}.katex .fontsize-ensurer.reset-size6.size3,.katex .sizing.reset-size6.size3{font-size:.7em}.katex .fontsize-ensurer.reset-size6.size4,.katex .sizing.reset-size6.size4{font-size:.8em}.katex .fontsize-ensurer.reset-size6.size5,.katex .sizing.reset-size6.size5{font-size:.9em}.katex .fontsize-ensurer.reset-size6.size6,.katex .sizing.reset-size6.size6{font-size:1em}.katex .fontsize-ensurer.reset-size6.size7,.katex .sizing.reset-size6.size7{font-size:1.2em}.katex .fontsize-ensurer.reset-size6.size8,.katex .sizing.reset-size6.size8{font-size:1.44em}.katex .fontsize-ensurer.reset-size6.size9,.katex .sizing.reset-size6.size9{font-size:1.728em}.katex .fontsize-ensurer.reset-size6.size10,.katex .sizing.reset-size6.size10{font-size:2.074em}.katex .fontsize-ensurer.reset-size6.size11,.katex .sizing.reset-size6.size11{font-size:2.488em}.katex .fontsize-ensurer.reset-size7.size1,.katex .sizing.reset-size7.size1{font-size:.41666667em}.katex .fontsize-ensurer.reset-size7.size2,.katex .sizing.reset-size7.size2{font-size:.5em}.katex .fontsize-ensurer.reset-size7.size3,.katex .sizing.reset-size7.size3{font-size:.58333333em}.katex .fontsize-ensurer.reset-size7.size4,.katex .sizing.reset-size7.size4{font-size:.66666667em}.katex .fontsize-ensurer.reset-size7.size5,.katex .sizing.reset-size7.size5{font-size:.75em}.katex .fontsize-ensurer.reset-size7.size6,.katex .sizing.reset-size7.size6{font-size:.83333333em}.katex .fontsize-ensurer.reset-size7.size7,.katex .sizing.reset-size7.size7{font-size:1em}.katex .fontsize-ensurer.reset-size7.size8,.katex .sizing.reset-size7.size8{font-size:1.2em}.katex .fontsize-ensurer.reset-size7.size9,.katex .sizing.reset-size7.size9{font-size:1.44em}.katex .fontsize-ensurer.reset-size7.size10,.katex .sizing.reset-size7.size10{font-size:1.72833333em}.katex .fontsize-ensurer.reset-size7.size11,.katex .sizing.reset-size7.size11{font-size:2.07333333em}.katex .fontsize-ensurer.reset-size8.size1,.katex .sizing.reset-size8.size1{font-size:.34722222em}.katex .fontsize-ensurer.reset-size8.size2,.katex .sizing.reset-size8.size2{font-size:.41666667em}.katex .fontsize-ensurer.reset-size8.size3,.katex .sizing.reset-size8.size3{font-size:.48611111em}.katex .fontsize-ensurer.reset-size8.size4,.katex .sizing.reset-size8.size4{font-size:.55555556em}.katex .fontsize-ensurer.reset-size8.size5,.katex .sizing.reset-size8.size5{font-size:.625em}.katex .fontsize-ensurer.reset-size8.size6,.katex .sizing.reset-size8.size6{font-size:.69444444em}.katex .fontsize-ensurer.reset-size8.size7,.katex .sizing.reset-size8.size7{font-size:.83333333em}.katex .fontsize-ensurer.reset-size8.size8,.katex .sizing.reset-size8.size8{font-size:1em}.katex .fontsize-ensurer.reset-size8.size9,.katex .sizing.reset-size8.size9{font-size:1.2em}.katex .fontsize-ensurer.reset-size8.size10,.katex .sizing.reset-size8.size10{font-size:1.44027778em}.katex .fontsize-ensurer.reset-size8.size11,.katex .sizing.reset-size8.size11{font-size:1.72777778em}.katex .fontsize-ensurer.reset-size9.size1,.katex .sizing.reset-size9.size1{font-size:.28935185em}.katex .fontsize-ensurer.reset-size9.size2,.katex .sizing.reset-size9.size2{font-size:.34722222em}.katex .fontsize-ensurer.reset-size9.size3,.katex .sizing.reset-size9.size3{font-size:.40509259em}.katex .fontsize-ensurer.reset-size9.size4,.katex .sizing.reset-size9.size4{font-size:.46296296em}.katex .fontsize-ensurer.reset-size9.size5,.katex .sizing.reset-size9.size5{font-size:.52083333em}.katex .fontsize-ensurer.reset-size9.size6,.katex .sizing.reset-size9.size6{font-size:.5787037em}.katex .fontsize-ensurer.reset-size9.size7,.katex .sizing.reset-size9.size7{font-size:.69444444em}.katex .fontsize-ensurer.reset-size9.size8,.katex .sizing.reset-size9.size8{font-size:.83333333em}.katex .fontsize-ensurer.reset-size9.size9,.katex .sizing.reset-size9.size9{font-size:1em}.katex .fontsize-ensurer.reset-size9.size10,.katex .sizing.reset-size9.size10{font-size:1.20023148em}.katex .fontsize-ensurer.reset-size9.size11,.katex .sizing.reset-size9.size11{font-size:1.43981481em}.katex .fontsize-ensurer.reset-size10.size1,.katex .sizing.reset-size10.size1{font-size:.24108004em}.katex .fontsize-ensurer.reset-size10.size2,.katex .sizing.reset-size10.size2{font-size:.28929605em}.katex .fontsize-ensurer.reset-size10.size3,.katex .sizing.reset-size10.size3{font-size:.33751205em}.katex .fontsize-ensurer.reset-size10.size4,.katex .sizing.reset-size10.size4{font-size:.38572806em}.katex .fontsize-ensurer.reset-size10.size5,.katex .sizing.reset-size10.size5{font-size:.43394407em}.katex .fontsize-ensurer.reset-size10.size6,.katex .sizing.reset-size10.size6{font-size:.48216008em}.katex .fontsize-ensurer.reset-size10.size7,.katex .sizing.reset-size10.size7{font-size:.57859209em}.katex .fontsize-ensurer.reset-size10.size8,.katex .sizing.reset-size10.size8{font-size:.69431051em}.katex .fontsize-ensurer.reset-size10.size9,.katex .sizing.reset-size10.size9{font-size:.83317261em}.katex .fontsize-ensurer.reset-size10.size10,.katex .sizing.reset-size10.size10{font-size:1em}.katex .fontsize-ensurer.reset-size10.size11,.katex .sizing.reset-size10.size11{font-size:1.19961427em}.katex .fontsize-ensurer.reset-size11.size1,.katex .sizing.reset-size11.size1{font-size:.20096463em}.katex .fontsize-ensurer.reset-size11.size2,.katex .sizing.reset-size11.size2{font-size:.24115756em}.katex .fontsize-ensurer.reset-size11.size3,.katex .sizing.reset-size11.size3{font-size:.28135048em}.katex .fontsize-ensurer.reset-size11.size4,.katex .sizing.reset-size11.size4{font-size:.32154341em}.katex .fontsize-ensurer.reset-size11.size5,.katex .sizing.reset-size11.size5{font-size:.36173633em}.katex .fontsize-ensurer.reset-size11.size6,.katex .sizing.reset-size11.size6{font-size:.40192926em}.katex .fontsize-ensurer.reset-size11.size7,.katex .sizing.reset-size11.size7{font-size:.48231511em}.katex .fontsize-ensurer.reset-size11.size8,.katex .sizing.reset-size11.size8{font-size:.57877814em}.katex .fontsize-ensurer.reset-size11.size9,.katex .sizing.reset-size11.size9{font-size:.69453376em}.katex .fontsize-ensurer.reset-size11.size10,.katex .sizing.reset-size11.size10{font-size:.83360129em}.katex .fontsize-ensurer.reset-size11.size11,.katex .sizing.reset-size11.size11{font-size:1em}.katex .delimsizing.size1{font-family:KaTeX_Size1}.katex .delimsizing.size2{font-family:KaTeX_Size2}.katex .delimsizing.size3{font-family:KaTeX_Size3}.katex .delimsizing.size4{font-family:KaTeX_Size4}.katex .delimsizing.mult .delim-size1>span{font-family:KaTeX_Size1}.katex .delimsizing.mult .delim-size4>span{font-family:KaTeX_Size4}.katex .nulldelimiter{display:inline-block;width:.12em}.katex .delimcenter,.katex .op-symbol{position:relative}.katex .op-symbol.small-op{font-family:KaTeX_Size1}.katex .op-symbol.large-op{font-family:KaTeX_Size2}.katex .accent>.vlist-t,.katex .op-limits>.vlist-t{text-align:center}.katex .accent .accent-body{position:relative}.katex .accent .accent-body:not(.accent-full){width:0}.katex .overlay{display:block}.katex .mtable .vertical-separator{display:inline-block;min-width:1px}.katex .mtable .arraycolsep{display:inline-block}.katex .mtable .col-align-c>.vlist-t{text-align:center}.katex .mtable .col-align-l>.vlist-t{text-align:left}.katex .mtable .col-align-r>.vlist-t{text-align:right}.katex .svg-align{text-align:left}.katex svg{fill:currentColor;stroke:currentColor;fill-rule:nonzero;fill-opacity:1;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;display:block;height:inherit;position:absolute;width:100%}.katex svg path{stroke:none}.katex img{border-style:none;max-height:none;max-width:none;min-height:0;min-width:0}.katex .stretchy{display:block;overflow:hidden;position:relative;width:100%}.katex .stretchy:after,.katex .stretchy:before{content:""}.katex .hide-tail{overflow:hidden;position:relative;width:100%}.katex .halfarrow-left{left:0;overflow:hidden;position:absolute;width:50.2%}.katex .halfarrow-right{overflow:hidden;position:absolute;right:0;width:50.2%}.katex .brace-left{left:0;overflow:hidden;position:absolute;width:25.1%}.katex .brace-center{left:25%;overflow:hidden;position:absolute;width:50%}.katex .brace-right{overflow:hidden;position:absolute;right:0;width:25.1%}.katex .x-arrow-pad{padding:0 .5em}.katex .cd-arrow-pad{padding:0 .55556em 0 .27778em}.katex .mover,.katex .munder,.katex .x-arrow{text-align:center}.katex .boxpad{padding:0 .3em}.katex .fbox,.katex .fcolorbox{border:.04em solid;box-sizing:border-box}.katex .cancel-pad{padding:0 .2em}.katex .cancel-lap{margin-left:-.2em;margin-right:-.2em}.katex .sout{border-bottom-style:solid;border-bottom-width:.08em}.katex .angl{border-right:.049em solid;border-top:.049em solid;box-sizing:border-content;margin-right:.03889em}.katex .anglpad{padding:0 .03889em}.katex .eqn-num:before{content:"(" counter(katexEqnNo) ")";counter-increment:katexEqnNo}.katex .mml-eqn-num:before{content:"(" counter(mmlEqnNo) ")";counter-increment:mmlEqnNo}.katex .mtr-glue{width:50%}.katex .cd-vert-arrow{display:inline-block;position:relative}.katex .cd-label-left{display:inline-block;position:absolute;right:-webkit-calc(50% + .3em);right:calc(50% + .3em);text-align:left}.katex .cd-label-right{display:inline-block;left:-webkit-calc(50% + .3em);left:calc(50% + .3em);position:absolute;text-align:right}.katex-display{display:block;margin:1em 0;text-align:center}.katex-display>.katex{display:block;text-align:center;white-space:nowrap}.katex-display>.katex>.katex-html{display:block;position:relative}.katex-display>.katex>.katex-html>.tag{position:absolute;right:0}.katex-display.leqno>.katex>.katex-html>.tag{left:0;right:auto}.katex-display.fleqn>.katex{padding-left:2em;text-align:left}body{counter-reset:katexEqnNo mmlEqnNo} +@font-face { + font-family: KaTeX_AMS; + font-style: normal; + font-weight: 400; + src: url(fonts/KaTeX_AMS-Regular.woff2) format("woff2"), + url(fonts/KaTeX_AMS-Regular.woff) format("woff"), + url(fonts/KaTeX_AMS-Regular.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Caligraphic; + font-style: normal; + font-weight: 700; + src: url(fonts/KaTeX_Caligraphic-Bold.woff2) format("woff2"), + url(fonts/KaTeX_Caligraphic-Bold.woff) format("woff"), + url(fonts/KaTeX_Caligraphic-Bold.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Caligraphic; + font-style: normal; + font-weight: 400; + src: url(fonts/KaTeX_Caligraphic-Regular.woff2) format("woff2"), + url(fonts/KaTeX_Caligraphic-Regular.woff) format("woff"), + url(fonts/KaTeX_Caligraphic-Regular.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Fraktur; + font-style: normal; + font-weight: 700; + src: url(fonts/KaTeX_Fraktur-Bold.woff2) format("woff2"), + url(fonts/KaTeX_Fraktur-Bold.woff) format("woff"), + url(fonts/KaTeX_Fraktur-Bold.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Fraktur; + font-style: normal; + font-weight: 400; + src: url(fonts/KaTeX_Fraktur-Regular.woff2) format("woff2"), + url(fonts/KaTeX_Fraktur-Regular.woff) format("woff"), + url(fonts/KaTeX_Fraktur-Regular.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Main; + font-style: normal; + font-weight: 700; + src: url(fonts/KaTeX_Main-Bold.woff2) format("woff2"), + url(fonts/KaTeX_Main-Bold.woff) format("woff"), + url(fonts/KaTeX_Main-Bold.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Main; + font-style: italic; + font-weight: 700; + src: url(fonts/KaTeX_Main-BoldItalic.woff2) format("woff2"), + url(fonts/KaTeX_Main-BoldItalic.woff) format("woff"), + url(fonts/KaTeX_Main-BoldItalic.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Main; + font-style: italic; + font-weight: 400; + src: url(fonts/KaTeX_Main-Italic.woff2) format("woff2"), + url(fonts/KaTeX_Main-Italic.woff) format("woff"), + url(fonts/KaTeX_Main-Italic.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Main; + font-style: normal; + font-weight: 400; + src: url(fonts/KaTeX_Main-Regular.woff2) format("woff2"), + url(fonts/KaTeX_Main-Regular.woff) format("woff"), + url(fonts/KaTeX_Main-Regular.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Math; + font-style: italic; + font-weight: 700; + src: url(fonts/KaTeX_Math-BoldItalic.woff2) format("woff2"), + url(fonts/KaTeX_Math-BoldItalic.woff) format("woff"), + url(fonts/KaTeX_Math-BoldItalic.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Math; + font-style: italic; + font-weight: 400; + src: url(fonts/KaTeX_Math-Italic.woff2) format("woff2"), + url(fonts/KaTeX_Math-Italic.woff) format("woff"), + url(fonts/KaTeX_Math-Italic.ttf) format("truetype"); +} +@font-face { + font-family: "KaTeX_SansSerif"; + font-style: normal; + font-weight: 700; + src: url(fonts/KaTeX_SansSerif-Bold.woff2) format("woff2"), + url(fonts/KaTeX_SansSerif-Bold.woff) format("woff"), + url(fonts/KaTeX_SansSerif-Bold.ttf) format("truetype"); +} +@font-face { + font-family: "KaTeX_SansSerif"; + font-style: italic; + font-weight: 400; + src: url(fonts/KaTeX_SansSerif-Italic.woff2) format("woff2"), + url(fonts/KaTeX_SansSerif-Italic.woff) format("woff"), + url(fonts/KaTeX_SansSerif-Italic.ttf) format("truetype"); +} +@font-face { + font-family: "KaTeX_SansSerif"; + font-style: normal; + font-weight: 400; + src: url(fonts/KaTeX_SansSerif-Regular.woff2) format("woff2"), + url(fonts/KaTeX_SansSerif-Regular.woff) format("woff"), + url(fonts/KaTeX_SansSerif-Regular.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Script; + font-style: normal; + font-weight: 400; + src: url(fonts/KaTeX_Script-Regular.woff2) format("woff2"), + url(fonts/KaTeX_Script-Regular.woff) format("woff"), + url(fonts/KaTeX_Script-Regular.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Size1; + font-style: normal; + font-weight: 400; + src: url(fonts/KaTeX_Size1-Regular.woff2) format("woff2"), + url(fonts/KaTeX_Size1-Regular.woff) format("woff"), + url(fonts/KaTeX_Size1-Regular.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Size2; + font-style: normal; + font-weight: 400; + src: url(fonts/KaTeX_Size2-Regular.woff2) format("woff2"), + url(fonts/KaTeX_Size2-Regular.woff) format("woff"), + url(fonts/KaTeX_Size2-Regular.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Size3; + font-style: normal; + font-weight: 400; + src: url(fonts/KaTeX_Size3-Regular.woff2) format("woff2"), + url(fonts/KaTeX_Size3-Regular.woff) format("woff"), + url(fonts/KaTeX_Size3-Regular.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Size4; + font-style: normal; + font-weight: 400; + src: url(fonts/KaTeX_Size4-Regular.woff2) format("woff2"), + url(fonts/KaTeX_Size4-Regular.woff) format("woff"), + url(fonts/KaTeX_Size4-Regular.ttf) format("truetype"); +} +@font-face { + font-family: KaTeX_Typewriter; + font-style: normal; + font-weight: 400; + src: url(fonts/KaTeX_Typewriter-Regular.woff2) format("woff2"), + url(fonts/KaTeX_Typewriter-Regular.woff) format("woff"), + url(fonts/KaTeX_Typewriter-Regular.ttf) format("truetype"); +} +.katex { + font: normal 1.21em KaTeX_Main, Times New Roman, serif; + line-height: 1.2; + text-indent: 0; + text-rendering: auto; +} +.katex * { + -ms-high-contrast-adjust: none !important; + border-color: currentColor; +} +.katex .katex-version:after { + content: "0.13.11"; +} +.katex .katex-mathml { + clip: rect(1px, 1px, 1px, 1px); + border: 0; + height: 1px; + overflow: hidden; + padding: 0; + position: absolute; + width: 1px; +} +.katex .katex-html > .newline { + display: block; +} +.katex .base { + position: relative; + white-space: nowrap; + width: -webkit-min-content; + width: -moz-min-content; + width: min-content; +} +.katex .base, +.katex .strut { + display: inline-block; +} +.katex .textbf { + font-weight: 700; +} +.katex .textit { + font-style: italic; +} +.katex .textrm { + font-family: KaTeX_Main; +} +.katex .textsf { + font-family: KaTeX_SansSerif; +} +.katex .texttt { + font-family: KaTeX_Typewriter; +} +.katex .mathnormal { + font-family: KaTeX_Math; + font-style: italic; +} +.katex .mathit { + font-family: KaTeX_Main; + font-style: italic; +} +.katex .mathrm { + font-style: normal; +} +.katex .mathbf { + font-family: KaTeX_Main; + font-weight: 700; +} +.katex .boldsymbol { + font-family: KaTeX_Math; + font-style: italic; + font-weight: 700; +} +.katex .amsrm, +.katex .mathbb, +.katex .textbb { + font-family: KaTeX_AMS; +} +.katex .mathcal { + font-family: KaTeX_Caligraphic; +} +.katex .mathfrak, +.katex .textfrak { + font-family: KaTeX_Fraktur; +} +.katex .mathtt { + font-family: KaTeX_Typewriter; +} +.katex .mathscr, +.katex .textscr { + font-family: KaTeX_Script; +} +.katex .mathsf, +.katex .textsf { + font-family: KaTeX_SansSerif; +} +.katex .mathboldsf, +.katex .textboldsf { + font-family: KaTeX_SansSerif; + font-weight: 700; +} +.katex .mathitsf, +.katex .textitsf { + font-family: KaTeX_SansSerif; + font-style: italic; +} +.katex .mainrm { + font-family: KaTeX_Main; + font-style: normal; +} +.katex .vlist-t { + border-collapse: collapse; + display: inline-table; + table-layout: fixed; +} +.katex .vlist-r { + display: table-row; +} +.katex .vlist { + display: table-cell; + position: relative; + vertical-align: bottom; +} +.katex .vlist > span { + display: block; + height: 0; + position: relative; +} +.katex .vlist > span > span { + display: inline-block; +} +.katex .vlist > span > .pstrut { + overflow: hidden; + width: 0; +} +.katex .vlist-t2 { + margin-right: -2px; +} +.katex .vlist-s { + display: table-cell; + font-size: 1px; + min-width: 2px; + vertical-align: bottom; + width: 2px; +} +.katex .vbox { + -webkit-box-orient: vertical; + -webkit-box-direction: normal; + -webkit-box-align: baseline; + align-items: baseline; + display: -webkit-inline-box; + display: inline-flex; + flex-direction: column; +} +.katex .hbox { + width: 100%; +} +.katex .hbox, +.katex .thinbox { + -webkit-box-orient: horizontal; + -webkit-box-direction: normal; + display: -webkit-inline-box; + display: inline-flex; + flex-direction: row; +} +.katex .thinbox { + max-width: 0; + width: 0; +} +.katex .msupsub { + text-align: left; +} +.katex .mfrac > span > span { + text-align: center; +} +.katex .mfrac .frac-line { + border-bottom-style: solid; + display: inline-block; + width: 100%; +} +.katex .hdashline, +.katex .hline, +.katex .mfrac .frac-line, +.katex .overline .overline-line, +.katex .rule, +.katex .underline .underline-line { + min-height: 1px; +} +.katex .mspace { + display: inline-block; +} +.katex .clap, +.katex .llap, +.katex .rlap { + position: relative; + width: 0; +} +.katex .clap > .inner, +.katex .llap > .inner, +.katex .rlap > .inner { + position: absolute; +} +.katex .clap > .fix, +.katex .llap > .fix, +.katex .rlap > .fix { + display: inline-block; +} +.katex .llap > .inner { + right: 0; +} +.katex .clap > .inner, +.katex .rlap > .inner { + left: 0; +} +.katex .clap > .inner > span { + margin-left: -50%; + margin-right: 50%; +} +.katex .rule { + border: 0 solid; + display: inline-block; + position: relative; +} +.katex .hline, +.katex .overline .overline-line, +.katex .underline .underline-line { + border-bottom-style: solid; + display: inline-block; + width: 100%; +} +.katex .hdashline { + border-bottom-style: underline; + display: inline-block; + width: 100%; +} +.katex .sqrt > .root { + margin-left: 0.27777778em; + margin-right: -0.55555556em; +} +.katex .fontsize-ensurer.reset-size1.size1, +.katex .sizing.reset-size1.size1 { + font-size: 1em; +} +.katex .fontsize-ensurer.reset-size1.size2, +.katex .sizing.reset-size1.size2 { + font-size: 1.2em; +} +.katex .fontsize-ensurer.reset-size1.size3, +.katex .sizing.reset-size1.size3 { + font-size: 1.4em; +} +.katex .fontsize-ensurer.reset-size1.size4, +.katex .sizing.reset-size1.size4 { + font-size: 1.6em; +} +.katex .fontsize-ensurer.reset-size1.size5, +.katex .sizing.reset-size1.size5 { + font-size: 1.8em; +} +.katex .fontsize-ensurer.reset-size1.size6, +.katex .sizing.reset-size1.size6 { + font-size: 2em; +} +.katex .fontsize-ensurer.reset-size1.size7, +.katex .sizing.reset-size1.size7 { + font-size: 2.4em; +} +.katex .fontsize-ensurer.reset-size1.size8, +.katex .sizing.reset-size1.size8 { + font-size: 2.88em; +} +.katex .fontsize-ensurer.reset-size1.size9, +.katex .sizing.reset-size1.size9 { + font-size: 3.456em; +} +.katex .fontsize-ensurer.reset-size1.size10, +.katex .sizing.reset-size1.size10 { + font-size: 4.148em; +} +.katex .fontsize-ensurer.reset-size1.size11, +.katex .sizing.reset-size1.size11 { + font-size: 4.976em; +} +.katex .fontsize-ensurer.reset-size2.size1, +.katex .sizing.reset-size2.size1 { + font-size: 0.83333333em; +} +.katex .fontsize-ensurer.reset-size2.size2, +.katex .sizing.reset-size2.size2 { + font-size: 1em; +} +.katex .fontsize-ensurer.reset-size2.size3, +.katex .sizing.reset-size2.size3 { + font-size: 1.16666667em; +} +.katex .fontsize-ensurer.reset-size2.size4, +.katex .sizing.reset-size2.size4 { + font-size: 1.33333333em; +} +.katex .fontsize-ensurer.reset-size2.size5, +.katex .sizing.reset-size2.size5 { + font-size: 1.5em; +} +.katex .fontsize-ensurer.reset-size2.size6, +.katex .sizing.reset-size2.size6 { + font-size: 1.66666667em; +} +.katex .fontsize-ensurer.reset-size2.size7, +.katex .sizing.reset-size2.size7 { + font-size: 2em; +} +.katex .fontsize-ensurer.reset-size2.size8, +.katex .sizing.reset-size2.size8 { + font-size: 2.4em; +} +.katex .fontsize-ensurer.reset-size2.size9, +.katex .sizing.reset-size2.size9 { + font-size: 2.88em; +} +.katex .fontsize-ensurer.reset-size2.size10, +.katex .sizing.reset-size2.size10 { + font-size: 3.45666667em; +} +.katex .fontsize-ensurer.reset-size2.size11, +.katex .sizing.reset-size2.size11 { + font-size: 4.14666667em; +} +.katex .fontsize-ensurer.reset-size3.size1, +.katex .sizing.reset-size3.size1 { + font-size: 0.71428571em; +} +.katex .fontsize-ensurer.reset-size3.size2, +.katex .sizing.reset-size3.size2 { + font-size: 0.85714286em; +} +.katex .fontsize-ensurer.reset-size3.size3, +.katex .sizing.reset-size3.size3 { + font-size: 1em; +} +.katex .fontsize-ensurer.reset-size3.size4, +.katex .sizing.reset-size3.size4 { + font-size: 1.14285714em; +} +.katex .fontsize-ensurer.reset-size3.size5, +.katex .sizing.reset-size3.size5 { + font-size: 1.28571429em; +} +.katex .fontsize-ensurer.reset-size3.size6, +.katex .sizing.reset-size3.size6 { + font-size: 1.42857143em; +} +.katex .fontsize-ensurer.reset-size3.size7, +.katex .sizing.reset-size3.size7 { + font-size: 1.71428571em; +} +.katex .fontsize-ensurer.reset-size3.size8, +.katex .sizing.reset-size3.size8 { + font-size: 2.05714286em; +} +.katex .fontsize-ensurer.reset-size3.size9, +.katex .sizing.reset-size3.size9 { + font-size: 2.46857143em; +} +.katex .fontsize-ensurer.reset-size3.size10, +.katex .sizing.reset-size3.size10 { + font-size: 2.96285714em; +} +.katex .fontsize-ensurer.reset-size3.size11, +.katex .sizing.reset-size3.size11 { + font-size: 3.55428571em; +} +.katex .fontsize-ensurer.reset-size4.size1, +.katex .sizing.reset-size4.size1 { + font-size: 0.625em; +} +.katex .fontsize-ensurer.reset-size4.size2, +.katex .sizing.reset-size4.size2 { + font-size: 0.75em; +} +.katex .fontsize-ensurer.reset-size4.size3, +.katex .sizing.reset-size4.size3 { + font-size: 0.875em; +} +.katex .fontsize-ensurer.reset-size4.size4, +.katex .sizing.reset-size4.size4 { + font-size: 1em; +} +.katex .fontsize-ensurer.reset-size4.size5, +.katex .sizing.reset-size4.size5 { + font-size: 1.125em; +} +.katex .fontsize-ensurer.reset-size4.size6, +.katex .sizing.reset-size4.size6 { + font-size: 1.25em; +} +.katex .fontsize-ensurer.reset-size4.size7, +.katex .sizing.reset-size4.size7 { + font-size: 1.5em; +} +.katex .fontsize-ensurer.reset-size4.size8, +.katex .sizing.reset-size4.size8 { + font-size: 1.8em; +} +.katex .fontsize-ensurer.reset-size4.size9, +.katex .sizing.reset-size4.size9 { + font-size: 2.16em; +} +.katex .fontsize-ensurer.reset-size4.size10, +.katex .sizing.reset-size4.size10 { + font-size: 2.5925em; +} +.katex .fontsize-ensurer.reset-size4.size11, +.katex .sizing.reset-size4.size11 { + font-size: 3.11em; +} +.katex .fontsize-ensurer.reset-size5.size1, +.katex .sizing.reset-size5.size1 { + font-size: 0.55555556em; +} +.katex .fontsize-ensurer.reset-size5.size2, +.katex .sizing.reset-size5.size2 { + font-size: 0.66666667em; +} +.katex .fontsize-ensurer.reset-size5.size3, +.katex .sizing.reset-size5.size3 { + font-size: 0.77777778em; +} +.katex .fontsize-ensurer.reset-size5.size4, +.katex .sizing.reset-size5.size4 { + font-size: 0.88888889em; +} +.katex .fontsize-ensurer.reset-size5.size5, +.katex .sizing.reset-size5.size5 { + font-size: 1em; +} +.katex .fontsize-ensurer.reset-size5.size6, +.katex .sizing.reset-size5.size6 { + font-size: 1.11111111em; +} +.katex .fontsize-ensurer.reset-size5.size7, +.katex .sizing.reset-size5.size7 { + font-size: 1.33333333em; +} +.katex .fontsize-ensurer.reset-size5.size8, +.katex .sizing.reset-size5.size8 { + font-size: 1.6em; +} +.katex .fontsize-ensurer.reset-size5.size9, +.katex .sizing.reset-size5.size9 { + font-size: 1.92em; +} +.katex .fontsize-ensurer.reset-size5.size10, +.katex .sizing.reset-size5.size10 { + font-size: 2.30444444em; +} +.katex .fontsize-ensurer.reset-size5.size11, +.katex .sizing.reset-size5.size11 { + font-size: 2.76444444em; +} +.katex .fontsize-ensurer.reset-size6.size1, +.katex .sizing.reset-size6.size1 { + font-size: 0.5em; +} +.katex .fontsize-ensurer.reset-size6.size2, +.katex .sizing.reset-size6.size2 { + font-size: 0.6em; +} +.katex .fontsize-ensurer.reset-size6.size3, +.katex .sizing.reset-size6.size3 { + font-size: 0.7em; +} +.katex .fontsize-ensurer.reset-size6.size4, +.katex .sizing.reset-size6.size4 { + font-size: 0.8em; +} +.katex .fontsize-ensurer.reset-size6.size5, +.katex .sizing.reset-size6.size5 { + font-size: 0.9em; +} +.katex .fontsize-ensurer.reset-size6.size6, +.katex .sizing.reset-size6.size6 { + font-size: 1em; +} +.katex .fontsize-ensurer.reset-size6.size7, +.katex .sizing.reset-size6.size7 { + font-size: 1.2em; +} +.katex .fontsize-ensurer.reset-size6.size8, +.katex .sizing.reset-size6.size8 { + font-size: 1.44em; +} +.katex .fontsize-ensurer.reset-size6.size9, +.katex .sizing.reset-size6.size9 { + font-size: 1.728em; +} +.katex .fontsize-ensurer.reset-size6.size10, +.katex .sizing.reset-size6.size10 { + font-size: 2.074em; +} +.katex .fontsize-ensurer.reset-size6.size11, +.katex .sizing.reset-size6.size11 { + font-size: 2.488em; +} +.katex .fontsize-ensurer.reset-size7.size1, +.katex .sizing.reset-size7.size1 { + font-size: 0.41666667em; +} +.katex .fontsize-ensurer.reset-size7.size2, +.katex .sizing.reset-size7.size2 { + font-size: 0.5em; +} +.katex .fontsize-ensurer.reset-size7.size3, +.katex .sizing.reset-size7.size3 { + font-size: 0.58333333em; +} +.katex .fontsize-ensurer.reset-size7.size4, +.katex .sizing.reset-size7.size4 { + font-size: 0.66666667em; +} +.katex .fontsize-ensurer.reset-size7.size5, +.katex .sizing.reset-size7.size5 { + font-size: 0.75em; +} +.katex .fontsize-ensurer.reset-size7.size6, +.katex .sizing.reset-size7.size6 { + font-size: 0.83333333em; +} +.katex .fontsize-ensurer.reset-size7.size7, +.katex .sizing.reset-size7.size7 { + font-size: 1em; +} +.katex .fontsize-ensurer.reset-size7.size8, +.katex .sizing.reset-size7.size8 { + font-size: 1.2em; +} +.katex .fontsize-ensurer.reset-size7.size9, +.katex .sizing.reset-size7.size9 { + font-size: 1.44em; +} +.katex .fontsize-ensurer.reset-size7.size10, +.katex .sizing.reset-size7.size10 { + font-size: 1.72833333em; +} +.katex .fontsize-ensurer.reset-size7.size11, +.katex .sizing.reset-size7.size11 { + font-size: 2.07333333em; +} +.katex .fontsize-ensurer.reset-size8.size1, +.katex .sizing.reset-size8.size1 { + font-size: 0.34722222em; +} +.katex .fontsize-ensurer.reset-size8.size2, +.katex .sizing.reset-size8.size2 { + font-size: 0.41666667em; +} +.katex .fontsize-ensurer.reset-size8.size3, +.katex .sizing.reset-size8.size3 { + font-size: 0.48611111em; +} +.katex .fontsize-ensurer.reset-size8.size4, +.katex .sizing.reset-size8.size4 { + font-size: 0.55555556em; +} +.katex .fontsize-ensurer.reset-size8.size5, +.katex .sizing.reset-size8.size5 { + font-size: 0.625em; +} +.katex .fontsize-ensurer.reset-size8.size6, +.katex .sizing.reset-size8.size6 { + font-size: 0.69444444em; +} +.katex .fontsize-ensurer.reset-size8.size7, +.katex .sizing.reset-size8.size7 { + font-size: 0.83333333em; +} +.katex .fontsize-ensurer.reset-size8.size8, +.katex .sizing.reset-size8.size8 { + font-size: 1em; +} +.katex .fontsize-ensurer.reset-size8.size9, +.katex .sizing.reset-size8.size9 { + font-size: 1.2em; +} +.katex .fontsize-ensurer.reset-size8.size10, +.katex .sizing.reset-size8.size10 { + font-size: 1.44027778em; +} +.katex .fontsize-ensurer.reset-size8.size11, +.katex .sizing.reset-size8.size11 { + font-size: 1.72777778em; +} +.katex .fontsize-ensurer.reset-size9.size1, +.katex .sizing.reset-size9.size1 { + font-size: 0.28935185em; +} +.katex .fontsize-ensurer.reset-size9.size2, +.katex .sizing.reset-size9.size2 { + font-size: 0.34722222em; +} +.katex .fontsize-ensurer.reset-size9.size3, +.katex .sizing.reset-size9.size3 { + font-size: 0.40509259em; +} +.katex .fontsize-ensurer.reset-size9.size4, +.katex .sizing.reset-size9.size4 { + font-size: 0.46296296em; +} +.katex .fontsize-ensurer.reset-size9.size5, +.katex .sizing.reset-size9.size5 { + font-size: 0.52083333em; +} +.katex .fontsize-ensurer.reset-size9.size6, +.katex .sizing.reset-size9.size6 { + font-size: 0.5787037em; +} +.katex .fontsize-ensurer.reset-size9.size7, +.katex .sizing.reset-size9.size7 { + font-size: 0.69444444em; +} +.katex .fontsize-ensurer.reset-size9.size8, +.katex .sizing.reset-size9.size8 { + font-size: 0.83333333em; +} +.katex .fontsize-ensurer.reset-size9.size9, +.katex .sizing.reset-size9.size9 { + font-size: 1em; +} +.katex .fontsize-ensurer.reset-size9.size10, +.katex .sizing.reset-size9.size10 { + font-size: 1.20023148em; +} +.katex .fontsize-ensurer.reset-size9.size11, +.katex .sizing.reset-size9.size11 { + font-size: 1.43981481em; +} +.katex .fontsize-ensurer.reset-size10.size1, +.katex .sizing.reset-size10.size1 { + font-size: 0.24108004em; +} +.katex .fontsize-ensurer.reset-size10.size2, +.katex .sizing.reset-size10.size2 { + font-size: 0.28929605em; +} +.katex .fontsize-ensurer.reset-size10.size3, +.katex .sizing.reset-size10.size3 { + font-size: 0.33751205em; +} +.katex .fontsize-ensurer.reset-size10.size4, +.katex .sizing.reset-size10.size4 { + font-size: 0.38572806em; +} +.katex .fontsize-ensurer.reset-size10.size5, +.katex .sizing.reset-size10.size5 { + font-size: 0.43394407em; +} +.katex .fontsize-ensurer.reset-size10.size6, +.katex .sizing.reset-size10.size6 { + font-size: 0.48216008em; +} +.katex .fontsize-ensurer.reset-size10.size7, +.katex .sizing.reset-size10.size7 { + font-size: 0.57859209em; +} +.katex .fontsize-ensurer.reset-size10.size8, +.katex .sizing.reset-size10.size8 { + font-size: 0.69431051em; +} +.katex .fontsize-ensurer.reset-size10.size9, +.katex .sizing.reset-size10.size9 { + font-size: 0.83317261em; +} +.katex .fontsize-ensurer.reset-size10.size10, +.katex .sizing.reset-size10.size10 { + font-size: 1em; +} +.katex .fontsize-ensurer.reset-size10.size11, +.katex .sizing.reset-size10.size11 { + font-size: 1.19961427em; +} +.katex .fontsize-ensurer.reset-size11.size1, +.katex .sizing.reset-size11.size1 { + font-size: 0.20096463em; +} +.katex .fontsize-ensurer.reset-size11.size2, +.katex .sizing.reset-size11.size2 { + font-size: 0.24115756em; +} +.katex .fontsize-ensurer.reset-size11.size3, +.katex .sizing.reset-size11.size3 { + font-size: 0.28135048em; +} +.katex .fontsize-ensurer.reset-size11.size4, +.katex .sizing.reset-size11.size4 { + font-size: 0.32154341em; +} +.katex .fontsize-ensurer.reset-size11.size5, +.katex .sizing.reset-size11.size5 { + font-size: 0.36173633em; +} +.katex .fontsize-ensurer.reset-size11.size6, +.katex .sizing.reset-size11.size6 { + font-size: 0.40192926em; +} +.katex .fontsize-ensurer.reset-size11.size7, +.katex .sizing.reset-size11.size7 { + font-size: 0.48231511em; +} +.katex .fontsize-ensurer.reset-size11.size8, +.katex .sizing.reset-size11.size8 { + font-size: 0.57877814em; +} +.katex .fontsize-ensurer.reset-size11.size9, +.katex .sizing.reset-size11.size9 { + font-size: 0.69453376em; +} +.katex .fontsize-ensurer.reset-size11.size10, +.katex .sizing.reset-size11.size10 { + font-size: 0.83360129em; +} +.katex .fontsize-ensurer.reset-size11.size11, +.katex .sizing.reset-size11.size11 { + font-size: 1em; +} +.katex .delimsizing.size1 { + font-family: KaTeX_Size1; +} +.katex .delimsizing.size2 { + font-family: KaTeX_Size2; +} +.katex .delimsizing.size3 { + font-family: KaTeX_Size3; +} +.katex .delimsizing.size4 { + font-family: KaTeX_Size4; +} +.katex .delimsizing.mult .delim-size1 > span { + font-family: KaTeX_Size1; +} +.katex .delimsizing.mult .delim-size4 > span { + font-family: KaTeX_Size4; +} +.katex .nulldelimiter { + display: inline-block; + width: 0.12em; +} +.katex .delimcenter, +.katex .op-symbol { + position: relative; +} +.katex .op-symbol.small-op { + font-family: KaTeX_Size1; +} +.katex .op-symbol.large-op { + font-family: KaTeX_Size2; +} +.katex .accent > .vlist-t, +.katex .op-limits > .vlist-t { + text-align: center; +} +.katex .accent .accent-body { + position: relative; +} +.katex .accent .accent-body:not(.accent-full) { + width: 0; +} +.katex .overlay { + display: block; +} +.katex .mtable .vertical-separator { + display: inline-block; + min-width: 1px; +} +.katex .mtable .arraycolsep { + display: inline-block; +} +.katex .mtable .col-align-c > .vlist-t { + text-align: center; +} +.katex .mtable .col-align-l > .vlist-t { + text-align: left; +} +.katex .mtable .col-align-r > .vlist-t { + text-align: right; +} +.katex .svg-align { + text-align: left; +} +.katex svg { + fill: currentColor; + stroke: currentColor; + fill-rule: nonzero; + fill-opacity: 1; + stroke-width: 1; + stroke-linecap: butt; + stroke-linejoin: miter; + stroke-miterlimit: 4; + stroke-dasharray: none; + stroke-dashoffset: 0; + stroke-opacity: 1; + display: block; + height: inherit; + position: absolute; + width: 100%; +} +.katex svg path { + stroke: none; +} +.katex img { + border-style: none; + max-height: none; + max-width: none; + min-height: 0; + min-width: 0; +} +.katex .stretchy { + display: block; + overflow: hidden; + position: relative; + width: 100%; +} +.katex .stretchy:after, +.katex .stretchy:before { + content: ""; +} +.katex .hide-tail { + overflow: hidden; + position: relative; + width: 100%; +} +.katex .halfarrow-left { + left: 0; + overflow: hidden; + position: absolute; + width: 50.2%; +} +.katex .halfarrow-right { + overflow: hidden; + position: absolute; + right: 0; + width: 50.2%; +} +.katex .brace-left { + left: 0; + overflow: hidden; + position: absolute; + width: 25.1%; +} +.katex .brace-center { + left: 25%; + overflow: hidden; + position: absolute; + width: 50%; +} +.katex .brace-right { + overflow: hidden; + position: absolute; + right: 0; + width: 25.1%; +} +.katex .x-arrow-pad { + padding: 0 0.5em; +} +.katex .cd-arrow-pad { + padding: 0 0.55556em 0 0.27778em; +} +.katex .mover, +.katex .munder, +.katex .x-arrow { + text-align: center; +} +.katex .boxpad { + padding: 0 0.3em; +} +.katex .fbox, +.katex .fcolorbox { + border: 0.04em solid; + box-sizing: border-box; +} +.katex .cancel-pad { + padding: 0 0.2em; +} +.katex .cancel-lap { + margin-left: -0.2em; + margin-right: -0.2em; +} +.katex .sout { + border-bottom-style: solid; + border-bottom-width: 0.08em; +} +.katex .angl { + border-right: 0.049em solid; + border-top: 0.049em solid; + box-sizing: border-content; + margin-right: 0.03889em; +} +.katex .anglpad { + padding: 0 0.03889em; +} +.katex .eqn-num:before { + content: "(" counter(katexEqnNo) ")"; + counter-increment: katexEqnNo; +} +.katex .mml-eqn-num:before { + content: "(" counter(mmlEqnNo) ")"; + counter-increment: mmlEqnNo; +} +.katex .mtr-glue { + width: 50%; +} +.katex .cd-vert-arrow { + display: inline-block; + position: relative; +} +.katex .cd-label-left { + display: inline-block; + position: absolute; + right: -webkit-calc(50% + 0.3em); + right: calc(50% + 0.3em); + text-align: left; +} +.katex .cd-label-right { + display: inline-block; + left: -webkit-calc(50% + 0.3em); + left: calc(50% + 0.3em); + position: absolute; + text-align: right; +} +.katex-display { + display: block; + margin: 1em 0; + text-align: center; +} +.katex-display > .katex { + display: block; + text-align: center; + white-space: nowrap; +} +.katex-display > .katex > .katex-html { + display: block; + position: relative; +} +.katex-display > .katex > .katex-html > .tag { + position: absolute; + right: 0; +} +.katex-display.leqno > .katex > .katex-html > .tag { + left: 0; + right: auto; +} +.katex-display.fleqn > .katex { + padding-left: 2em; + text-align: left; +} +body { + counter-reset: katexEqnNo mmlEqnNo; +} diff --git a/website/public/main-5e7fc0c942.min.css b/website/public/main-5e7fc0c942.min.css index 2901693d141..993a3515a7d 100644 --- a/website/public/main-5e7fc0c942.min.css +++ b/website/public/main-5e7fc0c942.min.css @@ -280,7 +280,7 @@ code { --body-font-color: #343a40; --button-background: #498bcb; --button-border-color: #4186c9; - --link-color: #0a539a; + --link-color: #21cd9b; --link-color-visited: #7749bf; --code-background: #f5f6f8; --code-accent-color: #e3e7eb; @@ -732,21 +732,32 @@ code { filter: none; } @media (prefers-color-scheme: light) { + h1, + h2, + h3, + p { + color: white; + } + .gdoc-brand__title, + .gdoc_keyborad_arrow_left, + .gdoc_keyborad_arrow_down { + color: white; + } :root { --header-background: #4186c9; --header-font-color: white; - --body-background: white; - --body-font-color: #343a40; + --body-background: #343a40; + --body-font-color: #ced3d8; --button-background: #498bcb; --button-border-color: #4186c9; - --link-color: #0a539a; - --link-color-visited: #7749bf; - --code-background: #f5f6f8; - --code-accent-color: #e3e7eb; - --code-accent-color-lite: #eff1f3; - --code-font-color: #5f5f5f; - --accent-color: #e9ecef; - --accent-color-lite: #f8f9fa; + --link-color: #21cd9b; + --link-color-visited: #ba8ef0; + --code-background: #2f353a; + --code-accent-color: #262b2f; + --code-accent-color-lite: #2b3035; + --code-font-color: #b9b9b9; + --accent-color: #2b3035; + --accent-color-lite: #2f353a; --control-icons: #b2bac1; --footer-background: #2f333e; --footer-font-color: white; @@ -798,8 +809,7 @@ code { color: inherit; } :root .chroma .err { - color: #a61717; - background-color: #e3d2d2; + color: inherit; } :root .chroma .lntd { vertical-align: top; @@ -831,7 +841,7 @@ code { :root .chroma .hl { display: block; width: 100%; - background-color: #ffc; + background-color: #4f1605; } :root .chroma .lnt { padding: 0 0.8em; @@ -839,78 +849,70 @@ code { :root .chroma .ln { margin-right: 0.4em; padding: 0 0.4em 0 0.4em; + color: #b3b3b3; } :root .chroma .k { - color: #000; - font-weight: 700; + color: #ff79c6; } :root .chroma .kc { - color: #000; - font-weight: 700; + color: #ff79c6; } :root .chroma .kd { - color: #000; - font-weight: 700; + color: #8be9fd; + font-style: italic; } :root .chroma .kn { - color: #000; - font-weight: 700; + color: #ff79c6; } :root .chroma .kp { - color: #000; - font-weight: 700; + color: #ff79c6; } :root .chroma .kr { - color: #000; - font-weight: 700; + color: #ff79c6; } :root .chroma .kt { - color: #458; - font-weight: 700; + color: #8be9fd; } :root .chroma .n { color: inherit; } :root .chroma .na { - color: #006767; + color: #50fa7b; } :root .chroma .nb { - color: #556165; + color: #8be9fd; + font-style: italic; } :root .chroma .bp { - color: #676767; + color: inherit; } :root .chroma .nc { - color: #458; - font-weight: 700; + color: #50fa7b; } :root .chroma .no { - color: #006767; + color: inherit; } :root .chroma .nd { - color: #3c5d5d; - font-weight: 700; + color: inherit; } :root .chroma .ni { - color: purple; + color: inherit; } :root .chroma .ne { - color: #900; - font-weight: 700; + color: inherit; } :root .chroma .nf { - color: #900; - font-weight: 700; + color: #50fa7b; } :root .chroma .fm { color: inherit; } :root .chroma .nl { - color: #900; - font-weight: 700; + color: #8be9fd; + font-style: italic; } :root .chroma .nn { - color: #555; + color: inherit; } :root .chroma .nx { color: inherit; @@ -919,19 +921,23 @@ code { color: inherit; } :root .chroma .nt { - color: navy; + color: #ff79c6; } :root .chroma .nv { - color: #006767; + color: #8be9fd; + font-style: italic; } :root .chroma .vc { - color: #006767; + color: #8be9fd; + font-style: italic; } :root .chroma .vg { - color: #006767; + color: #8be9fd; + font-style: italic; } :root .chroma .vi { - color: #006767; + color: #8be9fd; + font-style: italic; } :root .chroma .vm { color: inherit; @@ -943,157 +949,143 @@ code { color: inherit; } :root .chroma .s { - color: #d14; + color: #f1fa8c; } :root .chroma .sa { - color: #d14; + color: #f1fa8c; } :root .chroma .sb { - color: #d14; + color: #f1fa8c; } :root .chroma .sc { - color: #d14; + color: #f1fa8c; } :root .chroma .dl { - color: #d14; + color: #f1fa8c; } :root .chroma .sd { - color: #d14; + color: #f1fa8c; } :root .chroma .s2 { - color: #d14; + color: #f1fa8c; } :root .chroma .se { - color: #d14; + color: #f1fa8c; } :root .chroma .sh { - color: #d14; + color: #f1fa8c; } :root .chroma .si { - color: #d14; + color: #f1fa8c; } :root .chroma .sx { - color: #d14; + color: #f1fa8c; } :root .chroma .sr { - color: #009926; + color: #f1fa8c; } :root .chroma .s1 { - color: #d14; + color: #f1fa8c; } :root .chroma .ss { - color: #990073; + color: #f1fa8c; } :root .chroma .m { - color: #027e83; + color: #bd93f9; } :root .chroma .mb { - color: #027e83; + color: #bd93f9; } :root .chroma .mf { - color: #027e83; + color: #bd93f9; } :root .chroma .mh { - color: #027e83; + color: #bd93f9; } :root .chroma .mi { - color: #027e83; + color: #bd93f9; } :root .chroma .il { - color: #027e83; + color: #bd93f9; } :root .chroma .mo { - color: #027e83; + color: #bd93f9; } :root .chroma .o { - color: #000; - font-weight: 700; + color: #ff79c6; } :root .chroma .ow { - color: #000; - font-weight: 700; + color: #ff79c6; } :root .chroma .p { color: inherit; } :root .chroma .c { - color: #676765; - font-style: italic; + color: #96a6d8; } :root .chroma .ch { - color: #676765; - font-style: italic; + color: #96a6d8; } :root .chroma .cm { - color: #676765; - font-style: italic; + color: #96a6d8; } :root .chroma .c1 { - color: #676765; - font-style: italic; + color: #96a6d8; } :root .chroma .cs { - color: #676767; - font-weight: 700; - font-style: italic; + color: #96a6d8; } :root .chroma .cp { - color: #676767; - font-weight: 700; - font-style: italic; + color: #ff79c6; } :root .chroma .cpf { - color: #676767; - font-weight: 700; - font-style: italic; + color: #ff79c6; } :root .chroma .g { color: inherit; } :root .chroma .gd { - color: #000; - background-color: #fdd; + color: #d98f90; } :root .chroma .ge { - color: #000; - font-style: italic; + text-decoration: underline; } :root .chroma .gr { - color: #a00; + color: inherit; } :root .chroma .gh { - color: #676767; + font-weight: 700; + color: inherit; } :root .chroma .gi { - color: #000; - background-color: #dfd; - } - :root .chroma .go { - color: #6f6f6f; - } - :root .chroma .gp { - color: #555; - } - :root .chroma .gs { font-weight: 700; } + :root .chroma .go { + color: #8f9ea8; + } + :root .chroma .gp { + color: inherit; + } + :root .chroma .gs { + color: inherit; + } :root .chroma .gu { - color: #5f5f5f; + font-weight: 700; } :root .chroma .gt { - color: #a00; + color: inherit; } :root .chroma .gl { text-decoration: underline; } :root .chroma .w { - color: #bbb; + color: inherit; } :root .dark-mode-dim .gdoc-markdown img { - filter: none; + filter: brightness(0.75) grayscale(0.2); } :root .gdoc-markdown .gdoc-hint { - filter: none; + filter: saturate(2.5) brightness(0.85); } } :root[color-mode="dark"] { diff --git a/website/public/main-cc3cbe901b.min.css b/website/public/main-cc3cbe901b.min.css index 1a8113db98f..f420ccf731e 100644 --- a/website/public/main-cc3cbe901b.min.css +++ b/website/public/main-cc3cbe901b.min.css @@ -277,7 +277,7 @@ code { --body-font-color: #343a40; --button-background: #498bcb; --button-border-color: #4186c9; - --link-color: #0a539a; + --link-color: #21cd9b; --link-color-visited: #7749bf; --code-background: #f5f6f8; --code-accent-color: #e3e7eb; @@ -732,18 +732,18 @@ code { :root { --header-background: #4186c9; --header-font-color: white; - --body-background: white; - --body-font-color: #343a40; + --body-background: #343a40; + --body-font-color: #ced3d8; --button-background: #498bcb; --button-border-color: #4186c9; - --link-color: #0a539a; - --link-color-visited: #7749bf; - --code-background: #f5f6f8; - --code-accent-color: #e3e7eb; - --code-accent-color-lite: #eff1f3; - --code-font-color: #5f5f5f; - --accent-color: #e9ecef; - --accent-color-lite: #f8f9fa; + --link-color: #21cd9b; + --link-color-visited: #ba8ef0; + --code-background: #2f353a; + --code-accent-color: #262b2f; + --code-accent-color-lite: #2b3035; + --code-font-color: #b9b9b9; + --accent-color: #2b3035; + --accent-color-lite: #2f353a; --control-icons: #b2bac1; --footer-background: #2f333e; --footer-font-color: white; @@ -795,8 +795,7 @@ code { color: inherit; } :root .chroma .err { - color: #a61717; - background-color: #e3d2d2; + color: inherit; } :root .chroma .lntd { vertical-align: top; @@ -828,7 +827,7 @@ code { :root .chroma .hl { display: block; width: 100%; - background-color: #ffc; + background-color: #4f1605; } :root .chroma .lnt { padding: 0 0.8em; @@ -836,78 +835,70 @@ code { :root .chroma .ln { margin-right: 0.4em; padding: 0 0.4em 0 0.4em; + color: #b3b3b3; } :root .chroma .k { - color: #000; - font-weight: 700; + color: #ff79c6; } :root .chroma .kc { - color: #000; - font-weight: 700; + color: #ff79c6; } :root .chroma .kd { - color: #000; - font-weight: 700; + color: #8be9fd; + font-style: italic; } :root .chroma .kn { - color: #000; - font-weight: 700; + color: #ff79c6; } :root .chroma .kp { - color: #000; - font-weight: 700; + color: #ff79c6; } :root .chroma .kr { - color: #000; - font-weight: 700; + color: #ff79c6; } :root .chroma .kt { - color: #458; - font-weight: 700; + color: #8be9fd; } :root .chroma .n { color: inherit; } :root .chroma .na { - color: #006767; + color: #50fa7b; } :root .chroma .nb { - color: #556165; + color: #8be9fd; + font-style: italic; } :root .chroma .bp { - color: #676767; + color: inherit; } :root .chroma .nc { - color: #458; - font-weight: 700; + color: #50fa7b; } :root .chroma .no { - color: #006767; + color: inherit; } :root .chroma .nd { - color: #3c5d5d; - font-weight: 700; + color: inherit; } :root .chroma .ni { - color: purple; + color: inherit; } :root .chroma .ne { - color: #900; - font-weight: 700; + color: inherit; } :root .chroma .nf { - color: #900; - font-weight: 700; + color: #50fa7b; } :root .chroma .fm { color: inherit; } :root .chroma .nl { - color: #900; - font-weight: 700; + color: #8be9fd; + font-style: italic; } :root .chroma .nn { - color: #555; + color: inherit; } :root .chroma .nx { color: inherit; @@ -916,19 +907,23 @@ code { color: inherit; } :root .chroma .nt { - color: navy; + color: #ff79c6; } :root .chroma .nv { - color: #006767; + color: #8be9fd; + font-style: italic; } :root .chroma .vc { - color: #006767; + color: #8be9fd; + font-style: italic; } :root .chroma .vg { - color: #006767; + color: #8be9fd; + font-style: italic; } :root .chroma .vi { - color: #006767; + color: #8be9fd; + font-style: italic; } :root .chroma .vm { color: inherit; @@ -940,157 +935,143 @@ code { color: inherit; } :root .chroma .s { - color: #d14; + color: #f1fa8c; } :root .chroma .sa { - color: #d14; + color: #f1fa8c; } :root .chroma .sb { - color: #d14; + color: #f1fa8c; } :root .chroma .sc { - color: #d14; + color: #f1fa8c; } :root .chroma .dl { - color: #d14; + color: #f1fa8c; } :root .chroma .sd { - color: #d14; + color: #f1fa8c; } :root .chroma .s2 { - color: #d14; + color: #f1fa8c; } :root .chroma .se { - color: #d14; + color: #f1fa8c; } :root .chroma .sh { - color: #d14; + color: #f1fa8c; } :root .chroma .si { - color: #d14; + color: #f1fa8c; } :root .chroma .sx { - color: #d14; + color: #f1fa8c; } :root .chroma .sr { - color: #009926; + color: #f1fa8c; } :root .chroma .s1 { - color: #d14; + color: #f1fa8c; } :root .chroma .ss { - color: #990073; + color: #f1fa8c; } :root .chroma .m { - color: #027e83; + color: #bd93f9; } :root .chroma .mb { - color: #027e83; + color: #bd93f9; } :root .chroma .mf { - color: #027e83; + color: #bd93f9; } :root .chroma .mh { - color: #027e83; + color: #bd93f9; } :root .chroma .mi { - color: #027e83; + color: #bd93f9; } :root .chroma .il { - color: #027e83; + color: #bd93f9; } :root .chroma .mo { - color: #027e83; + color: #bd93f9; } :root .chroma .o { - color: #000; - font-weight: 700; + color: #ff79c6; } :root .chroma .ow { - color: #000; - font-weight: 700; + color: #ff79c6; } :root .chroma .p { color: inherit; } :root .chroma .c { - color: #676765; - font-style: italic; + color: #96a6d8; } :root .chroma .ch { - color: #676765; - font-style: italic; + color: #96a6d8; } :root .chroma .cm { - color: #676765; - font-style: italic; + color: #96a6d8; } :root .chroma .c1 { - color: #676765; - font-style: italic; + color: #96a6d8; } :root .chroma .cs { - color: #676767; - font-weight: 700; - font-style: italic; + color: #96a6d8; } :root .chroma .cp { - color: #676767; - font-weight: 700; - font-style: italic; + color: #ff79c6; } :root .chroma .cpf { - color: #676767; - font-weight: 700; - font-style: italic; + color: #ff79c6; } :root .chroma .g { color: inherit; } :root .chroma .gd { - color: #000; - background-color: #fdd; + color: #d98f90; } :root .chroma .ge { - color: #000; - font-style: italic; + text-decoration: underline; } :root .chroma .gr { - color: #a00; + color: inherit; } :root .chroma .gh { - color: #676767; + font-weight: 700; + color: inherit; } :root .chroma .gi { - color: #000; - background-color: #dfd; - } - :root .chroma .go { - color: #6f6f6f; - } - :root .chroma .gp { - color: #555; - } - :root .chroma .gs { font-weight: 700; } + :root .chroma .go { + color: #8f9ea8; + } + :root .chroma .gp { + color: inherit; + } + :root .chroma .gs { + color: inherit; + } :root .chroma .gu { - color: #5f5f5f; + font-weight: 700; } :root .chroma .gt { - color: #a00; + color: inherit; } :root .chroma .gl { text-decoration: underline; } :root .chroma .w { - color: #bbb; + color: inherit; } :root .dark-mode-dim .gdoc-markdown img { - filter: none; + filter: brightness(0.75) grayscale(0.2); } :root .gdoc-markdown .gdoc-hint { - filter: none; + filter: saturate(2.5) brightness(0.85); } } :root[color-mode="dark"] {