mirror of
https://github.com/OpenBB-finance/OpenBB.git
synced 2026-10-28 21:12:16 +00:00
* Fixes * Update stocks_helper.py * update git-actions set-output to new format * Update stocks_helper.py * Update terminal_helper.py * removed LineAnnotateDrawer from qa_view * lint * few changes * updates * sdk auto gen modules done * Update stocks_helper.py * updates to changed imports, and remove first sdk_modules * Update generate_sdk.py * Update generate_sdk.py * pylint * revert stocks_helper * Update generate_sdk.py * Update sdk.py * Update generate_sdk.py * full auto generation, added sdk.py/controllers creation * missed enable forecasting * added running black in subprocess after sdk files generation completes * removed deleted sdk_arg_logger * comment out tests * property doc fix * clean up * Update generate_sdk.py * make trailmap classes useable for doc generation * Update generate_sdk.py * added lineon to trailmap class for linking to func in markdown * changed lineon to dict * added full_path to trailmap for linking in docs * updated portfolio * feat: initial files * feat: added meta head * feat: added funcdef * added func_def to trailmap attributes for markdown in docs, added missing type hints to covid functions * feat: added view and merged with jaun * Update generate_sdk.py * Update generate_sdk.py * Update generate_sdk.py * Update generate_sdk.py * init * fix returns * fix: random stuff * fix: random * fixed encoding issue on windows * fix: generate tabs * update * Update generate_sdk_markdown.py * Create .pydocstyle.ini * added type hint classes for views * fixes * alt, ba * alt-economy * Update finviz_compare_model.py * fixs * Update substack_model.py * Update generate_sdk.py * last of my section * porfolio * po * Update optimizer_model.py * fixing more things * few more * keys done * update * fixes * Update generate_sdk_markdown.py * Update generate_sdk_markdown.py * mypy forecast fix * Update generate_sdk_markdown.py * Update generate_sdk_markdown.py * Update generate_sdk_markdown.py * fixes * forecast fixes * one more fix * Update coinbase_model.py * Update generate_sdk_markdown.py Co-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com> Co-authored-by: James Maslek <jmaslek11@gmail.com> Co-authored-by: jose-donato <zmcdonato@gmail.com> Co-authored-by: andrewkenreich <andrew.kenreich@gmail.com>
108 lines
3.1 KiB
Python
108 lines
3.1 KiB
Python
"""Factors model"""
|
|
__docformat__ = "numpy"
|
|
|
|
import logging
|
|
from io import BytesIO
|
|
from typing import Tuple
|
|
from urllib.request import urlopen
|
|
from zipfile import ZipFile
|
|
|
|
import pandas as pd
|
|
import statsmodels.api as sm
|
|
import yfinance as yf
|
|
|
|
from openbb_terminal.decorators import log_start_end
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
@log_start_end(log=logger)
|
|
def get_fama_raw() -> pd.DataFrame:
|
|
"""Gets base Fama French data to calculate risk
|
|
|
|
Returns
|
|
-------
|
|
fama : pd.DataFrame
|
|
A data with fama french model information
|
|
"""
|
|
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
|
|
|
|
|
|
@log_start_end(log=logger)
|
|
def get_historical_5(symbol: str) -> pd.DataFrame:
|
|
"""Get 5 year monthly historical performance for a ticker with dividends filtered
|
|
|
|
Parameters
|
|
----------
|
|
symbol : str
|
|
A ticker symbol in string form
|
|
|
|
Returns
|
|
-------
|
|
data : pd.DataFrame
|
|
A dataframe with historical information
|
|
"""
|
|
tick = yf.Ticker(symbol)
|
|
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
|
|
|
|
|
|
@log_start_end(log=logger)
|
|
def capm_information(symbol: str) -> Tuple[float, float]:
|
|
"""Provides information that relates to the CAPM model
|
|
|
|
Parameters
|
|
----------
|
|
symbol : str
|
|
A ticker symbol in string form
|
|
|
|
Returns
|
|
-------
|
|
Tuple[float, float]
|
|
The beta for a stock, The systematic risk for a stock
|
|
"""
|
|
df_f = get_fama_raw()
|
|
df_h = get_historical_5(symbol)
|
|
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"]
|
|
sy = model.rsquared
|
|
return beta, sy
|