Added Report Text (#886)

* Added basic paragraph

* Updated rmr with new format

* Added beta text

* Simplified get_rolling_beta

* Didier changes

* Removed advice and lowercased strings

* Didn't wait

* Fixed wording

* Added quantity multiplication

* Removed plot_ef, I don't think its operating properly

* wording changes, fixed beta

* Fixed cash error

* Added docstrings

Co-authored-by: Colin Delahunty <colindelahunty@Colins-Air.indiana.edu>
Co-authored-by: Colin Delahunty <colindelahunty@Colins-MacBook-Air.local>
This commit is contained in:
Colin Delahunty
2021-11-03 12:30:43 -04:00
committed by GitHub
parent a13be8d678
commit f3d6dd1db1
10 changed files with 315 additions and 87 deletions

1
.gitignore vendored
View File

@@ -14,6 +14,7 @@ exports/*
.coverage
htmlcov
gamestonk_terminal/reports/stored/*
gamestonk_terminal/portfolio/portfolios/*
# Jupyter Lab Extension build files
jupyterlab/*/*.bundle.*

View File

@@ -280,7 +280,7 @@ Graphs:
"-t",
"--type",
dest="type",
type=str,
type=lambda s: s.lower(),
choices=["stock", "cash"], # "bond", "option", "crypto",
default="stock",
help="Type of asset to add",
@@ -326,10 +326,10 @@ Graphs:
parser.add_argument(
"-a",
"--action",
type=str,
type=lambda s: s.lower(),
dest="action",
choices=["buy", "sell", "interest", "deposit", "withdrawal"],
default="buy",
default="deposit" if "cash" in other_args else "buy",
help="Select what you did in the transaction",
)
if other_args:
@@ -408,7 +408,7 @@ Graphs:
val, hist = portfolio_model.convert_df(self.portfolio)
if not val.empty:
portfolio_view.annual_report(val, hist, ns_parser.market)
portfolio_view.Report(val, hist, ns_parser.market, 365).generate_report()
@try_except
def call_rmr(self, other_args: List[str]):
@@ -439,7 +439,8 @@ Graphs:
val, _ = portfolio_model.convert_df(self.portfolio)
if not val.empty:
df_m = yfinance_model.get_market(val.index[0], ns_parser.market)
portfolio_view.plot_overall_return(val, df_m, 365, ns_parser.market, True)
returns, _ = portfolio_model.get_return(val, df_m, 365)
portfolio_view.plot_overall_return(returns, ns_parser.market, True)
else:
print("Cannot generate a graph from an empty dataframe\n")

View File

@@ -19,3 +19,44 @@ def is_ticker(ticker: str) -> bool:
"""
item = yf.Ticker(ticker)
return "previousClose" in item.info
def beta_word(beta: float) -> str:
"""Describe a beta
Parameters
----------
beta : float
The beta for a portfolio
Returns
----------
text : str
The description of the beta
"""
if abs(1 - beta) > 3:
part = "extremely "
elif abs(1 - beta) > 2:
part = "very "
elif abs(1 - beta) > 1:
part = ""
else:
part = "moderately "
return part + "high" if beta > 1 else "low"
def clean_name(name: str) -> str:
"""Clean a name to a ticker
Parameters
----------
name : str
The value to be cleaned
Returns
----------
text : str
A cleaned value
"""
return name.replace("beta_", "").upper()

View File

@@ -8,8 +8,14 @@ from typing import List
import numpy as np
import pandas as pd
import statsmodels.api as sm
from statsmodels.regression.rolling import RollingOLS
from gamestonk_terminal.portfolio import portfolio_view, yfinance_model
from gamestonk_terminal.portfolio import (
portfolio_view,
yfinance_model,
portfolio_helper,
)
# pylint: disable=E1136
# pylint: disable=unsupported-assignment-operation
@@ -153,6 +159,7 @@ def add_values(
if len(cash_vals.index) > 0:
for _, sub_row in cash_vals.iterrows():
amount = sub_row["Price"]
quantity = sub_row["Quantity"]
if sub_row["Side"] == "deposit":
d = 1
elif sub_row["Side"] == "withdrawal":
@@ -160,10 +167,10 @@ def add_values(
else:
raise ValueError("Cash type must be deposit or withdrawal")
log.at[index, ("Cash", "Cash")] = (
log.at[index, ("Cash", "Cash")] + d * amount
log.at[index, ("Cash", "Cash")] + d * amount * quantity
)
log.at[index, ("Cash", "User")] = (
log.at[index, ("Cash", "User")] + d * amount
log.at[index, ("Cash", "User")] + d * amount * quantity
)
return log
@@ -300,8 +307,12 @@ def get_return(df: pd.DataFrame, df_m: pd.DataFrame, n: int) -> pd.DataFrame:
+ (0 if "holdings" not in comb.columns else comb["holdings"].shift(1))
)
comb["return"] = comb["return"].fillna(1)
variance = np.var(comb["return"])
comb["return"] = comb["return"].cumprod() - 1
return comb
comb[("Market", "Return")] = (
comb[("Market", "Close")] - comb[("Market", "Close")][0]
) / comb[("Market", "Close")][0]
return comb, variance
def get_rolling_beta(
@@ -330,22 +341,91 @@ def get_rolling_beta(
res = df.div(df.sum(axis=1), axis=0)
res = res.fillna(0)
comb = pd.merge(
hist["Close"], mark["Market"], how="left", left_index=True, right_index=True
hist["Close"], mark["Market"], how="outer", left_index=True, right_index=True
)
comb = comb.fillna(method="ffill")
df_var = comb.rolling(252).var().unstack()["Close"].to_frame(name="var")
for col in hist["Close"].columns:
df1 = (
comb.rolling(252).cov().unstack()[col]["Close"].to_frame(name=f"cov_{col}")
)
df_var = pd.merge(df_var, df1, how="left", left_index=True, right_index=True)
df_var[f"beta_{col}"] = df_var[f"cov_{col}"] / df_var["var"]
final = pd.merge(res, df_var, how="left", left_index=True, right_index=True)
final = final.fillna(method="ffill")
final = final.drop(columns=["var"] + [f"cov_{x}" for x in uniques])
exog = sm.add_constant(comb["Close"])
rols = RollingOLS(comb[col], exog, window=252)
rres = rols.fit()
res[f"beta_{col}"] = rres.params["Close"]
final = res.fillna(method="ffill")
for uni in uniques:
final[f"prod_{uni}"] = final[uni] * final[f"beta_{uni}"]
dropped = final[[f"beta_{x}" for x in uniques]].copy()
final = final.drop(columns=[f"beta_{x}" for x in uniques] + uniques)
final["total"] = final.sum(axis=1)
final = final[final.index >= datetime.now() - timedelta(days=n + 1)]
return final
comb = pd.merge(final, dropped, how="left", left_index=True, right_index=True)
return comb
def get_main_text(df: pd.DataFrame) -> str:
"""Get main performance summary from a dataframe with returns
Parameters
----------
df : pd.DataFrame
Stock holdings and returns with market returns
Returns
----------
t : str
The main summary of performance
"""
d_debt = np.where(df[("Cash", "Cash")] > 0, 0, 1)
bcash = 0 if df[("Cash", "Cash")][0] > 0 else abs(df[("Cash", "Cash")][0])
ecash = 0 if df[("Cash", "Cash")][-1] > 0 else abs(df[("Cash", "Cash")][-1])
bdte = bcash / (df["holdings"][0] - bcash)
edte = ecash / (df["holdings"][-1] - ecash)
if sum(d_debt) > 0:
t_debt = (
f"Beginning debt to equity was {bdte:.2%} and ending debt to equity was"
f" {edte:.2%}. Debt adds risk to a portfolio by amplifying the gains and losses when"
" equities change in value."
)
if bdte > 1 or edte > 1:
t_debt += " Debt to equity ratios above one represent a significant amount of risk."
else:
t_debt = (
"Margin was not used this year. This reduces this risk of the portfolio."
)
string = (
f"Your portfolio's performance for the period was {df['return'][-1]:.2%}. This was"
f" {'greater' if df['return'][-1] > df[('Market', 'Return')][-1] else 'less'} than"
f" the market return of {df[('Market', 'Return')][-1]:.2%}. The variance for the"
f" portfolio is {np.var(df['return']):.2%}, while the variance for the market was"
f" {np.var(df[('Market', 'Return')]):.2%}. {t_debt} The following report details"
f" various analytics from the portfolio. Read below to see the moving beta for a"
f" stock."
)
return string
def get_beta_text(df: pd.DataFrame) -> str:
"""Get beta summary for a dataframe
Parameters
----------
df : pd.DataFrame
The beta history of the stock
Returns
----------
t : str
The beta history for a ticker
"""
betas = df[list(filter(lambda score: "beta" in score, list(df.columns)))]
high = betas.idxmax(axis=1)
low = betas.idxmin(axis=1)
string = (
"Beta is how strongly a portfolio's movements correlate with the market's movements."
" A stock with a high beta is considered to be riskier. The beginning beta for the period"
f" was {portfolio_helper.beta_word(df['total'][0])} at {df['total'][0]:.2f}. This went"
f" {'up' if df['total'][-1] > df['total'][0] else 'down'} to"
f" {portfolio_helper.beta_word(df['total'][-1])} at {df['total'][-1]:.2f} by the end"
f" of the period. The ending beta was pulled {'up' if df['total'][-1] > 1 else 'down'} by"
f" {portfolio_helper.clean_name(high[-1] if df['total'][-1] > 1 else low[-1])}, which had"
f" an ending beta of {df[high[-1]][-1] if df['total'][-1] > 1 else df[low[-1]][-1]:.2f}."
)
return string

View File

@@ -14,9 +14,8 @@ from tabulate import tabulate
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.config_plot import PLOT_DPI
from gamestonk_terminal.helper_funcs import plot_autoscale
from gamestonk_terminal.helper_funcs import plot_autoscale, get_rf
from gamestonk_terminal.portfolio.portfolio_optimization import optimizer_model
from gamestonk_terminal.helper_funcs import get_rf
d_period = {
"1d": "[1 Day]",

View File

@@ -1,21 +1,27 @@
"""Portfolio View"""
__docformat__ = "numpy"
from typing import List
from datetime import datetime
from io import BytesIO
import os
from os import path
import pandas as pd
from tabulate import tabulate
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader
from matplotlib.lines import Line2D
from matplotlib import pyplot as plt
import matplotlib.ticker as mtick
from pypfopt import plotting
from gamestonk_terminal.config_plot import PLOT_DPI
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.portfolio import portfolio_model, yfinance_model
from gamestonk_terminal.portfolio import reportlab_helpers
from gamestonk_terminal.helper_funcs import get_rf
from gamestonk_terminal.portfolio.portfolio_optimization import optimizer_model
def load_info():
@@ -72,18 +78,14 @@ def show_df(df: pd.DataFrame, show: bool) -> None:
def plot_overall_return(
df: pd.DataFrame, df_m: pd.DataFrame, n: int, m_tick: str, plot: bool = False
comb: pd.DataFrame, m_tick: str, plot: bool = False
) -> ImageReader:
"""Generates overall return graph
Parameters
----------
df : pd.DataFrame
The dataframe to be analyzed
df_m : pd.DataFrame
The dataframe for historical market performance
n : int
The number of days to include in chart
comb : pd.DataFrame
Dataframe with returns
m_tick : str
The ticker for the market asset
plot : bool
@@ -95,10 +97,6 @@ def plot_overall_return(
Overal return graph
"""
plt.close("all")
comb = portfolio_model.get_return(df, df_m, n)
comb[("Market", "Return")] = (
comb[("Market", "Close")] - comb[("Market", "Close")][0]
) / comb[("Market", "Close")][0]
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(comb.index, comb["return"], color="tab:blue", label="Portfolio")
ax.plot(comb.index, comb[("Market", "Return")], color="orange", label=m_tick)
@@ -119,7 +117,10 @@ def plot_overall_return(
fig.set_facecolor("white")
ax.set_title(
"%s - %s"
% (df.index[:1][0].strftime("%Y/%m/%d"), df.index[-1:][0].strftime("%Y/%m/%d")),
% (
comb.index[:1][0].strftime("%Y/%m/%d"),
comb.index[-1:][0].strftime("%Y/%m/%d"),
),
fontsize=12,
color="gray",
)
@@ -138,21 +139,13 @@ def plot_overall_return(
return ImageReader(imgdata)
def plot_rolling_beta(
df: pd.DataFrame, hist: pd.DataFrame, mark: pd.DataFrame, n: int
) -> ImageReader:
def plot_rolling_beta(df: pd.DataFrame) -> ImageReader:
"""Returns a chart with the portfolio's rolling beta
Parameters
----------
df : pd.DataFrame
The dataframe to be analyzed
hist : pd.DataFrame
A dataframe of historical returns
market : pd.DataFrame
A dataframe of SPY returns
n : int
The number of days to include in chart
Returns
----------
@@ -160,13 +153,11 @@ def plot_rolling_beta(
Rolling beta graph
"""
plt.close("all")
final = portfolio_model.get_rolling_beta(df, hist, mark, n)
# final[final == 0] = np.nan
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(
final.index,
final["total"],
df.index,
df["total"],
color="tab:blue",
)
@@ -186,7 +177,7 @@ def plot_rolling_beta(
fig.set_facecolor("white")
ax.set_title(
"%s - %s"
% (df.index[:1][0].strftime("%Y/%m/%d"), df.index[-1:][0].strftime("%Y/%m/%d")),
% (df.index[:1][0].strftime("%Y-%m-%d"), df.index[-1:][0].strftime("%Y-%m-%d")),
fontsize=12,
color="gray",
)
@@ -198,38 +189,133 @@ def plot_rolling_beta(
return ImageReader(imgdata)
def annual_report(df: pd.DataFrame, hist: pd.DataFrame, m_tick: str) -> None:
"""Generates an annual report
def plot_ef(
stocks: List[str],
variance: float,
per_ret: float,
period: str = "3mo",
n_portfolios: int = 300,
risk_free: bool = False,
):
"""Display efficient frontier
Parameters
----------
df : pd.DataFrame
The dataframe to be analyzed
m_tick : str
The ticker for the market asset
hist : pd.DataFrame
A dataframe of historical returns
stocks : List[str]
List of the stocks to be included in the weights
variance : float
The variance for the portfolio
per_ret : float
The portfolio's return for the portfolio
period : str
The period to track
n_portfolios : int
The number of portfolios to generate
risk_free : bool
Include the risk-free asset
"""
df_m = yfinance_model.get_market(df.index[0], m_tick)
dire = os.path.dirname(os.path.abspath(__file__)).replace(
"gamestonk_terminal", "exports"
fig, ax = plt.subplots(figsize=(10, 5), dpi=PLOT_DPI)
ef, rets, stds = optimizer_model.generate_random_portfolios(
[x.upper() for x in stocks], period, n_portfolios
)
sharpes = rets / stds
ax.scatter(stds, rets, marker=".", c=sharpes, cmap="viridis_r")
plotting.plot_efficient_frontier(ef, ax=ax, show_assets=True)
# Find the tangency portfolio
rfrate = get_rf()
ret_sharpe, std_sharpe, _ = ef.portfolio_performance(risk_free_rate=rfrate)
ax.scatter(std_sharpe, ret_sharpe, marker="*", s=100, c="r", label="Max Sharpe")
plt.plot(variance, per_ret, "ro", label="Portfolio")
# Add risk free line
if risk_free:
y = ret_sharpe * 1.2
m = (ret_sharpe - rfrate) / std_sharpe
x2 = (y - rfrate) / m
x = [0, x2]
y = [rfrate, y]
line = Line2D(x, y, color="#FF0000", label="Capital Allocation Line")
ax.set_xlim(xmin=min(stds) * 0.8)
ax.add_line(line)
ax.set_title(f"Efficient Frontier simulating {n_portfolios} portfolios")
ax.legend()
fig.tight_layout()
ax.grid(b=True, which="major", color="#666666", linestyle="-")
path = os.path.abspath(
os.path.join(
dire,
f"ar_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf",
if gtff.USE_ION:
plt.ion()
imgdata = BytesIO()
fig.savefig(imgdata, format="png")
imgdata.seek(0)
return ImageReader(imgdata)
class Report:
def __init__(self, df: pd.DataFrame, hist: pd.DataFrame, m_tick: str, n: int):
"""Generate financial reports.
Financial reports allow users to show the how they have been performing in
trades. This allows for a simple way to show progress and analyze metrics
that track portfolio performance
Parameters
----------
df : pd.DataFrame
The dataframe with previous holdings information
hist : pd.DataFrame
The dataframe with previous prices for stocks in the portfolio
m_tick : str
The market asset to be identified
n : int
The number of days to analyze
Attributes
----------
generate_report : None
Generates a report with the given parameters
generate_pg1 : None
Creates the first page of the PDF report
generate_pg2 : None
Creates the second page of the PDF report
"""
self.df = df
self.hist = hist
self.m_tick = m_tick
self.df_m = yfinance_model.get_market(self.df.index[0], self.m_tick)
self.returns, self.variance = portfolio_model.get_return(df, self.df_m, n)
def generate_report(self) -> None:
d = path.dirname(path.abspath(__file__)).replace(
"gamestonk_terminal", "exports"
)
)
report = canvas.Canvas(path, pagesize=letter)
reportlab_helpers.base_format(report, "Overview")
report.drawImage(
plot_overall_return(df, df_m, 365, m_tick, False), 15, 360, 600, 300
)
report.showPage()
reportlab_helpers.base_format(report, "Portfolio Analysis")
if "Holding" in df.columns:
report.drawImage(plot_rolling_beta(df, hist, df_m, 365), 15, 360, 600, 300)
report.save()
loc = path.abspath(
path.join(
d,
f"ar_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf",
)
)
report = canvas.Canvas(loc, pagesize=letter)
reportlab_helpers.base_format(report, "Overview")
self.generate_pg1(report)
self.generate_pg2(report, self.df_m)
report.save()
print("File save in:\n", loc, "\n")
print("File save in:\n", path, "\n")
def generate_pg1(self, report: canvas.Canvas) -> None:
report.drawImage(
plot_overall_return(self.returns, self.m_tick, False), 15, 400, 600, 300
)
main_t = portfolio_model.get_main_text(self.returns)
reportlab_helpers.draw_paragraph(report, main_t, 30, 410, 550, 200)
report.showPage()
def generate_pg2(self, report: canvas.Canvas, df_m: pd.DataFrame) -> None:
reportlab_helpers.base_format(report, "Portfolio Analysis")
if "Holding" in self.df.columns:
rolling_beta = portfolio_model.get_rolling_beta(
self.df, self.hist, df_m, 365
)
report.drawImage(plot_rolling_beta(rolling_beta), 15, 400, 600, 300)
main_t = portfolio_model.get_beta_text(rolling_beta)
reportlab_helpers.draw_paragraph(report, main_t, 30, 410, 550, 200)
# report.drawImage(plot_ef(uniques, self.variance, self.returns["return"][-1]), 15, 65, 600, 300)

View File

@@ -0,0 +1,11 @@
Name,Type,Quantity,Date,Price,Fees,Premium,Side
cash,cash,1.0,2019/6/22,2000.0,,,deposit
amzn,stock,300.0,2019/10/21,2000.0,20.0,,Buy
amzn,stock,100.0,2019/10/21,2100.0,20.0,,Sell
amc,stock,400.0,2019/10/21,20.0,20.0,,Buy
tsla,stock,10.0,2020/10/10,200.0,20.0,,Sell
gme,stock,1.0,2020/10/20,50.0,,,Buy
gme,stock,1.0,2021/10/20,50.0,,,Buy
amzn,stock,50.0,2021/10/20,2000.0,20.0,,Sell
tsla,stock,15.0,2021/10/12,200.0,20.0,,Sell
tsla,stock,15.0,2021/10/21,20,0,,Interest
1 Name Type Quantity Date Price Fees Premium Side
2 cash cash 1.0 2019/6/22 2000.0 deposit
3 amzn stock 300.0 2019/10/21 2000.0 20.0 Buy
4 amzn stock 100.0 2019/10/21 2100.0 20.0 Sell
5 amc stock 400.0 2019/10/21 20.0 20.0 Buy
6 tsla stock 10.0 2020/10/10 200.0 20.0 Sell
7 gme stock 1.0 2020/10/20 50.0 Buy
8 gme stock 1.0 2021/10/20 50.0 Buy
9 amzn stock 50.0 2021/10/20 2000.0 20.0 Sell
10 tsla stock 15.0 2021/10/12 200.0 20.0 Sell
11 tsla stock 15.0 2021/10/21 20 0 Interest

View File

@@ -4,6 +4,8 @@ __docformat__ = "numpy"
from datetime import datetime
from reportlab.pdfgen import canvas
from reportlab.lib.styles import ParagraphStyle
from reportlab.platypus import Paragraph
def base_format(report: canvas.Canvas, header: str) -> None:
@@ -18,13 +20,20 @@ def base_format(report: canvas.Canvas, header: str) -> None:
"""
report.setLineWidth(0.3)
report.setFont("Helvetica", 12)
report.drawString(30, 750, "Gamestonk Terminal")
report.drawString(500, 750, datetime.now().strftime("%Y/%m/%d"))
report.drawString(275, 725, "Annual Report")
report.setFillColorRGB(255, 0, 0)
report.drawString(200, 710, "Warning: currently only analyzes stocks")
report.setFillColorRGB(0, 0, 0)
report.line(50, 700, 580, 700)
report.drawString(30, 760, "Gamestonk Terminal")
report.drawString(500, 760, datetime.now().strftime("%Y/%m/%d"))
report.drawString(275, 750, "Annual Report")
report.line(50, 730, 580, 730)
report.setFont("Helvetica", 20)
report.drawString(50, 670, header)
report.drawString(50, 705, header)
report.setFont("Helvetica", 12)
def draw_paragraph(
report: canvas.Canvas, msg: str, x: int, y: int, max_width: int, max_height: int
) -> None:
message_style = ParagraphStyle("Normal")
message = msg.replace("\n", "<br />")
paragraph = Paragraph(message, style=message_style)
_, h = paragraph.wrap(max_width, max_height)
paragraph.drawOn(report, x, y - h)

View File

@@ -25,7 +25,7 @@ def get_stocks(tickers: List[str], start: datetime) -> pd.DataFrame:
"""
df = yf.download(
tickers=tickers,
start=start - timedelta(days=255),
start=start - timedelta(days=365),
interval="1d",
progress=False,
)
@@ -79,7 +79,7 @@ def get_market(start: datetime, ticker: str = "SPY") -> pd.DataFrame:
"""
tick = yf.Ticker(ticker)
df = tick.history(
start=start - timedelta(days=255),
start=start - timedelta(days=365),
interval="1d",
)["Close"]
return df.to_frame(name=("Market", "Close"))

View File

@@ -1,5 +1,5 @@
```
usage: ret [-m MARKET] [-h]
usage: rmr [-m MARKET] [-h]
```
Show portfolio returns versus market returns