mirror of
https://github.com/OpenBB-finance/OpenBB.git
synced 2026-10-29 13:32:08 +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>
266 lines
7.0 KiB
Python
266 lines
7.0 KiB
Python
"""Google View."""
|
|
__docformat__ = "numpy"
|
|
|
|
import logging
|
|
import os
|
|
from typing import Optional, List
|
|
import pandas as pd
|
|
|
|
import matplotlib.pyplot as plt
|
|
|
|
from openbb_terminal.config_terminal import theme
|
|
from openbb_terminal.config_plot import PLOT_DPI
|
|
from openbb_terminal.common.behavioural_analysis import google_model
|
|
from openbb_terminal.decorators import log_start_end
|
|
from openbb_terminal.helper_funcs import (
|
|
export_data,
|
|
plot_autoscale,
|
|
print_rich_table,
|
|
is_valid_axes_count,
|
|
)
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
@log_start_end(log=logger)
|
|
def display_mentions(
|
|
symbol: str,
|
|
start_date: str = "",
|
|
export: str = "",
|
|
external_axes: Optional[List[plt.Axes]] = None,
|
|
):
|
|
"""Plots weekly bars of stock's interest over time. other users watchlist. [Source: Google].
|
|
|
|
Parameters
|
|
----------
|
|
symbol : str
|
|
Ticker symbol
|
|
start_date : str
|
|
Start date as YYYY-MM-DD string
|
|
export: str
|
|
Format to export data
|
|
external_axes : Optional[List[plt.Axes]], optional
|
|
External axes (1 axis is expected in the list), by default None
|
|
"""
|
|
|
|
df_interest = google_model.get_mentions(symbol)
|
|
|
|
if df_interest.empty:
|
|
return
|
|
|
|
# This plot has 1 axis
|
|
if external_axes is None:
|
|
_, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
|
elif is_valid_axes_count(external_axes, 1):
|
|
(ax,) = external_axes
|
|
else:
|
|
return
|
|
|
|
ax.set_title(f"Interest over time on {symbol}")
|
|
if start_date:
|
|
df_interest = df_interest[start_date:] # type: ignore
|
|
ax.bar(df_interest.index, df_interest[symbol], width=2)
|
|
ax.bar(
|
|
df_interest.index[-1],
|
|
df_interest[symbol].values[-1],
|
|
width=theme.volume_bar_width,
|
|
)
|
|
else:
|
|
ax.bar(df_interest.index, df_interest[symbol], width=1)
|
|
ax.bar(
|
|
df_interest.index[-1],
|
|
df_interest[symbol].values[-1],
|
|
width=theme.volume_bar_width,
|
|
)
|
|
ax.set_ylabel("Interest [%]")
|
|
ax.set_xlim(df_interest.index[0], df_interest.index[-1])
|
|
theme.style_primary_axis(ax)
|
|
|
|
if external_axes is None:
|
|
theme.visualize_output()
|
|
|
|
export_data(
|
|
export, os.path.dirname(os.path.abspath(__file__)), "mentions", df_interest
|
|
)
|
|
|
|
|
|
@log_start_end(log=logger)
|
|
def display_correlation_interest(
|
|
symbol: str,
|
|
data: pd.DataFrame,
|
|
words: List[str],
|
|
export: str = "",
|
|
external_axes: Optional[List[plt.Axes]] = None,
|
|
):
|
|
"""Plots interest over time of words/sentences versus stock price. [Source: Google].
|
|
|
|
Parameters
|
|
----------
|
|
symbol : str
|
|
Ticker symbol to check price
|
|
data : pd.DataFrame
|
|
Data dataframe
|
|
words : List[str]
|
|
Words to check for interest for
|
|
export: str
|
|
Format to export data
|
|
external_axes : Optional[List[plt.Axes]], optional
|
|
External axes (1 axis is expected in the list), by default None
|
|
"""
|
|
|
|
# This plot has 1 axis
|
|
if external_axes is None:
|
|
_, ax = plt.subplots(
|
|
figsize=plot_autoscale(),
|
|
dpi=PLOT_DPI,
|
|
nrows=2,
|
|
ncols=1,
|
|
sharex=True,
|
|
gridspec_kw={"height_ratios": [1, 2]},
|
|
)
|
|
elif is_valid_axes_count(external_axes, 1):
|
|
(ax,) = external_axes
|
|
else:
|
|
return
|
|
ax[0].set_title(
|
|
f"{symbol.upper()} stock price and interest over time on {','.join(words)}"
|
|
)
|
|
ax[0].plot(
|
|
data.index,
|
|
data["Adj Close"].values,
|
|
c="#FCED00",
|
|
)
|
|
ax[0].set_ylabel("Stock Price")
|
|
ax[0].set_xlim(data.index[0], data.index[-1])
|
|
|
|
colors = theme.get_colors()[1:]
|
|
for idx, word in enumerate(words):
|
|
df_interest = google_model.get_mentions(word)
|
|
ax[1].plot(df_interest.index, df_interest[word], "-", color=colors[idx])
|
|
|
|
ax[1].set_ylabel("Interest [%]")
|
|
ax[1].set_xlim(data.index[0], data.index[-1])
|
|
ax[1].legend(words)
|
|
theme.style_primary_axis(ax[0])
|
|
theme.style_primary_axis(ax[1])
|
|
|
|
if external_axes is None:
|
|
theme.visualize_output()
|
|
|
|
export_data(
|
|
export, os.path.dirname(os.path.abspath(__file__)), "interest", df_interest
|
|
)
|
|
|
|
|
|
@log_start_end(log=logger)
|
|
def display_regions(
|
|
symbol: str,
|
|
limit: int = 5,
|
|
export: str = "",
|
|
external_axes: Optional[List[plt.Axes]] = None,
|
|
):
|
|
"""Plots bars of regions based on stock's interest. [Source: Google].
|
|
|
|
Parameters
|
|
----------
|
|
symbol : str
|
|
Ticker symbol
|
|
limit: int
|
|
Number of regions to show
|
|
export: str
|
|
Format to export data
|
|
external_axes : Optional[List[plt.Axes]], optional
|
|
External axes (1 axis is expected in the list), by default None
|
|
"""
|
|
df_interest_region = google_model.get_regions(symbol)
|
|
|
|
if df_interest_region.empty:
|
|
return
|
|
|
|
# This plot has 1 axis
|
|
if external_axes is None:
|
|
_, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
|
elif is_valid_axes_count(external_axes, 1):
|
|
(ax,) = external_axes
|
|
else:
|
|
return
|
|
|
|
df_interest_region = df_interest_region.head(limit)
|
|
df = df_interest_region.sort_values([symbol], ascending=True)
|
|
|
|
ax.set_title(f"Regions with highest interest in {symbol}")
|
|
ax.barh(
|
|
y=df.index, width=df[symbol], color=theme.get_colors(reverse=True), zorder=3
|
|
)
|
|
ax.set_xlabel("Interest [%]")
|
|
ax.set_ylabel("Region")
|
|
theme.style_primary_axis(ax)
|
|
|
|
if external_axes is None:
|
|
theme.visualize_output()
|
|
|
|
export_data(export, os.path.dirname(os.path.abspath(__file__)), "regions", df)
|
|
|
|
|
|
@log_start_end(log=logger)
|
|
def display_queries(symbol: str, limit: int = 5, export: str = ""):
|
|
"""Prints table showing top related queries with this stock's query. [Source: Google].
|
|
|
|
Parameters
|
|
----------
|
|
symbol : str
|
|
Ticker symbol
|
|
limit: int
|
|
Number of regions to show
|
|
export: str
|
|
Format to export data
|
|
{"csv","json","xlsx","png","jpg","pdf","svg"}
|
|
"""
|
|
# Retrieve a dict with top and rising queries
|
|
df = google_model.get_queries(symbol, limit)
|
|
|
|
if df.empty:
|
|
return
|
|
|
|
print_rich_table(
|
|
df,
|
|
headers=list(df.columns),
|
|
title=f"Top {symbol}'s related queries",
|
|
)
|
|
|
|
export_data(
|
|
export,
|
|
os.path.dirname(os.path.abspath(__file__)),
|
|
"queries",
|
|
df,
|
|
)
|
|
|
|
|
|
@log_start_end(log=logger)
|
|
def display_rise(symbol: str, limit: int = 10, export: str = ""):
|
|
"""Prints top rising related queries with this stock's query. [Source: Google].
|
|
|
|
Parameters
|
|
----------
|
|
symbol : str
|
|
Ticker symbol
|
|
limit: int
|
|
Number of queries to show
|
|
export: str
|
|
Format to export data
|
|
"""
|
|
df_related_queries = google_model.get_rise(symbol, limit)
|
|
|
|
if df_related_queries.empty:
|
|
return
|
|
|
|
print_rich_table(
|
|
df_related_queries,
|
|
headers=list(df_related_queries.columns),
|
|
title=f"Top rising {symbol}'s related queries",
|
|
)
|
|
|
|
export_data(
|
|
export, os.path.dirname(os.path.abspath(__file__)), "rise", df_related_queries
|
|
)
|