diff --git a/openbb_terminal/common/quantitative_analysis/qa_model.py b/openbb_terminal/common/quantitative_analysis/qa_model.py index 91e40b17113..43763c3d118 100644 --- a/openbb_terminal/common/quantitative_analysis/qa_model.py +++ b/openbb_terminal/common/quantitative_analysis/qa_model.py @@ -473,3 +473,87 @@ def get_es( es_list = [es_90, es_95, es_99, es_custom] hist_es_list = [hist_es_90, hist_es_95, hist_es_99, hist_es_custom] return es_list, hist_es_list + + +def get_sharpe(data: pd.DataFrame, rfr: float = 0, window: float = 252): + """Calculates the sharpe ratio + Parameters + ---------- + data: pd.DataFrame + selected dataframe column + rfr: float + risk free rate + window: float + length of the rolling window + """ + data_return = data.pct_change().rolling(window).sum() * 100 + std = data.rolling(window).std() / np.sqrt(252) * 100 + + sharpe = (data_return - rfr) / std + + return sharpe + + +def get_sortino( + data: pd.DataFrame, + target_return: float = 0, + window: float = 252, + adjusted: bool = False, +): + """Calculates the sortino ratio + Parameters + ---------- + data: pd.DataFrame + selected dataframe + target_return: float + target return of the asset + window: float + length of the rolling window + adjusted: bool + adjust the sortino ratio + """ + data = data * 100 + + # Sortino Ratio + # For method & terminology see: + # http://www.redrockcapital.com/Sortino__A__Sharper__Ratio_Red_Rock_Capital.pdf + + target_downside_deviation = data.rolling(window).apply( + lambda x: (x.values[x.values < 0]).std() / np.sqrt(252) * 100 + ) + data_return = data.rolling(window).sum() + sortino_ratio = (data_return - target_return) / target_downside_deviation + + if adjusted: + # Adjusting the sortino ratio inorder to compare it to sharpe ratio + # Thus if the deviation is neutral then it's equal to the sharpe ratio + sortino_ratio = sortino_ratio / np.sqrt(2) + + return sortino_ratio + + +def get_omega(data: pd.DataFrame, threshold: float = 0): + """Calculates the omega ratio + Parameters + ---------- + data: pd.DataFrame + selected dataframe + threshold: float + target return threshold + """ + # Omega ratio; for more information and explanation see: + # https://en.wikipedia.org/wiki/Omega_ratio + + # Calculating daily threshold from annualised threshold value + daily_threshold = (threshold + 1) ** np.sqrt(1 / 252) - 1 + + # Get excess return + data_excess = data - daily_threshold + + # Values excess return + data_positive_sum = data_excess[data_excess > 0].sum() + data_negative_sum = data_excess[data_excess < 0].sum() + + omega_ratio = data_positive_sum / (-data_negative_sum) + + return omega_ratio diff --git a/openbb_terminal/common/quantitative_analysis/qa_view.py b/openbb_terminal/common/quantitative_analysis/qa_view.py index edcf7444171..11fa6bb0937 100644 --- a/openbb_terminal/common/quantitative_analysis/qa_view.py +++ b/openbb_terminal/common/quantitative_analysis/qa_view.py @@ -1127,3 +1127,91 @@ def display_es( floatfmt=".4f", ) console.print("") + + +def display_sharpe(data: pd.DataFrame, rfr: float, window: float): + """Calculates the sharpe ratio + Parameters + ---------- + data: pd.DataFrame + selected dataframe column + rfr: float + risk free rate + window: float + length of the rolling window + """ + sharpe_ratio = qa_model.get_sharpe(data, rfr, window) + + fig, ax = plt.subplots() + ax.plot(sharpe_ratio[int(window - 1) :]) + ax.set_title(f"Sharpe Ratio - over a {window} day window") + ax.set_ylabel("Sharpe ratio") + ax.set_xlabel("Date") + fig.legend() + + theme.style_primary_axis(ax) + theme.visualize_output() + + +def display_sortino( + data: pd.DataFrame, target_return: float, window: float, adjusted: bool +): + """Displays the sortino ratio + Parameters + ---------- + data: pd.DataFrame + selected dataframe + target_return: float + target return of the asset + window: float + length of the rolling window + adjusted: bool + adjust the sortino ratio + """ + sortino_ratio = qa_model.get_sortino(data, target_return, window, adjusted) + if adjusted: + str_adjusted = "Adjusted " + else: + str_adjusted = "" + + fig, ax = plt.subplots() + ax.plot(sortino_ratio[int(window - 1) :]) + ax.set_title(f"{str_adjusted}Sortino Ratio - over a {window} day window") + ax.set_ylabel("Sortino ratio") + ax.set_xlabel("Date") + fig.legend() + + theme.style_primary_axis(ax) + theme.visualize_output() + + +def display_omega( + data: pd.DataFrame, threshold_start: float = 0, threshold_end: float = 1.5 +): + """Displays the omega ratio + Parameters + ---------- + data: pd.DataFrame + stock dataframe + threshold_start: float + annualized target return threshold start of plotted threshold range + threshold_end: float + annualized target return threshold end of plotted threshold range + """ + threshold = np.linspace(threshold_start, threshold_end, 50) + omega_list = [] + + for i in threshold: + omega_list.append(qa_model.get_omega(data, i)) + + # Plotting + fig, ax = plt.subplots() + ax.plot(threshold, omega_list) + ax.set_title(f"Omega Curve - over last {len(data)}'s period") + ax.set_ylabel("Omega Ratio") + ax.set_xlabel("Threshold (%)") + fig.legend() + ax.set_ylim(threshold_start, threshold_end) + + theme.style_primary_axis(ax) + theme.visualize_output() diff --git a/openbb_terminal/portfolio/portfolio_controller.py b/openbb_terminal/portfolio/portfolio_controller.py index bd70d925b07..1f6e6b43433 100644 --- a/openbb_terminal/portfolio/portfolio_controller.py +++ b/openbb_terminal/portfolio/portfolio_controller.py @@ -51,6 +51,9 @@ class PortfolioController(BaseController): "rolling", "var", "es", + "sh", + "so", + "om", ] CHOICES_MENUS = [ "bro", @@ -114,7 +117,10 @@ Loaded:[/info] {self.portfolio_name or None} [info]Risk Metrics:[/info][cmds] var display value at risk - es display expected shortfall[/cmds] + es display expected shortfall + sh display sharpe ratio + so display sortino ratio + om display omega ratio[/cmds] """ # TODO: Clean up the reports inputs # TODO: Edit the allocation to allow the different asset classes @@ -557,6 +563,146 @@ Loaded:[/info] {self.portfolio_name or None} True, ) + @log_start_end(log=logger) + def call_sh(self, other_args: List[str]): + """Process sh command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="sh", + description=""" + Provides the sharpe ratio of the selected portfolio. + """, + ) + parser.add_argument( + "-r", + "--rfr", + action="store", + dest="rfr", + type=float, + default=0, + help="Risk free return", + ) + parser.add_argument( + "-w", + "--window", + action="store", + dest="window", + type=int, + default=252, + help="Rolling window length", + ) + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + from openbb_terminal.common.quantitative_analysis import qa_view + + if self.portfolio.empty: + console.print("[red]No portfolio loaded.[/red]\n") + return + self.portfolio.generate_holdings_from_trades() + data = self.portfolio.portfolio_value[1:] + qa_view.display_sharpe(data, ns_parser.rfr, ns_parser.window) + + @log_start_end(log=logger) + def call_so(self, other_args: List[str]): + """Process so command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="so", + description=""" + Provides the sortino ratio of the selected portfolio. + """, + ) + parser.add_argument( + "-t", + "--target", + action="store", + dest="target_return", + type=float, + default=0, + help="Target return", + ) + parser.add_argument( + "-a", + "--adjusted", + action="store_true", + default=False, + dest="adjusted", + help="If one should adjust the sortino ratio inorder to make it comparable to the sharpe ratio", + ) + parser.add_argument( + "-w", + "--window", + action="store", + dest="window", + type=int, + default=252, + help="Rolling window length", + ) + + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + from openbb_terminal.common.quantitative_analysis import qa_view + + if self.portfolio.empty: + console.print("[red]No portfolio loaded.[/red]\n") + return + self.portfolio.generate_holdings_from_trades() + data = self.portfolio.returns[1:] + qa_view.display_sortino( + data, ns_parser.target_return, ns_parser.window, ns_parser.adjusted + ) + + @log_start_end(log=logger) + def call_om(self, other_args: List[str]): + """Process om command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="om", + description=""" + Provides omega ratio of the selected portfolio. + """, + ) + parser.add_argument( + "-s", + "--start", + action="store", + dest="start", + type=float, + default=0, + help=""" + Start of the omega ratio threshold + """, + ) + parser.add_argument( + "-e", + "--end", + action="store", + dest="end", + type=float, + default=1.5, + help=""" + End of the omega ratio threshold + """, + ) + + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + from openbb_terminal.common.quantitative_analysis import qa_view + + if self.portfolio.empty: + console.print("[red]No portfolio loaded.[/red]\n") + return + self.portfolio.generate_holdings_from_trades() + data = self.portfolio.returns[1:] + qa_view.display_omega( + data, + ns_parser.start, + ns_parser.end, + ) + @log_start_end(log=logger) def call_rmr(self, other_args: List[str]): """Process rmr command""" diff --git a/openbb_terminal/stocks/quantitative_analysis/qa_controller.py b/openbb_terminal/stocks/quantitative_analysis/qa_controller.py index 099eae8b869..1f1d1680187 100644 --- a/openbb_terminal/stocks/quantitative_analysis/qa_controller.py +++ b/openbb_terminal/stocks/quantitative_analysis/qa_controller.py @@ -57,6 +57,9 @@ class QaController(StockBaseController): "capm", "var", "es", + "sh", + "so", + "om", ] stock_interval = [1, 5, 15, 30, 60] @@ -135,6 +138,9 @@ class QaController(StockBaseController): [info]Risk:[/info] var display value at risk es display expected shortfall + sh display sharpe ratio + so display sortino ratio + om display omega ratio [info]Other:[/info] raw print raw data decompose decomposition in cyclic-trend, season, and residuals of prices @@ -810,6 +816,7 @@ class QaController(StockBaseController): False, ) + @log_start_end(log=logger) def call_es(self, other_args: List[str]): """Process es command""" parser = argparse.ArgumentParser( @@ -860,3 +867,125 @@ class QaController(StockBaseController): ns_parser.percentile / 100, False, ) + + @log_start_end(log=logger) + def call_sh(self, other_args: List[str]): + """Process sh command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="sh", + description=""" + Provides the sharpe ratio of the selected stock. + """, + ) + parser.add_argument( + "-r", + "--rfr", + action="store", + dest="rfr", + type=float, + default=0, + help="Risk free return", + ) + parser.add_argument( + "-w", + "--window", + action="store", + dest="window", + type=int, + default=min(len(self.stock["adjclose"].values), 252), + help="Rolling window length", + ) + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + data = self.stock["adjclose"] + qa_view.display_sharpe(data, ns_parser.rfr, ns_parser.window) + + @log_start_end(log=logger) + def call_so(self, other_args: List[str]): + """Process so command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="so", + description=""" + Provides the sortino ratio of the selected stock. + """, + ) + parser.add_argument( + "-t", + "--target", + action="store", + dest="target_return", + type=float, + default=0, + help="Target return", + ) + parser.add_argument( + "-a", + "--adjusted", + action="store_true", + default=False, + dest="adjusted", + help="If one should adjust the sortino ratio inorder to make it comparable to the sharpe ratio", + ) + parser.add_argument( + "-w", + "--window", + action="store", + dest="window", + type=int, + default=min(len(self.stock["returns"].values), 252), + help="Rolling window length", + ) + + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + data = self.stock["returns"] + qa_view.display_sortino( + data, ns_parser.target_return, ns_parser.window, ns_parser.adjusted + ) + + @log_start_end(log=logger) + def call_om(self, other_args: List[str]): + """Process om command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="om", + description=""" + Provides omega ratio of the selected stock. + """, + ) + parser.add_argument( + "-s", + "--start", + action="store", + dest="start", + type=float, + default=0, + help=""" + Start of the omega ratio threshold + """, + ) + parser.add_argument( + "-e", + "--end", + action="store", + dest="end", + type=float, + default=1.5, + help=""" + End of the omega ratio threshold + """, + ) + + ns_parser = parse_known_args_and_warn(parser, other_args) + if ns_parser: + data = self.stock["returns"] + qa_view.display_omega( + data, + ns_parser.start, + ns_parser.end, + ) diff --git a/scripts/test_port.openbb b/scripts/test_port.openbb index 8c56f5dda23..b82eaf1d16e 100644 --- a/scripts/test_port.openbb +++ b/scripts/test_port.openbb @@ -16,4 +16,7 @@ equal mktcap es var +sh +so +om exit diff --git a/scripts/test_stocks_qa.openbb b/scripts/test_stocks_qa.openbb index 78dd8fdd18a..9ef8c9c4248 100644 --- a/scripts/test_stocks_qa.openbb +++ b/scripts/test_stocks_qa.openbb @@ -29,4 +29,7 @@ cusum capm var es +sh +so +om exit \ No newline at end of file diff --git a/tests/openbb_terminal/portfolio/txt/test_portfolio_controller/test_print_help.txt b/tests/openbb_terminal/portfolio/txt/test_portfolio_controller/test_print_help.txt index 6ae2ce98bb4..2151d7d66cc 100644 --- a/tests/openbb_terminal/portfolio/txt/test_portfolio_controller/test_print_help.txt +++ b/tests/openbb_terminal/portfolio/txt/test_portfolio_controller/test_print_help.txt @@ -20,4 +20,7 @@ Graphs: Risk Metrics: var display value at risk - es display expected shortfall \ No newline at end of file + es display expected shortfall + sh display sharpe ratio + so display sortino ratio + om display omega ratio \ No newline at end of file diff --git a/tests/openbb_terminal/stocks/quantitative_analysis/txt/test_qa_controller/test_print_help.txt b/tests/openbb_terminal/stocks/quantitative_analysis/txt/test_qa_controller/test_print_help.txt index bc2b6886e63..eeab9a98c75 100644 --- a/tests/openbb_terminal/stocks/quantitative_analysis/txt/test_qa_controller/test_print_help.txt +++ b/tests/openbb_terminal/stocks/quantitative_analysis/txt/test_qa_controller/test_print_help.txt @@ -25,6 +25,9 @@ Rolling Metrics: Risk: var display value at risk es display expected shortfall + sh display sharpe ratio + so display sortino ratio + om display omega ratio Other: raw print raw data decompose decomposition in cyclic-trend, season, and residuals of prices diff --git a/website/content/terminal/common/quantitative_analysis/om/_index.md b/website/content/terminal/common/quantitative_analysis/om/_index.md new file mode 100644 index 00000000000..143ad6fec91 --- /dev/null +++ b/website/content/terminal/common/quantitative_analysis/om/_index.md @@ -0,0 +1,18 @@ +``` +usage: om [-s START] [-e END] [-h] +``` + +Provides omega ratio of the selected stock. + +The omega ratio is the probability weighted ratio of gains versus losses for a threshold return. This is in practice +done by getting the sum of the returns above the threshold return and of the returns below it and then calculating the +ratio between these sums. For more, read: https://en.wikipedia.org/wiki/Omega_ratio + +``` +optional arguments: + -s START, --start START + Start of the omega ratio threshold (default: 0) + -e END, --end END End of the omega ratio threshold (default: 1.5) + -h, --help show this help message (default: False) +``` +![image](https://user-images.githubusercontent.com/75195383/163530147-557ad48b-c6ec-43d3-8d33-6ad4f02a6cfb.png) diff --git a/website/content/terminal/common/quantitative_analysis/sh/_index.md b/website/content/terminal/common/quantitative_analysis/sh/_index.md new file mode 100644 index 00000000000..9efa172447d --- /dev/null +++ b/website/content/terminal/common/quantitative_analysis/sh/_index.md @@ -0,0 +1,17 @@ +``` +usage: sh [-r RFR] [-w WINDOW] [-h] +``` + +Provides the sharpe ratio of the selected stock. + +The sharpe ratio is calculated by subtracting the risk-free rates from the return and then divide it by the risk, +measured by the volatility. This gives the return per volatility point. + +``` +optional arguments: + -r RFR, --rfr RFR Risk free return (default: 0) + -w WINDOW, --window WINDOW + Rolling window length (default: 252) + -h, --help show this help message (default: False) +``` +![image](https://user-images.githubusercontent.com/75195383/163530426-77abe5ac-9c21-43e5-a975-5a37c7eb452f.png) diff --git a/website/content/terminal/common/quantitative_analysis/so/_index.md b/website/content/terminal/common/quantitative_analysis/so/_index.md new file mode 100644 index 00000000000..826ddbf059a --- /dev/null +++ b/website/content/terminal/common/quantitative_analysis/so/_index.md @@ -0,0 +1,21 @@ +``` +usage: so [-t TARGET_RETURN] [-a] [-w WINDOW] [-h] +``` + +Provides the sortino ratio of the selected stock. + +The sortino ratio is very similar to the sharpe ratio, but different in a crucial way. Sharpe ratio punishes the +standard deviation of positive return. The sortino ratio only punishes standard deviation of negative returns. For +more, read: http://www.redrockcapital.com/Sortino__A__Sharper__Ratio_Red_Rock_Capital.pdf + +``` +optional arguments: + -t TARGET_RETURN, --target TARGET_RETURN + Target return (default: 0) + -a, --adjusted If one should adjust the sortino ratio inorder to make it comparable to the sharpe ratio + (default: False) + -w WINDOW, --window WINDOW + Rolling window length (default: 252) + -h, --help show this help message (default: False) +``` +![image](https://user-images.githubusercontent.com/75195383/163530572-e527bc75-7ecd-44e3-b971-83b9a0662d0d.png) diff --git a/website/content/terminal/portfolio/om/_index.md b/website/content/terminal/portfolio/om/_index.md new file mode 100644 index 00000000000..53e75e6d266 --- /dev/null +++ b/website/content/terminal/portfolio/om/_index.md @@ -0,0 +1,18 @@ +``` +usage: om [-s START] [-e END] [-h] +``` + +Provides omega ratio of the selected portfolio. + +The omega ratio is the probability weighted ratio of gains versus losses for a threshold return. This is in practice +done by getting the sum of the returns above the threshold return and of the returns below it and then calculating the +ratio between these sums. For more, read: https://en.wikipedia.org/wiki/Omega_ratio + +``` +optional arguments: + -s START, --start START + Start of the omega ratio threshold (default: 0) + -e END, --end END End of the omega ratio threshold (default: 1.5) + -h, --help show this help message (default: False) +``` +![image](https://user-images.githubusercontent.com/75195383/163531048-c8efc8f7-d2a2-40ba-acca-811c8b92b264.png) diff --git a/website/content/terminal/portfolio/sh/_index.md b/website/content/terminal/portfolio/sh/_index.md new file mode 100644 index 00000000000..49e541a0064 --- /dev/null +++ b/website/content/terminal/portfolio/sh/_index.md @@ -0,0 +1,17 @@ +``` +usage: sh [-r RFR] [-w WINDOW] [-h] +``` + +Provides the sharpe ratio of the selected portfolio. + +The sharpe ratio is calculated by subtracting the risk-free rates from the return and then divide it by the risk, +measured by the volatility. This gives the return per volatility point. + +``` +optional arguments: + -r RFR, --rfr RFR Risk free return (default: 0) + -w WINDOW, --window WINDOW + Rolling window length (default: 252) + -h, --help show this help message (default: False) +``` +![image](https://user-images.githubusercontent.com/75195383/163530796-6e21684d-82e4-40f9-9e4d-4c834028e707.png) diff --git a/website/content/terminal/portfolio/so/_index.md b/website/content/terminal/portfolio/so/_index.md new file mode 100644 index 00000000000..0beb718ddb4 --- /dev/null +++ b/website/content/terminal/portfolio/so/_index.md @@ -0,0 +1,21 @@ +``` +usage: so [-t TARGET_RETURN] [-a] [-w WINDOW] [-h] +``` + +Provides the sortino ratio of the selected portfolio. + +The sortino ratio is very similar to the sharpe ratio, but different in a crucial way. Sharpe ratio punishes the +standard deviation of positive return. The sortino ratio only punishes standard deviation of negative returns. For +more, read: http://www.redrockcapital.com/Sortino__A__Sharper__Ratio_Red_Rock_Capital.pdf + +``` +optional arguments: + -t TARGET_RETURN, --target TARGET_RETURN + Target return (default: 0) + -a, --adjusted If one should adjust the sortino ratio inorder to make it comparable to the sharpe ratio + (default: False) + -w WINDOW, --window WINDOW + Rolling window length (default: 252) + -h, --help show this help message (default: False) +``` +![image](https://user-images.githubusercontent.com/75195383/163530932-e112931d-4820-404b-8f51-8a126391883a.png)