Terminal Wide Rich (#1161)

* My idea for how we handle Rich moving forward

* remove independent consoles

* FIxed pylint issues

* add a few vars

* Switched print to console

* More transitions

* Changed more prints

* Replaced all prints

* Fixing tabulate

* Finished replace tabulate

* Finished removing rich from Tabulate

* add Panel around menu

* add GST watermark under feature flag

* Fixed 46 tests

* Delete test_screener[False].yaml

* Delete test_screener[True].yaml

* Fixed the rest of the tests

* add help and source color vars and use rgb

* rich on stocks/options

* update rich on disc, dps, sia

* rich in gov, ins and scr menus

* ba and ca menus with rich

* Fixed import issue

* Fixed some tests

* removed termcolor

* Removed prettytable

* add rich to remaining stocks menus

* FIxed linting issue

* Added James' changes

* Updated dependencies

* Add rich to cryptocurrency menu

* refactor economy and forex

* refactor etf with rich

* refactor mfunds

* refactor rich rest

* not specify style so default color works well on any background

* Fixing mypy issues

* Updated tests

* More test fixes

* James' test fixes

* Updating tests : stocks/screener - fix cassettes using BR

* Updating tests : crypto

* Updating tests : disable DEBUG_MODE

* Updating tests : stocks/fa/yfinance

* minor fixes that escape

* Improve the rich table function (that replaces tabulate :D )

* Fixed bad code

* delete rogue file + dcf fix + NoConsole

* sia mypy

* fuck you linter

* fuck you linter pt 2

* skip hehe

* i hate the black linter

* ubuntu mypy attempt

* Update : rich_config + gtff

* Updating tests : conftest

* Updating tests : stocks

* Update : rich_config

* Updating : rich_config

* make panel configurable for Theodore :b

* colors update

* Merged

* Updating : rich_config + feature_flags

* Updating : rich_config

* Updating tests : stocks

* Updating : feature_flags

Co-authored-by: DidierRLopes <dro.lopes@campus.fct.unl.pt>
Co-authored-by: Chavithra PARANA <chavithra@gmail.com>
Co-authored-by: james <jmaslek11@gmail.com>
Co-authored-by: jose-donato <zmcdonato@gmail.com>
This commit is contained in:
Colin Delahunty
2022-01-14 21:06:00 -05:00
committed by GitHub
parent d334d5e087
commit 82747072c5
288 changed files with 16660 additions and 25965 deletions

5
CONTRIBUTING.md vendored
View File

@@ -196,6 +196,7 @@ __docformat__ = "numpy"
import os
from tabulate import tabulate
from gamestonk_terminal.rich_config import console
from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal.stocks.dark_pool_shorts import yahoofinance_model
@@ -215,7 +216,7 @@ def display_most_shorted(num_stocks: int, export: str):
df = df.replace(float("NaN"), "")
if df.empty:
print("No data found.")
console.print("No data found.")
else:
print(
tabulate(
@@ -226,7 +227,7 @@ def display_most_shorted(num_stocks: int, export: str):
tablefmt="fancy_grid",
)
)
print("")
console.print("")
export_data(
export,

View File

@@ -107,6 +107,7 @@ import os
from datetime import datetime, timedelta
import discord
import yfinance as yf
from gamestonk_terminal.rich_config import console
import discordbot.config_discordbot as cfg
import discordbot.helpers
from matplotlib import pyplot as plt
@@ -124,7 +125,7 @@ async def ftd_command(ctx, ticker="", start="", end=""):
try:
# DEBUG USER INPUT
if cfg.DEBUG:
print(f"\n!stocks.dps.ftd {ticker} {start} {end}")
console.print(f"\n!stocks.dps.ftd {ticker} {start} {end}")
# CHECK FOR ARGUMENT VALIDITY
if ticker == "":
@@ -147,7 +148,7 @@ async def ftd_command(ctx, ticker="", start="", end=""):
# DEBUG OUTPUT
if cfg.DEBUG:
print(ftds_data.to_string())
console.print(ftds_data.to_string())
# PROCESS DATA TO OUTPUT
plt.bar(
@@ -249,7 +250,7 @@ async def dark_pool_shorts_menu(self, ctx: discord.ext.commands.Context):
"""Stocks Context - Shows Dark Pool Shorts Menu"""
if cfg.DEBUG:
print(f"\n!stocks.dps {ticker}")
console.print(f"\n!stocks.dps {ticker}")
text = (
"0️⃣ !stocks.dps.shorted <NUM>\n"
@@ -278,15 +279,15 @@ async def dark_pool_shorts_menu(self, ctx: discord.ext.commands.Context):
)
if reaction.emoji == "0️⃣":
if cfg.DEBUG:
print("Reaction selected: 0")
console.print("Reaction selected: 0")
await shorted_command(ctx)
elif reaction.emoji == "1️⃣":
if cfg.DEBUG:
print("Reaction selected: 1")
console.print("Reaction selected: 1")
await hsi_command(ctx)
elif reaction.emoji == "2️⃣":
if cfg.DEBUG:
print("Reaction selected: 2")
console.print("Reaction selected: 2")
await pos_command(ctx)
for emoji in emoji_list:

View File

@@ -149,7 +149,6 @@ pmdarima==1.8.4; python_version >= "3.6"
praw==7.5.0; python_version >= "3.6" and python_version < "4.0"
prawcore==2.3.0; python_version >= "3.6" and python_version < "4.0"
pre-commit==2.16.0; python_full_version >= "3.6.1"
prettytable==2.5.0; python_version >= "3.6"
prometheus-client==0.12.0; python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.4.0" and python_version >= "3.6"
prompt-toolkit==3.0.24; python_full_version >= "3.6.2"
protobuf==3.19.1; python_full_version >= "3.7.1" and python_full_version < "4.0.0" and python_version >= "3.5"

View File

@@ -11,6 +11,7 @@ from discordbot.stocks.options.oi import oi_command
from discordbot.stocks.options.puts import puts_command
from discordbot.stocks.options.unu import unu_command
from discordbot.stocks.options.vol import vol_command
from gamestonk_terminal.rich_config import console
# pylint: disable=R0912
@@ -70,35 +71,35 @@ async def opt_command(ctx, ticker="", expiration="", strike="", put=""):
)
if reaction.emoji == "0️⃣":
if cfg.DEBUG:
print("Reaction selected: 0")
console.print("Reaction selected: 0")
await unu_command(ctx)
elif reaction.emoji == "1️⃣":
if cfg.DEBUG:
print("Reaction selected: 1")
console.print("Reaction selected: 1")
await expirations_command(ctx, ticker)
elif reaction.emoji == "2️⃣":
if cfg.DEBUG:
print("Reaction selected: 2")
console.print("Reaction selected: 2")
await iv_command(ctx, ticker)
elif reaction.emoji == "3️⃣":
if cfg.DEBUG:
print("Reaction selected: 3")
console.print("Reaction selected: 3")
await calls_command(ctx, ticker, expiration)
elif reaction.emoji == "4️⃣":
if cfg.DEBUG:
print("Reaction selected: 4")
console.print("Reaction selected: 4")
await puts_command(ctx, ticker, expiration)
elif reaction.emoji == "5️⃣":
if cfg.DEBUG:
print("Reaction selected: 5")
console.print("Reaction selected: 5")
await oi_command(ctx, ticker, expiration)
elif reaction.emoji == "6️⃣":
if cfg.DEBUG:
print("Reaction selected: 6")
console.print("Reaction selected: 6")
await vol_command(ctx, ticker, expiration)
elif reaction.emoji == "7️⃣":
if cfg.DEBUG:
print("Reaction selected: 7")
console.print("Reaction selected: 7")
strike = float(strike)
await hist_command(ctx, ticker, expiration, strike, put)

View File

@@ -5,12 +5,11 @@ import logging
from typing import List
from prompt_toolkit.completion import NestedCompleter
from rich.console import Console
from gamestonk_terminal.rich_config import console
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.parent_classes import BaseController
from gamestonk_terminal.menu import session
t_console = Console()
logger = logging.getLogger(__name__)
# pylint:disable=import-outside-toplevel
@@ -32,10 +31,10 @@ class AlternativeDataController(BaseController):
@staticmethod
def print_help():
"""Print help"""
help_str = """
> covid cases, deaths, rates
help_text = """[menu]
> covid COVID menu, e.g.: cases, deaths, rates[/menu]
"""
t_console.print(help_str)
console.print(text=help_text, menu="Alternative")
def call_covid(self, _):
"""Process covid command"""

View File

@@ -8,7 +8,7 @@ from typing import List
import pandas as pd
from prompt_toolkit.completion import NestedCompleter
from rich.console import Console
from gamestonk_terminal.rich_config import console
from gamestonk_terminal.parent_classes import BaseController
from gamestonk_terminal import feature_flags as gtff
@@ -22,7 +22,6 @@ from gamestonk_terminal.helper_funcs import (
from gamestonk_terminal.menu import session
logger = logging.getLogger(__name__)
t_console = Console()
country_file = pathlib.Path(__file__).parent.joinpath("countries.txt")
@@ -48,18 +47,18 @@ class CovidController(BaseController):
def print_help(self):
"""Print help"""
help_str = f"""
help_text = f"""[cmds]
slopes get countries with highest slope in cases
country select country for data
country select country for data[/cmds]
Country: [cyan]{self.country}[/cyan]
[param]Country: [/param]{self.country}[cmds]
ov get overview (cases and deaths) for selected country
deaths get deaths for selected country
cases get cases for selected country
rates get death/cases rate for selected country
rates get death/cases rate for selected country[/cmds]
"""
t_console.print(help_str)
console.print(text=help_text, menu="Alternative - COVID")
def custom_reset(self):
"""Class specific component of reset command"""
@@ -88,12 +87,12 @@ Country: [cyan]{self.country}[/cyan]
if ns_parser.country:
country = " ".join(ns_parser.country)
if country not in self.COUNTRY_LIST:
t_console.print(f"[red]{country} not a valid selection.[/red]\n")
console.print(f"[red]{country} not a valid selection.[/red]\n")
return
self.country = country
t_console.print(f"[cyan]{country}[/cyan] loaded\n")
console.print(f"[cyan]{country}[/cyan] loaded\n")
else:
t_console.print("[red]Please input a country.[/red]\n")
console.print("[red]Please input a country.[/red]\n")
def call_ov(self, other_args: List[str]):
"""Process hist command"""

View File

@@ -6,7 +6,7 @@ import os
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import pandas as pd
from rich.console import Console
from gamestonk_terminal.rich_config import console
import gamestonk_terminal.feature_flags as gtff
from gamestonk_terminal.alternative.covid import covid_model
@@ -17,8 +17,6 @@ from gamestonk_terminal.helper_funcs import (
rich_table_from_df,
)
t_console = Console()
def display_covid_ov(country, raw: bool = False, limit: int = 10, export: str = ""):
"""Show historical cases and deaths by country
@@ -34,7 +32,7 @@ def display_covid_ov(country, raw: bool = False, limit: int = 10, export: str =
export: str
Format to export data
"""
t_console.print("")
console.print("")
cases = covid_model.get_global_cases(country) / 1_000
deaths = covid_model.get_global_deaths(country)
ov = pd.concat([cases, deaths], axis=1)
@@ -69,7 +67,7 @@ def display_covid_ov(country, raw: bool = False, limit: int = 10, export: str =
if raw:
ov.index = [x.strftime("%Y-%m-%d") for x in ov.index]
if gtff.USE_TABULATE_DF:
t_console.print(
console.print(
rich_table_from_df(
ov.tail(limit),
headers=[x.title() for x in ov.columns],
@@ -79,9 +77,9 @@ def display_covid_ov(country, raw: bool = False, limit: int = 10, export: str =
)
)
else:
t_console.print(ov.tail(limit).to_string())
console.print(ov.tail(limit).to_string())
t_console.print("")
console.print("")
if export:
export_data(export, os.path.dirname(os.path.abspath(__file__)), "ov", ov)
@@ -105,7 +103,7 @@ def display_covid_stat(
export: str
Format to export data
"""
t_console.print("")
console.print("")
if stat == "cases":
data = covid_model.get_global_cases(country) / 1_000
elif stat == "deaths":
@@ -115,7 +113,7 @@ def display_covid_stat(
deaths = covid_model.get_global_deaths(country)
data = (deaths / cases).fillna(0) * 100
else:
t_console.print("Invalid stat selected.\n")
console.print("Invalid stat selected.\n")
return
fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
@@ -143,7 +141,7 @@ def display_covid_stat(
if raw:
data.index = [x.strftime("%Y-%m-%d") for x in data.index]
if gtff.USE_TABULATE_DF:
t_console.print(
console.print(
rich_table_from_df(
data.tail(limit),
headers=[stat.title()],
@@ -153,9 +151,9 @@ def display_covid_stat(
)
)
else:
t_console.print(data.tail(limit).to_string())
console.print(data.tail(limit).to_string())
t_console.print("")
console.print("")
export_data(export, os.path.dirname(os.path.abspath(__file__)), stat, data)
@@ -186,7 +184,7 @@ def display_country_slopes(
by="Slope", ascending=ascend
)
if gtff.USE_TABULATE_DF:
t_console.print(
console.print(
rich_table_from_df(
hist_slope.head(limit),
show_index=True,
@@ -195,8 +193,8 @@ def display_country_slopes(
)
)
else:
t_console.print(hist_slope.head(limit).to_string())
t_console.print("")
console.print(hist_slope.head(limit).to_string())
console.print("")
export_data(
export,

View File

@@ -13,6 +13,7 @@ from gamestonk_terminal.helper_funcs import plot_autoscale, export_data
from gamestonk_terminal.common.behavioural_analysis import finbrain_model
from gamestonk_terminal.config_plot import PLOT_DPI
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
register_matplotlib_converters()
@@ -91,7 +92,7 @@ def display_sentiment_analysis(ticker: str, export: str = ""):
"""
df_sentiment = finbrain_model.get_sentiment(ticker)
if df_sentiment.empty:
print("No sentiment data found.\n")
console.print("No sentiment data found.\n")
return
plot_sentiment(df_sentiment, ticker)
@@ -109,7 +110,7 @@ def display_sentiment_analysis(ticker: str, export: str = ""):
)
print(tabulate(color_df, headers=["Sentiment"], tablefmt="fancy_grid"))
else:
print(color_df.to_string())
console.print(color_df.to_string())
else:
if gtff.USE_TABULATE_DF:
print(
@@ -124,8 +125,8 @@ def display_sentiment_analysis(ticker: str, export: str = ""):
)
else:
print(df_sentiment.to_string())
print("")
console.print(df_sentiment.to_string())
console.print("")
export_data(
export, os.path.dirname(os.path.abspath(__file__)), "headlines", df_sentiment
)

View File

@@ -7,6 +7,7 @@ import pandas as pd
from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal.common.behavioural_analysis import finnhub_model
from gamestonk_terminal.rich_config import console
def display_sentiment_stats(ticker: str, export: str = ""):
@@ -24,7 +25,7 @@ def display_sentiment_stats(ticker: str, export: str = ""):
d_stats = finnhub_model.get_sentiment_stats(ticker)
if d_stats:
print(
console.print(
f"""
Buzz: {round(100*d_stats['buzz']['buzz'],2)} %
News Score: {round(100*d_stats['companyNewsScore'],2)} %
@@ -46,5 +47,5 @@ Sector Average News Score: {round(100*d_stats['sectorAverageNewsScore'],2)} %"""
)
else:
print("No sentiment stats found.")
print("")
console.print("No sentiment stats found.")
console.print("")

View File

@@ -10,6 +10,7 @@ import matplotlib.pyplot as plt
from gamestonk_terminal.helper_funcs import plot_autoscale, export_data
from gamestonk_terminal.common.behavioural_analysis import google_model
from gamestonk_terminal import config_plot as cfp, feature_flags as gtff
from gamestonk_terminal.rich_config import console
def display_mentions(ticker: str, start: datetime, export: str = ""):
@@ -54,7 +55,7 @@ def display_mentions(ticker: str, start: datetime, export: str = ""):
plt.ion()
fig.tight_layout()
plt.show()
print("")
console.print("")
export_data(
export, os.path.dirname(os.path.abspath(__file__)), "mentions", df_interest
)
@@ -89,8 +90,8 @@ def display_regions(ticker: str, num: int = 5, export: str = ""):
fig.tight_layout()
plt.show()
else:
print("No region data found.")
print("")
console.print("No region data found.")
console.print("")
export_data(export, os.path.dirname(os.path.abspath(__file__)), "regions", df)
@@ -113,7 +114,7 @@ def display_queries(ticker: str, num: int = 5, export: str = ""):
df_related_queries["value"] = df_related_queries["value"].apply(
lambda x: str(x) + "%"
)
print(f"Top {ticker}'s related queries")
console.print(f"Top {ticker}'s related queries")
if gtff.USE_TABULATE_DF:
print(
tabulate(
@@ -123,8 +124,8 @@ def display_queries(ticker: str, num: int = 5, export: str = ""):
)
)
else:
print(df_related_queries.to_string(index=False))
print("")
console.print(df_related_queries.to_string(index=False))
console.print("")
export_data(export, os.path.dirname(os.path.abspath(__file__)), "queries", df)
@@ -144,7 +145,7 @@ def display_rise(ticker: str, num: int, export: str = ""):
df = df_related_queries.copy()
df_related_queries = df_related_queries.head(num)
print(f"Top rising {ticker}'s related queries")
console.print(f"Top rising {ticker}'s related queries")
if gtff.USE_TABULATE_DF:
print(
@@ -155,6 +156,6 @@ def display_rise(ticker: str, num: int, export: str = ""):
)
)
else:
print(df_related_queries.to_string(index=False))
print("")
console.print(df_related_queries.to_string(index=False))
console.print("")
export_data(export, os.path.dirname(os.path.abspath(__file__)), "rise", df)

View File

@@ -10,7 +10,7 @@ from psaw import PushshiftAPI
import praw
import finviz
from gamestonk_terminal import config_terminal as cfg
from gamestonk_terminal.rich_config import console
from gamestonk_terminal.common.behavioural_analysis.reddit_helpers import find_tickers
l_sub_reddits = [
@@ -131,7 +131,7 @@ def get_popular_tickers(
psaw_api = PushshiftAPI()
for s_sub_reddit in sub_reddit_list:
print(
console.print(
f"Search for latest tickers for {posts_to_look_at} '{s_sub_reddit}' posts"
)
submissions = psaw_api.search_submissions(
@@ -172,12 +172,12 @@ def get_popular_tickers(
d_watchlist_tickers[key] = 1
except ResponseException:
print(
console.print(
"Received a response from Reddit with an authorization error. check your token.\n"
)
return pd.DataFrame()
print(f" {n_tickers} potential tickers found.")
console.print(f" {n_tickers} potential tickers found.")
lt_watchlist_sorted = sorted(
d_watchlist_tickers.items(), key=lambda item: item[1], reverse=True
)
@@ -208,9 +208,9 @@ def get_popular_tickers(
n_top_stocks += 1
except HTTPError as e:
if e.response.status_code != 404:
print(f"Unexpected exception from Finviz: {e}")
console.print(f"Unexpected exception from Finviz: {e}")
except Exception as e:
print(e, "\n")
console.print(e, "\n")
return
popular_tickers_df = pd.DataFrame(

View File

@@ -8,12 +8,13 @@ from typing import Dict
import finviz
import praw
from prettytable import PrettyTable
from tabulate import tabulate
import pandas as pd
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.common.behavioural_analysis import reddit_model
from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal.rich_config import console
def print_and_record_reddit_post(
@@ -51,23 +52,27 @@ def print_and_record_reddit_post(
"awards": s_all_awards,
}
# Print post data collected so far
print(f"{s_datetime} - {submission.title}")
print(f"{s_link}")
t_post = PrettyTable(
["Subreddit", "Flair", "Score", "# Comments", "Upvote %", "Awards"]
console.print(f"{s_datetime} - {submission.title}")
console.print(f"{s_link}")
columns = ["Subreddit", "Flair", "Score", "# Comments", "Upvote %", "Awards"]
data = [
submission.subreddit,
submission.link_flair_text,
submission.score,
submission.num_comments,
f"{round(100 * submission.upvote_ratio)}%",
s_all_awards,
]
df = pd.DataFrame(data, columns=columns)
t_post = tabulate(
df,
headers=df.columns,
tablefmt="fancy_grid",
showindex=False,
)
t_post.add_row(
[
submission.subreddit,
submission.link_flair_text,
submission.score,
submission.num_comments,
f"{round(100 * submission.upvote_ratio)}%",
s_all_awards,
]
)
print(t_post)
print("\n")
console.print(t_post)
console.print("\n")
def display_watchlist(num: int):
@@ -96,15 +101,15 @@ def display_watchlist(num: int):
s_watchlist_tickers += f"{t_ticker[1]} {t_ticker[0]}, "
n_tickers += 1
except Exception:
# print(e, "\n")
# console.print(e, "\n")
pass
if n_tickers:
print(
console.print(
"The following stock tickers have been mentioned more than once across the previous watchlists:"
)
print(s_watchlist_tickers[:-2] + "\n")
console.print(s_watchlist_tickers[:-2] + "\n")
print("")
console.print("")
def display_popular_tickers(
@@ -127,7 +132,7 @@ def display_popular_tickers(
n_top, posts_to_look_at, subreddits
)
if not popular_tickers_df.empty:
print(f"\nThe following TOP {n_top} tickers have been mentioned:")
console.print(f"\nThe following TOP {n_top} tickers have been mentioned:")
if gtff.USE_TABULATE_DF:
print(
tabulate(
@@ -138,11 +143,11 @@ def display_popular_tickers(
)
)
else:
print(popular_tickers_df.to_string())
console.print(popular_tickers_df.to_string())
else:
print("No tickers found")
console.print("No tickers found")
print("")
console.print("")
export_data(
export,
os.path.dirname(os.path.abspath(__file__)),
@@ -180,15 +185,15 @@ def display_spac_community(limit: int = 10, popular: bool = False):
s_watchlist_tickers += f"{t_ticker[1]} {t_ticker[0]}, "
n_tickers += 1
except Exception:
# print(e, "\n")
# console.print(e, "\n")
pass
if n_tickers:
print(
console.print(
"The following stock tickers have been mentioned more than once across the previous SPACs:"
)
print(s_watchlist_tickers[:-2])
print("")
console.print(s_watchlist_tickers[:-2])
console.print("")
def display_spac(limit: int = 5):
@@ -221,11 +226,11 @@ def display_spac(limit: int = 5):
except Exception:
pass
if n_tickers:
print(
console.print(
"The following stock tickers have been mentioned more than once across the previous SPACs:"
)
print(s_watchlist_tickers[:-2])
print("")
console.print(s_watchlist_tickers[:-2])
console.print("")
def display_wsb_community(limit: int = 10, new: bool = False):
@@ -264,4 +269,4 @@ def display_due_diligence(
for sub in subs:
print_and_record_reddit_post({}, sub)
if not subs:
print(f"No DD posts found for {ticker}\n")
console.print(f"No DD posts found for {ticker}\n")

View File

@@ -20,6 +20,7 @@ from gamestonk_terminal.common.behavioural_analysis.sentimentinvestor_model impo
from gamestonk_terminal.config_plot import PLOT_DPI
from gamestonk_terminal.helper_funcs import plot_autoscale
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
sentipy: Sentipy = Sentipy(
token=cfg.API_SENTIMENTINVESTOR_TOKEN, key=cfg.API_SENTIMENTINVESTOR_KEY
@@ -43,7 +44,7 @@ def display_top(metric: str, limit: int):
"""
table = sentimentinvestor_model.get_top(metric, limit)
print(tabulate.tabulate(table, headers=["Rank", "Ticker", metric], floatfmt=".3f"))
print("")
console.print("")
def _tabulate_metrics(ticker: str, metrics_list: List[_Metric]):
@@ -98,33 +99,33 @@ def _customise_plot() -> None:
def display_metrics(ticker: str) -> None:
"""Display sentiment investor metrics for stock ticker"""
if not sentipy.supported(ticker):
print("This stock is not supported by the SentimentInvestor API.")
console.print("This stock is not supported by the SentimentInvestor API.")
return
metric_values = sentimentinvestor_model.get_metrics(ticker)
if not metric_values:
print("No data available or an error occurred.")
console.print("No data available or an error occurred.")
return
print(_tabulate_metrics(ticker, metric_values))
print()
console.print(_tabulate_metrics(ticker, metric_values))
console.print()
def display_social(ticker: str) -> None:
"""Display sentiment investor social metrics for ticker"""
if not sentipy.supported(ticker):
print("This stock is not supported by the SentimentInvestor API.")
console.print("This stock is not supported by the SentimentInvestor API.")
return
metric_values = sentimentinvestor_model.get_socials(ticker)
if not metric_values:
print("No data available or an error occurred.")
console.print("No data available or an error occurred.")
return
print(_tabulate_metrics(ticker, metric_values))
print("")
console.print(_tabulate_metrics(ticker, metric_values))
console.print("")
def display_historical(
@@ -144,13 +145,13 @@ def display_historical(
Metric to get data for. Either 'sentiment', 'AHI', 'RHI', 'SGP'
"""
if not sentipy.supported(ticker):
print("This stock is not supported by the SentimentInvestor API.")
console.print("This stock is not supported by the SentimentInvestor API.")
return
df = sentimentinvestor_model.get_historical(ticker, metric)
if df.empty:
print("The dataset is empty, something must have gone wrong")
console.print("The dataset is empty, something must have gone wrong")
return
_customise_plot()

View File

@@ -6,6 +6,7 @@ import pandas as pd
from tabulate import tabulate
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.common.behavioural_analysis import stocktwits_model
from gamestonk_terminal.rich_config import console
def display_bullbear(ticker: str):
@@ -19,14 +20,14 @@ def display_bullbear(ticker: str):
Stock ticker
"""
watchlist_count, n_cases, n_bull, n_bear = stocktwits_model.get_bullbear(ticker)
print(f"Watchlist count: {watchlist_count}")
console.print(f"Watchlist count: {watchlist_count}")
if n_cases > 0:
print(f"\nLast {n_cases} sentiment messages:")
print(f"Bullish {round(100*n_bull/n_cases, 2)}%")
print(f"Bearish {round(100*n_bear/n_cases, 2)}%")
console.print(f"\nLast {n_cases} sentiment messages:")
console.print(f"Bullish {round(100*n_bull/n_cases, 2)}%")
console.print(f"Bearish {round(100*n_bear/n_cases, 2)}%")
else:
print("No messages found")
print("")
console.print("No messages found")
console.print("")
def display_messages(ticker: str, limit: int = 30):
@@ -49,7 +50,7 @@ def display_messages(ticker: str, limit: int = 30):
)
else:
for message in messages:
print(message, "\n")
console.print(message, "\n")
def display_trending():
@@ -65,8 +66,8 @@ def display_trending():
)
)
else:
print(df_trending.to_string(index=False))
print("")
console.print(df_trending.to_string(index=False))
console.print("")
def display_stalker(user: str, limit: int = 10):
@@ -81,9 +82,9 @@ def display_stalker(user: str, limit: int = 10):
"""
messages = stocktwits_model.get_stalker(user, limit)
for message in messages:
print(
console.print(
"------------------------------------------------------------------------------"
)
print(message["created_at"].replace("T", " ").replace("Z", ""))
print(message["body"])
print("")
console.print(message["created_at"].replace("T", " ").replace("Z", ""))
console.print(message["body"])
console.print("")

View File

@@ -9,6 +9,7 @@ from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from gamestonk_terminal import config_terminal as cfg
from gamestonk_terminal.helper_funcs import clean_tweet, get_data
from gamestonk_terminal.rich_config import console
analyzer = SentimentIntensityAnalyzer()
@@ -65,10 +66,10 @@ def load_analyze_tweets(
row = get_data(tweet)
df_tweets = df_tweets.append(row, ignore_index=True)
elif response.status_code == 401:
print("Twitter API Key provided is incorrect\n")
console.print("Twitter API Key provided is incorrect\n")
return pd.DataFrame()
elif response.status_code == 400:
print(
console.print(
"Status Code 400. This means you are requesting data from beyond the API's 7 day limit"
)
return pd.DataFrame()

View File

@@ -15,6 +15,7 @@ from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.common.behavioural_analysis import twitter_model
from gamestonk_terminal.helper_funcs import export_data, plot_autoscale
import gamestonk_terminal.config_plot as cfg_plot
from gamestonk_terminal.rich_config import console
def display_inference(ticker: str, num: int, export: str = ""):
@@ -37,13 +38,13 @@ def display_inference(ticker: str, num: int, export: str = ""):
# Parse tweets
dt_from = dparse.parse(df_tweets["created_at"].values[-1])
dt_to = dparse.parse(df_tweets["created_at"].values[0])
print(f"From: {dt_from.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"To: {dt_to.strftime('%Y-%m-%d %H:%M:%S')}")
console.print(f"From: {dt_from.strftime('%Y-%m-%d %H:%M:%S')}")
console.print(f"To: {dt_to.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"{len(df_tweets)} tweets were analyzed.")
console.print(f"{len(df_tweets)} tweets were analyzed.")
dt_delta = dt_to - dt_from
n_freq = dt_delta.total_seconds() / len(df_tweets)
print(f"Frequency of approx 1 tweet every {round(n_freq)} seconds.")
console.print(f"Frequency of approx 1 tweet every {round(n_freq)} seconds.")
pos = df_tweets["positive"]
neg = df_tweets["negative"]
@@ -52,15 +53,15 @@ def display_inference(ticker: str, num: int, export: str = ""):
percent_neg = len(np.where(pos < neg)[0]) / len(df_tweets)
total_sent = np.round(np.sum(df_tweets["sentiment"]), 2)
mean_sent = np.round(np.mean(df_tweets["sentiment"]), 2)
print(f"The summed compound sentiment of {ticker} is: {total_sent}")
print(f"The average compound sentiment of {ticker} is: {mean_sent}")
print(
console.print(f"The summed compound sentiment of {ticker} is: {total_sent}")
console.print(f"The average compound sentiment of {ticker} is: {mean_sent}")
console.print(
f"Of the last {len(df_tweets)} tweets, {100*percent_pos:.2f} % had a higher positive sentiment"
)
print(
console.print(
f"Of the last {len(df_tweets)} tweets, {100*percent_neg:.2f} % had a higher negative sentiment"
)
print("")
console.print("")
export_data(export, os.path.dirname(os.path.abspath(__file__)), "infer", df_tweets)
@@ -84,7 +85,7 @@ def display_sentiment(ticker: str, n_tweets: int, n_days_past: int, export: str
# Algorithm to extract
dt_recent = datetime.now() - timedelta(seconds=20)
dt_old = dt_recent - timedelta(days=n_days_past)
print(
console.print(
f"From {dt_recent.date()} retrieving {n_tweets*24} tweets ({n_tweets} tweets/hour)"
)
@@ -118,7 +119,7 @@ def display_sentiment(ticker: str, n_tweets: int, n_days_past: int, export: str
df_tweets = pd.concat([df_tweets, temp])
if dt_past.day < dt_recent.day:
print(
console.print(
f"From {dt_past.date()} retrieving {n_tweets*24} tweets ({n_tweets} tweets/hour)"
)
@@ -176,7 +177,7 @@ def display_sentiment(ticker: str, n_tweets: int, n_days_past: int, export: str
if gtff.USE_ION:
plt.ion()
plt.show()
print("")
console.print("")
export_data(
export, os.path.dirname(os.path.abspath(__file__)), "sentiment", df_tweets
)

View File

@@ -4,6 +4,7 @@ __docformat__ = "numpy"
import requests
from gamestonk_terminal import config_terminal as cfg
from gamestonk_terminal.rich_config import console
def news(
@@ -40,13 +41,15 @@ def news(
# Check that the API response was successful
if response.status_code == 426:
print(f"Error in request: {response.json()['message']}", "\n")
console.print(f"Error in request: {response.json()['message']}", "\n")
elif response.status_code != 200:
print(f"Error in request {response.status_code}. Check News API token", "\n")
console.print(
f"Error in request {response.status_code}. Check News API token", "\n"
)
else:
print(
console.print(
f"{response.json()['totalResults']} news articles for {term} were found since {s_from}\n"
)
@@ -57,13 +60,13 @@ def news(
articles = response.json()["articles"][::-1]
for idx, article in enumerate(articles):
print(
console.print(
article["publishedAt"].replace("T", " ").replace("Z", ""),
" ",
article["title"],
)
# Unnecessary to use name of the source because contained in link article["source"]["name"]
print(article["url"], "\n")
console.print(article["url"], "\n")
if idx >= num - 1:
break

View File

@@ -25,6 +25,7 @@ from gamestonk_terminal.helper_funcs import (
patch_pandas_text_adjustment,
plot_autoscale,
)
from gamestonk_terminal.rich_config import console
register_matplotlib_converters()
@@ -83,7 +84,7 @@ def display_arima(
)[1:]
if future_index[-1] > datetime.datetime.now():
print(
console.print(
"Backtesting not allowed, since End Date + Prediction days is in the future\n"
)
return
@@ -109,8 +110,8 @@ def display_arima(
df_pred = pd.Series(l_predictions, index=l_pred_days, name="Price")
if results:
print(model.summary())
print("")
console.print(model.summary())
console.print("")
# Plotting
fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
@@ -287,8 +288,8 @@ def display_arima(
)
else:
patch_pandas_text_adjustment()
print("Time Real [$] x Prediction [$]")
print(
console.print("Time Real [$] x Prediction [$]")
console.print(
df_pred.apply(
price_prediction_backtesting_color, axis=1
).to_string()
@@ -310,13 +311,13 @@ def display_arima(
)
)
else:
print(df_pred[["Real", "Prediction"]].round(2).to_string())
console.print(df_pred[["Real", "Prediction"]].round(2).to_string())
print("")
console.print("")
print_prediction_kpis(df_pred["Real"].values, df_pred["Prediction"].values)
else:
# Print prediction data
print_pretty_prediction(df_pred, values.values[-1])
export_data(export, os.path.dirname(os.path.abspath(__file__)), "arima")
print("")
console.print("")

View File

@@ -27,6 +27,7 @@ from gamestonk_terminal.helper_funcs import (
patch_pandas_text_adjustment,
plot_autoscale,
)
from gamestonk_terminal.rich_config import console
register_matplotlib_converters()
@@ -79,7 +80,7 @@ def display_exponential_smoothing(
)[1:]
if future_index[-1] > datetime.datetime.now():
print(
console.print(
"Backtesting not allowed, since End Date + Prediction days is in the future\n"
)
return
@@ -93,11 +94,11 @@ def display_exponential_smoothing(
)
if not forecast:
print("No forecast made. Model did not converge.\n")
console.print("No forecast made. Model did not converge.\n")
return
if np.isnan(forecast).any():
print("Model predicted NaN values. Runtime Error.\n")
console.print("Model predicted NaN values. Runtime Error.\n")
return
if not time_res:
@@ -112,15 +113,15 @@ def display_exponential_smoothing(
df_pred = pd.Series(forecast, index=l_pred_days, name="Price")
print(f"\n{title}")
print("\nFit model parameters:")
console.print(f"\n{title}")
console.print("\nFit model parameters:")
for key, value in model.params.items():
print(f"{key} {' '*(18-len(key))}: {value}")
console.print(f"{key} {' '*(18-len(key))}: {value}")
print("\nAssess fit model:")
print(f"AIC: {round(model.aic, 2)}")
print(f"BIC: {round(model.bic, 2)}")
print(f"SSE: {round(model.sse, 2)}\n")
console.print("\nAssess fit model:")
console.print(f"AIC: {round(model.aic, 2)}")
console.print(f"BIC: {round(model.bic, 2)}")
console.print(f"SSE: {round(model.sse, 2)}\n")
# Plotting
fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
@@ -292,12 +293,14 @@ def display_exponential_smoothing(
patch_pandas_text_adjustment()
print("Time Real [$] x Prediction [$]")
print(df_pred.apply(price_prediction_backtesting_color, axis=1).to_string())
console.print("Time Real [$] x Prediction [$]")
console.print(
df_pred.apply(price_prediction_backtesting_color, axis=1).to_string()
)
else:
print(df_pred[["Real", "Prediction"]].round(2).to_string())
console.print(df_pred[["Real", "Prediction"]].round(2).to_string())
print("")
console.print("")
print_prediction_kpis(df_pred["Real"].values, df_pred["Prediction"].values)
else:
@@ -305,4 +308,4 @@ def display_exponential_smoothing(
print_pretty_prediction(df_pred, values.values[-1])
export_data(export, os.path.dirname(os.path.abspath(__file__)), "ets")
print("")
console.print("")

View File

@@ -10,6 +10,7 @@ from gamestonk_terminal.helper_funcs import get_next_stock_market_days
from gamestonk_terminal.common.prediction_techniques.pred_helper import (
prepare_scale_train_valid_test,
)
from gamestonk_terminal.rich_config import console
def get_knn_model_data(
@@ -75,7 +76,7 @@ def get_knn_model_data(
future_dates = get_next_stock_market_days(
dates_forecast_input[-1], n_next_days=n_predict_days
)
print(
console.print(
f"Training on {X_train.shape[0]} sequences of length {X_train.shape[1]}. Using {X_valid.shape[0]} sequences "
f" of length {X_valid.shape[1]} for validation"
)

View File

@@ -11,6 +11,7 @@ from gamestonk_terminal.common.prediction_techniques.pred_helper import (
plot_data_predictions,
)
from gamestonk_terminal.common.prediction_techniques import knn_model
from gamestonk_terminal.rich_config import console
register_matplotlib_converters()
@@ -62,7 +63,7 @@ def display_k_nearest_neighbors(
)
if forecast_data_df.empty:
print("Issue performing data prep and prediction")
console.print("Issue performing data prep and prediction")
return
if time_res:
@@ -81,4 +82,4 @@ def display_k_nearest_neighbors(
1,
time_res,
)
print("")
console.print("")

View File

@@ -18,6 +18,7 @@ from gamestonk_terminal.helper_funcs import (
)
from gamestonk_terminal.config_plot import PLOT_DPI
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
def display_mc_forecast(
@@ -80,4 +81,4 @@ def display_mc_forecast(
plt.ion()
plt.show()
export_data(export, os.path.dirname(os.path.abspath(__file__)), "mc")
print("")
console.print("")

View File

@@ -32,6 +32,7 @@ from gamestonk_terminal.common.prediction_techniques.pred_helper import (
forecast,
)
from gamestonk_terminal import config_neural_network_models as cfg_nn_models
from gamestonk_terminal.rich_config import console
optimizers = {
@@ -130,7 +131,7 @@ def build_neural_network_model(
elif str(*d_layer) == "Flatten":
model.add(Flatten())
else:
print(f"Incorrect neuron type: {str(*d_layer)}")
console.print(f"Incorrect neuron type: {str(*d_layer)}")
return model
@@ -201,7 +202,7 @@ def mlp_model(
if is_error:
return pd.DataFrame(), np.array(0), np.array(0), np.array(0), None
print(
console.print(
f"Training on {X_train.shape[0]} sequences of length {X_train.shape[1]}. Using {X_valid.shape[0]} sequences "
f" of length {X_valid.shape[1]} for validation. Model will run {n_loops} loops"
)
@@ -321,7 +322,7 @@ def rnn_model(
if is_error:
return pd.DataFrame(), np.array(0), np.array(0), np.array(0), None
print(
console.print(
f"Training on {X_train.shape[0]} sequences of length {X_train.shape[1]}. Using {X_valid.shape[0]} sequences "
f" of length {X_valid.shape[1]} for validation. Model will run {n_loops} loops"
)
@@ -434,7 +435,7 @@ def lstm_model(
if is_error:
return pd.DataFrame(), np.array(0), np.array(0), np.array(0), None
print(
console.print(
f"Training on {X_train.shape[0]} sequences of length {X_train.shape[1]}. Using {X_valid.shape[0]} sequences "
f" of length {X_valid.shape[1]} for validation. Model will run {n_loops} loops"
)
@@ -547,7 +548,7 @@ def conv1d_model(
if is_error:
return pd.DataFrame(), np.array(0), np.array(0), np.array(0), None
print(
console.print(
f"Training on {X_train.shape[0]} sequences of length {X_train.shape[1]}. Using {X_valid.shape[0]} sequences "
f" of length {X_valid.shape[1]} for validation. Model will run {n_loops} loops"
)

View File

@@ -10,6 +10,7 @@ from gamestonk_terminal.common.prediction_techniques.pred_helper import (
print_pretty_prediction,
)
from gamestonk_terminal.common.prediction_techniques import neural_networks_model
from gamestonk_terminal.rich_config import console
# pylint:disable=too-many-arguments
@@ -93,7 +94,7 @@ def display_mlp(
n_loops,
time_res,
)
print("")
console.print("")
def display_rnn(
@@ -174,7 +175,7 @@ def display_rnn(
n_loops,
time_res,
)
print("")
console.print("")
def display_lstm(
@@ -255,7 +256,7 @@ def display_lstm(
n_loops,
time_res,
)
print("")
console.print("")
def display_conv1d(
@@ -336,4 +337,4 @@ def display_conv1d(
n_loops,
time_res,
)
print("")
console.print("")

View File

@@ -31,6 +31,7 @@ from gamestonk_terminal.helper_funcs import (
from gamestonk_terminal import config_neural_network_models as cfg
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.config_plot import PLOT_DPI
from gamestonk_terminal.rich_config import console
register_matplotlib_converters()
@@ -217,7 +218,7 @@ def parse_args(prog: str, description: str, other_args: List[str]):
return ns_parser
except SystemExit:
print("")
console.print("")
return None
@@ -281,7 +282,9 @@ def prepare_scale_train_valid_test(
if s_end_date:
data = data[data.index <= s_end_date]
if n_input_days + n_predict_days > data.shape[0]:
print("Cannot train enough input days to predict with loaded dataframe\n")
console.print(
"Cannot train enough input days to predict with loaded dataframe\n"
)
return (
None,
None,
@@ -554,49 +557,53 @@ def price_prediction_color(val: float, last_val: float) -> str:
def print_pretty_prediction(df_pred: pd.DataFrame, last_price: float):
"""Print predictions"""
print("")
console.print("")
if gtff.USE_COLOR:
print(f"Actual price: {Fore.YELLOW}{last_price:.2f} ${Style.RESET_ALL}\n")
console.print(
f"Actual price: {Fore.YELLOW}{last_price:.2f} ${Style.RESET_ALL}\n"
)
if gtff.USE_TABULATE_DF:
df_pred = pd.DataFrame(df_pred)
df_pred.columns = ["pred"]
df_pred["pred"] = df_pred["pred"].apply(
lambda x: price_prediction_color(x, last_val=last_price)
)
print("Prediction:")
console.print("Prediction:")
print(tabulate(df_pred, headers=["Prediction"], tablefmt="fancy_grid"))
else:
print("Prediction:")
print(
console.print("Prediction:")
console.print(
df_pred.apply(price_prediction_color, last_val=last_price).to_string()
)
else:
if gtff.USE_TABULATE_DF:
df_pred = pd.DataFrame(df_pred)
df_pred.columns = ["pred"]
print("Prediction:")
console.print("Prediction:")
print(tabulate(df_pred, headers=["Prediction"], tablefmt="fancy_grid"))
else:
print(f"Actual price: {last_price:.2f} $\n")
print("Prediction:")
print(df_pred.to_string())
console.print(f"Actual price: {last_price:.2f} $\n")
console.print("Prediction:")
console.print(df_pred.to_string())
def print_pretty_prediction_nn(df_pred: pd.DataFrame, last_price: float):
if gtff.USE_COLOR:
print(f"Actual price: {Fore.YELLOW}{last_price:.2f} ${Style.RESET_ALL}\n")
print("Prediction:")
print(
console.print(
f"Actual price: {Fore.YELLOW}{last_price:.2f} ${Style.RESET_ALL}\n"
)
console.print("Prediction:")
console.print(
df_pred.applymap(
lambda x: price_prediction_color(x, last_val=last_price)
).to_string()
)
else:
print(f"Actual price: {last_price:.2f} $\n")
print("Prediction:")
print(df_pred.to_string())
console.print(f"Actual price: {last_price:.2f} $\n")
console.print("Prediction:")
console.print(df_pred.to_string())
def mean_absolute_percentage_error(y_true: np.ndarray, y_pred: np.ndarray) -> np.number:
@@ -615,12 +622,12 @@ def print_prediction_kpis(real: np.ndarray, pred: np.ndarray):
"RMSE": f"{mean_squared_error(real, pred, squared=False):.3f}",
}
print("KPIs")
console.print("KPIs")
df = pd.DataFrame.from_dict(kpis, orient="index")
if gtff.USE_TABULATE_DF:
print(tabulate(df, tablefmt="fancy_grid", showindex=True))
else:
print(df.to_string())
console.print(df.to_string())
def price_prediction_backtesting_color(val: list) -> str:

View File

@@ -6,6 +6,7 @@ import numpy as np
from sklearn import linear_model
from sklearn import pipeline
from sklearn import preprocessing
from gamestonk_terminal.rich_config import console
# The tsxv dependence was removed so this fails. Taking from didiers source
@@ -42,7 +43,7 @@ def split_train(
y: List = []
if numInputs + numOutputs > len(sequence):
print(
console.print(
"To have at least one X,y arrays, the sequence size needs to be bigger than numInputs+numOutputs"
)
return X, y
@@ -101,7 +102,7 @@ def get_regression_model(
)
if not stock_x:
print("Given the model parameters more training data is needed.\n")
console.print("Given the model parameters more training data is needed.\n")
return [], None
# Machine Learning model

View File

@@ -23,6 +23,7 @@ from gamestonk_terminal.common.prediction_techniques.pred_helper import (
from gamestonk_terminal.common.prediction_techniques import regression_model
from gamestonk_terminal.config_plot import PLOT_DPI
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
register_matplotlib_converters()
@@ -149,7 +150,7 @@ def display_regression(
plt.show()
export_data(export, os.path.dirname(os.path.abspath(__file__)), "regression")
print("")
console.print("")
# BACKTESTING
if s_end_date:
@@ -240,15 +241,17 @@ def display_regression(
patch_pandas_text_adjustment()
print("Time Real [$] x Prediction [$]")
print(df_pred.apply(price_prediction_backtesting_color, axis=1).to_string())
console.print("Time Real [$] x Prediction [$]")
console.print(
df_pred.apply(price_prediction_backtesting_color, axis=1).to_string()
)
else:
print(df_pred[["Real", "Prediction"]].round(2).to_string())
console.print(df_pred[["Real", "Prediction"]].round(2).to_string())
print("")
console.print("")
print_prediction_kpis(df_pred["Real"].values, df_pred["Prediction"].values)
else:
# Print prediction data
print_pretty_prediction(df_pred, values.values[-1])
print("")
console.print("")

View File

@@ -12,7 +12,6 @@ from matplotlib import gridspec
import numpy as np
import pandas as pd
from rich.console import Console
import seaborn as sns
import statsmodels.api as sm
from detecta import detect_cusum
@@ -20,6 +19,7 @@ from pandas.plotting import register_matplotlib_converters
from scipy import stats
from statsmodels.graphics.gofplots import qqplot
from gamestonk_terminal.rich_config import console
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.common.quantitative_analysis import qa_model
from gamestonk_terminal.config_plot import PLOT_DPI
@@ -31,7 +31,6 @@ from gamestonk_terminal.helper_funcs import (
from gamestonk_terminal.helper_classes import LineAnnotateDrawer
register_matplotlib_converters()
t_console = Console()
# TODO : Since these are common/ they should be independent of 'stock' info.
# df_stock should be replaced with a generic df and a column variable
@@ -56,7 +55,7 @@ def display_summary(df: pd.DataFrame, export: str):
"""
summary = qa_model.get_summary(df)
t_console.print(
console.print(
rich_table_from_df(
summary,
headers=list(summary.columns),
@@ -65,7 +64,7 @@ def display_summary(df: pd.DataFrame, export: str):
title="[bold]Summary Statistics[/bold]",
)
)
t_console.print("")
console.print("")
export_data(
export,
os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
@@ -108,7 +107,7 @@ def display_hist(
plt.ion()
fig.tight_layout()
plt.show()
t_console.print("")
console.print("")
def display_cdf(
@@ -182,7 +181,7 @@ def display_cdf(
plt.ion()
plt.show()
t_console.print("")
console.print("")
export_data(
export,
os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
@@ -248,7 +247,7 @@ def display_bw(
plt.ion()
plt.show()
t_console.print("")
console.print("")
def display_acf(name: str, df: pd.DataFrame, target: str, lags: int):
@@ -298,7 +297,7 @@ def display_acf(name: str, df: pd.DataFrame, target: str, lags: int):
plt.ion()
plt.show()
t_console.print("")
console.print("")
def display_cusum(df: pd.DataFrame, target: str, threshold: float, drift: float):
@@ -319,7 +318,7 @@ def display_cusum(df: pd.DataFrame, target: str, threshold: float, drift: float)
if gtff.USE_ION:
plt.ion()
plt.show()
t_console.print("")
console.print("")
def display_seasonal(
@@ -383,20 +382,20 @@ def display_seasonal(
plt.ion()
plt.show()
t_console.print("")
console.print("")
# From # https://otexts.com/fpp2/seasonal-strength.html
t_console.print("Time-Series Level is " + str(round(data.mean(), 2)))
console.print("Time-Series Level is " + str(round(data.mean(), 2)))
Ft = max(0, 1 - np.var(result.resid)) / np.var(result.trend + result.resid)
t_console.print(f"Strength of Trend: {Ft:.4f}")
console.print(f"Strength of Trend: {Ft:.4f}")
Fs = max(
0,
1 - np.var(result.resid) / np.var(result.seasonal + result.resid),
)
t_console.print(f"Strength of Seasonality: {Fs:.4f}\n")
console.print(f"Strength of Seasonality: {Fs:.4f}\n")
export_data(
export,
@@ -424,7 +423,7 @@ def display_normality(df: pd.DataFrame, target: str, export: str = ""):
stats1.iloc[:, 1] = stats1.iloc[:, 1].apply(lambda x: color_red(x))
if gtff.USE_TABULATE_DF:
t_console.print(
console.print(
rich_table_from_df(
stats1,
show_index=True,
@@ -433,9 +432,9 @@ def display_normality(df: pd.DataFrame, target: str, export: str = ""):
title="[bold]Normality Statistics[/bold]",
)
)
t_console.print("")
console.print("")
else:
t_console.print(normal.round(4).to_string(), "\n")
console.print(normal.round(4).to_string(), "\n")
export_data(
export,
@@ -471,7 +470,7 @@ def display_qqplot(name: str, df: pd.DataFrame, target: str):
plt.ion()
fig.tight_layout(pad=1)
plt.show()
t_console.print("")
console.print("")
def display_unitroot(
@@ -495,7 +494,7 @@ def display_unitroot(
df = df[target]
data = qa_model.get_unitroot(df, fuller_reg, kpss_reg)
if gtff.USE_TABULATE_DF:
t_console.print(
console.print(
rich_table_from_df(
data,
show_index=True,
@@ -505,8 +504,8 @@ def display_unitroot(
)
)
else:
t_console.print(data.round(4).to_string(), "\n")
t_console.print("")
console.print(data.round(4).to_string(), "\n")
console.print("")
export_data(
export,
os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
@@ -548,7 +547,7 @@ def display_raw(
df = df.sort_values(by=sort, ascending=des)
df.index = [x.strftime("%Y-%m-%d") for x in df.index]
if gtff.USE_TABULATE_DF:
t_console.print(
console.print(
rich_table_from_df(
df.tail(num),
headers=[x.title() if x != "" else "Date" for x in df.columns],
@@ -558,9 +557,9 @@ def display_raw(
)
)
else:
t_console.print(df.to_string(index=False))
console.print(df.to_string(index=False))
t_console.print("")
console.print("")
def display_line(
@@ -585,7 +584,7 @@ def display_line(
export: str
Format to export data
"""
t_console.print("")
console.print("")
fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
if log_y:
@@ -610,6 +609,16 @@ def display_line(
if gtff.USE_ION:
plt.ion()
if gtff.USE_WATERMARK:
ax.text(
0.73,
0.025,
"Gamestonk Terminal",
transform=ax.transAxes,
fontsize=12,
color="gray",
alpha=0.5,
)
if draw:
LineAnnotateDrawer(ax).draw_lines_and_annotate()

View File

@@ -11,6 +11,7 @@ from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.common.quantitative_analysis import rolling_model
from gamestonk_terminal.config_plot import PLOT_DPI
from gamestonk_terminal.helper_funcs import export_data, plot_autoscale
from gamestonk_terminal.rich_config import console
register_matplotlib_converters()
@@ -76,7 +77,7 @@ def display_mean_std(
fig.tight_layout(pad=1)
plt.gcf().autofmt_xdate()
plt.show()
print("")
console.print("")
export_data(
export,
os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
@@ -137,7 +138,7 @@ def display_spread(
plt.gcf().autofmt_xdate()
fig.tight_layout(pad=1)
plt.show()
print("")
console.print("")
export_data(
export,
os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
@@ -193,7 +194,7 @@ def display_quantile(
plt.legend()
plt.show()
print("")
console.print("")
export_data(
export,
os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
@@ -246,7 +247,7 @@ def display_skew(
plt.legend()
plt.show()
print("")
console.print("")
export_data(
export,
os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
@@ -297,7 +298,7 @@ def display_kurtosis(
plt.legend()
plt.show()
print("")
console.print("")
export_data(
export,
os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),

View File

@@ -5,6 +5,8 @@ from typing import Any, Tuple
import pandas as pd
from gamestonk_terminal.rich_config import console
def calculate_fib_levels(
df_stock: pd.DataFrame,
@@ -41,12 +43,12 @@ def calculate_fib_levels(
if open_date and close_date:
if open_date not in df_stock.index:
date0 = df_stock.index[df_stock.index.get_loc(open_date, method="nearest")]
print(f"Start date not in df_stock. Using nearest: {date0}")
console.print(f"Start date not in df_stock. Using nearest: {date0}")
else:
date0 = open_date
if close_date not in df_stock.index:
date1 = df_stock.index[df_stock.index.get_loc(close_date, method="nearest")]
print(f"End date not in df_stock. Using nearest: {date1}")
console.print(f"End date not in df_stock. Using nearest: {date1}")
else:
date1 = close_date

View File

@@ -12,6 +12,7 @@ from gamestonk_terminal import config_plot as cfp
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.common.technical_analysis import custom_indicators_model
from gamestonk_terminal.helper_funcs import export_data, plot_autoscale
from gamestonk_terminal.rich_config import console
def fibonacci_retracement(
@@ -85,7 +86,7 @@ def fibonacci_retracement(
tablefmt="fancy_grid",
)
)
print("")
console.print("")
export_data(
export,

View File

@@ -12,6 +12,7 @@ from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.common.technical_analysis import momentum_model
from gamestonk_terminal.config_plot import PLOT_DPI
from gamestonk_terminal.helper_funcs import export_data, plot_autoscale
from gamestonk_terminal.rich_config import console
register_matplotlib_converters()
@@ -70,7 +71,7 @@ def display_cci(
fig.tight_layout(pad=1)
plt.show()
print("")
console.print("")
export_data(
export,
@@ -137,7 +138,7 @@ def display_macd(
fig.tight_layout(pad=1)
plt.show()
print("")
console.print("")
export_data(
export,
os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
@@ -201,7 +202,7 @@ def display_rsi(
plt.gcf().autofmt_xdate()
fig.tight_layout(pad=1)
plt.show()
print("")
console.print("")
export_data(
export,
@@ -278,7 +279,7 @@ def display_stoch(
plt.gcf().autofmt_xdate()
fig.tight_layout(pad=1)
plt.show()
print("")
console.print("")
export_data(
export,
@@ -356,7 +357,7 @@ def display_fisher(
plt.legend()
plt.show()
print("")
console.print("")
export_data(
export,
@@ -411,7 +412,7 @@ def display_cg(
fig.tight_layout(pad=1)
plt.legend()
plt.show()
print("")
console.print("")
export_data(
export,

View File

@@ -13,6 +13,7 @@ import gamestonk_terminal.feature_flags as gtff
from gamestonk_terminal.common.technical_analysis import overlap_model
from gamestonk_terminal.config_plot import PLOT_DPI
from gamestonk_terminal.helper_funcs import export_data, plot_autoscale
from gamestonk_terminal.rich_config import console
register_matplotlib_converters()
@@ -87,7 +88,7 @@ def view_ma(
fig.tight_layout(pad=1)
plt.show()
print("")
console.print("")
export_data(
export,
@@ -146,7 +147,7 @@ def view_vwap(
plt.ion()
plt.show()
print("")
console.print("")
export_data(
export,

View File

@@ -11,6 +11,7 @@ from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.common.technical_analysis import trend_indicators_model
from gamestonk_terminal.config_plot import PLOT_DPI
from gamestonk_terminal.helper_funcs import export_data, plot_autoscale
from gamestonk_terminal.rich_config import console
register_matplotlib_converters()
@@ -82,7 +83,7 @@ def display_adx(
plt.gcf().autofmt_xdate()
plt.show()
print("")
console.print("")
export_data(
export,
@@ -156,7 +157,7 @@ def display_aroon(
plt.show()
plt.gcf().autofmt_xdate()
print("")
console.print("")
export_data(
export,

View File

@@ -11,6 +11,7 @@ from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.common.technical_analysis import volatility_model
from gamestonk_terminal.config_plot import PLOT_DPI
from gamestonk_terminal.helper_funcs import export_data, plot_autoscale
from gamestonk_terminal.rich_config import console
register_matplotlib_converters()
@@ -71,7 +72,7 @@ def display_bbands(
fig.tight_layout(pad=1)
plt.show()
print("")
console.print("")
export_data(
export,
@@ -138,7 +139,7 @@ def display_donchian(
plt.legend()
plt.show()
print("")
console.print("")
export_data(
export,
@@ -213,7 +214,7 @@ def view_kc(
plt.legend()
plt.show()
print("")
console.print("")
export_data(
export,
os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),

View File

@@ -10,6 +10,7 @@ from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.common.technical_analysis import volume_model
from gamestonk_terminal.config_plot import PLOT_DPI
from gamestonk_terminal.helper_funcs import export_data, plot_autoscale
from gamestonk_terminal.rich_config import console
register_matplotlib_converters()
@@ -84,7 +85,7 @@ def display_ad(
fig.tight_layout(pad=1)
plt.show()
print("")
console.print("")
export_data(
export,
@@ -169,7 +170,7 @@ def display_adosc(
fig.tight_layout(pad=1)
plt.legend()
plt.show()
print("")
console.print("")
export_data(
export,
@@ -243,7 +244,7 @@ def display_obv(df_stock: pd.DataFrame, s_ticker: str = "", export: str = ""):
fig.tight_layout(pad=1)
plt.show()
print("")
console.print("")
export_data(
export,

View File

@@ -12,6 +12,7 @@ import base64
import requests
from requests.auth import AuthBase
import gamestonk_terminal.config_terminal as cfg
from gamestonk_terminal.rich_config import console
class CoinbaseProAuth(AuthBase):
@@ -163,5 +164,5 @@ def _check_account_validity(account: str) -> Union[str, Any]:
if account in list(accounts.values()):
return account
print("Wrong account id or coin symbol")
console.print("Wrong account id or coin symbol")
return None

View File

@@ -7,9 +7,8 @@ from typing import List
from datetime import datetime, timedelta
import pandas as pd
from prompt_toolkit.completion import NestedCompleter
from rich import console
from binance.client import Client
from gamestonk_terminal.rich_config import console
from gamestonk_terminal.parent_classes import BaseController
from gamestonk_terminal.cryptocurrency.pycoingecko_helpers import calc_change
from gamestonk_terminal.cryptocurrency.due_diligence import pycoingecko_model
@@ -49,8 +48,6 @@ CRYPTO_SOURCES = {
"cb": "Coinbase",
}
t_console = console.Console()
class CryptoController(BaseController):
"""Crypto Controller"""
@@ -89,36 +86,32 @@ class CryptoController(BaseController):
def print_help(self):
"""Print help"""
help_text = """
load load a specific cryptocurrency for analysis
find find coins in a certain source
coins find coins and check map across multiple sources
source_txt = CRYPTO_SOURCES.get(self.source, "?") if self.source != "" else ""
has_ticker_start = "" if self.current_coin else "[unvl]"
has_ticker_end = "" if self.current_coin else "[/unvl]"
help_text = f"""[cmds]
load load a specific cryptocurrency for analysis
find find coins in a certain source
coins find coins and check map across multiple sources[/cmds]
[param]Coin: [/param]{self.current_coin}
[param]Source: [/param]{source_txt}
[cmds]
headlines crypto sentiment from 15+ major news headlines [src][Finbrain][/src]{has_ticker_start}
chart view a candle chart for a specific cryptocurrency
prt potential returns tool - check how much upside if ETH reaches BTC market cap{has_ticker_end}
[/cmds][menu]
> disc discover trending cryptocurrencies, e.g.: top gainers, losers, top sentiment
> ov overview of the cryptocurrencies, e.g.: market cap, DeFi, latest news, top exchanges, stables
> onchain information on different blockchains, e.g.: eth gas fees, whale alerts, DEXes info
> defi decentralized finance information, e.g.: dpi, llama, tvl, lending, borrow, funding
> nft non-fungible tokens, e.g.: today drops{has_ticker_start}
> dd due-diligence for loaded coin, e.g.: coin information, social media, market stats
> ta technical analysis for loaded coin, e.g.: ema, macd, rsi, adx, bbands, obv
> pred prediction techniques e.g.: regression, arima, rnn, lstm, conv1d, monte carlo[/menu]
{has_ticker_end}
"""
help_text += (
f"\nCoin: {self.current_coin}" if self.current_coin != "" else "\nCoin: ?"
)
help_text += (
f"\nSource: {CRYPTO_SOURCES.get(self.source, '?')}\n"
if self.source != ""
else "\nSource: ?\n"
)
help_text += self.price_str + "\n"
help_text += f"""
headlines crypto sentiment from 15+ major news headlines [Finbrain]{'[dim]' if not self.current_coin else ''}
chart view a candle chart for a specific cryptocurrency
prt potential returns tool e.g.: check how much upside if eth reaches btc market cap{'[/dim]' if not self.current_coin else ''}
""" # noqa
help_text += f"""
> disc discover trending cryptocurrencies, e.g.: top gainers, losers, top sentiment
> ov overview of the cryptocurrencies, e.g.: market cap, DeFi, latest news, top exchanges, stables
> onchain information on different blockchains, e.g.: eth gas fees, whale alerts, DEXes info
> defi decentralized finance information, e.g.: dpi, llama, tvl, lending, borrow, funding
> nft non-fungible tokens, e.g.: today drops{'[dim]' if not self.current_coin else ''}
> dd due-diligence for loaded coin, e.g.: coin information, social media, market stats
> ta technical analysis for loaded coin, e.g.: ema, macd, rsi, adx, bbands, obv
> pred prediction techniques e.g.: regression, arima, rnn, lstm, conv1d, monte carlo{'[/dim]' if not self.current_coin else ''}
""" # noqa
t_console.print(help_text)
console.print(text=help_text, menu="Cryptocurrency")
def call_prt(self, other_args):
"""Process prt command"""
@@ -162,7 +155,9 @@ class CryptoController(BaseController):
if ns_parser.vs:
coin_found = pycoingecko_model.check_coin(ns_parser.vs)
if not coin_found:
print(f"VS Coin '{ns_parser.vs}' not found in CoinGecko\n")
console.print(
f"VS Coin '{ns_parser.vs}' not found in CoinGecko\n"
)
return
pycoingecko_view.display_coin_potential_returns(
self.coin_map_df["CoinGecko"],
@@ -172,7 +167,7 @@ class CryptoController(BaseController):
)
else:
print(
console.print(
"No coin selected. Use 'load' to load the coin you want to look at.\n"
)
@@ -333,7 +328,7 @@ class CryptoController(BaseController):
Performance in interval ({self.current_interval}): {'[green]' if interval_change > 0 else "[red]"}{round(interval_change,2)}%{'[/green]' if interval_change > 0 else "[/red]"}
Performance since {ns_parser.start.strftime('%Y-%m-%d')}: {'[green]' if since_start_change > 0 else "[red]"}{round(since_start_change,2)}%{'[/green]' if since_start_change > 0 else "[/red]"}""" # noqa
t_console.print(
console.print(
f"""
Loaded {self.current_coin} against {self.current_currency} from {CRYPTO_SOURCES[self.source]} source
@@ -447,7 +442,7 @@ Loaded {self.current_coin} against {self.current_currency} from {CRYPTO_SOURCES[
self.current_coin
)
if len(quotes) < 0:
print(
console.print(
f"Couldn't find any quoted coins for provided symbol {self.current_coin}"
)
return
@@ -517,7 +512,7 @@ Loaded {self.current_coin} against {self.current_currency} from {CRYPTO_SOURCES[
).menu()
else:
print("No coin selected. Use 'load' to load a coin.\n")
console.print("No coin selected. Use 'load' to load a coin.\n")
def call_disc(self, _):
"""Process disc command"""
@@ -589,7 +584,7 @@ Loaded {self.current_coin} against {self.current_currency} from {CRYPTO_SOURCES[
queue=self.queue,
).menu()
else:
print("No coin selected. Use 'load' to load a coin.\n")
console.print("No coin selected. Use 'load' to load a coin.\n")
def call_pred(self, _):
"""Process pred command"""
@@ -599,7 +594,7 @@ Loaded {self.current_coin} against {self.current_currency} from {CRYPTO_SOURCES[
)
if self.current_interval != "1day":
print("Only interval `1day` is possible for now.\n")
console.print("Only interval `1day` is possible for now.\n")
else:
self.queue = pred_controller.PredictionTechniquesController(
self.current_coin,
@@ -607,7 +602,7 @@ Loaded {self.current_coin} against {self.current_currency} from {CRYPTO_SOURCES[
self.queue,
).menu()
else:
print(
console.print(
"No coin selected. Use 'load' to load the coin you want to look at.\n"
)

View File

@@ -36,6 +36,7 @@ from gamestonk_terminal.cryptocurrency.due_diligence import coinbase_model
import gamestonk_terminal.config_terminal as cfg
from gamestonk_terminal.feature_flags import USE_ION as ion
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
INTERVALS = ["1H", "3H", "6H", "1D"]
@@ -269,10 +270,10 @@ def load(
"""
if source in ("cg", "cp"):
if vs not in ("USD", "BTC", "usd", "btc"):
print("You can only compare with usd or btc (e.g., --vs usd)\n")
console.print("You can only compare with usd or btc (e.g., --vs usd)\n")
return None, None, None, None, None, None
if interval != "1day":
print(
console.print(
"Only daily data is supported for coingecko and coinpaprika (e.g., -i 1day)\n"
)
return None, None, None, None, None, None
@@ -341,7 +342,7 @@ def load(
if vs == "usd":
vs = "USDT"
if interval not in SOURCES_INTERVALS["bin"]:
print(
console.print(
"Interval not available on binance. Run command again with one supported (e.g., -i 1day):\n",
SOURCES_INTERVALS["bin"],
)
@@ -352,7 +353,7 @@ def load(
current_coin, pairs = show_available_pairs_for_given_symbol(parsed_coin)
if len(pairs) > 0:
if vs not in pairs:
print(
console.print(
"vs specified not supported by binance. Run command again with one supported (e.g., --vs USDT):\n",
pairs,
)
@@ -363,7 +364,7 @@ def load(
if isinstance(coin_map_df, pd.DataFrame)
else coin_map_df
)
# print(f"Coin found : {current_coin}\n")
# console.print(f"Coin found : {current_coin}\n")
if should_load_ta_data:
df_prices, currency = load_ta_data(
coin_map_df=coin_map_df,
@@ -388,7 +389,7 @@ def load(
if vs == "usd":
vs = "USDT"
if interval not in SOURCES_INTERVALS["cb"]:
print(
console.print(
"Interval not available on coinbase. Run command again with one supported (e.g., -i 1day):\n",
SOURCES_INTERVALS["cb"],
)
@@ -400,13 +401,13 @@ def load(
coinbase_coin
)
if vs not in pairs:
print(
console.print(
"vs specified not supported by coinbase. Run command again with one supported (e.g., --vs USDT):\n",
pairs,
)
return None, None, None, None, None, None
if len(pairs) > 0:
# print(f"Coin found : {current_coin}\n")
# console.print(f"Coin found : {current_coin}\n")
coin_map_df = coins_map_df.loc[coin]
coin_map_df = (
@@ -425,7 +426,7 @@ def load(
)
return (current_coin, source, coin, coin_map_df, df_prices, currency)
return (current_coin, source, coin, coin_map_df, None, None)
print(f"Couldn't find coin with symbol {current_coin}\n")
console.print(f"Couldn't find coin with symbol {current_coin}\n")
return None, None, None, None, None, None
return None, None, None, None, None, None
@@ -521,7 +522,7 @@ def find(source: str, coin: str, key: str, top: int, export: str) -> None:
df = df.merge(coins, on=key)
else:
print(
console.print(
"Couldn't execute find methods for CoinPaprika, Binance, Coinbase or CoinGecko\n"
)
df = pd.DataFrame()
@@ -538,7 +539,7 @@ def find(source: str, coin: str, key: str, top: int, export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -637,13 +638,13 @@ def display_all_coins(
else:
df = pd.DataFrame(columns=["index", "id", "symbol"])
print("Couldn't find any coins")
print("")
console.print("Couldn't find any coins")
console.print("")
try:
df = df[skip : skip + top]
except Exception as e:
print(e)
console.print(e)
if gtff.USE_TABULATE_DF:
print(
@@ -657,7 +658,7 @@ def display_all_coins(
)
else:
print(df.fillna("N/A").to_string, "\n")
console.print(df.fillna("N/A").to_string, "\n")
export_data(
export,
@@ -724,7 +725,7 @@ def load_ta_data(
pair = symbol_binance + currency.upper()
if check_valid_binance_str(pair):
# print(f"{symbol_binance} loaded vs {currency.upper()}")
# console.print(f"{symbol_binance} loaded vs {currency.upper()}")
candles = client.get_klines(
symbol=pair,
@@ -754,7 +755,7 @@ def load_ta_data(
)
if df.empty:
print("No data found", "\n")
console.print("No data found", "\n")
return pd.DataFrame(), ""
df.drop(["time_close", "market_cap"], axis=1, inplace=True)
@@ -789,7 +790,7 @@ def load_ta_data(
pair = f"{coin}-{currency}"
if coinbase_model.check_validity_of_product(pair):
# print(f"{coin} loaded vs {currency}")
# console.print(f"{coin} loaded vs {currency}")
df = coinbase_model.get_candles(
product_id=pair,
@@ -862,7 +863,7 @@ def plot_chart(
pair = symbol_binance + currency
if check_valid_binance_str(pair):
# print(f"{symbol_binance} loaded vs {currency.upper()}")
# console.print(f"{symbol_binance} loaded vs {currency.upper()}")
candles = client.get_klines(
symbol=pair,
@@ -895,7 +896,7 @@ def plot_chart(
)
if df.empty:
print("There is not data to plot chart\n")
console.print("There is not data to plot chart\n")
return
df.drop(["time_close", "market_cap"], axis=1, inplace=True)
@@ -931,7 +932,7 @@ def plot_chart(
if ion:
plt.ion()
plt.show()
print("")
console.print("")
if source == "cg":
symbol_coingecko = coin_map_df["CoinGecko"]
@@ -969,7 +970,7 @@ def plot_chart(
if ion:
plt.ion()
plt.show()
print("")
console.print("")
if source == "cb":
symbol_coinbase = coin_map_df["Coinbase"]
@@ -977,7 +978,7 @@ def plot_chart(
pair = f"{coin}-{currency}"
if coinbase_model.check_validity_of_product(pair):
# print(f"{coin} loaded vs {currency}")
# console.print(f"{coin} loaded vs {currency}")
df = coinbase_model.get_candles(
product_id=pair,
@@ -1010,7 +1011,7 @@ def plot_chart(
if ion:
plt.ion()
plt.show()
print("")
console.print("")
def plot_order_book(bids: np.ndarray, asks: np.ndarray, coin: str) -> None:
@@ -1042,4 +1043,4 @@ def plot_order_book(bids: np.ndarray, asks: np.ndarray, coin: str) -> None:
if ion:
plt.ion()
plt.show()
print("")
console.print("")

View File

@@ -5,7 +5,7 @@ import argparse
from typing import List
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal.rich_config import console
from gamestonk_terminal.cryptocurrency.defi import (
graph_model,
coindix_model,
@@ -77,32 +77,30 @@ class DefiController(BaseController):
def print_help(self):
"""Print help"""
help_text = """
Decentralized Finance Menu:
Overview:
newsletter Recent DeFi related newsletters
dpi DeFi protocols listed on DefiPulse
funding Funding rates - current or last 30 days average
borrow DeFi borrow rates - current or last 30 days average
lending DeFi ending rates - current or last 30 days average
vaults Top DeFi Vaults on different blockchains [Source: Coindix]
Defi Llama:
ldapps Lists dApps
gdapps Display top DeFi dApps grouped by chain
stvl Display historical values of the total sum of TVLs from all dApps
dtvl Display historical total value locked (TVL) by dApp
Uniswap:
help_text = """[cmds]
[info]Overview:[/info]
newsletter Recent DeFi related newsletters [src][Substack][/src]
dpi DeFi protocols listed on DefiPulse [src][Defipulse][/src]
funding Funding rates - current or last 30 days average [src][Defirate][/src]
borrow DeFi borrow rates - current or last 30 days average [src][Defirate][/src]
lending DeFi ending rates - current or last 30 days average [src][Defirate][/src]
vaults Top DeFi Vaults on different blockchains [src][[Coindix][/src]
[src][The Graph][/src] [info]Uniswap[/info]
tokens Tokens trade-able on Uniswap
stats Base statistics about Uniswap
pairs Recently added pairs on Uniswap
pools Pools by volume on Uniswap
swaps Recent swaps done on Uniswap
TerraEngineer:
[src][Defi Llama][/src]
ldapps Lists dApps
gdapps Display top DeFi dApps grouped by chain
stvl Display historical values of the total sum of TVLs from all dApps
dtvl Display historical total value locked (TVL) by dApp
[src][Terra Engineer][/src]
aterra Displays 30-day history of specified asset in terra address
ayr Displays 30-day history of anchor yield reserve
ayr Displays 30-day history of anchor yield reserve[/cmds]
"""
print(help_text)
console.print(text=help_text, menu="Cryptocurrency - Decentralized Finance")
def call_aterra(self, other_args: List[str]):
parser = argparse.ArgumentParser(

View File

@@ -6,6 +6,7 @@ from tabulate import tabulate
from gamestonk_terminal.cryptocurrency.defi import defipulse_model
from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
def display_defipulse(top: int, sortby: str, descend: bool, export: str = "") -> None:
@@ -41,7 +42,7 @@ def display_defipulse(top: int, sortby: str, descend: bool, export: str = "") ->
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,

View File

@@ -6,6 +6,7 @@ from tabulate import tabulate
from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal.cryptocurrency.defi import defirate_model
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
def display_funding_rates(top: int, current: bool = True, export: str = "") -> None:
@@ -38,7 +39,7 @@ def display_funding_rates(top: int, current: bool = True, export: str = "") -> N
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -79,7 +80,7 @@ def display_lending_rates(top: int, current: bool = True, export: str = "") -> N
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -121,7 +122,7 @@ def display_borrow_rates(top: int, current: bool = True, export: str = "") -> No
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,

View File

@@ -9,6 +9,7 @@ from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.cryptocurrency.dataframe_helpers import (
very_long_number_formatter,
)
from gamestonk_terminal.rich_config import console
def display_uni_tokens(
@@ -56,7 +57,7 @@ def display_uni_tokens(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -92,7 +93,7 @@ def display_uni_stats(export: str = "") -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -161,7 +162,7 @@ def display_recently_added(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -207,7 +208,7 @@ def display_uni_pools(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -255,7 +256,7 @@ def display_last_uni_swaps(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,

View File

@@ -3,7 +3,6 @@ __docformat__ = "numpy"
import os
from matplotlib import ticker, dates as mdates
from rich.console import Console
import matplotlib.pyplot as plt
from gamestonk_terminal.cryptocurrency.cryptocurrency_helpers import read_data_file
from gamestonk_terminal.cryptocurrency.dataframe_helpers import (
@@ -18,8 +17,7 @@ from gamestonk_terminal.helper_funcs import (
)
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.config_plot import PLOT_DPI
t_console = Console()
from gamestonk_terminal.rich_config import console
def display_grouped_defi_protocols(num: int = 50, export: str = "") -> None:
@@ -120,7 +118,7 @@ def display_defi_protocols(
)
if gtff.USE_TABULATE_DF:
t_console.print(
console.print(
rich_table_from_df(
df.head(top),
headers=list(df.columns),
@@ -130,7 +128,7 @@ def display_defi_protocols(
"\n",
)
else:
t_console.print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -230,7 +228,7 @@ def display_defi_tvl(top: int, export: str = "") -> None:
if gtff.USE_ION:
plt.ion()
plt.show()
print("")
console.print("")
export_data(
export,

View File

@@ -8,6 +8,8 @@ import requests
from bs4 import BeautifulSoup
from dateutil import parser
from gamestonk_terminal.rich_config import console
def scrape_substack(url: str) -> list:
"""Helper method to scrape newsletters from substack.
@@ -66,7 +68,7 @@ def get_newsletters() -> pd.DataFrame:
try:
newsletters.append(pd.DataFrame(newsletter))
except KeyError as e:
print(e, "\n")
console.print(e, "\n")
continue
df = pd.concat(newsletters, ignore_index=True)

View File

@@ -7,6 +7,7 @@ from tabulate import tabulate
from gamestonk_terminal.cryptocurrency.defi import substack_model
from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
def display_newsletters(top: int = 10, export: str = "") -> None:
@@ -36,7 +37,7 @@ def display_newsletters(top: int = 10, export: str = "") -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,

View File

@@ -6,6 +6,7 @@ from tabulate import tabulate
from gamestonk_terminal.cryptocurrency.discovery import coinmarketcap_model
from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
sort_map = {
"Symbol": "Symbol",
@@ -35,7 +36,7 @@ def display_cmc_top_coins(top: int, sortby: str, descend: bool, export: str) ->
df = coinmarketcap_model.get_cmc_top_n()
if df.empty:
print("No Data Found\n")
console.print("No Data Found\n")
return
df = df.sort_values(by=sort_map[sortby], ascending=descend)
@@ -52,7 +53,7 @@ def display_cmc_top_coins(top: int, sortby: str, descend: bool, export: str) ->
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,

View File

@@ -6,6 +6,7 @@ from tabulate import tabulate
from gamestonk_terminal.helper_funcs import export_data
import gamestonk_terminal.cryptocurrency.discovery.coinpaprika_model as paprika
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
def display_search_results(
@@ -35,7 +36,9 @@ def display_search_results(
df = paprika.get_search_results(query=query, category=category)
if df.empty:
print(f"No results for search query '{query}' in category '{category}'\n")
console.print(
f"No results for search query '{query}' in category '{category}'\n"
)
return
df = df.sort_values(by=sortby, ascending=descend)
@@ -52,7 +55,7 @@ def display_search_results(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,

View File

@@ -5,6 +5,7 @@ __docformat__ = "numpy"
import argparse
from typing import List
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal.rich_config import console
from gamestonk_terminal.parent_classes import BaseController
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.helper_funcs import (
@@ -91,13 +92,13 @@ class DiscoveryController(BaseController):
def print_help(self):
"""Print help"""
help_text = """
CoinGecko:
cgtrending trending coins on CoinGecko
cgvoted most voted coins on CoinGecko
cgvisited most visited coins on CoinGecko
cgvolume coins with highest volume on CoinGecko
cgrecently recently added on CoinGecko
help_text = """[cmds]
[src][CoinGecko][/src]
cgtrending trending coins
cgvoted most voted coins
cgvisited most visited coins
cgvolume coins with highest volume
cgrecently recently added
cgsentiment coins with most positive sentiment
cggainers top gainers - coins which price gained the most in given period
cglosers top losers - coins which price dropped the most in given period
@@ -105,12 +106,12 @@ CoinGecko:
cgdefi top defi protocols
cgdex top decentralized exchanges
cgnft top non fungible tokens
CoinPaprika:
cpsearch search on CoinPaprika
CoinMarketCap:
cmctop top coins from CoinMarketCap
[src][CoinPaprika][/src]
cpsearch search for coins
[src][CoinMarketCap][/src]
cmctop top coins[/cmds]
"""
print(help_text)
console.print(text=help_text, menu="Cryptocurrency - Discovery")
def call_cggainers(self, other_args):
"""Process gainers command"""

View File

@@ -20,6 +20,7 @@ from gamestonk_terminal.cryptocurrency.pycoingecko_helpers import (
get_btc_price,
GECKO_BASE_URL,
)
from gamestonk_terminal.rich_config import console
PERIODS = {
"1h": "?time=h1",
@@ -123,7 +124,7 @@ def get_gainers_or_losers(period: str = "1h", typ: str = "gainers") -> pd.DataFr
try:
scraped_data = scrape_gecko_data(url)
except RetryError as e:
print(e)
console.print(e)
return pd.DataFrame()
rows = scraped_data.find_all("tbody")[category.get(typ)].find_all("tr")
results = []
@@ -133,7 +134,7 @@ def get_gainers_or_losers(period: str = "1h", typ: str = "gainers") -> pd.DataFr
try:
change = percent_to_float(change)
except (ValueError, TypeError) as e:
print(e)
console.print(e)
results.append([symbol, name, volume, price, change, url])
df = pd.DataFrame(
results,
@@ -180,7 +181,7 @@ def get_discovered_coins(category: str = "trending") -> pd.DataFrame:
try:
scraped_data = scrape_gecko_data(url)
except RetryError as e:
print(e)
console.print(e)
return pd.DataFrame()
popular = scraped_data.find_all("div", class_="col-12 col-sm-6 col-md-6 col-lg-4")[
CATEGORIES[category]
@@ -234,7 +235,7 @@ def get_recently_added_coins() -> pd.DataFrame:
try:
scraped_data = scrape_gecko_data(url)
except RetryError as e:
print(e)
console.print(e)
return pd.DataFrame()
rows = scraped_data.find("tbody").find_all("tr")
results = []
@@ -286,7 +287,7 @@ def get_yield_farms() -> pd.DataFrame:
try:
scraped_data = scrape_gecko_data(url)
except RetryError as e:
print(e)
console.print(e)
return pd.DataFrame()
rows = scraped_data.find("tbody").find_all("tr")
results = []
@@ -357,7 +358,7 @@ def get_top_volume_coins() -> pd.DataFrame:
try:
scraped_data = scrape_gecko_data(url)
except RetryError as e:
print(e)
console.print(e)
return pd.DataFrame()
rows = scraped_data.find("tbody").find_all("tr")
results = []
@@ -401,7 +402,7 @@ Defi has currently a market cap of {int(float(data['defi_market_cap']))} USD dol
try:
scraped_data = scrape_gecko_data(url)
except RetryError as e:
print(e)
console.print(e)
return ["", pd.DataFrame()]
rows = scraped_data.find("tbody").find_all("tr")
results = []
@@ -467,7 +468,7 @@ def get_top_dexes() -> pd.DataFrame:
try:
scraped_data = scrape_gecko_data(url)
except RetryError as e:
print(e)
console.print(e)
return pd.DataFrame()
rows = scraped_data.find("tbody").find_all("tr")
results = []
@@ -510,7 +511,7 @@ def get_top_nfts() -> pd.DataFrame:
try:
scraped_data = scrape_gecko_data(url)
except RetryError as e:
print(e)
console.print(e)
return pd.DataFrame()
rows = scraped_data.find("tbody").find_all("tr")
results = []

View File

@@ -7,6 +7,7 @@ from tabulate import tabulate
from gamestonk_terminal.cryptocurrency.discovery import pycoingecko_model
from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
register_matplotlib_converters()
@@ -60,7 +61,7 @@ def display_gainers(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -69,9 +70,9 @@ def display_gainers(
df_data,
)
else:
print("")
print("Unable to retrieve data from CoinGecko.")
print("")
console.print("")
console.print("Unable to retrieve data from CoinGecko.")
console.print("")
def display_losers(
@@ -119,7 +120,7 @@ def display_losers(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -128,9 +129,9 @@ def display_losers(
df_data,
)
else:
print("")
print("Unable to retrieve data from CoinGecko.")
print("")
console.print("")
console.print("Unable to retrieve data from CoinGecko.")
console.print("")
def display_discover(
@@ -183,7 +184,7 @@ def display_discover(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -192,9 +193,9 @@ def display_discover(
df_data,
)
else:
print("")
print("Unable to retrieve data from CoinGecko.")
print("")
console.print("")
console.print("Unable to retrieve data from CoinGecko.")
console.print("")
def display_recently_added(
@@ -239,7 +240,7 @@ def display_recently_added(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -274,7 +275,7 @@ def display_top_defi_coins(
stats_str = res[0]
df = res[1].sort_values(by=sortby, ascending=descend)
if df.empty:
print("No available data\n")
console.print("No available data\n")
else:
df_data = df.copy()
@@ -283,7 +284,7 @@ def display_top_defi_coins(
else:
df.drop("Url", axis=1, inplace=True)
print("\n", stats_str, "\n")
console.print("\n", stats_str, "\n")
if gtff.USE_TABULATE_DF:
print(
tabulate(
@@ -296,7 +297,7 @@ def display_top_defi_coins(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -336,7 +337,7 @@ def display_top_dex(top: int, sortby: str, descend: bool, export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -377,7 +378,7 @@ def display_top_volume_coins(top: int, sortby: str, descend: bool, export: str)
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -386,9 +387,9 @@ def display_top_volume_coins(top: int, sortby: str, descend: bool, export: str)
df,
)
else:
print("")
print("Unable to retrieve data from CoinGecko.")
print("")
console.print("")
console.print("Unable to retrieve data from CoinGecko.")
console.print("")
def display_top_nft(
@@ -436,7 +437,7 @@ def display_top_nft(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -445,9 +446,9 @@ def display_top_nft(
df_data,
)
else:
print("")
print("Unable to retrieve data from CoinGecko.")
print("")
console.print("")
console.print("Unable to retrieve data from CoinGecko.")
console.print("")
def display_yieldfarms(top: int, sortby: str, descend: bool, export: str) -> None:
@@ -485,7 +486,7 @@ def display_yieldfarms(top: int, sortby: str, descend: bool, export: str) -> Non
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -494,6 +495,6 @@ def display_yieldfarms(top: int, sortby: str, descend: bool, export: str) -> Non
df_data,
)
else:
print("")
print("Unable to retrieve data from CoinGecko.")
print("")
console.print("")
console.print("Unable to retrieve data from CoinGecko.")
console.print("")

View File

@@ -13,6 +13,7 @@ from binance.exceptions import BinanceAPIException
import gamestonk_terminal.config_terminal as cfg
from gamestonk_terminal.helper_funcs import plot_autoscale
from gamestonk_terminal.feature_flags import USE_ION as ion
from gamestonk_terminal.rich_config import console
def _get_trading_pairs() -> List[dict]:
@@ -119,7 +120,7 @@ def show_available_pairs_for_given_symbol(
for k, v in pairs.items():
if k == symbol_upper:
return k, v
print(f"Couldn't find anything for symbol {symbol_upper}\n")
console.print(f"Couldn't find anything for symbol {symbol_upper}\n")
return None, []
@@ -151,4 +152,4 @@ def plot_candles(candles_df: pd.DataFrame, title: str) -> None:
if ion:
plt.ion()
plt.show()
print("")
console.print("")

View File

@@ -12,6 +12,7 @@ from gamestonk_terminal.helper_funcs import (
from gamestonk_terminal.cryptocurrency.cryptocurrency_helpers import plot_order_book
import gamestonk_terminal.config_terminal as cfg
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
def display_order_book(coin: str, limit: int, currency: str, export: str) -> None:
@@ -66,17 +67,17 @@ def display_balance(coin: str, currency: str, export: str) -> None:
pair = coin + currency
current_balance = client.get_asset_balance(asset=pair)
if current_balance is None:
print("Check loaded coin")
console.print("Check loaded coin")
return
print("")
console.print("")
amounts = [float(current_balance["free"]), float(current_balance["locked"])]
total = np.sum(amounts)
df = pd.DataFrame(amounts).apply(lambda x: str(float(x)))
df.columns = ["Amount"]
df.index = ["Free", "Locked"]
df["Percent"] = df.div(df.sum(axis=0), axis=1).round(3)
print(f"You currently have {total} coins and the breakdown is:")
console.print(f"You currently have {total} coins and the breakdown is:")
if gtff.USE_TABULATE_DF:
print(
@@ -84,7 +85,7 @@ def display_balance(coin: str, currency: str, export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,

View File

@@ -8,6 +8,7 @@ from gamestonk_terminal.cryptocurrency.coinbase_helpers import (
check_validity_of_product,
make_coinbase_request,
)
from gamestonk_terminal.rich_config import console
def show_available_pairs_for_given_symbol(symbol: str = "ETH") -> Tuple[str, list]:
@@ -15,7 +16,7 @@ def show_available_pairs_for_given_symbol(symbol: str = "ETH") -> Tuple[str, lis
df = pd.DataFrame(pairs)[["base_currency", "quote_currency"]]
if not isinstance(symbol, str):
print(
console.print(
f"You did not provide correct symbol {symbol}. Symbol needs to be a string.\n"
)
return symbol, []
@@ -42,7 +43,7 @@ def get_trading_pair_info(product_id: str) -> pd.DataFrame:
pair = make_coinbase_request(f"/products/{product_id}")
df = pd.Series(pair).to_frame().reset_index()
df.columns = ["Metric", "Value"]
print(df)
console.print(df)
return df
@@ -141,7 +142,9 @@ def get_candles(product_id: str, interval: str = "24h") -> pd.DataFrame:
"1day": 86400,
}
if interval not in interval_map:
print(f"Wrong interval. Please use on from {list(interval_map.keys())}\n")
console.print(
f"Wrong interval. Please use on from {list(interval_map.keys())}\n"
)
return pd.DataFrame()
granularity: int = interval_map[interval]

View File

@@ -10,6 +10,7 @@ from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.cryptocurrency.due_diligence import coinbase_model
from gamestonk_terminal.cryptocurrency.cryptocurrency_helpers import plot_order_book
from gamestonk_terminal.rich_config import console
register_matplotlib_converters()
@@ -67,7 +68,7 @@ def display_trades(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -105,7 +106,7 @@ def display_candles(product_id: str, interval: str, export) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -142,7 +143,7 @@ def display_stats(product_id: str, export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,

View File

@@ -8,6 +8,7 @@ from gamestonk_terminal.cryptocurrency.due_diligence.coinglass_model import (
from gamestonk_terminal.helper_funcs import export_data, plot_autoscale
from gamestonk_terminal import config_plot as cfgPlot
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
def display_open_interest(symbol: str, interval: int, export: str) -> None:
@@ -24,10 +25,10 @@ def display_open_interest(symbol: str, interval: int, export: str) -> None:
Export dataframe data to csv,json,xlsx file"""
df = get_open_interest_per_exchange(symbol, interval)
if df.empty:
print("Error in coinglass request")
console.print("Error in coinglass request")
else:
plot_data(df, symbol)
print("")
console.print("")
export_data(
export,

View File

@@ -7,6 +7,7 @@ import textwrap
import pandas as pd
from dateutil import parser
from gamestonk_terminal.cryptocurrency.coinpaprika_helpers import PaprikaSession
from gamestonk_terminal.rich_config import console
def get_coin(coin_id: str = "eth-ethereum") -> dict:
@@ -44,7 +45,7 @@ def get_coin_twitter_timeline(coin_id: str = "eth-ethereum") -> pd.DataFrame:
session = PaprikaSession()
res = session.make_request(session.ENDPOINTS["coin_tweeter"].format(coin_id))
if "error" in res:
print(res)
console.print(res)
return pd.DataFrame()
if isinstance(res, list) and len(res) == 0:
return pd.DataFrame()
@@ -160,7 +161,7 @@ def get_coin_markets_by_id(
session.ENDPOINTS["coin_markets"].format(coin_id), quotes=quotes
)
if "error" in markets:
print(markets)
console.print(markets)
return pd.DataFrame()
data = []
@@ -222,7 +223,7 @@ def get_ohlc_historical(
end=end,
)
if "error" in data:
print(data)
console.print(data)
return pd.DataFrame()
return pd.DataFrame(data)
@@ -292,21 +293,21 @@ def get_tickers_info_for_coin(
try:
tickers[key] = parser.parse(date).strftime("%Y-%m-%d %H:%M:%S")
except (KeyError, ValueError, TypeError) as e:
print(e)
console.print(e)
if key == "quotes":
try:
tickers[key][quotes]["ath_date"] = parser.parse(
tickers[key][quotes]["ath_date"]
).strftime("%Y-%m-%d %H:%M:%S")
except (KeyError, ValueError, TypeError) as e:
print(e)
console.print(e)
df = pd.json_normalize(tickers)
try:
df.columns = [col.replace("quotes.", "") for col in list(df.columns)]
df.columns = [col.replace(".", "_").lower() for col in list(df.columns)]
except KeyError as e:
print(e)
console.print(e)
df = df.T.reset_index()
df.columns = ["Metric", "Value"]
return df
@@ -340,7 +341,7 @@ def validate_coin(coin: str, coins_dct: dict) -> Tuple[str, Optional[Any]]:
if not coin_found:
raise ValueError(f"Could not find coin with given id: {coin}\n")
# print(f"Coin found : {coin_found} with symbol {symbol}\n")
# console.print(f"Coin found : {coin_found} with symbol {symbol}\n")
return coin_found, symbol

View File

@@ -12,6 +12,7 @@ from gamestonk_terminal.cryptocurrency.dataframe_helpers import (
long_number_format_with_type_check,
)
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
register_matplotlib_converters()
@@ -101,7 +102,7 @@ def display_twitter(
df = coinpaprika_model.get_coin_twitter_timeline(coin_id)
if df.empty:
print(f"Couldn't find any tweets for coin {coin_id}", "\n")
console.print(f"Couldn't find any tweets for coin {coin_id}", "\n")
return
df = df.sort_values(by=sortby, ascending=descend)
@@ -121,7 +122,7 @@ def display_twitter(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -155,7 +156,7 @@ def display_events(
df = coinpaprika_model.get_coin_events_by_id(coin_id)
if df.empty:
print(f"Couldn't find any events for coin {coin_id}\n")
console.print(f"Couldn't find any events for coin {coin_id}\n")
return
df = df.sort_values(by=sortby, ascending=descend)
@@ -179,7 +180,7 @@ def display_events(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -211,7 +212,7 @@ def display_exchanges(
df = coinpaprika_model.get_coin_exchanges_by_id(coin_id)
if df.empty:
print("No data found", "\n")
console.print("No data found", "\n")
return
df = df.sort_values(by=sortby, ascending=descend)
@@ -228,7 +229,7 @@ def display_exchanges(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -273,7 +274,7 @@ def display_markets(
df = coinpaprika_model.get_coin_markets_by_id(coin_id, currency)
if df.empty:
print("There is no data \n")
console.print("There is no data \n")
return
df = df.sort_values(by=sortby, ascending=descend)
@@ -297,7 +298,7 @@ def display_markets(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -324,7 +325,7 @@ def display_price_supply(coin_id: str, currency: str, export: str) -> None:
df = coinpaprika_model.get_tickers_info_for_coin(coin_id, currency)
if df.empty:
print("No data found", "\n")
console.print("No data found", "\n")
return
df = df.applymap(lambda x: long_number_format_with_type_check(x))
@@ -341,7 +342,7 @@ def display_price_supply(coin_id: str, currency: str, export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -366,7 +367,7 @@ def display_basic(coin_id: str, export: str) -> None:
df = coinpaprika_model.basic_coin_info(coin_id)
if df.empty:
print("No data available\n")
console.print("No data available\n")
return
if gtff.USE_TABULATE_DF:
@@ -381,7 +382,7 @@ def display_basic(coin_id: str, export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,

View File

@@ -7,6 +7,7 @@ from typing import List
from datetime import datetime, timedelta
import pandas as pd
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal.rich_config import console
from gamestonk_terminal.parent_classes import BaseController
from gamestonk_terminal.cryptocurrency.due_diligence import (
coinglass_model,
@@ -135,34 +136,28 @@ class DueDiligenceController(BaseController):
def print_help(self):
"""Print help"""
help_text = "Due Diligence Menu:\n"
help_text += """
source_txt = CRYPTO_SOURCES.get(self.source, "?") if self.source != "" else ""
help_text = f"""[cmds]
load load a specific cryptocurrency for analysis
"""
help_text += (
f"\nCoin: {self.current_coin}" if self.current_coin != "" else "\nCoin: ?"
)
help_text += (
f"\nSource: {CRYPTO_SOURCES.get(self.source, '?')}\n"
if self.source != ""
else "\nSource: ?\n"
)
help_text += """
Glassnode:
[param]Coin: [/param]{self.current_coin}
[param]Source: [/param]{source_txt}
[src]Glassnode[/src]
active active addresses
nonzero addresses with non-zero balances
change 30d change of supply held on exchange wallets
eb total balance held on exchanges (in percentage and units)
Coinglass:
[src]Coinglass[/src]
oi open interest per exchange
CoinPaprika:
[src]CoinPaprika[/src]
basic basic information about loaded coin
ps price and supply related metrics for loaded coin
mkt all markets for loaded coin
ex all exchanges where loaded coin is listed
twitter tweets for loaded coin
events events related to loaded coin
CoinGecko:
[src]CoinGecko[/src]
info basic information about loaded coin
market market stats about loaded coin
ath all time high related stats for loaded coin
@@ -172,15 +167,15 @@ CoinGecko:
score different kind of scores for loaded coin, e.g developer score, sentiment score
dev github, bitbucket coin development statistics
bc links to blockchain explorers for loaded coin
Binance:
[src]Binance[/src]
binbook show order book
balance show coin balance
Coinbase:
[src]Coinbase[/src]
cbbook show order book
trades show last trades
stats show coin stats
stats show coin stats[/cmds]
"""
print(help_text)
console.print(text=help_text, menu="Stocks - Due Diligence")
def custom_reset(self):
"""Class specific component of reset command"""
@@ -233,7 +228,9 @@ Coinbase:
coin=ns_parser.coin, source=ns_parser.source
)
if self.symbol:
print(f"\nLoaded {self.current_coin} from source {self.source}\n")
console.print(
f"\nLoaded {self.current_coin} from source {self.source}\n"
)
def call_nonzero(self, other_args: List[str]):
"""Process nonzero command"""
@@ -292,7 +289,7 @@ Coinbase:
)
else:
print("Glassnode source does not support this symbol\n")
console.print("Glassnode source does not support this symbol\n")
def call_active(self, other_args: List[str]):
"""Process active command"""
@@ -350,7 +347,7 @@ Coinbase:
)
else:
print("Glassnode source does not support this symbol\n")
console.print("Glassnode source does not support this symbol\n")
def call_change(self, other_args: List[str]):
"""Process change command"""
@@ -422,7 +419,7 @@ Coinbase:
export=ns_parser.export,
)
else:
print("Glassnode source does not support this symbol\n")
console.print("Glassnode source does not support this symbol\n")
def call_eb(self, other_args: List[str]):
"""Process eb command"""
@@ -503,7 +500,7 @@ Coinbase:
)
else:
print("Glassnode source does not support this symbol\n")
console.print("Glassnode source does not support this symbol\n")
def call_oi(self, other_args):
"""Process oi command"""
@@ -781,7 +778,7 @@ Coinbase:
_, quotes = coinbase_model.show_available_pairs_for_given_symbol(coin)
if len(quotes) < 0:
print(f"Couldn't find any quoted coins for provided symbol {coin}")
console.print(f"Couldn't find any quoted coins for provided symbol {coin}")
parser.add_argument(
"--vs",
@@ -843,7 +840,7 @@ Coinbase:
coin = self.coin_map_df["Coinbase"]
_, quotes = coinbase_model.show_available_pairs_for_given_symbol(coin)
if len(quotes) < 0:
print(
console.print(
f"Couldn't find any quoted coins for provided symbol {self.current_coin}"
)

View File

@@ -10,6 +10,7 @@ from gamestonk_terminal.common.behavioural_analysis.finbrain_view import (
)
from gamestonk_terminal.common.behavioural_analysis.finbrain_model import get_sentiment
from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal.rich_config import console
PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -43,21 +44,21 @@ def display_crypto_sentiment_analysis(coin: str, export: str) -> None:
) # Currently only USD pairs are available
if df_sentiment.empty:
print(f"Couldn't find Sentiment Data for {coin}\n")
console.print(f"Couldn't find Sentiment Data for {coin}\n")
return
plot_sentiment(df_sentiment, coin)
df_sentiment.sort_index(ascending=True, inplace=True)
if gtff.USE_COLOR:
print(
console.print(
df_sentiment["Sentiment Analysis"]
.apply(sentiment_coloring, last_val=0)
.to_string(),
"\n",
)
else:
print(df_sentiment.to_string(), "\n")
console.print(df_sentiment.to_string(), "\n")
export_data(
export,

View File

@@ -14,6 +14,7 @@ from gamestonk_terminal.cryptocurrency.due_diligence.glassnode_model import (
get_non_zero_addresses,
)
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
def display_btc_rainbow(since: int, until: int, export: str = ""):
@@ -158,7 +159,7 @@ def display_active_addresses(
df_addresses = get_active_addresses(asset, interval, since, until)
if df_addresses.empty:
print("Error in glassnode request")
console.print("Error in glassnode request")
else:
_, main_ax = plt.subplots(figsize=plot_autoscale(), dpi=cfgPlot.PLOT_DPI)
@@ -179,7 +180,7 @@ def display_active_addresses(
plt.show()
print("")
console.print("")
export_data(
export,
@@ -212,7 +213,7 @@ def display_non_zero_addresses(
df_addresses = get_non_zero_addresses(asset, interval, since, until)
if df_addresses.empty:
print("Error in glassnode request")
console.print("Error in glassnode request")
else:
_, main_ax = plt.subplots(figsize=plot_autoscale(), dpi=cfgPlot.PLOT_DPI)
@@ -233,7 +234,7 @@ def display_non_zero_addresses(
plt.show()
print("")
console.print("")
export_data(
export,
@@ -270,7 +271,7 @@ def display_exchange_net_position_change(
)
if df_addresses.empty:
print("Error in glassnode request")
console.print("Error in glassnode request")
else:
_, ax1 = plt.subplots(figsize=(25, 7))
@@ -304,7 +305,7 @@ def display_exchange_net_position_change(
plt.ion()
plt.show()
print("")
console.print("")
export_data(
export,
@@ -347,7 +348,7 @@ def display_exchange_balances(
df_balance = get_exchange_balances(asset, exchange, interval, since, until)
if df_balance.empty:
print("Error in glassnode request")
console.print("Error in glassnode request")
else:
_, ax1 = plt.subplots(figsize=(25, 7))
if percentage:
@@ -375,7 +376,7 @@ def display_exchange_balances(
plt.show()
print("")
console.print("")
export_data(
export,
@@ -412,7 +413,7 @@ def display_hashrate(
df = get_hashrate(asset, interval, since, until)
if df.empty:
print("Error in glassnode request")
console.print("Error in glassnode request")
else:
_, ax1 = plt.subplots(figsize=plot_autoscale(), dpi=cfgPlot.PLOT_DPI)
ax1.plot(df.index, df["hashrate"] / 1_000_000_000_000, c="k")
@@ -435,7 +436,7 @@ def display_hashrate(
plt.show()
print("")
console.print("")
export_data(
export,

View File

@@ -19,6 +19,7 @@ from gamestonk_terminal.cryptocurrency.pycoingecko_helpers import (
from gamestonk_terminal.cryptocurrency.dataframe_helpers import (
replace_underscores_in_column_names,
)
from gamestonk_terminal.rich_config import console
CHANNELS = {
"telegram_channel_identifier": "telegram",
@@ -552,7 +553,7 @@ class Coin:
single_stats["circulating_supply"] / single_stats["total_supply"]
)
except (ZeroDivisionError, TypeError) as e:
print(e)
console.print(e)
df = pd.Series(single_stats).to_frame().reset_index()
df.columns = ["Metric", "Value"]
df["Metric"] = df["Metric"].apply(

View File

@@ -11,6 +11,7 @@ from gamestonk_terminal.helper_funcs import (
import gamestonk_terminal.cryptocurrency.due_diligence.pycoingecko_model as gecko
from gamestonk_terminal.cryptocurrency.dataframe_helpers import wrap_text_in_df
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
register_matplotlib_converters()
@@ -60,7 +61,7 @@ def display_coin_potential_returns(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -97,7 +98,7 @@ def display_info(symbol: str, export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -134,7 +135,7 @@ def display_web(symbol: str, export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -169,7 +170,7 @@ def display_social(symbol: str, export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -205,7 +206,7 @@ def display_dev(symbol: str, export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -244,7 +245,7 @@ def display_ath(symbol: str, currency: str, export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -283,7 +284,7 @@ def display_atl(symbol: str, currency: str, export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -319,7 +320,7 @@ def display_score(symbol: str, export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -355,7 +356,7 @@ def display_bc(symbol: str, export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -391,7 +392,7 @@ def display_market(symbol: str, export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,

View File

@@ -2,6 +2,7 @@ import argparse
from typing import List
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal.rich_config import console
from gamestonk_terminal.parent_classes import BaseController
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.menu import session
@@ -30,16 +31,16 @@ class NFTController(BaseController):
def print_help(self):
"""Print help"""
help_text = """
nftcalendar.io:
help_text = """[cmds]
[src][Nftcalendar.io][/src]
today today's NFT drops
upcoming upcoming NFT drops
ongoing Ongoing NFT drops
newest Recently NFTs added
opensea.io
stats check open sea collection stats
[src][Opensea.io][/src]
stats check open sea collection stats[/cmds]
"""
print(help_text)
console.print(text=help_text, menu="Cryptocurrency - Non Fungible Token")
def call_stats(self, other_args: List[str]):
"""Process stats command"""

View File

@@ -4,6 +4,7 @@ __docformat__ = "numpy"
import os
from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal.cryptocurrency.nft import nftcalendar_model
from gamestonk_terminal.rich_config import console
def display_nft_today_drops(num: int, export: str):
@@ -19,13 +20,13 @@ def display_nft_today_drops(num: int, export: str):
nft_drops = nftcalendar_model.get_nft_today_drops()
if nft_drops.empty:
print("No data found.", "\n")
console.print("No data found.", "\n")
else:
for _, nft in nft_drops.head(num).iterrows():
print(nft["Dates"] + " - " + nft["Title"])
print(nft["Link"])
print(nft["Description"])
print("")
console.print(nft["Dates"] + " - " + nft["Title"])
console.print(nft["Link"])
console.print(nft["Description"])
console.print("")
export_data(
export,
@@ -48,13 +49,13 @@ def display_nft_upcoming_drops(num: int, export: str):
nft_drops = nftcalendar_model.get_nft_upcoming_drops()
if nft_drops.empty:
print("No data found.", "\n")
console.print("No data found.", "\n")
else:
for _, nft in nft_drops.head(num).iterrows():
print(nft["Dates"] + " - " + nft["Title"])
print(nft["Link"])
print(nft["Description"])
print("")
console.print(nft["Dates"] + " - " + nft["Title"])
console.print(nft["Link"])
console.print(nft["Description"])
console.print("")
export_data(
export,
@@ -77,13 +78,13 @@ def display_nft_ongoing_drops(num: int, export: str):
nft_drops = nftcalendar_model.get_nft_ongoing_drops()
if nft_drops.empty:
print("No data found.", "\n")
console.print("No data found.", "\n")
else:
for _, nft in nft_drops.head(num).iterrows():
print(nft["Dates"] + " - " + nft["Title"])
print(nft["Link"])
print(nft["Description"])
print("")
console.print(nft["Dates"] + " - " + nft["Title"])
console.print(nft["Link"])
console.print(nft["Description"])
console.print("")
export_data(
export,
@@ -106,13 +107,13 @@ def display_nft_newest_drops(num: int, export: str):
nft_drops = nftcalendar_model.get_nft_newest_drops()
if nft_drops.empty:
print("No data found.", "\n")
console.print("No data found.", "\n")
else:
for _, nft in nft_drops.head(num).iterrows():
print(nft["Dates"] + " - " + nft["Title"])
print(nft["Link"])
print(nft["Description"])
print("")
console.print(nft["Dates"] + " - " + nft["Title"])
console.print(nft["Link"])
console.print(nft["Description"])
console.print("")
export_data(
export,

View File

@@ -5,6 +5,7 @@ from tabulate import tabulate
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal.cryptocurrency.nft.opensea_model import get_collection_stats
from gamestonk_terminal.rich_config import console
def display_collection_stats(slug: str, export: str):
@@ -20,7 +21,7 @@ def display_collection_stats(slug: str, export: str):
collection_stats_df = get_collection_stats(slug)
if collection_stats_df.empty:
print("No data found.", "\n")
console.print("No data found.", "\n")
else:
if gtff.USE_TABULATE_DF:
print(
@@ -34,7 +35,7 @@ def display_collection_stats(slug: str, export: str):
"\n",
)
else:
print(collection_stats_df.to_string, "\n")
console.print(collection_stats_df.to_string, "\n")
export_data(
export,

View File

@@ -11,6 +11,7 @@ from gamestonk_terminal.cryptocurrency.dataframe_helpers import (
from gamestonk_terminal.cryptocurrency.onchain import bitquery_model
from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
def display_dex_trades(
@@ -70,7 +71,7 @@ def display_dex_trades(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -140,7 +141,7 @@ def display_daily_volume_for_given_pair(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -204,7 +205,7 @@ def display_dex_volume_for_token(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -268,7 +269,7 @@ def display_ethereum_unique_senders(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -328,7 +329,7 @@ def display_most_traded_pairs(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -388,7 +389,7 @@ def display_spread_for_crypto_pair(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,

View File

@@ -5,6 +5,7 @@ from tabulate import tabulate
from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal.cryptocurrency.onchain.ethgasstation_model import get_gwei_fees
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
def display_gwei_fees(export: str) -> None:
@@ -20,9 +21,9 @@ def display_gwei_fees(export: str) -> None:
df_fees = get_gwei_fees()
if df_fees.empty:
print("\nError in ethgasstation request\n")
console.print("\nError in ethgasstation request\n")
else:
print("\nCurrent ETH gas fees (gwei):")
console.print("\nCurrent ETH gas fees (gwei):")
if gtff.USE_TABULATE_DF:
print(
@@ -36,7 +37,7 @@ def display_gwei_fees(export: str) -> None:
"\n",
)
else:
print(df_fees.to_string(index=False), "\n")
console.print(df_fees.to_string(index=False), "\n")
export_data(
export,

View File

@@ -9,6 +9,7 @@ from gamestonk_terminal.cryptocurrency.dataframe_helpers import (
)
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.cryptocurrency.onchain import ethplorer_model
from gamestonk_terminal.rich_config import console
def display_address_info(
@@ -54,7 +55,7 @@ def display_address_info(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -104,7 +105,7 @@ def display_top_tokens(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -154,7 +155,7 @@ def display_top_token_holders(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -206,7 +207,7 @@ def display_address_history(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -255,7 +256,7 @@ def display_token_info(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -293,7 +294,7 @@ def display_tx_info(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -332,7 +333,7 @@ def display_token_history(
df = ethplorer_model.get_token_history(address)
df_data = df.copy()
if df.empty:
print(f"No results found for balance: {address}\n")
console.print(f"No results found for balance: {address}\n")
return
df["value"] = df["value"].apply(lambda x: very_long_number_formatter(x))
@@ -355,7 +356,7 @@ def display_token_history(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -392,7 +393,7 @@ def display_token_historical_prices(
df_data = df.copy()
if df.empty:
print(f"No results found for balance: {address}\n")
console.print(f"No results found for balance: {address}\n")
return
df["volumeConverted"] = df["volumeConverted"].apply(
@@ -413,7 +414,7 @@ def display_token_historical_prices(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,

View File

@@ -8,9 +8,8 @@ import difflib
from datetime import datetime, timedelta
from typing import List
from colorama.ansi import Style
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal.rich_config import console
from gamestonk_terminal.parent_classes import BaseController
from gamestonk_terminal.cryptocurrency.due_diligence.glassnode_model import (
GLASSNODE_SUPPORTED_HASHRATE_ASSETS,
@@ -123,6 +122,48 @@ class OnchainController(BaseController):
choices["baas"]["-s"] = {c: None for c in bitquery_model.BAAS_FILTERS}
self.completer = NestedCompleter.from_nested_dict(choices)
def print_help(self):
"""Print help"""
has_account_start = "[unvl]" if self.address_type != "account" else ""
has_account_end = "[unvl]" if self.address_type != "account" else ""
has_token_start = "[unvl]" if self.address_type != "token" else ""
has_token_end = "[unvl]" if self.address_type != "token" else ""
has_tx_start = "[unvl]" if self.address_type != "tx" else ""
has_tx_end = "[unvl]" if self.address_type != "tx" else ""
help_text = f"""[cmds]
[src][Glassnode][/src]
hr check blockchain hashrate over time (BTC or ETH)
[src][Eth Gas Station][/src]
gwei check current eth gas fees
[src][Whale Alert][/src]
whales check crypto wales transactions
[src][BitQuery][/src]
lt last trades by dex or month
dvcp daily volume for crypto pair
tv token volume on DEXes
ueat unique ethereum addresses which made a transaction
ttcp top traded crypto pairs on given decentralized exchange
baas bid, ask prices, average spread for given crypto pair
[param]Ethereum address: [/param]{self.address}
[param]Address type: [/param]{self.address_type if self.address_type else ''}
[src][Ethplorer][/src] [info]Ethereum:[/info]
address load ethereum address of token, account or transaction
top top ERC20 tokens{has_account_start}
balance check ethereum balance
hist ethereum balance history (transactions){has_account_end}{has_token_start}
info ERC20 token info
holders top ERC20 token holders
th ERC20 token history
prices ERC20 token historical prices{has_token_end}{has_tx_start}
tx ethereum blockchain transaction info{has_tx_end}
"""
console.print(text=help_text, menu="Cryptocurrency - Onchain")
def call_hr(self, other_args: List[str]):
"""Process hr command"""
@@ -333,7 +374,7 @@ class OnchainController(BaseController):
if ns_parser:
if len(ns_parser.address) not in [42, 66]:
print(
console.print(
f"Couldn't load address {ns_parser.address}. "
f"Token or account address should be 42 characters long. "
f"Transaction hash should be 66 characters long\n"
@@ -406,7 +447,7 @@ class OnchainController(BaseController):
export=ns_parser.export,
)
else:
print("You need to set an ethereum address\n")
console.print("You need to set an ethereum address\n")
def call_hist(self, other_args: List[str]):
"""Process hist command"""
@@ -461,7 +502,7 @@ class OnchainController(BaseController):
export=ns_parser.export,
)
else:
print("You need to set an ethereum address\n")
console.print("You need to set an ethereum address\n")
def call_holders(self, other_args: List[str]):
"""Process holders command"""
@@ -515,7 +556,7 @@ class OnchainController(BaseController):
export=ns_parser.export,
)
else:
print("You need to set an ethereum address\n")
console.print("You need to set an ethereum address\n")
def call_top(self, other_args: List[str]):
"""Process top command"""
@@ -599,7 +640,7 @@ class OnchainController(BaseController):
export=ns_parser.export,
)
else:
print("You need to set an ethereum address\n")
console.print("You need to set an ethereum address\n")
def call_th(self, other_args: List[str]):
"""Process th command"""
@@ -663,7 +704,7 @@ class OnchainController(BaseController):
export=ns_parser.export,
)
else:
print("You need to set an ethereum address\n")
console.print("You need to set an ethereum address\n")
def call_tx(self, other_args: List[str]):
"""Process tx command"""
@@ -688,7 +729,7 @@ class OnchainController(BaseController):
export=ns_parser.export,
)
else:
print("You need to set an ethereum address\n")
console.print("You need to set an ethereum address\n")
def call_prices(self, other_args: List[str]):
"""Process prices command"""
@@ -742,7 +783,7 @@ class OnchainController(BaseController):
export=ns_parser.export,
)
else:
print("You need to set an ethereum address\n")
console.print("You need to set an ethereum address\n")
def call_lt(self, other_args: List[str]):
"""Process lt command"""
@@ -1122,7 +1163,7 @@ class OnchainController(BaseController):
)
if similar_cmd:
print(f"Replacing by '{similar_cmd[0]}'")
console.print(f"Replacing by '{similar_cmd[0]}'")
exchange = similar_cmd[0]
else:
@@ -1133,15 +1174,15 @@ class OnchainController(BaseController):
cutoff=0.5,
)
if similar_cmd:
print(f"Did you mean '{similar_cmd[0]}'?")
console.print(f"Did you mean '{similar_cmd[0]}'?")
print(
console.print(
f"Couldn't find any exchange with provided name: {ns_parser.exchange}. "
f"Please choose one from list: {bitquery_model.DECENTRALIZED_EXCHANGES}\n"
)
else:
print("Exchange not provided setting default to Uniswap.\n")
console.print("Exchange not provided setting default to Uniswap.\n")
bitquery_view.display_most_traded_pairs(
days=ns_parser.days,
@@ -1223,7 +1264,7 @@ class OnchainController(BaseController):
)
else:
print(f"Coin '{ns_parser.coin}' does not exist.")
console.print(f"Coin '{ns_parser.coin}' does not exist.")
if ns_parser.coin.upper() == "BTC":
token = "WBTC"
else:
@@ -1235,7 +1276,7 @@ class OnchainController(BaseController):
)
token = similar_cmd[0]
if similar_cmd[0]:
print(f"Replacing with '{token}'")
console.print(f"Replacing with '{token}'")
bitquery_view.display_spread_for_crypto_pair(
token=token,
vs=ns_parser.vs,
@@ -1252,52 +1293,7 @@ class OnchainController(BaseController):
cutoff=0.5,
)
if similar_cmd:
print(f"Did you mean '{similar_cmd[0]}'?")
console.print(f"Did you mean '{similar_cmd[0]}'?")
else:
print("You didn't provide coin symbol.\n")
def print_help(self):
"""Print help"""
help_text = """
Onchain Menu:
Glassnode:
hr check blockchain hashrate over time (BTC or ETH)
Eth Gas Station:
gwei check current eth gas fees
Whale Alert:
whales check crypto wales transactions
BitQuery:
lt last trades by dex or month
dvcp daily volume for crypto pair
tv token volume on DEXes
ueat unique ethereum addresses which made a transaction
ttcp top traded crypto pairs on given decentralized exchange
baas bid, ask prices, average spread for given crypto pair
"""
help_text += f"\nEthereum address: {self.address if self.address else '?'}"
help_text += (
f"\nAddress type: {self.address_type if self.address_type else '?'}\n"
)
help_text += """
Ethereum [Ethplorer]:
address load ethereum address of token, account or transaction
top top ERC20 tokens"""
help_text += f"""{Style.DIM if self.address_type != "account" else ""}
balance check ethereum balance
hist ethereum balance history (transactions){Style.RESET_ALL if self.address_type != "account" else ""}"""
help_text += f"""{Style.DIM if self.address_type != "token" else ""}
info ERC20 token info
holders top ERC20 token holders
th ERC20 token history
prices ERC20 token historical prices{Style.RESET_ALL if self.address_type != "token" else ""}"""
help_text += f"""{Style.DIM if self.address_type != "tx" else ""}
tx ethereum blockchain transaction info{Style.RESET_ALL if self.address_type != "tx" else ""}
"""
print(help_text)
console.print("You didn't provide coin symbol.\n")

View File

@@ -6,6 +6,7 @@ from tabulate import tabulate
from gamestonk_terminal.helper_funcs import export_data, long_number_format
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.cryptocurrency.onchain import whale_alert_model
from gamestonk_terminal.rich_config import console
def display_whales_transactions(
@@ -59,7 +60,7 @@ def display_whales_transactions(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,

View File

@@ -8,6 +8,7 @@ from gamestonk_terminal.cryptocurrency.overview.blockchaincenter_model import (
)
from gamestonk_terminal.helper_funcs import export_data, plot_autoscale
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
def display_altcoin_index(
@@ -34,7 +35,7 @@ def display_altcoin_index(
df = get_altcoin_index(period, since, until)
if df.empty:
print("\nError scraping blockchain central\n")
console.print("\nError scraping blockchain central\n")
else:
_, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
ax.set_ylabel("Altcoin Index")
@@ -53,7 +54,7 @@ def display_altcoin_index(
if gtff.USE_ION:
plt.ion()
plt.show()
print("")
console.print("")
export_data(
export,

View File

@@ -8,6 +8,7 @@ from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.cryptocurrency.overview import coinbase_model
from gamestonk_terminal.helper_funcs import long_number_format
from gamestonk_terminal.rich_config import console
def display_trading_pairs(top: int, sortby: str, descend: bool, export: str) -> None:
@@ -50,7 +51,7 @@ def display_trading_pairs(top: int, sortby: str, descend: bool, export: str) ->
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,

View File

@@ -6,6 +6,7 @@ import textwrap
import pandas as pd
from dateutil import parser
from gamestonk_terminal.cryptocurrency.coinpaprika_helpers import PaprikaSession
from gamestonk_terminal.rich_config import console
MARKETS_FILTERS = [
"rank",
@@ -85,7 +86,7 @@ def get_global_market() -> pd.DataFrame:
try:
global_markets[key] = parser.parse(date).strftime("%Y-%m-%d %H:%M:%S")
except (KeyError, ValueError, TypeError) as e:
print(e)
console.print(e)
df = pd.Series(global_markets).to_frame().reset_index()
df.columns = ["Metric", "Value"]
return df
@@ -171,7 +172,7 @@ def _get_coins_info_helper(quotes: str = "USD") -> pd.DataFrame:
]
data.columns = [col.replace("percent", "pct") for col in list(data.columns)]
except KeyError as e:
print(e)
console.print(e)
data.rename(
columns={
"market_cap_change_24h": "mcap_change_24h",
@@ -267,7 +268,7 @@ def get_list_of_exchanges(quotes: str = "USD") -> pd.DataFrame:
col.replace(f"quotes.{quotes}.", "") for col in df.columns.tolist()
]
except KeyError as e:
print(e)
console.print(e)
df = df[df["active"]]
cols = [
"adjusted_rank",
@@ -319,7 +320,7 @@ def get_exchanges_market(
session.ENDPOINTS["exchange_markets"].format(exchange_id), quotes=quotes
)
if "error" in data:
print(data)
console.print(data)
return pd.DataFrame()
cols = [
"exchange_id",

View File

@@ -10,6 +10,7 @@ from gamestonk_terminal.cryptocurrency.dataframe_helpers import (
long_number_format_with_type_check,
)
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
register_matplotlib_converters()
@@ -93,7 +94,7 @@ def display_global_market(export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -131,13 +132,13 @@ def display_all_coins_market_info(
df_data = df.copy()
if df.empty:
print("No data found", "\n")
console.print("No data found", "\n")
return
cols = [col for col in df.columns if col != "rank"]
df[cols] = df[cols].applymap(lambda x: long_number_format_with_type_check(x))
print(f"\nDisplaying data vs {currency}")
console.print(f"\nDisplaying data vs {currency}")
if gtff.USE_TABULATE_DF:
print(
@@ -151,7 +152,7 @@ def display_all_coins_market_info(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -189,13 +190,13 @@ def display_all_coins_info(
df_data = df.copy()
if df.empty:
print("Not data found", "\n")
console.print("Not data found", "\n")
return
cols = [col for col in df.columns if col != "rank"]
df[cols] = df[cols].applymap(lambda x: long_number_format_with_type_check(x))
print(f"\nDisplaying data vs {currency}")
console.print(f"\nDisplaying data vs {currency}")
if gtff.USE_TABULATE_DF:
print(
@@ -209,7 +210,7 @@ def display_all_coins_info(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -248,12 +249,12 @@ def display_all_exchanges(
df_data = df.copy()
if df.empty:
print("No data found", "\n")
console.print("No data found", "\n")
return
cols = [col for col in df.columns if col != "rank"]
df[cols] = df[cols].applymap(lambda x: long_number_format_with_type_check(x))
print(f"\nDisplaying data vs {currency}")
console.print(f"\nDisplaying data vs {currency}")
if gtff.USE_TABULATE_DF:
print(
@@ -267,7 +268,7 @@ def display_all_exchanges(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -303,7 +304,7 @@ def display_exchange_markets(
df_data = df.copy()
if df.empty:
print("No data found", "\n")
console.print("No data found", "\n")
return
df = df.sort_values(by=sortby, ascending=descend)
@@ -325,7 +326,7 @@ def display_exchange_markets(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -358,7 +359,7 @@ def display_all_platforms(export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -390,7 +391,7 @@ def display_contracts(
df = paprika.get_contract_platform(platform)
if df.empty:
print(f"Nothing found for platform: {platform}", "\n")
console.print(f"Nothing found for platform: {platform}", "\n")
return
df = df.sort_values(by=sortby, ascending=descend)
@@ -407,7 +408,7 @@ def display_contracts(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,

View File

@@ -8,6 +8,7 @@ from tabulate import tabulate
from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal.cryptocurrency.overview import cryptopanic_model
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
def display_news(
@@ -64,7 +65,7 @@ def display_news(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,

View File

@@ -7,6 +7,7 @@ import difflib
from datetime import datetime, timedelta
from typing import List
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal.rich_config import console
from gamestonk_terminal.parent_classes import BaseController
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.cryptocurrency.overview.blockchaincenter_model import DAYS
@@ -131,10 +132,10 @@ class OverviewController(BaseController):
def print_help(self):
"""Print help"""
help_text = """
CoinGecko:
help_text = """[cmds]
[src][CoinGecko][/src]
cgglobal global crypto market info
cgnews last news available on CoinGecko
cgnews last news available
cgdefi global DeFi market info
cgstables stablecoins
cgnft non fungible token market status
@@ -147,28 +148,27 @@ CoinGecko:
cgderivatives crypto derivatives
cgcategories crypto categories
cghold ethereum, bitcoin holdings overview statistics
CoinPaprika:
[src][CoinPaprika][/src]
cpglobal global crypto market info
cpinfo basic info about all coins available on CoinPaprika
cpmarkets market related info about all coins available on CoinPaprika
cpinfo basic info about all coins available
cpmarkets market related info about all coins available
cpexchanges list all exchanges
cpexmarkets all available markets on given exchange
cpplatforms list blockchain platforms eg. ethereum, solana, kusama, terra
cpcontracts all smart contracts for given platform
Coinbase:
cbpairs info about available trading pairs on Coinbase
CryptoPanic:
news recent crypto news from CryptoPanic aggregator
WithdrawalFees:
[src][Coinbase][/src]
cbpairs info about available trading pairs
[src][CryptoPanic][/src]
news recent crypto news
[src][WithdrawalFees][/src]
wf overall withdrawal fees
ewf overall exchange withdrawal fees
wfpe crypto withdrawal fees per exchange
BlockchainCenter:
altindex displays altcoin season index (if 75% of top 50 coins perform better than btc)
btcrb display bitcoin rainbow price chart (logarithmic regression)
[src][BlockchainCenter][/src]
altindex displays altcoin season index (if 75% of top 50 coins perform better than BTC)
btcrb display bitcoin rainbow price chart (logarithmic regression)[/cmds]
"""
print(help_text)
console.print(text=help_text, menu="Cryptocurrency - Overview")
def call_btcrb(self, other_args: List[str]):
"""Process btcrb command"""
@@ -350,7 +350,7 @@ BlockchainCenter:
symbol=ns_parser.coin, export=ns_parser.export
)
else:
print(f"Coin '{ns_parser.coin}' does not exist.")
console.print(f"Coin '{ns_parser.coin}' does not exist.")
similar_cmd = difflib.get_close_matches(
ns_parser.coin,
@@ -359,7 +359,7 @@ BlockchainCenter:
cutoff=0.75,
)
if similar_cmd:
print(f"Replacing by '{similar_cmd[0]}'")
console.print(f"Replacing by '{similar_cmd[0]}'")
withdrawalfees_view.display_crypto_withdrawal_fees(
symbol=similar_cmd[0], export=ns_parser.export
)
@@ -371,9 +371,9 @@ BlockchainCenter:
cutoff=0.5,
)
if similar_cmd:
print(f"Did you mean '{similar_cmd[0]}'?")
console.print(f"Did you mean '{similar_cmd[0]}'?")
else:
print(
console.print(
f"Couldn't find any coin with provided name: {ns_parser.coin}. "
f"Please choose one from list: {withdrawalfees_model.POSSIBLE_CRYPTOS}\n"
)

View File

@@ -20,6 +20,7 @@ from gamestonk_terminal.cryptocurrency.pycoingecko_helpers import (
GECKO_BASE_URL,
RetryError,
)
from gamestonk_terminal.rich_config import console
HOLD_COINS = ["ethereum", "bitcoin"]
@@ -140,7 +141,7 @@ def get_news(n: int = 100) -> pd.DataFrame:
try:
scraped_data = scrape_gecko_data(url)
except RetryError as e:
print(e)
console.print(e)
return pd.DataFrame()
rows = scraped_data.find_all("article")
results = []
@@ -198,7 +199,7 @@ def get_top_crypto_categories() -> pd.DataFrame:
try:
scraped_data = scrape_gecko_data(url)
except RetryError as e:
print(e)
console.print(e)
return pd.DataFrame()
rows = scraped_data.find("tbody").find_all("tr")
results = []
@@ -258,7 +259,7 @@ def get_stable_coins() -> pd.DataFrame:
try:
scraped_data = scrape_gecko_data(url)
except RetryError as e:
print(e)
console.print(e)
return pd.DataFrame()
rows = scraped_data.find("tbody").find_all("tr")
results = []
@@ -313,7 +314,7 @@ def get_nft_of_the_day() -> pd.DataFrame:
try:
scraped_data = scrape_gecko_data(url)
except RetryError as e:
print(e)
console.print(e)
return pd.DataFrame()
row = scraped_data.find("div", class_="tw-px-4 tw-py-5 sm:tw-p-6")
try:
@@ -356,7 +357,7 @@ def get_nft_market_status() -> pd.DataFrame:
try:
scraped_data = scrape_gecko_data(url)
except RetryError as e:
print(e)
console.print(e)
return pd.DataFrame()
rows = scraped_data.find_all("span", class_="overview-box d-inline-block p-3 mr-2")
kpis = {}

View File

@@ -8,6 +8,7 @@ from tabulate import tabulate
from gamestonk_terminal.helper_funcs import export_data
import gamestonk_terminal.cryptocurrency.overview.pycoingecko_model as gecko
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
register_matplotlib_converters()
@@ -31,9 +32,9 @@ def display_holdings_overview(coin: str, export: str) -> None:
df = res[1]
if df.empty:
print("\nZero companies holding this crypto\n")
console.print("\nZero companies holding this crypto\n")
else:
print(f"\n{stats_string}\n")
console.print(f"\n{stats_string}\n")
if gtff.USE_TABULATE_DF:
print(
tabulate(
@@ -46,7 +47,7 @@ def display_holdings_overview(coin: str, export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -82,7 +83,7 @@ def display_nft_of_the_day(export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -118,7 +119,7 @@ def display_nft_market_status(export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -127,9 +128,9 @@ def display_nft_market_status(export: str) -> None:
df,
)
else:
print("")
print("Unable to retrieve data from CoinGecko.")
print("")
console.print("")
console.print("Unable to retrieve data from CoinGecko.")
console.print("")
def display_exchange_rates(sortby: str, descend: bool, top: int, export: str) -> None:
@@ -162,7 +163,7 @@ def display_exchange_rates(sortby: str, descend: bool, top: int, export: str) ->
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -171,9 +172,9 @@ def display_exchange_rates(sortby: str, descend: bool, top: int, export: str) ->
df,
)
else:
print("")
print("Unable to retrieve data from CoinGecko.")
print("")
console.print("")
console.print("Unable to retrieve data from CoinGecko.")
console.print("")
def display_global_market_info(export: str) -> None:
@@ -205,7 +206,7 @@ def display_global_market_info(export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -214,9 +215,9 @@ def display_global_market_info(export: str) -> None:
df,
)
else:
print("")
print("Unable to retrieve data from CoinGecko.")
print("")
console.print("")
console.print("Unable to retrieve data from CoinGecko.")
console.print("")
def display_global_defi_info(export: str) -> None:
@@ -243,7 +244,7 @@ def display_global_defi_info(export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -252,9 +253,9 @@ def display_global_defi_info(export: str) -> None:
df,
)
else:
print("")
print("Unable to retrieve data from CoinGecko.")
print("")
console.print("")
console.print("Unable to retrieve data from CoinGecko.")
console.print("")
def display_stablecoins(
@@ -299,7 +300,7 @@ def display_stablecoins(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -308,9 +309,9 @@ def display_stablecoins(
df_data,
)
else:
print("")
print("Unable to retrieve data from CoinGecko.")
print("")
console.print("")
console.print("Unable to retrieve data from CoinGecko.")
console.print("")
def display_news(
@@ -359,7 +360,7 @@ def display_news(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -368,9 +369,9 @@ def display_news(
df_data,
)
else:
print("")
print("Unable to retrieve data from CoinGecko.")
print("")
console.print("")
console.print("Unable to retrieve data from CoinGecko.")
console.print("")
def display_categories(
@@ -417,7 +418,7 @@ def display_categories(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -426,9 +427,9 @@ def display_categories(
df_data,
)
else:
print("")
print("Unable to retrieve data from CoinGecko.")
print("")
console.print("")
console.print("Unable to retrieve data from CoinGecko.")
console.print("")
def display_exchanges(
@@ -472,7 +473,7 @@ def display_exchanges(
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -481,9 +482,9 @@ def display_exchanges(
df,
)
else:
print("")
print("Unable to retrieve data from CoinGecko.")
print("")
console.print("")
console.print("Unable to retrieve data from CoinGecko.")
console.print("")
def display_platforms(sortby: str, descend: bool, top: int, export: str) -> None:
@@ -518,7 +519,7 @@ def display_platforms(sortby: str, descend: bool, top: int, export: str) -> None
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -527,9 +528,9 @@ def display_platforms(sortby: str, descend: bool, top: int, export: str) -> None
df,
)
else:
print("")
print("Unable to retrieve data from CoinGecko.")
print("")
console.print("")
console.print("Unable to retrieve data from CoinGecko.")
console.print("")
def display_products(sortby: str, descend: bool, top: int, export: str) -> None:
@@ -564,7 +565,7 @@ def display_products(sortby: str, descend: bool, top: int, export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -573,9 +574,9 @@ def display_products(sortby: str, descend: bool, top: int, export: str) -> None:
df,
)
else:
print("")
print("Unable to retrieve data from CoinGecko.")
print("")
console.print("")
console.print("Unable to retrieve data from CoinGecko.")
console.print("")
def display_indexes(sortby: str, descend: bool, top: int, export: str) -> None:
@@ -609,7 +610,7 @@ def display_indexes(sortby: str, descend: bool, top: int, export: str) -> None:
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -618,9 +619,9 @@ def display_indexes(sortby: str, descend: bool, top: int, export: str) -> None:
df,
)
else:
print("")
print("Unable to retrieve data from CoinGecko.")
print("")
console.print("")
console.print("Unable to retrieve data from CoinGecko.")
console.print("")
def display_derivatives(sortby: str, descend: bool, top: int, export: str) -> None:
@@ -655,7 +656,7 @@ def display_derivatives(sortby: str, descend: bool, top: int, export: str) -> No
"\n",
)
else:
print(df.to_string, "\n")
console.print(df.to_string, "\n")
export_data(
export,
@@ -664,6 +665,6 @@ def display_derivatives(sortby: str, descend: bool, top: int, export: str) -> No
df,
)
else:
print("")
print("Unable to retrieve data from CoinGecko.")
print("")
console.print("")
console.print("Unable to retrieve data from CoinGecko.")
console.print("")

View File

@@ -9,6 +9,7 @@ from gamestonk_terminal.cryptocurrency.overview.withdrawalfees_model import (
)
from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
def display_overall_withdrawal_fees(top: int, export: str = "") -> None:
@@ -26,9 +27,9 @@ def display_overall_withdrawal_fees(top: int, export: str = "") -> None:
df_fees = get_overall_withdrawal_fees(top)
if df_fees.empty:
print("\nError in withdrawal fees request\n")
console.print("\nError in withdrawal fees request\n")
else:
print("\nWithdrawal fees on exchanges:")
console.print("\nWithdrawal fees on exchanges:")
if gtff.USE_TABULATE_DF:
print(
@@ -42,7 +43,7 @@ def display_overall_withdrawal_fees(top: int, export: str = "") -> None:
"\n",
)
else:
print(df_fees.to_string(index=False), "\n")
console.print(df_fees.to_string(index=False), "\n")
export_data(
export,
@@ -65,9 +66,9 @@ def display_overall_exchange_withdrawal_fees(export: str) -> None:
df_fees = get_overall_exchange_withdrawal_fees()
if df_fees.empty:
print("\nError in withdrawal fees request\n")
console.print("\nError in withdrawal fees request\n")
else:
print("\nWithdrawal fees per exchange:")
console.print("\nWithdrawal fees per exchange:")
if gtff.USE_TABULATE_DF:
print(
@@ -81,7 +82,7 @@ def display_overall_exchange_withdrawal_fees(export: str) -> None:
"\n",
)
else:
print(df_fees.to_string(index=False), "\n")
console.print(df_fees.to_string(index=False), "\n")
export_data(
export,
@@ -107,11 +108,11 @@ def display_crypto_withdrawal_fees(symbol: str, export: str = "") -> None:
stats_string = res[0]
df_fees = res[1]
if df_fees.empty:
print("\nError in withdrawal fees request\n")
console.print("\nError in withdrawal fees request\n")
else:
print(f"\nWithdrawal fees for {symbol}:")
console.print(f"\nWithdrawal fees for {symbol}:")
print(f"\n{stats_string}\n")
console.print(f"\n{stats_string}\n")
if gtff.USE_TABULATE_DF:
print(
@@ -125,7 +126,7 @@ def display_crypto_withdrawal_fees(symbol: str, export: str = "") -> None:
"\n",
)
else:
print(df_fees.to_string(index=False), "\n")
console.print(df_fees.to_string(index=False), "\n")
export_data(
export,

View File

@@ -8,7 +8,7 @@ from typing import List
import pandas as pd
import numpy as np
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal.rich_config import console
from gamestonk_terminal.parent_classes import BaseController
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.helper_funcs import (
@@ -90,17 +90,14 @@ class PredictionTechniquesController(BaseController):
def print_help(self):
"""Print help"""
help_string = f"""
Prediction Techniques Menu:
help_text = f"""[cmds]
load load new ticker
pick pick new target variable
pick pick new target variable[/cmds]
Coin Loaded: {self.coin}
Target Column: {self.target}
[param]Coin Loaded: [/param]{self.coin}
[param]Target Column: [/param]{self.target}
Models:
[info]Models:[/info][cmds]
ets exponential smoothing (e.g. Holt-Winters)
knn k-Nearest Neighbors
regression polynomial regression
@@ -109,9 +106,9 @@ Models:
rnn Recurrent Neural Network
lstm Long-Short Term Memory
conv1d 1D Convolutional Neural Network
mc Monte-Carlo simulations
mc Monte-Carlo simulations[/cmds]
"""
print(help_string)
console.print(text=help_text, menu="Cryptocurrency - Prediction Techniques")
def custom_reset(self):
"""Class specific component of reset command"""
@@ -199,7 +196,7 @@ Models:
interval="1day",
vs=ns_parser.vs,
)
print(
console.print(
f"{delta} Days of {self.coin} vs {self.current_currency} loaded with {res} resolution.\n"
)
@@ -226,7 +223,7 @@ Models:
ns_parser = parse_known_args_and_warn(parser, other_args)
if ns_parser:
self.target = ns_parser.target
print("")
console.print("")
def call_ets(self, other_args: List[str]):
"""Process ets command"""
@@ -301,7 +298,7 @@ Models:
if ns_parser:
if ns_parser.s_end_date:
if ns_parser.s_end_date < self.data.index[0]:
print(
console.print(
"Backtesting not allowed, since End Date is older than Start Date of historical data\n"
)
@@ -309,7 +306,7 @@ Models:
last_stock_day=self.data.index[0],
n_next_days=5 + ns_parser.n_days,
)[-1]:
print(
console.print(
"Backtesting not allowed, since End Date is too close to Start Date to train model\n"
)
@@ -484,7 +481,7 @@ Models:
# BACKTESTING CHECK
if ns_parser.s_end_date:
if ns_parser.s_end_date < self.data.index[0]:
print(
console.print(
"Backtesting not allowed, since End Date is older than Start Date of historical data\n"
)
@@ -492,7 +489,7 @@ Models:
last_stock_day=self.data.index[0],
n_next_days=5 + ns_parser.n_days,
)[-1]:
print(
console.print(
"Backtesting not allowed, since End Date is too close to Start Date to train model\n"
)
@@ -585,7 +582,7 @@ Models:
# BACKTESTING CHECK
if ns_parser.s_end_date:
if ns_parser.s_end_date < self.data.index[0]:
print(
console.print(
"Backtesting not allowed, since End Date is older than Start Date of historical data\n"
)
@@ -593,7 +590,7 @@ Models:
last_stock_day=self.data.index[0],
n_next_days=5 + ns_parser.n_days,
)[-1]:
print(
console.print(
"Backtesting not allowed, since End Date is too close to Start Date to train model\n"
)
@@ -633,7 +630,7 @@ Models:
time_res=self.resolution,
)
except Exception as e:
print(e, "\n")
console.print(e, "\n")
finally:
pred_helper.restore_env()
@@ -662,7 +659,7 @@ Models:
)
except Exception as e:
print(e, "\n")
console.print(e, "\n")
finally:
pred_helper.restore_env()
@@ -691,7 +688,7 @@ Models:
)
except Exception as e:
print(e, "\n")
console.print(e, "\n")
finally:
pred_helper.restore_env()
@@ -720,7 +717,7 @@ Models:
)
except Exception as e:
print(e, "\n")
console.print(e, "\n")
finally:
pred_helper.restore_env()
@@ -762,7 +759,7 @@ Models:
parser, other_args, export_allowed=EXPORT_ONLY_FIGURES_ALLOWED
)
if self.target != "Close":
print("MC Prediction designed for AdjClose prices\n")
console.print("MC Prediction designed for AdjClose prices\n")
if ns_parser:
mc_view.display_mc_forecast(

View File

@@ -14,6 +14,7 @@ from dateutil import parser
from requests.adapters import HTTPAdapter, RetryError
from urllib3.util.retry import Retry
from gamestonk_terminal.helper_funcs import get_user_agent
from gamestonk_terminal.rich_config import console
GECKO_BASE_URL = "https://www.coingecko.com"
@@ -113,7 +114,7 @@ def scrape_gecko_data(url: str) -> BeautifulSoup:
try:
req = session.get(url, headers=headers, timeout=5)
except Exception as error:
print(error)
console.print(error)
raise RetryError(
"Connection error. Couldn't connect to CoinGecko and scrape the data. "
"Please visit CoinGecko site, and check if it's not under maintenance"

View File

@@ -5,11 +5,10 @@ __docformat__ = "numpy"
import argparse
from typing import List
from datetime import datetime, timedelta
from colorama import Style
import pandas as pd
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal.rich_config import console
from gamestonk_terminal.parent_classes import BaseController
from gamestonk_terminal.cryptocurrency.cryptocurrency_helpers import load
from gamestonk_terminal import feature_flags as gtff
@@ -80,46 +79,39 @@ class TechnicalAnalysisController(BaseController):
def print_help(self):
"""Print help"""
s_intraday = (f"Interval: Intraday {self.interval}", "Daily")[
self.interval == "1440min"
]
if self.start:
crypto_str = f"{s_intraday}\nCoin Loaded: {self.ticker} (from {self.start.strftime('%Y-%m-%d')})"
else:
crypto_str = f"{s_intraday}\nCoin Loaded: {self.ticker}"
crypto_str = f" {self.ticker} (from {self.start.strftime('%Y-%m-%d')})"
help_text = f"""[cmds]
[param]Coin Loaded: [/param]{crypto_str}
dim = Style.DIM if "Volume" not in self.stock else ""
not_dim = Style.RESET_ALL if "Volume" not in self.stock else ""
help_str = f"""
Technical Analysis Menu:
{crypto_str}
Overlap:
[info]Overlap:[/info]
ema exponential moving average
sma simple moving average
zlma zero lag moving average{dim}
vwap volume weighted average price{not_dim}
Momentum:
wma weighted moving average
hma hull moving average
zlma zero lag moving average
vwap volume weighted average price
[info]Momentum:[/info]
cci commodity channel index
macd moving average convergence/divergence
rsi relative strength index
stoch stochastic oscillator
fisher fisher transform
cg centre of gravity
Trend:
[info]Trend:[/info]
adx average directional movement index
aroon aroon indicator
Volatility:
[info]Volatility:[/info]
bbands bollinger bands
donchian donchian channels{dim}
Volume:
ad accumulation/distribution line values
obv on balance volume{not_dim}
Custom:
fib fibonacci retracement
donchian donchian channels
kc keltner channels
[info]Volume:[/info]
ad accumulation/distribution line
adosc chaikin oscillator
obv on balance volume
[info]Custom:[/info]
fib fibonacci retracement[/cmds]
"""
print(help_str)
console.print(text=help_text, menu="Cryptocurrency - Technical Analysis")
def custom_reset(self):
"""Class specific component of reset command"""
@@ -197,7 +189,7 @@ Custom:
interval=ns_parser.interval,
vs=ns_parser.vs,
)
print(f"{delta} Days of {self.ticker} vs {self.currency} loaded\n")
console.print(f"{delta} Days of {self.ticker} vs {self.currency} loaded\n")
# TODO: Go through all models and make sure all needed columns are in dfs
@@ -387,7 +379,7 @@ Custom:
)
if ns_parser:
if self.interval == "1440min":
print("VWAP should be used with intraday data.\n")
console.print("VWAP should be used with intraday data.\n")
overlap_view.view_vwap(
s_ticker=self.ticker,

View File

@@ -10,6 +10,7 @@ from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.economy import alphavantage_model
from gamestonk_terminal.helper_funcs import export_data, plot_autoscale
from gamestonk_terminal import config_plot as cfp
from gamestonk_terminal.rich_config import console
def realtime_performance_sector(raw: bool, export: str):
@@ -39,7 +40,7 @@ def realtime_performance_sector(raw: bool, export: str):
)
)
else:
print(df_rtp.to_string())
console.print(df_rtp.to_string())
else:
df_rtp.plot(kind="bar")
@@ -47,7 +48,7 @@ def realtime_performance_sector(raw: bool, export: str):
plt.tight_layout()
plt.grid()
print("")
console.print("")
export_data(
export,
@@ -80,7 +81,7 @@ def display_real_gdp(
"""
gdp_full = alphavantage_model.get_real_gdp(interval)
if gdp_full.empty:
print("Error getting data. Check API Key")
console.print("Error getting data. Check API Key")
return
gdp = gdp_full[gdp_full.date >= f"{start_year}-01-01"]
int_string = "Annual" if interval == "a" else "Quarterly"
@@ -113,8 +114,8 @@ def display_real_gdp(
)
)
else:
print(gdp.head(20).to_string())
print("")
console.print(gdp.head(20).to_string())
console.print("")
def display_gdp_capita(start_year: int = 2010, raw: bool = False, export: str = ""):
@@ -131,7 +132,7 @@ def display_gdp_capita(start_year: int = 2010, raw: bool = False, export: str =
"""
gdp_capita = alphavantage_model.get_gdp_capita()
if gdp_capita.empty:
print("Error getting data. Check API Key")
console.print("Error getting data. Check API Key")
return
gdp = gdp_capita[gdp_capita.date >= f"{start_year}-01-01"]
fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=cfp.PLOT_DPI)
@@ -162,8 +163,8 @@ def display_gdp_capita(start_year: int = 2010, raw: bool = False, export: str =
)
)
else:
print(gdp.head(20).to_string())
print("")
console.print(gdp.head(20).to_string())
console.print("")
def display_inflation(start_year: int = 2010, raw: bool = False, export: str = ""):
@@ -180,7 +181,7 @@ def display_inflation(start_year: int = 2010, raw: bool = False, export: str = "
"""
inflation = alphavantage_model.get_inflation()
if inflation.empty:
print("Error getting data. Check API Key")
console.print("Error getting data. Check API Key")
return
inf = inflation[inflation.date >= f"{start_year}-01-01"]
fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=cfp.PLOT_DPI)
@@ -211,8 +212,8 @@ def display_inflation(start_year: int = 2010, raw: bool = False, export: str = "
)
)
else:
print(inf.head(20).to_string())
print("")
console.print(inf.head(20).to_string())
console.print("")
def display_cpi(
@@ -233,7 +234,7 @@ def display_cpi(
"""
cpi_full = alphavantage_model.get_cpi(interval)
if cpi_full.empty:
print("Error getting data. Check API Key")
console.print("Error getting data. Check API Key")
return
cpi = cpi_full[cpi_full.date >= f"{start_year}-01-01"]
int_string = "Semi-Annual" if interval == "s" else "Monthly"
@@ -266,8 +267,8 @@ def display_cpi(
)
)
else:
print(cpi.head(20).to_string())
print("")
console.print(cpi.head(20).to_string())
console.print("")
def display_treasury_yield(
@@ -291,7 +292,7 @@ def display_treasury_yield(
d_maturity = {"3m": "3month", "5y": "5year", "10y": "10year", "30y": "30year"}
yields = alphavantage_model.get_treasury_yield(interval, maturity)
if yields.empty:
print("Error getting data. Check API Key")
console.print("Error getting data. Check API Key")
return
yld = yields[yields.date >= start_date]
fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=cfp.PLOT_DPI)
@@ -322,8 +323,8 @@ def display_treasury_yield(
)
)
else:
print(yld.head(20).to_string())
print("")
console.print(yld.head(20).to_string())
console.print("")
def display_unemployment(start_year: int = 2015, raw: bool = False, export: str = ""):
@@ -342,7 +343,7 @@ def display_unemployment(start_year: int = 2015, raw: bool = False, export: str
unemp = alphavantage_model.get_unemployment()
if unemp.empty:
print("Error getting data. Check API Key")
console.print("Error getting data. Check API Key")
return
un = unemp[unemp.date >= f"{start_year}-01-01"]
@@ -376,6 +377,6 @@ def display_unemployment(start_year: int = 2015, raw: bool = False, export: str
)
)
else:
print(un.head(20).to_string())
console.print(un.head(20).to_string())
print("")
console.print("")

View File

@@ -9,6 +9,7 @@ from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.config_plot import PLOT_DPI
from gamestonk_terminal.economy import cnn_model
from gamestonk_terminal.helper_funcs import plot_autoscale, export_data
from gamestonk_terminal.rich_config import console
register_matplotlib_converters()
@@ -29,7 +30,7 @@ def fear_and_greed_index(indicator: str, export: str):
report, im = cnn_model.get_feargreed_report(indicator, fig)
print(report)
console.print(report)
if indicator:
plt.imshow(im)

View File

@@ -5,11 +5,12 @@ import argparse
from datetime import datetime, timedelta
import os
from typing import List
import logging
from rich.console import Console
import pandas as pd
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal.rich_config import console
from gamestonk_terminal.parent_classes import BaseController
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.economy import (
@@ -29,7 +30,7 @@ from gamestonk_terminal.helper_funcs import (
)
from gamestonk_terminal.menu import session
t_console = Console()
logger = logging.getLogger(__name__)
class EconomyController(BaseController):
@@ -164,17 +165,17 @@ class EconomyController(BaseController):
@staticmethod
def print_help():
"""Print help"""
help_text = """
CNN:
help_text = """[cmds]
[src][CNN][/src]
feargreed CNN Fear and Greed Index
Wall St. Journal:
[src][Wall St. Journal][/src]
overview market data overview
indices US indices overview
futures futures and commodities overview
usbonds US bonds overview
glbonds global bonds overview
currencies currencies overview
Finviz:
[src][Finviz][/src]
energy energy futures overview
metals metals futures overview
meats meats futures overview
@@ -184,7 +185,7 @@ Finviz:
valuation valuation of sectors, industry, country
performance performance of sectors, industry, country
spectrum spectrum of sectors, industry, country
Alpha Vantage:
[src][Alpha Vantage][/src]
rtps real-time performance sectors
gdp real GDP for United States
gdpc quarterly real GDP per Capita data of the United States
@@ -192,13 +193,12 @@ Alpha Vantage:
cpi consumer price index for United States
tyld treasury yields for United States
unemp United States unemployment rates
NASDAQ DataLink (formerly Quandl):
bigmac the economists Big Mac index
> fred Federal Reserve Economic Data submenu
[src][NASDAQ DataLink][/src]
bigmac the economists Big Mac index[/cmds]
[menu]
> fred Federal Reserve Economic Data submenu[/menu]
"""
print(type(help_text))
t_console.print(help_text)
console.print(text=help_text, menu="Economy")
def call_feargreed(self, other_args: List[str]):
"""Process feargreed command"""
@@ -1009,7 +1009,7 @@ NASDAQ DataLink (formerly Quandl):
file = os.path.join(
os.path.dirname(__file__), "NASDAQ_CountryCodes.csv"
)
t_console.print(
console.print(
pd.read_csv(file, index_col=0).to_string(index=False), "\n"
)
else:

View File

@@ -5,6 +5,7 @@ from tabulate import tabulate
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.economy import finnhub_model
from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal.rich_config import console
def economy_calendar_events(country: str, num: int, impact: str, export: str):
@@ -24,7 +25,7 @@ def economy_calendar_events(country: str, num: int, impact: str, export: str):
df_events = finnhub_model.get_economy_calendar_events()
if df_events.empty:
print("No latest economy calendar events found\n")
console.print("No latest economy calendar events found\n")
return
df_econ_calendar = df_events[df_events["country"] == country].sort_values(
@@ -32,14 +33,16 @@ def economy_calendar_events(country: str, num: int, impact: str, export: str):
)
if df_econ_calendar.empty:
print("No latest economy calendar events found in the specified country\n")
console.print(
"No latest economy calendar events found in the specified country\n"
)
return
if impact != "all":
df_econ_calendar = df_econ_calendar[df_econ_calendar["impact"] == impact]
if df_econ_calendar.empty:
print(
console.print(
"No latest economy calendar events found in the specified country with this impact\n"
)
return
@@ -75,8 +78,8 @@ def economy_calendar_events(country: str, num: int, impact: str, export: str):
)
)
else:
print(df_econ_calendar.to_string(index=False))
print("")
console.print(df_econ_calendar.to_string(index=False))
console.print("")
export_data(
export,

View File

@@ -11,6 +11,7 @@ from tabulate import tabulate
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.economy import finviz_model
from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal.rich_config import console
def map_sp500_view(period: str, map_type: str):
@@ -30,7 +31,7 @@ def map_sp500_view(period: str, map_type: str):
webbrowser.open(
f"https://finviz.com/map.ashx?t={d_type[map_type]}&st={d_period[period]}"
)
print("")
console.print("")
def display_performance(
@@ -96,8 +97,8 @@ def display_performance(
)
)
else:
print(df_group.fillna("").to_string(index=False))
print("")
console.print(df_group.fillna("").to_string(index=False))
console.print("")
export_data(
export,
@@ -143,8 +144,8 @@ def display_valuation(
)
)
else:
print(df_group.fillna("").to_string(index=False))
print("")
console.print(df_group.fillna("").to_string(index=False))
console.print("")
export_data(
export,
@@ -165,7 +166,7 @@ def display_spectrum(s_group: str, export: str = ""):
Format to export data
"""
finviz_model.get_spectrum_data(s_group)
print("")
console.print("")
img = Image.open(s_group + ".jpg")
@@ -213,7 +214,9 @@ def display_future(
)
)
else:
print(df[["prevClose", "last", "change"]].fillna("").to_string(index=True))
console.print(
df[["prevClose", "last", "change"]].fillna("").to_string(index=True)
)
export_data(
export,
@@ -221,4 +224,4 @@ def display_future(
future_type.lower(),
df,
)
print("")
console.print("")

View File

@@ -4,9 +4,9 @@ __docformat__ = "numpy"
import argparse
from typing import List, Dict
from rich.console import Console
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal.rich_config import console
from gamestonk_terminal.parent_classes import BaseController
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.economy.fred import fred_view, fred_model
@@ -20,8 +20,6 @@ from gamestonk_terminal.menu import session
# pylint: disable=import-outside-toplevel
t_console = Console()
class FredController(BaseController):
"""FRED Controller Class"""
@@ -45,23 +43,23 @@ class FredController(BaseController):
id_string = ""
for s_id, sub_dict in self.current_series.items():
id_string += (
f" [blue]{s_id.upper()}{(self.long_id-len(s_id)) * ' '}[/blue] :"
f" {s_id.upper()}{(self.long_id-len(s_id)) * ' '} :"
f" [italic]{sub_dict['title']}[/italic]\n"
)
if not id_string:
id_string += " [bold][red]None[/red][/bold]\n"
help_text = f"""
help_text = f"""[cmds]
search search FRED series notes
add add series ID to list
rmv remove series ID from list
rmv remove series ID from list[/cmds]
Current Series IDs:
{id_string}{'[dim]'if not self.current_series else ""}
plot plot selected series {'[/dim]'if not self.current_series else ""}
{'[dim]'if len(self.current_series.keys())!=1 else ""}
> pred prediction techniques (single SeriesID){'[/dim]'if len(self.current_series.keys())!=1 else ""}
[param]Current Series IDs:[/param]
{id_string}{'[dim]'if not self.current_series else ""}[cmds]
plot plot selected series [/cmds]{'[/dim]'if not self.current_series else ""}
{'[dim]'if len(self.current_series.keys())!=1 else ""}[menu]
> pred prediction techniques (single SeriesID)[/menu]{'[/dim]'if len(self.current_series.keys())!=1 else ""}
"""
t_console.print(help_text)
console.print(text=help_text, menu="Economy - Federal Reserve Economic Data")
def call_search(self, other_args: List[str]):
"""Process search command"""
@@ -129,9 +127,9 @@ Current Series IDs:
}
self.long_id = max(self.long_id, len(s_id))
else:
t_console.print(f"[red]{s_id} not found[/red].")
console.print(f"[red]{s_id} not found[/red].")
t_console.print(
console.print(
f"Current Series:[blue] {', '.join(self.current_series.keys()) .upper() or None}[/blue]\n"
)
@@ -176,10 +174,10 @@ Current Series IDs:
if ns_parser.all:
self.current_series = {}
self.long_id = 0
t_console.print("")
console.print("")
self.current_series.pop(ns_parser.series_id)
t_console.print(
console.print(
f"Current Series Ids: [blue]{', '.join(self.current_series.keys()) or None}[/blue]\n"
)
@@ -228,10 +226,10 @@ Current Series IDs:
def call_pred(self, _):
"""Process pred command"""
if not self.current_series:
t_console.print("Please select 1 Series to use.\n")
console.print("Please select 1 Series to use.\n")
return
if len(self.current_series.keys()) != 1:
t_console.print("Only 1 Series can be input into prediction.\n")
console.print("Only 1 Series can be input into prediction.\n")
return
from gamestonk_terminal.economy.fred.prediction.pred_controller import (
PredictionTechniquesController,

View File

@@ -8,7 +8,7 @@ import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from pandas.plotting import register_matplotlib_converters
from rich.console import Console
from gamestonk_terminal.rich_config import console
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.config_plot import PLOT_DPI
@@ -21,8 +21,6 @@ from gamestonk_terminal.helper_funcs import (
register_matplotlib_converters()
t_console = Console()
def format_units(num: int) -> str:
"""Helper to format number into string with K,M,B,T. Number will be in form of 10^n"""
@@ -51,7 +49,7 @@ def notes(series_term: str, num: int):
"""
df_search = fred_model.get_series_notes(series_term)
if df_search.empty:
t_console.print("No matches found. \n")
console.print("No matches found. \n")
return
df_search["notes"] = df_search["notes"].apply(
lambda x: "\n".join(textwrap.wrap(x, width=100)) if isinstance(x, str) else x
@@ -60,7 +58,7 @@ def notes(series_term: str, num: int):
lambda x: "\n".join(textwrap.wrap(x, width=50)) if isinstance(x, str) else x
)
if gtff.USE_TABULATE_DF:
t_console.print(
console.print(
rich_table_from_df(
df_search[["id", "title", "notes"]].head(num),
title=f"[bold]Search results for {series_term}[/bold]",
@@ -69,10 +67,10 @@ def notes(series_term: str, num: int):
)
)
else:
t_console.print(
console.print(
df_search[["id", "title", "notes"]].head(num).to_string(index=False)
)
t_console.print("")
console.print("")
def display_fred_series(
@@ -145,7 +143,7 @@ def display_fred_series(
data.index = [x.strftime("%Y-%m-%d") for x in data.index]
if raw:
if gtff.USE_TABULATE_DF:
t_console.print(
console.print(
rich_table_from_df(
data.tail(limit),
headers=list(data.columns),
@@ -154,11 +152,11 @@ def display_fred_series(
)
)
else:
t_console.print(data.tail(limit).to_string())
console.print(data.tail(limit).to_string())
export_data(
export,
os.path.dirname(os.path.abspath(__file__)),
"plot",
data,
)
t_console.print("")
console.print("")

View File

@@ -6,7 +6,7 @@ from typing import List, Dict
import logging
from prompt_toolkit.completion import NestedCompleter
from rich.console import Console
from gamestonk_terminal.rich_config import console
from gamestonk_terminal.parent_classes import BaseController
from gamestonk_terminal import feature_flags as gtff
@@ -33,7 +33,6 @@ from gamestonk_terminal.common.prediction_techniques import (
from gamestonk_terminal.economy.fred import fred_model
logger = logging.getLogger(__name__)
t_console = Console()
class PredictionTechniquesController(BaseController):
@@ -81,15 +80,13 @@ class PredictionTechniquesController(BaseController):
id_string = ""
for s_id, sub_dict in self.current_series.items():
id_string += f" [cyan]{s_id.upper()}[/cyan] : {sub_dict['title']}"
help_string = f"""
Prediction Techniques Menu:
help_string = f"""[cmds]
load load new series[/cmds]
load load new series
Selected Series (starting from [green]{self.start_date}[/green]):
[param]Selected Series[/param]: From {self.start_date}
{id_string}
Models:
[info]Models:[/info][cmds]
ets exponential smoothing (e.g. Holt-Winters)
knn k-Nearest Neighbors
regression polynomial regression
@@ -98,9 +95,9 @@ Models:
rnn Recurrent Neural Network
lstm Long-Short Term Memory
conv1d 1D Convolutional Neural Network
mc Monte-Carlo simulations
mc Monte-Carlo simulations[/cmds]
"""
t_console.print(help_string)
console.print(help_string)
def custom_reset(self):
"""Class specific component of reset command"""
@@ -152,8 +149,8 @@ Models:
ns_parser.series_id, ns_parser.start_date
).dropna()
else:
t_console.print(f"[red]{ns_parser.series_id} not found[/red].")
t_console.print(
console.print(f"[red]{ns_parser.series_id} not found[/red].")
console.print(
f"Current Series: {', '.join(self.current_series.keys()).upper() or None}\n"
)
@@ -230,7 +227,7 @@ Models:
if ns_parser:
if ns_parser.s_end_date:
if ns_parser.s_end_date < self.data.index[0]:
t_console.print(
console.print(
"Backtesting not allowed, since End Date is older than Start Date of historical data\n"
)
@@ -238,7 +235,7 @@ Models:
last_stock_day=self.data.index[0],
n_next_days=5 + ns_parser.n_days,
)[-1]:
t_console.print(
console.print(
"Backtesting not allowed, since End Date is too close to Start Date to train model\n"
)
@@ -331,7 +328,7 @@ Models:
)
if ns_parser:
if ns_parser.n_inputs > len(self.data):
t_console.print(
console.print(
f"[red]Data only contains {len(self.data)} samples and the model is trying "
f"to use {ns_parser.n_inputs} inputs. Either use less inputs or load with"
f" an earlier start date[/red]\n"
@@ -350,7 +347,7 @@ Models:
time_res=self.resolution,
)
except ValueError:
t_console.print("The loaded data does not have enough data")
console.print("The loaded data does not have enough data")
def call_regression(self, other_args: List[str]):
"""Process linear command"""
@@ -422,7 +419,7 @@ Models:
# BACKTESTING CHECK
if ns_parser.s_end_date:
if ns_parser.s_end_date < self.data.index[0]:
t_console.print(
console.print(
"Backtesting not allowed, since End Date is older than Start Date of historical data\n"
)
return
@@ -431,14 +428,14 @@ Models:
last_stock_day=self.data.index[0],
n_next_days=5 + ns_parser.n_days,
)[-1]:
t_console.print(
console.print(
"Backtesting not allowed, since End Date is too close to Start Date to train model\n"
)
return
try:
if ns_parser.n_inputs > len(self.data):
t_console.print(
console.print(
f"[red]Data only contains {len(self.data)} samples and the model is trying "
f"to use {ns_parser.n_inputs} inputs. Either use less inputs or load with"
f" an earlier start date[/red]\n"
@@ -456,7 +453,7 @@ Models:
time_res=self.resolution,
)
except ValueError as e:
t_console.print(e)
console.print(e)
def call_arima(self, other_args: List[str]):
"""Process arima command"""
@@ -535,7 +532,7 @@ Models:
# BACKTESTING CHECK
if ns_parser.s_end_date:
if ns_parser.s_end_date < self.data.index[0]:
t_console.print(
console.print(
"Backtesting not allowed, since End Date is older than Start Date of historical data\n"
)
return
@@ -544,7 +541,7 @@ Models:
last_stock_day=self.data.index[0],
n_next_days=5 + ns_parser.n_days,
)[-1]:
t_console.print(
console.print(
"Backtesting not allowed, since End Date is too close to Start Date to train model\n"
)
return
@@ -572,7 +569,7 @@ Models:
)
if ns_parser:
if ns_parser.n_inputs > len(self.data):
t_console.print(
console.print(
f"[red]Data only contains {len(self.data)} samples and the model is trying "
f"to use {ns_parser.n_inputs} inputs. Either use less inputs or load with"
f" an earlier start date[/red]\n"
@@ -592,7 +589,7 @@ Models:
time_res=self.resolution,
)
except Exception as e:
t_console.print(e, "\n")
console.print(e, "\n")
finally:
pred_helper.restore_env()
@@ -607,7 +604,7 @@ Models:
)
if ns_parser:
if ns_parser.n_inputs > len(self.data):
t_console.print(
console.print(
f"[red]Data only contains {len(self.data)} samples and the model is trying "
f"to use {ns_parser.n_inputs} inputs. Either use less inputs or load with"
f" an earlier start date[/red]\n"
@@ -628,7 +625,7 @@ Models:
)
except Exception as e:
t_console.print(e)
console.print(e)
finally:
pred_helper.restore_env()
@@ -643,7 +640,7 @@ Models:
)
if ns_parser:
if ns_parser.n_inputs > len(self.data):
t_console.print(
console.print(
f"[red]Data only contains {len(self.data)} samples and the model is trying "
f"to use {ns_parser.n_inputs} inputs. Either use less inputs or load with"
f" an earlier start date[/red]\n"
@@ -664,7 +661,7 @@ Models:
)
except Exception as e:
t_console.print(e, "\n")
console.print(e, "\n")
finally:
pred_helper.restore_env()
@@ -679,7 +676,7 @@ Models:
)
if ns_parser:
if ns_parser.n_inputs > len(self.data):
t_console.print(
console.print(
f"[red]Data only contains {len(self.data)} samples and the model is trying "
f"to use {ns_parser.n_inputs} inputs. Either use less inputs or load with"
f" an earlier start date[/red]\n"
@@ -700,7 +697,7 @@ Models:
)
except Exception as e:
t_console.print(e, "\n")
console.print(e, "\n")
finally:
pred_helper.restore_env()

View File

@@ -11,6 +11,7 @@ from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.economy import nasdaq_model
from gamestonk_terminal.helper_funcs import export_data, plot_autoscale
from gamestonk_terminal.config_plot import PLOT_DPI
from gamestonk_terminal.rich_config import console
def display_big_mac_index(
@@ -50,7 +51,7 @@ def display_big_mac_index(
if gtff.USE_TABULATE_DF:
print(tabulate(big_mac, headers=big_mac.columns, tablefmt="fancy_grid"))
else:
print(big_mac.head(20).to_string())
console.print(big_mac.head(20).to_string())
export_data(export, os.path.dirname(os.path.abspath(__file__)), "bigmac", big_mac)
print("")
console.print("")

View File

@@ -8,6 +8,7 @@ from tabulate import tabulate
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.economy import wsj_model
from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal.rich_config import console
def display_overview(export: str):
@@ -20,7 +21,7 @@ def display_overview(export: str):
"""
df_data = wsj_model.market_overview()
if df_data.empty:
print("No overview data available\n")
console.print("No overview data available\n")
return
if gtff.USE_TABULATE_DF:
@@ -34,8 +35,8 @@ def display_overview(export: str):
)
)
else:
print(df_data.to_string(index=False))
print("")
console.print(df_data.to_string(index=False))
console.print("")
export_data(
export,
@@ -55,7 +56,7 @@ def display_indices(export: str):
"""
df_data = wsj_model.us_indices()
if df_data.empty:
print("No indices data available\n")
console.print("No indices data available\n")
return
if gtff.USE_TABULATE_DF:
@@ -69,8 +70,8 @@ def display_indices(export: str):
)
)
else:
print(df_data.to_string(index=False))
print("")
console.print(df_data.to_string(index=False))
console.print("")
export_data(
export,
@@ -90,7 +91,7 @@ def display_futures(export: str):
"""
df_data = wsj_model.top_commodities()
if df_data.empty:
print("No futures/commodities data available\n")
console.print("No futures/commodities data available\n")
return
if gtff.USE_TABULATE_DF:
@@ -104,8 +105,8 @@ def display_futures(export: str):
)
)
else:
print(df_data.to_string(index=False))
print("")
console.print(df_data.to_string(index=False))
console.print("")
export_data(
export,
@@ -125,7 +126,7 @@ def display_usbonds(export: str):
"""
df_data = wsj_model.us_bonds()
if df_data.empty:
print("No US bonds data available\n")
console.print("No US bonds data available\n")
return
if gtff.USE_TABULATE_DF:
@@ -139,8 +140,8 @@ def display_usbonds(export: str):
)
)
else:
print(df_data.to_string(index=False))
print("")
console.print(df_data.to_string(index=False))
console.print("")
export_data(
export,
@@ -160,7 +161,7 @@ def display_glbonds(export: str):
"""
df_data = wsj_model.global_bonds()
if df_data.empty:
print("No global bonds data available\n")
console.print("No global bonds data available\n")
return
if gtff.USE_TABULATE_DF:
@@ -174,8 +175,8 @@ def display_glbonds(export: str):
)
)
else:
print(df_data.to_string(index=False))
print("")
console.print(df_data.to_string(index=False))
console.print("")
export_data(
export,
@@ -195,7 +196,7 @@ def display_currencies(export: str):
"""
df_data = wsj_model.global_currencies()
if df_data.empty:
print("No currencies data available\n")
console.print("No currencies data available\n")
return
if gtff.USE_TABULATE_DF:
@@ -209,8 +210,8 @@ def display_currencies(export: str):
)
)
else:
print(df_data.to_string(index=False))
print("")
console.print(df_data.to_string(index=False))
console.print("")
export_data(
export,

View File

@@ -5,7 +5,7 @@ import argparse
from typing import List
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal.rich_config import console
from gamestonk_terminal.parent_classes import BaseController
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.helper_funcs import (
@@ -36,12 +36,13 @@ class DiscoveryController(BaseController):
def print_help(self):
"""Print help"""
help_str = """
gainers show top gainers [WSJ]
decliners show top decliners [WSJ]
active show most active [WSJ]
help_text = """
[src][Wall Street Journal][/src][cmds]
gainers top gainers
decliners top decliners
active most active[/cmds]
"""
print(help_str)
console.print(text=help_text, menu="ETF - Discovery")
def call_gainers(self, other_args):
"""Process gainers command"""

View File

@@ -10,6 +10,7 @@ from gamestonk_terminal.helper_funcs import (
export_data,
)
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
def show_top_mover(sort_type: str, limit: int = 10, export=""):
@@ -26,7 +27,7 @@ def show_top_mover(sort_type: str, limit: int = 10, export=""):
"""
data = wsj_model.etf_movers(sort_type)
if data.empty:
print("No data available\n")
console.print("No data available\n")
return
if gtff.USE_TABULATE_DF:
@@ -40,11 +41,11 @@ def show_top_mover(sort_type: str, limit: int = 10, export=""):
)
)
else:
print(data.head(limit).to_string())
console.print(data.head(limit).to_string())
export_data(
export,
os.path.dirname(os.path.abspath(__file__)),
sort_type,
data,
)
print("")
console.print("")

View File

@@ -8,11 +8,10 @@ from typing import List
import yfinance as yf
import matplotlib.pyplot as plt
import mplfinance as mpf
from colorama import Style
from prompt_toolkit.completion import NestedCompleter
from thepassiveinvestor import create_ETF_report
from gamestonk_terminal.rich_config import console
from gamestonk_terminal.parent_classes import BaseController
from gamestonk_terminal import feature_flags as gtff
@@ -81,33 +80,36 @@ class ETFController(BaseController):
def print_help(self):
"""Print help"""
help_txt = f"""
ln lookup by name [FinanceDatabase/StockAnalysis.com]
ld lookup by description [FinanceDatabase]
load load ETF data [Yfinance]
{Style.DIM if not self.etf_name else ""}
Symbol: {self.etf_name}{Style.DIM if len(self.etf_holdings)==0 else ""}
Major holdings: {', '.join(self.etf_holdings)}
has_ticker_start = "" if self.etf_name else "[unvl]"
has_ticker_end = "" if self.etf_name else "[/unvl]"
has_etfs_start = "[unvl]" if len(self.etf_holdings) == 0 else ""
has_etfs_end = "[/unvl]" if len(self.etf_holdings) == 0 else ""
help_text = f"""[cmds]
ln lookup by name [src][FinanceDatabase/StockAnalysis.com][/src]
ld lookup by description [src][FinanceDatabase][/src]
load load ETF data [src][Yfinance][/src][/cmds]
> ca comparison analysis, e.g.: get similar, historical, correlation, financials
{Style.RESET_ALL}
[param]Symbol: [/param]{self.etf_name}{has_etfs_start}
[param]Major holdings: [/param]{', '.join(self.etf_holdings)}
[menu]
> ca comparison analysis, e.g.: get similar, historical, correlation, financials{has_etfs_end}
> disc discover ETFs, e.g.: gainers/decliners/active
> scr screener ETFs, e.g.: overview/performance, using preset filters
{Style.DIM if not self.etf_name else ""}
overview get overview [StockAnalysis]
holdings top company holdings [StockAnalysis]
weights sector weights allocation [Yfinance]
summary summary description of the ETF [Yfinance]
> scr screener ETFs, e.g.: overview/performance, using preset filters[/menu]
{has_ticker_start}[cmds]
overview get overview [src][StockAnalysis][/src]
holdings top company holdings [src][StockAnalysis][/src]
weights sector weights allocation [src][Yfinance][/src]
summary summary description of the ETF [src][Yfinance][/src]
candle view a candle chart for ETF
news latest news of the company [News API]
pir create (multiple) passive investor excel report(s) [PassiveInvestor]
compare compare multiple different ETFs [StockAnalysis]
news latest news of the company [src][News API][/src]
pir create (multiple) passive investor excel report(s) [src][PassiveInvestor][/src]
compare compare multiple different ETFs [src][StockAnalysis][/src][/cmds]
[menu]
> ta technical analysis, e.g.: ema, macd, rsi, adx, bbands, obv
> pred prediction techniques, e.g.: regression, arima, rnn, lstm
{Style.RESET_ALL}"""
print(help_txt)
> pred prediction techniques, e.g.: regression, arima, rnn, lstm[/menu]
{has_ticker_end}"""
console.print(text=help_text, menu="ETF")
def custom_reset(self):
"""Class specific component of reset command"""
@@ -171,7 +173,7 @@ Major holdings: {', '.join(self.etf_holdings)}
export=ns_parser.export,
)
else:
print("Wrong source choice!\n")
console.print("Wrong source choice!\n")
def call_ld(self, other_args: List[str]):
"""Process ld command"""
@@ -265,7 +267,7 @@ Major holdings: {', '.join(self.etf_holdings)}
progress=False,
)
if df_etf_candidate.empty:
print("ETF ticker provided does not exist!\n")
console.print("ETF ticker provided does not exist!\n")
return
df_etf_candidate.index.name = "date"
@@ -275,12 +277,14 @@ Major holdings: {', '.join(self.etf_holdings)}
holdings = stockanalysis_model.get_etf_holdings(self.etf_name)
if holdings.empty:
print("No company holdings found!\n")
console.print("No company holdings found!\n")
else:
self.etf_holdings = holdings.index[: ns_parser.limit].tolist()
print(f"Top company holdings found: {', '.join(self.etf_holdings)}\n")
console.print(
f"Top company holdings found: {', '.join(self.etf_holdings)}\n"
)
print("")
console.print("")
def call_overview(self, other_args: List[str]):
"""Process overview command"""
@@ -392,7 +396,7 @@ Major holdings: {', '.join(self.etf_holdings)}
sources=",".join(sources),
)
else:
print("Use 'load <ticker>' prior to this command!", "\n")
console.print("Use 'load <ticker>' prior to this command!", "\n")
def call_candle(self, other_args: List[str]):
"""Process candle command"""
@@ -453,7 +457,7 @@ Major holdings: {', '.join(self.etf_holdings)}
candle_linewidth=1.0, candle_width=0.8, volume_linewidth=1.0
),
)
print("")
console.print("")
export_data(
ns_parser.export,
@@ -463,7 +467,7 @@ Major holdings: {', '.join(self.etf_holdings)}
)
else:
print("No ticker loaded. First use `load {ticker}`\n")
console.print("No ticker loaded. First use `load {ticker}`\n")
def call_pir(self, other_args):
"""Process pir command"""
@@ -505,7 +509,7 @@ Major holdings: {', '.join(self.etf_holdings)}
filename=ns_parser.filename,
folder=ns_parser.folder,
)
print(
console.print(
f"Created ETF report as {ns_parser.filename} in folder {ns_parser.folder} \n"
)
@@ -569,7 +573,7 @@ Major holdings: {', '.join(self.etf_holdings)}
self.etf_name, self.etf_data.index[0], self.etf_data, self.queue
).menu()
else:
print("Use 'load <ticker>' prior to this command!", "\n")
console.print("Use 'load <ticker>' prior to this command!", "\n")
def call_pred(self, _):
"""Process pred command"""
@@ -588,15 +592,15 @@ Major holdings: {', '.join(self.etf_holdings)}
self.queue,
).menu()
except ModuleNotFoundError as e:
print(
console.print(
"One of the optional packages seems to be missing: ",
e,
"\n",
)
else:
print("Use 'load <ticker>' prior to this command!", "\n")
console.print("Use 'load <ticker>' prior to this command!", "\n")
else:
print(
console.print(
"Predict is disabled. Check ENABLE_PREDICT flag on feature_flags.py",
"\n",
)
@@ -607,6 +611,8 @@ Major holdings: {', '.join(self.etf_holdings)}
self.queue = ca_controller.ComparisonAnalysisController(
self.etf_holdings, self.queue
).menu(custom_path_menu_above="/stocks/")
else:
print("Load a ticker with major holdings to compare them on this menu\n")
def call_scr(self, _):
"""Process scr command"""

View File

@@ -7,6 +7,7 @@ from tabulate import tabulate
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.etf import financedatabase_model
from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal.rich_config import console
def display_etf_by_name(
@@ -27,7 +28,7 @@ def display_etf_by_name(
"""
data = financedatabase_model.get_etfs_by_name(name)
if not data:
print("No data was found with that name\n")
console.print("No data was found with that name\n")
return
tabulate_data = pd.DataFrame(data).T[
@@ -48,7 +49,7 @@ def display_etf_by_name(
"\n",
)
else:
print(tabulate_data_sorted.iloc[:limit].to_string(), "\n")
console.print(tabulate_data_sorted.iloc[:limit].to_string(), "\n")
export_data(export, os.path.dirname(os.path.abspath(__file__)), "ln_fd", data)
@@ -71,7 +72,7 @@ def display_etf_by_description(
"""
data = financedatabase_model.get_etfs_by_description(description)
if not data:
print("No data was found with that description\n")
console.print("No data was found with that description\n")
return
tabulate_data = pd.DataFrame(data).T[
@@ -92,7 +93,7 @@ def display_etf_by_description(
"\n",
)
else:
print(tabulate_data_sorted.iloc[:limit].to_string(), "\n")
console.print(tabulate_data_sorted.iloc[:limit].to_string(), "\n")
export_data(export, os.path.dirname(os.path.abspath(__file__)), "ld", data)
@@ -115,7 +116,7 @@ def display_etf_by_category(
"""
data = financedatabase_model.get_etfs_by_category(category)
if not data:
print("No data was found on that category\n")
console.print("No data was found on that category\n")
return
tabulate_data = pd.DataFrame(data).T[
@@ -136,7 +137,7 @@ def display_etf_by_category(
"\n",
)
else:
print(tabulate_data_sorted.iloc[:limit].to_string(), "\n")
console.print(tabulate_data_sorted.iloc[:limit].to_string(), "\n")
export_data(
export,

View File

@@ -7,7 +7,7 @@ from datetime import datetime, timedelta
import pandas as pd
import numpy as np
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal.rich_config import console
from gamestonk_terminal.parent_classes import BaseController
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.helper_funcs import (
@@ -86,22 +86,16 @@ class PredictionTechniquesController(BaseController):
def print_help(self):
"""Print help"""
s_intraday = (f"Intraday {self.interval}", "Daily")[self.interval == "1440min"]
if self.start:
stock_info = f"{s_intraday} Stock: {self.ticker} (from {self.start.strftime('%Y-%m-%d')})"
else:
stock_info = "{s_intraday} Stock: {self.ticker}"
help_string = f"""
Prediction Techniques Menu:
etf_info = f"{self.ticker} (from {self.start.strftime('%Y-%m-%d')})"
help_text = f"""[cmds]
load load new ticker
pick pick new target variable
pick pick new target variable[/cmds]
Ticker Loaded: {stock_info}
Target Column: {self.target}
[param]Ticker Loaded: [/param]{etf_info}
[param]Target Column: [/param]{self.target}
Models:
[info]Models:[/info][cmds]
ets exponential smoothing (e.g. Holt-Winters)
knn k-Nearest Neighbors
regression polynomial regression
@@ -110,9 +104,9 @@ Models:
rnn Recurrent Neural Network
lstm Long-Short Term Memory
conv1d 1D Convolutional Neural Network
mc Monte-Carlo simulations
mc Monte-Carlo simulations[/cmds]
"""
print(help_string)
console.print(text=help_text, menu="ETF - Prediction Techniques")
def custom_reset(self):
"""Class specific component of reset command"""
@@ -240,7 +234,7 @@ Models:
)
if ns_parser:
self.target = ns_parser.target
print("")
console.print("")
def call_ets(self, other_args: List[str]):
"""Process ets command"""
@@ -317,7 +311,7 @@ Models:
if ns_parser.s_end_date:
if ns_parser.s_end_date < self.stock.index[0]:
print(
console.print(
"Backtesting not allowed, since End Date is older than Start Date of historical data\n"
)
@@ -325,7 +319,7 @@ Models:
last_stock_day=self.stock.index[0],
n_next_days=5 + ns_parser.n_days,
)[-1]:
print(
console.print(
"Backtesting not allowed, since End Date is too close to Start Date to train model\n"
)
@@ -498,7 +492,7 @@ Models:
# BACKTESTING CHECK
if ns_parser.s_end_date:
if ns_parser.s_end_date < self.stock.index[0]:
print(
console.print(
"Backtesting not allowed, since End Date is older than Start Date of historical data\n"
)
@@ -506,7 +500,7 @@ Models:
last_stock_day=self.stock.index[0],
n_next_days=5 + ns_parser.n_days,
)[-1]:
print(
console.print(
"Backtesting not allowed, since End Date is too close to Start Date to train model\n"
)
@@ -599,7 +593,7 @@ Models:
if ns_parser.s_end_date:
if ns_parser.s_end_date < self.stock.index[0]:
print(
console.print(
"Backtesting not allowed, since End Date is older than Start Date of historical data\n"
)
@@ -607,7 +601,7 @@ Models:
last_stock_day=self.stock.index[0],
n_next_days=5 + ns_parser.n_days,
)[-1]:
print(
console.print(
"Backtesting not allowed, since End Date is too close to Start Date to train model\n"
)
@@ -645,7 +639,7 @@ Models:
no_shuffle=ns_parser.no_shuffle,
)
except Exception as e:
print(e, "\n")
console.print(e, "\n")
finally:
pred_helper.restore_env()
@@ -673,7 +667,7 @@ Models:
)
except Exception as e:
print(e, "\n")
console.print(e, "\n")
finally:
pred_helper.restore_env()
@@ -701,7 +695,7 @@ Models:
)
except Exception as e:
print(e, "\n")
console.print(e, "\n")
finally:
pred_helper.restore_env()
@@ -729,7 +723,7 @@ Models:
)
except Exception as e:
print(e, "\n")
console.print(e, "\n")
finally:
pred_helper.restore_env()
@@ -772,7 +766,7 @@ Models:
)
if ns_parser:
if self.target != "AdjClose":
print("MC Prediction designed for AdjClose prices\n")
console.print("MC Prediction designed for AdjClose prices\n")
mc_view.display_mc_forecast(
data=self.stock[self.target],

View File

@@ -8,7 +8,7 @@ import configparser
from typing import List
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal.rich_config import console
from gamestonk_terminal.parent_classes import BaseController
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.helper_funcs import (
@@ -73,17 +73,17 @@ class ScreenerController(BaseController):
def print_help(self):
"""Print help"""
help_str = f"""
help_text = f"""[cmds]
view view available presets
set set one of the available presets
set set one of the available presets[/cmds]
PRESET: {self.preset}
[param]PRESET: [/param]{self.preset}[cmds]
screen screen ETF using preset selected [StockAnalysis]
screen screen ETF using preset selected [src][StockAnalysis][/src]
sbc screen by category [FinanceDatabase]
sbc screen by category [src][FinanceDatabase][/src][/cmds]
"""
print(help_str)
console.print(text=help_text, menu="ETF - Screener")
def call_view(self, other_args: List[str]):
"""Process view command"""
@@ -127,19 +127,19 @@ PRESET: {self.preset}
"YrHigh",
]
print("")
console.print("")
for filter_header in headers:
print(f" - {filter_header} -")
console.print(f" - {filter_header} -")
d_filters = {**preset_filter[filter_header]}
d_filters = {k: v for k, v in d_filters.items() if v}
if d_filters:
max_len = len(max(d_filters, key=len))
for key, value in d_filters.items():
print(f"{key}{(max_len-len(key))*' '}: {value}")
print("")
console.print(f"{key}{(max_len-len(key))*' '}: {value}")
console.print("")
else:
print("\nPresets:")
console.print("\nPresets:")
for preset in self.preset_choices:
with open(
presets_path + preset + ".ini",
@@ -150,10 +150,10 @@ PRESET: {self.preset}
if line.strip() == "[Price]":
break
description += line.strip()
print(
console.print(
f" {preset}{(30-len(preset)) * ' '}{description.split('Description: ')[1].replace('#', '')}"
)
print("")
console.print("")
def call_set(self, other_args: List[str]):
"""Process set command"""
@@ -177,7 +177,7 @@ PRESET: {self.preset}
ns_parser = parse_known_args_and_warn(parser, other_args)
if ns_parser:
self.preset = ns_parser.preset
print("")
console.print("")
def call_screen(self, other_args):
"""Process screen command"""
@@ -266,7 +266,7 @@ PRESET: {self.preset}
export=ns_parser.export,
)
else:
print(
console.print(
"The category selected does not exist, choose one from:"
f" {', '.join(financedatabase_model.get_etfs_categories())}\n"
)

View File

@@ -8,6 +8,7 @@ from tabulate import tabulate
from gamestonk_terminal.etf.screener import screener_model
from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.rich_config import console
# pylint:disable=no-member
@@ -46,8 +47,8 @@ def view_screener(
)
)
else:
print(screened_data.head(num_to_show).fillna("").to_string())
print("")
console.print(screened_data.head(num_to_show).fillna("").to_string())
console.print("")
export_data(
export,

Some files were not shown because too many files have changed in this diff Show More