Files
OpenBB/openbb_terminal/reports/templates/equity.ipynb
2022-11-22 10:03:26 +00:00

1466 lines
42 KiB
Plaintext
Vendored

{
"cells": [
{
"cell_type": "markdown",
"id": "70ba2c8a",
"metadata": {},
"source": [
"## Notebook setup"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "driven-billion",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import io\n",
"import warnings\n",
"import datetime\n",
"import numpy as np\n",
"import base64\n",
"import dotenv\n",
"\n",
"import matplotlib.pyplot as plt\n",
"import matplotlib_inline.backend_inline\n",
"\n",
"from IPython.display import HTML\n",
"\n",
"# import sys\n",
"# sys.path.append('../../')\n",
"\n",
"from openbb_terminal.reports import widget_helpers as widgets\n",
"from openbb_terminal.sdk import openbb\n",
"from openbb_terminal import config_terminal as cfg\n",
"from openbb_terminal.helper_classes import TerminalStyle\n",
"from openbb_terminal.core.config.paths import USER_ENV_FILE, REPOSITORY_DIRECTORY\n",
"\n",
"%matplotlib inline\n",
"matplotlib_inline.backend_inline.set_matplotlib_formats(\"svg\")\n",
"warnings.filterwarnings(\"ignore\")\n",
"\n",
"# Detect if prediction capabilities are present. If they are not, disable prediction in the rest of the script\n",
"# so that the report can still be generated without prediction results.\n",
"# predictions = True\n",
"# try:\n",
"# openbb.stocks.pred.models\n",
"# except Exception as e:\n",
"# predictions = False\n",
"\n",
"# TODO Fix predictions virtual path on api refactored\n",
"\n",
"predictions = False"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c3fe7db5-ec6a-42cf-9e66-52dc1de22370",
"metadata": {},
"outputs": [],
"source": [
"cfg.theme = TerminalStyle(\"light\", \"light\", \"light\")\n",
"\n",
"stylesheet = widgets.html_report_stylesheet()"
]
},
{
"cell_type": "markdown",
"id": "807fda4e",
"metadata": {},
"source": [
"## Select symbol"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "intended-sherman",
"metadata": {
"tags": [
"parameters"
]
},
"outputs": [],
"source": [
"# Parameters that will be replaced when calling this notebook\n",
"# Do not leave parameters blank as notebook will not run otherwise\n",
"symbol = \"msft\"\n",
"report_name = f\"Equity report for {symbol}\""
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a441ddbc-d75b-4a18-84d4-e01b677674d3",
"metadata": {},
"outputs": [],
"source": [
"if \".\" in symbol:\n",
" import sys\n",
"\n",
" sys.exit(0)\n",
"symbol = symbol.upper()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1be26dae-cafe-4a22-80aa-eff296fc1a9b",
"metadata": {},
"outputs": [],
"source": [
"ticker_data = openbb.stocks.load(\n",
" symbol=symbol, start_date=datetime.datetime.now() - datetime.timedelta(days=18 * 30)\n",
")\n",
"ticker_data = openbb.stocks.process_candle(data=ticker_data)\n",
"\n",
"author = \"\"\n",
"report_title = f\"Investment Research Report on {symbol.upper()}\"\n",
"report_date = datetime.datetime.now().strftime(\"%d %B, %Y\")\n",
"report_time = datetime.datetime.now().strftime(\"%H:%M\")\n",
"report_timezone = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo\n",
"report_title, report_date, report_time, report_timezone"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e3b15d6f-dc9e-4f97-aa07-37d949a4e4bb",
"metadata": {},
"outputs": [],
"source": [
"info = openbb.stocks.fa.info(symbol=symbol).transpose()\n",
"\n",
"if info[\"Long business summary\"][0] != \"NA\":\n",
" overview = info[\"Long business summary\"][0]\n",
"else:\n",
" overview = info[\"Long name\"][0]"
]
},
{
"cell_type": "markdown",
"id": "f8a0d747",
"metadata": {},
"source": [
"## Data"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "aca4b6ef",
"metadata": {},
"outputs": [],
"source": [
"(\n",
" df_year_estimates,\n",
" df_quarter_earnings,\n",
" df_quarter_revenues,\n",
") = openbb.stocks.dd.est(symbol=symbol)\n",
"df_quarter_revenues"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c0f0a1ca",
"metadata": {},
"outputs": [],
"source": [
"display_year = sorted(df_year_estimates.columns.tolist())[:3]\n",
"df_year_estimates = df_year_estimates[display_year].head(5)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6976c1d5",
"metadata": {},
"outputs": [],
"source": [
"tables = openbb.etf.news(info[\"Short name\"][0], 5)\n",
"for table in tables:\n",
" table[0].loc[\"link\"] = (\n",
" table[0].loc[\"link\"].apply(lambda x: f'<a href=\"{x}\">{x}</a>')\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "38e38d7c",
"metadata": {},
"outputs": [],
"source": [
"quote_data = openbb.stocks.quote(symbol)\n",
"quote_data"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fde46353",
"metadata": {},
"outputs": [],
"source": [
"df_institutional_shareholders = openbb.stocks.fa.shrs(symbol, holder=\"institutional\")\n",
"df_institutional_shareholders.index += 1\n",
"df_institutional_shareholders"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e101e24e",
"metadata": {},
"outputs": [],
"source": [
"openbb.stocks.fa.shrs(symbol)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "51dfd9d2",
"metadata": {},
"outputs": [],
"source": [
"df_institutional_shareholders = openbb.stocks.fa.shrs(symbol)\n",
"df_institutional_shareholders.index += 1\n",
"df_institutional_shareholders"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3022130e",
"metadata": {},
"outputs": [],
"source": [
"df_sec_filings = openbb.stocks.dd.sec(symbol=symbol)[[\"Type\", \"Category\", \"Link\"]].head(\n",
" 5\n",
")\n",
"df_sec_filings[\"Link\"] = df_sec_filings[\"Link\"].apply(\n",
" lambda x: f'<a href=\"{x}\">{x}</a>'\n",
")\n",
"df_sec_filings"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4662b1ac",
"metadata": {},
"outputs": [],
"source": [
"df_analyst = openbb.stocks.dd.analyst(symbol=symbol)\n",
"print(df_analyst.columns)\n",
"if not df_analyst.empty:\n",
" if \"target\" in df_analyst.columns:\n",
" if \"target_to\" in df_analyst.columns:\n",
" df_analyst[\"target\"] = df_analyst[\"target_to\"].combine_first(\n",
" df_analyst[\"target\"]\n",
" )\n",
" else:\n",
" df_analyst[\"target\"] = df_analyst[\"target_to\"]\n",
" df_analyst = df_analyst[[\"category\", \"analyst\", \"rating\", \"target\"]].rename(\n",
" columns={\n",
" \"category\": \"Category\",\n",
" \"analyst\": \"Analyst\",\n",
" \"rating\": \"Rating\",\n",
" \"target\": \"Price Target\",\n",
" }\n",
" )\n",
"df_analyst"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "df8bdb7d",
"metadata": {},
"outputs": [],
"source": [
"df_rating = openbb.stocks.dd.rating(symbol)\n",
"df_rating"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d0df953b",
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(11, 3), dpi=150)\n",
"openbb.stocks.options.pcr_chart(\n",
" symbol,\n",
" window=30,\n",
" external_axes=[\n",
" ax,\n",
" ],\n",
")\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"pcr_chart = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bd79195c",
"metadata": {},
"outputs": [],
"source": [
"expiry_dates = openbb.stocks.options.expirations(symbol)\n",
"exp = expiry_dates[0]\n",
"option_chain = openbb.stocks.options.chains(symbol, expiration=exp)\n",
"current_price = float(info[\"Previous close\"][0])"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ad6d0c24",
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(11, 3), dpi=150)\n",
"ax.plot(\n",
" option_chain[\"strike\"], option_chain[\"c_Openinterest\"], label=\"Call Open Interest\"\n",
")\n",
"ax.plot(\n",
" option_chain[\"strike\"], option_chain[\"p_Openinterest\"], label=\"Put Open Interest\"\n",
")\n",
"ax.legend()\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"vol_chart = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "be2d1e3a",
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(11, 8), dpi=150)\n",
"ax.plot(option_chain[\"strike\"], option_chain[\"c_Volume\"], label=\"Call Volume\")\n",
"ax.plot(option_chain[\"strike\"], option_chain[\"p_Volume\"], label=\"Put Volume\")\n",
"ax.legend()\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"voi_chart = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "324e2d4b-b2f6-4da3-bac4-ef785ad4e436",
"metadata": {},
"outputs": [],
"source": [
"fig, ax1 = plt.subplots(figsize=(11, 5), dpi=150)\n",
"ax2 = ax1.twinx()\n",
"openbb.stocks.dps.spos_chart(\n",
" symbol=symbol,\n",
" limit=84,\n",
" raw=False,\n",
" export=\"\",\n",
" external_axes=[ax1, ax2],\n",
")\n",
"fig.tight_layout()\n",
"\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"net_short_position = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ac0bfbda-e4b8-4b3b-b8e7-c02639fdb971",
"metadata": {},
"outputs": [],
"source": [
"fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, figsize=(11, 5), dpi=150)\n",
"openbb.stocks.dps.dpotc_chart(symbol=symbol, external_axes=[ax1, ax2])\n",
"fig.tight_layout()\n",
"\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"dark_pools = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "22a7266f",
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(11, 3), dpi=150)\n",
"openbb.stocks.gov.gtrades_chart(\n",
" symbol,\n",
" past_transactions_months=12,\n",
" external_axes=[\n",
" ax,\n",
" ],\n",
")\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"gtrades_chart = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4c670ba3",
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(11, 3), dpi=150)\n",
"openbb.stocks.gov.contracts_chart(\n",
" symbol,\n",
" past_transaction_days=365,\n",
" external_axes=[\n",
" ax,\n",
" ],\n",
")\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"gov_contracts_chart = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "caa3dae2",
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(11, 3), dpi=150)\n",
"openbb.stocks.ba.mentions_chart(\n",
" symbol,\n",
" external_axes=[\n",
" ax,\n",
" ],\n",
")\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"google_mentions_chart = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b77e60d8",
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(11, 3), dpi=150)\n",
"openbb.stocks.ba.regions_chart(\n",
" symbol,\n",
" limit=10,\n",
" external_axes=[\n",
" ax,\n",
" ],\n",
")\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"google_regions_chart = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "78593369",
"metadata": {},
"outputs": [],
"source": [
"similar_companies = openbb.stocks.ca.similar(symbol, source=\"Polygon\")\n",
"similar_companies.append(symbol)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4639665b",
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(11, 3), dpi=150)\n",
"openbb.stocks.ca.hist_chart(\n",
" similar_companies,\n",
" external_axes=[\n",
" ax,\n",
" ],\n",
" normalize=False,\n",
")\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"historical_similar = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "74565e53",
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(11, 3), dpi=150)\n",
"openbb.stocks.ca.hcorr_chart(\n",
" similar_companies,\n",
" external_axes=[\n",
" ax,\n",
" ],\n",
")\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"hcorr_similar = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "936babfd",
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(11, 3), dpi=150)\n",
"openbb.stocks.ca.volume_chart(\n",
" similar_companies,\n",
" external_axes=[\n",
" ax,\n",
" ],\n",
")\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"vol_similar = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "99388d4e",
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(11, 3), dpi=150)\n",
"openbb.stocks.ca.scorr_chart(\n",
" similar_companies,\n",
" external_axes=[\n",
" ax,\n",
" ],\n",
")\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"scorr_similar = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "eaa67343",
"metadata": {},
"outputs": [],
"source": [
"income_comparison = openbb.stocks.ca.income(similar_companies)\n",
"income_comparison"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "13ad71cf",
"metadata": {},
"outputs": [],
"source": [
"try:\n",
" df_related_queries = openbb.stocks.ba.queries(symbol)\n",
" df_related_queries.index += 1\n",
" df_related_queries.index\n",
"except:\n",
" pass"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "58c06129",
"metadata": {},
"outputs": [],
"source": [
"try:\n",
" df_rising_queries = openbb.stocks.ba.rise(symbol)\n",
" df_rising_queries.index += 1\n",
" df_rising_queries\n",
"except:\n",
" pass"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0a467f1a",
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(11, 3), dpi=150)\n",
"openbb.stocks.gov.histcont_chart(\n",
" symbol,\n",
" external_axes=[\n",
" ax,\n",
" ],\n",
")\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"gov_histcont_chart = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "730cae26",
"metadata": {},
"outputs": [],
"source": [
"df_lobbying = openbb.stocks.gov.lobbying(symbol, limit=5)\n",
"df_lobbying"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d8bb53c1-147e-4342-af61-0d0a9cc56e59",
"metadata": {},
"outputs": [],
"source": [
"fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, figsize=(11, 5), dpi=150)\n",
"ax3 = ax1.twinx()\n",
"openbb.stocks.dps.psi_sg_chart(\n",
" symbol=symbol,\n",
" external_axes=[ax1, ax2, ax3],\n",
")\n",
"fig.tight_layout()\n",
"\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"price_vs_short_interest = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "394668e1-1158-4a2b-8a38-04c72a6abdd6",
"metadata": {},
"outputs": [],
"source": [
"fig, (candles, volume) = plt.subplots(nrows=2, ncols=1, figsize=(11, 5), dpi=150)\n",
"openbb.stocks.candle(\n",
" symbol=symbol,\n",
" data=ticker_data,\n",
" use_matplotlib=True,\n",
" external_axes=[candles, volume],\n",
")\n",
"candles.set_xticklabels(\"\")\n",
"fig.tight_layout()\n",
"\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"price_chart = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "900686a3",
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(11, 3), dpi=150)\n",
"openbb.stocks.dd.pt_chart(\n",
" symbol=symbol,\n",
" start_date=\"2022-01-01\",\n",
" data=ticker_data,\n",
" limit=10,\n",
" raw=False,\n",
" external_axes=[ax],\n",
")\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"price_target_chart = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "61d62e1a-199e-481d-b57d-38ab486951be",
"metadata": {},
"outputs": [],
"source": [
"df = openbb.stocks.dd.pt(symbol=symbol)\n",
"avg_ratings_last_30_days = 0\n",
"days = 0\n",
"if not df.empty:\n",
" df_ratings = df[datetime.datetime.now() - datetime.timedelta(days=days) :]\n",
" while df_ratings.empty:\n",
" days += 30\n",
" df_ratings = df[datetime.datetime.now() - datetime.timedelta(days=days) :]\n",
"\n",
" if days > 100:\n",
" break\n",
"\n",
" if not df_ratings.empty:\n",
" avg_ratings_last_30_days = round(np.mean(df_ratings[\"Price Target\"].values), 2)\n",
" else:\n",
" avg_ratings = 0\n",
"\n",
"last_price = round(ticker_data[\"Close\"][-1], 2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f3733ff2",
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(11, 3), dpi=150)\n",
"openbb.stocks.dd.rot_chart(\n",
" symbol=symbol,\n",
" limit=10,\n",
" raw=False,\n",
" export=\"\",\n",
" external_axes=[ax],\n",
")\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"ratings_over_time_chart = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "924f8042-e58a-449c-91a3-7923158ff714",
"metadata": {},
"outputs": [],
"source": [
"fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, figsize=(11, 3), dpi=150)\n",
"openbb.ta.rsi_chart(ticker_data[\"Close\"], external_axes=[ax1, ax2])\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"ta_rsi = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "953a340e-7ea1-4aa3-ae1d-872683dced41",
"metadata": {},
"outputs": [],
"source": [
"df = openbb.ta.rsi(ticker_data[\"Close\"])\n",
"rsi_value = round(df.values[-1][0], 2)\n",
"rsi_value"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "dce71711-20b3-4c69-af52-e0f9a69991f8",
"metadata": {},
"outputs": [],
"source": [
"from sklearn.linear_model import LinearRegression\n",
"\n",
"model = LinearRegression().fit(\n",
" np.array(range(len(ticker_data[\"Close\"][-30:].index))).reshape(-1, 1),\n",
" ticker_data[\"Close\"][-30:].values,\n",
")\n",
"regression_slope = round(model.coef_[0], 2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6272e34b-9511-4b48-9eea-ea882ce9846a",
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"\n",
"df_insider = pd.DataFrame.from_dict(openbb.stocks.ins.lins(symbol=symbol)).head(10)\n",
"df_insider[\"Val ($)\"] = df_insider[\"Value ($)\"].replace({\",\": \"\"}, regex=True)\n",
"df_insider[\"Trade\"] = df_insider.apply(\n",
" lambda row: (-1 * float(row[\"Val ($)\"]))\n",
" if row[\"Transaction\"] == \"Sale\"\n",
" else (float(row[\"Val ($)\"]) if row[\"Transaction\"] == \"Buy\" else 0),\n",
" axis=1,\n",
")\n",
"last_10_insider_trading = round(sum(df_insider[\"Trade\"]) / 1_000_000, 2)\n",
"df_insider = df_insider.drop(columns=[\"Val ($)\", \"Trade\"])\n",
"df_insider"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "29254666-58c6-4686-87e6-2635ad8387e2",
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(11, 3), dpi=150)\n",
"openbb.stocks.ba.headlines_chart(symbol=symbol, external_axes=[ax])\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"finbrain_sentiment = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b8251b47-8ecc-47be-83f3-d9f108596898",
"metadata": {},
"outputs": [],
"source": [
"df_sentiment_finbrain = openbb.stocks.ca.sentiment(symbols=[symbol])\n",
"finbrain_sentiment_val = float(df_sentiment_finbrain.values[-1][0])"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6fe6e513-d568-41b4-8aa0-37cc578c9dc3",
"metadata": {},
"outputs": [],
"source": [
"(\n",
" watchlist_count,\n",
" n_cases,\n",
" n_bull,\n",
" n_bear,\n",
") = openbb.stocks.ba.bullbear(symbol=symbol)\n",
"stocktwits_sentiment = f\"Watchlist count: {watchlist_count}</br>\"\n",
"if n_cases > 0:\n",
" stocktwits_sentiment += f\"\\nLast {n_cases} sentiment messages:</br>\"\n",
" stocktwits_sentiment += f\"Bullish {round(100*n_bull/n_cases, 2)}%</br>\"\n",
" stocktwits_sentiment += f\"Bearish {round(100*n_bear/n_cases, 2)}%\"\n",
"else:\n",
" stocktwits_sentiment += \"No messages found\"\n",
"stocktwits_sentiment"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bfb75909-b877-4b3a-82a7-21ce174a7bb4",
"metadata": {},
"outputs": [],
"source": [
"fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, figsize=(11, 5), dpi=150)\n",
"openbb.stocks.ba.snews_chart(symbol, external_axes=[ax1, ax2])\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"snews = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "329c9e1b-e1de-4836-91fd-656cc87f7111",
"metadata": {},
"outputs": [],
"source": [
"ticker_data_all = openbb.stocks.load(\n",
" symbol=symbol,\n",
" start_date=datetime.datetime.now() - datetime.timedelta(days=5 * 12 * 21),\n",
")\n",
"ticker_data_all[\"Returns\"] = ticker_data_all[\"Adj Close\"].pct_change()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "37743ef3-2f16-4166-bfcc-a0fe3eb959bc",
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(11, 3), dpi=150)\n",
"openbb.qa.bw(\n",
" ticker_data_all,\n",
" \"Returns\",\n",
" symbol,\n",
" yearly=False,\n",
" external_axes=[ax],\n",
")\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"bw_month = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "16b33868-23dc-4c77-ac00-acb452da386c",
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(11, 3), dpi=150)\n",
"openbb.qa.bw(\n",
" ticker_data_all,\n",
" \"Returns\",\n",
" symbol,\n",
" yearly=True,\n",
" external_axes=[ax],\n",
")\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"bw_year = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "28ce0827",
"metadata": {},
"outputs": [],
"source": [
"income_df = openbb.stocks.fa.income(symbol, source=\"YahooFinance\")\n",
"data_df = openbb.stocks.fa.data(symbol)\n",
"mgmt_df = openbb.stocks.fa.mgmt(symbol)\n",
"mgmt_df[\"Info\"] = mgmt_df[\"Info\"].apply(lambda x: f'<a href=\"{x}\">{x}</a>')\n",
"mgmt_df[\"Insider Activity\"] = mgmt_df[\"Insider Activity\"].apply(\n",
" lambda x: f'<a href=\"{x}\">{x}</a>' if x != \"-\" else x\n",
")\n",
"try:\n",
" hist_dcf = openbb.stocks.fa.dcf(symbol)\n",
"except:\n",
" pass\n",
"enterprise_df = openbb.stocks.fa.enterprise(symbol)\n",
"score = openbb.stocks.fa.score(symbol)\n",
"if score:\n",
" score = round(float(score), 2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "42e289ab",
"metadata": {},
"outputs": [],
"source": [
"fig, (ax1, ax2, ax3) = plt.subplots(\n",
" nrows=3, ncols=1, figsize=(11, 8), sharex=True, dpi=150\n",
")\n",
"openbb.ta.ma(ticker_data[\"Close\"], symbol=symbol, external_axes=[ax1])\n",
"openbb.ta.ma(ticker_data[\"Close\"], symbol=symbol, ma_type=\"SMA\", external_axes=[ax2])\n",
"openbb.ta.ma(ticker_data[\"Close\"], symbol=symbol, ma_type=\"WMA\", external_axes=[ax3])\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"ma_chart = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e8846a6f",
"metadata": {},
"outputs": [],
"source": [
"fig, (ax, ax1) = plt.subplots(nrows=2, ncols=1, figsize=(11, 5), sharex=True, dpi=150)\n",
"openbb.ta.macd_chart(ticker_data[\"Close\"], symbol=symbol, external_axes=[ax, ax1])\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"macd_chart = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "48a7a427",
"metadata": {},
"outputs": [],
"source": [
"fig, (ax, ax1) = plt.subplots(nrows=2, ncols=1, figsize=(11, 5), sharex=True, dpi=150)\n",
"openbb.ta.cci_chart(ticker_data, symbol=symbol, external_axes=[ax, ax1])\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"cci_chart = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6a1bd2c6",
"metadata": {},
"outputs": [],
"source": [
"fig, (ax, ax1) = plt.subplots(nrows=2, ncols=1, figsize=(11, 5), dpi=150)\n",
"ax2 = ax1.twinx()\n",
"openbb.ta.stoch_chart(ticker_data, symbol=symbol, external_axes=[ax, ax1, ax2])\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"stoch_chart = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2611d3c6",
"metadata": {},
"outputs": [],
"source": [
"fig, (ax, ax1) = plt.subplots(2, 1, sharex=True, figsize=(11, 5), dpi=150)\n",
"openbb.ta.adx_chart(ticker_data, symbol=symbol, external_axes=[ax, ax1])\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"adx_chart = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6ecb6e17",
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(11, 3), dpi=150)\n",
"openbb.ta.bbands_chart(ticker_data, symbol=symbol, external_axes=[ax])\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"bbands_chart = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "07e42fdb",
"metadata": {},
"outputs": [],
"source": [
"fig, (ax, ax1, ax2) = plt.subplots(3, 1, sharex=True, figsize=(11, 8), dpi=150)\n",
"openbb.ta.ad_chart(ticker_data, symbol=symbol, external_axes=[ax, ax1, ax2])\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"ad_chart = f.getvalue().decode(\"utf-8\")"
]
},
{
"cell_type": "markdown",
"id": "ac501a32-124d-4d21-aae1-a8d147bb1071",
"metadata": {},
"source": [
"## Render the report template to a file"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "abfe37e4-ea38-42c3-8fb5-7cceb233fb12",
"metadata": {},
"outputs": [],
"source": [
"body = \"\"\n",
"\n",
"img = (\n",
" str(REPOSITORY_DIRECTORY)\n",
" + \"/openbb_terminal/reports/templates/OpenBB_reports_logo.png\"\n",
")\n",
"floppy_disk_img = (\n",
" str(REPOSITORY_DIRECTORY) + \"/openbb_terminal/reports/templates/floppy-disc.png\"\n",
")\n",
"body += widgets.header(\n",
" img,\n",
" floppy_disk_img,\n",
" author,\n",
" report_date,\n",
" report_time,\n",
" report_timezone,\n",
" report_title,\n",
")\n",
"\n",
"body += widgets.tablinks(\n",
" [\n",
" \"SUMMARY\",\n",
" \"Overview\",\n",
" \"Fundamental Analysis\",\n",
" \"Technical Analysis\",\n",
" \"Behavioural Analysis\",\n",
" \"Government Menu\",\n",
" \"Comparison Menu\",\n",
" \"Options\",\n",
" \"Dark Pool and Shorts\",\n",
" \"Quantitative Analysis\",\n",
" \"Analyst Opinions\",\n",
" \"Insider Trading\",\n",
" # \"Prediction Techniques\",\n",
" ]\n",
")\n",
"\n",
"htmlcode = widgets.h(3, \"KPIs\")\n",
"htmlcode += widgets.kpi(\n",
" [last_price],\n",
" [\n",
" \"Last closing price is above the average price ratings of last 30 days\",\n",
" \"Average price ratings of last 30 day is above last closing price\",\n",
" ],\n",
" avg_ratings_last_30_days,\n",
")\n",
"if predictions:\n",
" htmlcode += widgets.kpi(\n",
" [0],\n",
" [\n",
" \"Regression (dollars per market day) on last 30 market days is negative\",\n",
" \"Regression (dollars per market day) on last 30 market days is positive\",\n",
" ],\n",
" regression_slope,\n",
" )\n",
"htmlcode += widgets.kpi(\n",
" [30, 70],\n",
" [\"RSI level is oversold\", \"RSI level is normal\", \"RSI level is overbought\"],\n",
" rsi_value,\n",
")\n",
"htmlcode += widgets.kpi(\n",
" [0],\n",
" [\n",
" \"The sum of last 10 insider trading (in millions) was negative\",\n",
" \"The sum of last 10 insider trading (in millions) was positive\",\n",
" ],\n",
" last_10_insider_trading,\n",
")\n",
"htmlcode += widgets.kpi(\n",
" [-0.1, 0.1],\n",
" [\n",
" \"Last FinBrain sentiment is bearish\",\n",
" \" Last FinBrain sentiment is neutral\",\n",
" \"Last FinBrain sentiment is bullish\",\n",
" ],\n",
" finbrain_sentiment_val,\n",
")\n",
"if score:\n",
" htmlcode += widgets.kpi(\n",
" [25, 75],\n",
" [\n",
" \"Buffet Score is not favourable\",\n",
" \"Buffet Score is neutral\",\n",
" \"Buffet Score is favourable\",\n",
" ],\n",
" score,\n",
" )\n",
"if predictions:\n",
" htmlcode += widgets.kpi(\n",
" [0],\n",
" [\n",
" \"The regression for the next 20th market price is below closing price\",\n",
" \"The regression for the next 20th market price is above closing price\",\n",
" ],\n",
" round(regression_val - last_price, 2),\n",
" )\n",
"body += widgets.add_tab(\"SUMMARY\", htmlcode)\n",
"\n",
"htmlcode = widgets.row([widgets.h(3, \"Description\") + widgets.p(overview)])\n",
"htmlcode += widgets.row([widgets.h(3, \"Price Chart\") + price_chart])\n",
"htmlcode += widgets.row([widgets.h(3, \"Quote\") + quote_data.to_html()])\n",
"htmlcode += widgets.row([widgets.h(3, \"Latest News for \" + symbol)])\n",
"try:\n",
" for table in tables:\n",
" htmlcode += widgets.row(\n",
" [widgets.h(4, table[1][\"title\"]) + table[0].to_html(escape=False)]\n",
" )\n",
"except:\n",
" pass\n",
"htmlcode += widgets.row(\n",
" [widgets.h(3, f\"Management team of {symbol}\") + mgmt_df.to_html(escape=False)]\n",
")\n",
"body += widgets.add_tab(\"Overview\", htmlcode)\n",
"\n",
"htmlcode = widgets.row([widgets.h(3, \"Price Target Chart\") + price_target_chart])\n",
"htmlcode += widgets.row(\n",
" [widgets.h(3, \"Analyst Ratings over time\") + ratings_over_time_chart]\n",
")\n",
"try:\n",
" htmlcode += widgets.row([widgets.h(3, \"Analyst Ratings\") + df_analyst.to_html()])\n",
"except:\n",
" pass\n",
"try:\n",
" htmlcode += widgets.row(\n",
" [widgets.h(3, \"Analyst Recommendations\") + df_rating.to_html()]\n",
" )\n",
"except:\n",
" pass\n",
"\n",
"body += widgets.add_tab(\"Analyst Opinions\", htmlcode)\n",
"\n",
"try:\n",
" htmlcode = widgets.row(\n",
" [widgets.h(3, \"Estimates\") + df_year_estimates.head().to_html()]\n",
" )\n",
"except:\n",
" pass\n",
"htmlcode += widgets.row(\n",
" [widgets.h(3, \"Earnings\") + df_quarter_earnings.head().to_html()]\n",
")\n",
"htmlcode += widgets.row(\n",
" [widgets.h(3, \"Revenues\") + df_quarter_revenues.head().to_html()]\n",
")\n",
"try:\n",
" htmlcode += widgets.row(\n",
" [\n",
" widgets.h(3, \"Major Institutional Shareholders\")\n",
" + df_institutional_shareholders.head().to_html()\n",
" ]\n",
" )\n",
"except:\n",
" pass\n",
"try:\n",
" htmlcode += widgets.row(\n",
" [widgets.h(3, f\"Historical DCF for {symbol}\") + hist_dcf.to_html()]\n",
" )\n",
"except:\n",
" pass\n",
"htmlcode += widgets.row(\n",
" [widgets.h(3, f\"Enterprise data for {symbol}\") + enterprise_df.to_html()]\n",
")\n",
"htmlcode += widgets.row(\n",
" [widgets.h(3, f\"Income Statement for {symbol}\") + income_df.to_html()]\n",
")\n",
"try:\n",
" htmlcode += widgets.row([widgets.h(3, f\"Data for {symbol}\") + data_df.to_html()])\n",
"except:\n",
" pass\n",
"try:\n",
" htmlcode += widgets.row(\n",
" [widgets.h(3, \"SEC filings\") + df_sec_filings.to_html(escape=False)]\n",
" )\n",
"except:\n",
" pass\n",
"\n",
"body += widgets.add_tab(\"Fundamental Analysis\", htmlcode)\n",
"\n",
"htmlcode = widgets.row([widgets.h(3, \"Put to call ratio\") + pcr_chart])\n",
"htmlcode += widgets.row(\n",
" [widgets.h(3, \"Option Volume for closest expiry date\") + vol_chart]\n",
")\n",
"htmlcode += widgets.row(\n",
" [widgets.h(3, \"Volume and Open Interest for closest expiry date\") + voi_chart]\n",
")\n",
"try:\n",
" htmlcode += widgets.row([widgets.h(3, \"Option Chains\") + options_df.to_html()])\n",
"except:\n",
" pass\n",
"body += widgets.add_tab(\"Options\", htmlcode)\n",
"\n",
"htmlcode = widgets.row([net_short_position])\n",
"htmlcode += widgets.row([price_vs_short_interest])\n",
"# htmlcode += widgets.row([dark_pools])\n",
"body += widgets.add_tab(\"Dark Pool and Shorts\", htmlcode)\n",
"\n",
"htmlcode = widgets.row(\n",
" [\n",
" widgets.h(3, \"Congress trading in the past 12 months for \" + symbol)\n",
" + gtrades_chart\n",
" ]\n",
")\n",
"htmlcode += widgets.row([gov_histcont_chart])\n",
"htmlcode += widgets.row([gov_contracts_chart])\n",
"htmlcode += widgets.row([widgets.h(3, \"Recent Corporate Lobbying by \" + symbol)])\n",
"try:\n",
" for _, row in df_lobbying.iterrows():\n",
" amount = (\n",
" \"$\" + str(int(float(row[\"Amount\"]))) if row[\"Amount\"] is not None else \"N/A\"\n",
" )\n",
" htmlcode += widgets.row([widgets.p(f\"{row['Date']}: {row['Client']} {amount}\")])\n",
" if (row[\"Amount\"] is not None) and (row[\"Specific_Issue\"] is not None):\n",
" htmlcode += widgets.row(\n",
" [\n",
" widgets.p(\n",
" \"\\t\"\n",
" + row[\"Specific_Issue\"].replace(\"\\n\", \" \").replace(\"\\r\", \"\")\n",
" )\n",
" ]\n",
" )\n",
"except:\n",
" pass\n",
"\n",
"body += widgets.add_tab(\"Government Menu\", htmlcode)\n",
"\n",
"htmlcode = widgets.row(\n",
" [\n",
" widgets.h(3, f\"Price over the past year for companies similar to {symbol}\")\n",
" + historical_similar\n",
" ]\n",
")\n",
"htmlcode += widgets.row(\n",
" [\n",
" widgets.h(3, f\"Price correlation with similar companies for {symbol}\")\n",
" + hcorr_similar\n",
" ]\n",
")\n",
"htmlcode += widgets.row(\n",
" [\n",
" widgets.h(3, f\"Volume over the past year for companies similar to {symbol}\")\n",
" + vol_similar\n",
" ]\n",
")\n",
"htmlcode += widgets.row(\n",
" [\n",
" widgets.h(3, f\"Sentiment correlation with similar companies for {symbol}\")\n",
" + scorr_similar\n",
" ]\n",
")\n",
"htmlcode += widgets.row(\n",
" [\n",
" widgets.h(3, f\"Income data for similar companies to {symbol}\")\n",
" + income_comparison.to_html()\n",
" ]\n",
")\n",
"htmlcode += widgets.row(\n",
" [\n",
" widgets.p(\n",
" \"Note that similar companies have been found using openbb.stocks.ca.similar\"\n",
" )\n",
" ]\n",
")\n",
"body += widgets.add_tab(\"Comparison Menu\", htmlcode)\n",
"\n",
"htmlcode = widgets.row([widgets.h(3, f\"Moving Averages for {symbol}\") + ma_chart])\n",
"htmlcode += widgets.row([macd_chart])\n",
"htmlcode += widgets.row([ta_rsi])\n",
"htmlcode += widgets.row([stoch_chart])\n",
"htmlcode += widgets.row([cci_chart])\n",
"htmlcode += widgets.row([ad_chart])\n",
"htmlcode += widgets.row([bbands_chart])\n",
"htmlcode += widgets.row([adx_chart])\n",
"body += widgets.add_tab(\"Technical Analysis\", htmlcode)\n",
"\n",
"try:\n",
" htmlcode = widgets.row(\n",
" [widgets.h(3, \"Last Activity\") + df_insider.head(10).to_html(col_space=\"75px\")]\n",
" )\n",
"except:\n",
" pass\n",
"body += widgets.add_tab(\"Insider Trading\", htmlcode)\n",
"\n",
"htmlcode = widgets.row([bw_year])\n",
"htmlcode += widgets.row([bw_month])\n",
"body += widgets.add_tab(\"Quantitative Analysis\", htmlcode)\n",
"\n",
"\n",
"htmlcode = widgets.row([finbrain_sentiment])\n",
"htmlcode += widgets.row([snews])\n",
"htmlcode += widgets.row(\n",
" [\n",
" widgets.h(3, \"Interest in \" + symbol + \" based on google analytics\")\n",
" + google_mentions_chart\n",
" ]\n",
")\n",
"htmlcode += widgets.row(\n",
" [widgets.h(3, f\"Regions with highest interest in {symbol}\") + google_regions_chart]\n",
")\n",
"try:\n",
" htmlcode += widgets.row(\n",
" [\n",
" widgets.h(3, f\"Top queries related to {symbol}\")\n",
" + df_related_queries.to_html()\n",
" ]\n",
" )\n",
" htmlcode += widgets.row(\n",
" [\n",
" widgets.h(3, f\"Top rising queries related to {symbol}\")\n",
" + df_rising_queries.to_html()\n",
" ]\n",
" )\n",
"except:\n",
" pass\n",
"htmlcode += widgets.row(\n",
" [widgets.h(3, f\"Stocktwits sentiment for {symbol}\") + stocktwits_sentiment]\n",
")\n",
"body += widgets.add_tab(\"Behavioural Analysis\", htmlcode)\n",
"\n",
"if predictions:\n",
" htmlcode = widgets.row([regression])\n",
" htmlcode += widgets.row([mc])\n",
"else:\n",
" htmlcode = widgets.row([\"Prediction features not enabled.\"])\n",
"# body += widgets.add_tab(\"Prediction Techniques\", htmlcode)\n",
"\n",
"body += widgets.tab_clickable_and_save_evt()\n",
"\n",
"report = widgets.html_report(\n",
" title=report_name, stylesheet=widgets.html_report_stylesheet(), body=body\n",
")\n",
"\n",
"# to save the results\n",
"with open(report_name + \".html\", \"w\", encoding=\"utf-8\") as fh:\n",
" fh.write(report)\n",
"\n",
"dotenv.load_dotenv(USER_ENV_FILE)\n",
"cfg.theme = TerminalStyle(\n",
" os.getenv(\"OPENBB_MPLSTYLE\") or \"dark\",\n",
" os.getenv(\"OPENBB_MPFSTYLE\") or \"dark\",\n",
" os.getenv(\"OPENBB_RICHSTYLE\") or \"dark\",\n",
")"
]
}
],
"metadata": {
"celltoolbar": "Tags",
"kernelspec": {
"display_name": "Python 3.9.6 ('obb')",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.6"
},
"vscode": {
"interpreter": {
"hash": "cb66ba39c97f15743fbb79e204a841ea03600987d49579cfb0ffc8e8dd934c69"
}
}
},
"nbformat": 4,
"nbformat_minor": 5
}