Added risk indicators (#775)

* Added risk indicators

* Fixed issues

* Updated description

* Moved to QA

* Added website

* Added website

Co-authored-by: Colin Delahunty <colindelahunty@Colins-Air.indiana.edu>
This commit is contained in:
Colin Delahunty
2021-10-03 17:26:48 -04:00
committed by GitHub
parent f3800fd566
commit 0b0cf88a56
8 changed files with 147 additions and 0 deletions

1
data.txt vendored Normal file
View File

@@ -0,0 +1 @@
{"installed": true}

View File

@@ -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 <a name="summary"></a>
@@ -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 <a name="capm"></a>
```text
usage: capm
```
Capital asset pricing model for a given stock.
![capm]

View File

@@ -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

View File

@@ -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")

View File

@@ -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"""

View File

@@ -1,6 +1,7 @@
"""Technical Analysis Controller Module"""
__docformat__ = "numpy"
# pylint:disable=too-many-lines
# pylint:disable=R0904
import argparse
import os

View File

@@ -0,0 +1,12 @@
```text
usage: capm [-h]
```
Capital asset pricing model
```
optional arguments:
-h, --help show this help message (default: False)
```
![capm]

View File

@@ -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: