diff --git a/data.txt b/data.txt new file mode 100644 index 00000000000..585322d7de1 --- /dev/null +++ b/data.txt @@ -0,0 +1 @@ +{"installed": true} diff --git a/gamestonk_terminal/stocks/quantitative_analysis/README.md b/gamestonk_terminal/stocks/quantitative_analysis/README.md index a82c3b02159..4aa3c596c8f 100644 --- a/gamestonk_terminal/stocks/quantitative_analysis/README.md +++ b/gamestonk_terminal/stocks/quantitative_analysis/README.md @@ -20,6 +20,9 @@ This menu aims to perform exploratory data analysis on a pre-loaded stock, and t * detects abrupt changes using cumulative sum algorithm * [acf](#acf) * (partial) auto-correlation function differentials +* [capm](#capm) + * capital asset pricing model + ## summary @@ -132,3 +135,15 @@ Auto-Correlation and Partial Auto-Correlation Functions for diff and diff diff s * -l : maximum lags to display in plots. Default 40. ![acf](https://user-images.githubusercontent.com/25267873/112733336-637c5d00-8f37-11eb-9aae-38e75dff9ad2.png) + + +## capm + +```text +usage: capm +``` + +Capital asset pricing model for a given stock. + + +![capm] diff --git a/gamestonk_terminal/stocks/quantitative_analysis/factors_model.py b/gamestonk_terminal/stocks/quantitative_analysis/factors_model.py new file mode 100644 index 00000000000..57822c05dfb --- /dev/null +++ b/gamestonk_terminal/stocks/quantitative_analysis/factors_model.py @@ -0,0 +1,78 @@ +"""Factors model""" +__docformat__ = "numpy" + +from urllib.request import urlopen +from zipfile import ZipFile +from io import BytesIO + +import statsmodels.api as sm +import yfinance as yf +import pandas as pd +import numpy as np + + +def get_fama_raw(): + """Gets base Fama French data to calculate risk""" + with urlopen( + "http://mba.tuck.dartmouth.edu/pages/faculty/ken.french/ftp/F-F_Research_Data_Factors_CSV.zip" + ) as url: + + # Download Zipfile and create pandas DataFrame + with ZipFile(BytesIO(url.read())) as zipfile: + with zipfile.open("F-F_Research_Data_Factors.CSV") as zip_open: + df = pd.read_csv( + zip_open, + header=0, + names=["Date", "MKT-RF", "SMB", "HML", "RF"], + skiprows=3, + ) + + df = df[df["Date"].apply(lambda x: len(str(x).strip()) == 6)] + df["Date"] = df["Date"].astype(str) + "01" + df["Date"] = pd.to_datetime(df["Date"], format="%Y%m%d") + df["MKT-RF"] = pd.to_numeric(df["MKT-RF"], downcast="float") + df["SMB"] = pd.to_numeric(df["SMB"], downcast="float") + df["HML"] = pd.to_numeric(df["HML"], downcast="float") + df["RF"] = pd.to_numeric(df["RF"], downcast="float") + df["MKT-RF"] = df["MKT-RF"] / 100 + df["SMB"] = df["SMB"] / 100 + df["HML"] = df["HML"] / 100 + df["RF"] = df["RF"] / 100 + df = df.set_index("Date") + return df + + +def get_historical_5(ticker: str): + """Get 5 year monthly historical performance for a ticker with dividends filtered""" + tick = yf.Ticker(ticker) + df = tick.history(period="5y", interval="1mo") + df = df[df.index.to_series().apply(lambda x: x.day == 1)] + df = df.drop(["Dividends", "Stock Splits"], axis=1) + df = df.dropna() + return df + + +def capm_information(ticker): + """Provides information that relates to the CAPM model""" + df_f = get_fama_raw() + df_h = get_historical_5(ticker) + df = df_h.join(df_f) + df = df.dropna() + df["Monthly Return"] = df["Close"].pct_change() + df["Excess Monthly Return"] = df["Monthly Return"] - df["RF"] + df["Excess MKT-RF"] = df["MKT-RF"] - df["RF"] + df = df.dropna() + y = df[["Excess Monthly Return"]] + x = df["Excess MKT-RF"] + x = sm.add_constant(x) + model = sm.OLS(y, x).fit() + beta = model.params["Excess MKT-RF"] + beta2 = beta ** 2 + m_variance = np.var(df["Excess MKT-RF"]) + syst = beta2 * m_variance + ss = model.ssr + deg_free = model.df_resid + unsys = ss / deg_free + sy = (syst / (syst + unsys)) * 100 + us = (unsys / (syst + unsys)) * 100 + return beta, m_variance, sy, us diff --git a/gamestonk_terminal/stocks/quantitative_analysis/factors_view.py b/gamestonk_terminal/stocks/quantitative_analysis/factors_view.py new file mode 100644 index 00000000000..99219ee4d1f --- /dev/null +++ b/gamestonk_terminal/stocks/quantitative_analysis/factors_view.py @@ -0,0 +1,15 @@ +"""Factors view""" +__docformat__ = "numpy" + +from gamestonk_terminal.stocks.quantitative_analysis.factors_model import ( + capm_information, +) + + +def capm_view(ticker): + """A view that displays information for the CAPM model.""" + beta, m_variance, sy, us = capm_information(ticker) + print(f"Beta:\t\t\t{beta:.2f}") + print(f"Market Variance:\t{m_variance:.4f}") + print(f"Systematic Risk:\t{sy:.2f}%") + print(f"Unsystematic Risk:\t{us:.2f}%\n") diff --git a/gamestonk_terminal/stocks/quantitative_analysis/qa_controller.py b/gamestonk_terminal/stocks/quantitative_analysis/qa_controller.py index 2a196f69714..202b930d461 100644 --- a/gamestonk_terminal/stocks/quantitative_analysis/qa_controller.py +++ b/gamestonk_terminal/stocks/quantitative_analysis/qa_controller.py @@ -24,6 +24,7 @@ from gamestonk_terminal.helper_funcs import ( parse_known_args_and_warn, ) from gamestonk_terminal.menu import session +from gamestonk_terminal.stocks.quantitative_analysis.factors_view import capm_view class QaController: @@ -49,6 +50,7 @@ class QaController: "unitroot", "goodness", "unitroot", + "capm", ] CHOICES += CHOICES_COMMANDS @@ -116,6 +118,7 @@ Rolling Metrics: Other: decompose decomposition in cyclic-trend, season, and residuals of prices cusum detects abrupt changes using cumulative sum algorithm of prices + capm capital asset pricing model """ print(help_str) @@ -768,6 +771,26 @@ Other: except Exception as e: print(e, "\n") + def call_capm(self, other_args: List[str]): + """Process capm command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="capm", + description=""" + Provides detailed information about a stock's risk compared to the market risk. + """, + ) + + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + capm_view(self.ticker) + + except Exception as e: + print(e, "\n") + def menu(ticker: str, start: datetime, interval: str, stock: pd.DataFrame): """Statistics Menu""" diff --git a/gamestonk_terminal/stocks/technical_analysis/ta_controller.py b/gamestonk_terminal/stocks/technical_analysis/ta_controller.py index 0f0954ed1ca..3ca1324e2d4 100644 --- a/gamestonk_terminal/stocks/technical_analysis/ta_controller.py +++ b/gamestonk_terminal/stocks/technical_analysis/ta_controller.py @@ -1,6 +1,7 @@ """Technical Analysis Controller Module""" __docformat__ = "numpy" # pylint:disable=too-many-lines +# pylint:disable=R0904 import argparse import os diff --git a/website/content/stocks/quantitative_analysis/capm/_index.md b/website/content/stocks/quantitative_analysis/capm/_index.md new file mode 100644 index 00000000000..0c63e6f6d75 --- /dev/null +++ b/website/content/stocks/quantitative_analysis/capm/_index.md @@ -0,0 +1,12 @@ +```text +usage: capm [-h] +``` + +Capital asset pricing model + +``` +optional arguments: + -h, --help show this help message (default: False) +``` + +![capm] diff --git a/website/data/menu/main.yml b/website/data/menu/main.yml index 051c91d7ccb..e6bf380fe48 100755 --- a/website/data/menu/main.yml +++ b/website/data/menu/main.yml @@ -501,6 +501,8 @@ main: ref: "/stocks/quantitative_analysis/decompose" - name: cusum ref: "/stocks/quantitative_analysis/cusum" + - name: capm + ref: "/stocks/quantitative_analysis/capm" - name: prediction techniques ref: "/stocks/prediction_techniques" sub: