def display_exchange_rates(sortby: str, descend: bool, top: int, export: str) -> None: """Shows list of crypto, fiats, commodity exchange rates. [Source: CoinGecko] Parameters ---------- top: int Number of records to display sortby: str Key by which to sort data descend: bool Flag to sort data descending export : str Export dataframe data to csv,json,xlsx file """ df = gecko.get_exchange_rates().sort_values(by=sortby, ascending=descend) if not df.empty: print_rich_table( df.head(top), headers=list(df.columns), show_index=False, title="Exchange Rates", ) console.print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "exrates", df, ) else: console.print("") console.print("Unable to retrieve data from CoinGecko.") console.print("")
def display_quote(to_symbol: str, from_symbol: str): """Display current forex pair exchange rate. Parameters ---------- to_symbol : str To symbol from_symbol : str From forex symbol """ quote = av_model.get_quote(to_symbol, from_symbol) if not quote: return df = pd.DataFrame.from_dict(quote) df.index = df.index.to_series().apply(lambda x: x[3:]).values df = df.iloc[[0, 2, 5, 4, 7, 8]] print_rich_table( df, show_index=True, title=f"[bold]{from_symbol}/{to_symbol} Quote [/bold]", ) console.print("")
def display_crypto_withdrawal_fees(symbol: str, export: str = "") -> None: """Coin withdrawal fees per exchange [Source: https://withdrawalfees.com/] Parameters ---------- symbol: str Coin to check withdrawal fees export : str Export dataframe data to csv,json,xlsx file """ res = get_crypto_withdrawal_fees(symbol) stats_string = res[0] df_fees = res[1] if df_fees.empty: console.print("\nError in withdrawal fees request\n") else: console.print(f"\nWithdrawal fees for {symbol}:") console.print(f"\n{stats_string}\n") print_rich_table( df_fees, headers=list(df_fees.columns), show_index=False, title="Withdrawal Fees per Exchange", ) console.print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "crypto_withdrawal_fees", df_fees, )
def view_overview(symbol: str, export: str = ""): """Print etf overview information Parameters ---------- symbol:str ETF symbols to display overview for export:str Format to export data """ if symbol.upper() not in stockanalysis_model.get_all_names_symbols()[0]: console.print(f"{symbol.upper()} not found in ETFs\n") return data = stockanalysis_model.get_etf_overview(symbol) print_rich_table(data, headers=list(data.columns), title="ETF Overview Information") console.print("") export_data(export, os.path.dirname(os.path.abspath(__file__)), "overview", data)
def show_treasury_maturities(treasuries: Dict): """Obtain treasury maturity options [Source: EconDB] Parameters ---------- treasuries: dict A dictionary containing the options structured {instrument : {maturities: {abbreviation : name}}} Returns ---------- A table containing the instruments and maturities. """ instrument_maturities = econdb_model.obtain_treasury_maturities(treasuries) print_rich_table( instrument_maturities, headers=list(["Maturities"]), show_index=True, index_name="Instrument", title="Maturity options per instrument", ) console.print()
def display_popular_tickers(n_top: int = 10, posts_to_look_at: int = 50, subreddits: str = "", export: str = ""): """Print latest popular tickers. [Source: Reddit] Parameters ---------- n_top : int Number of top tickers to get posts_to_look_at : int How many posts to analyze in each subreddit subreddits : str, optional String of comma separated subreddits. export : str Format to export dataframe """ popular_tickers_df = reddit_model.get_popular_tickers( n_top, posts_to_look_at, subreddits) if not popular_tickers_df.empty: print_rich_table( popular_tickers_df, headers=list(popular_tickers_df.columns), show_index=False, title=f"\nThe following TOP {n_top} tickers have been mentioned:", ) else: console.print("No tickers found") console.print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "popular", popular_tickers_df, )
def display_borrow_rates(top: int, current: bool = True, export: str = "") -> None: """Displays DeFi borrow rates. By using smart contracts, borrowers are able to lock collateral to protect against defaults while seamlessly adding to or closing their loans at any time. [Source: https://defirate.com/] Parameters ---------- top: int Number of records to display current: bool If true displays current funding rate values. If false displays last 30 day average of funding rates. export : str Export dataframe data to csv,json,xlsx file """ df = defirate_model.get_borrow_rates(current) df_data = df.copy() df = df.loc[:, ~df.eq("–").all()] print_rich_table( df.head(top), headers=list(df.columns), show_index=False, title="DeFi Borrow Rates", ) console.print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "borrow", df_data, )
def notes(series_term: str, num: int): """Print Series notes. [Source: FRED] Parameters ---------- series_term : str Search for these series_term num : int Maximum number of series notes to display """ df_search = fred_model.get_series_notes(series_term) if df_search.empty: 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) df_search["title"] = df_search["title"].apply(lambda x: "\n".join( textwrap.wrap(x, width=50)) if isinstance(x, str) else x) print_rich_table( df_search[["id", "title", "notes"]].head(num), title=f"[bold]Search results for {series_term}[/bold]", show_index=False, headers=["Series ID", "Title", "Description"], ) console.print("")
def display_top_nfts(top: int = 10, sortby: str = "", export: str = "") -> None: """Displays top nft collections [Source: https://dappradar.com/] Parameters ---------- top: int Number of records to display sortby: str Key by which to sort data export : str Export dataframe data to csv,json,xlsx file """ df = dappradar_model.get_top_nfts() if df.empty: console.print("Failed to fetch data from DappRadar\n") else: if sortby in dappradar_model.NFT_COLUMNS: df = df.sort_values(by=sortby, ascending=False) for col in ["Floor Price [$]", "Avg Price [$]", "Market Cap [$]", "Volume [$]"]: if col in df.columns: df[col] = df[col].apply(lambda x: very_long_number_formatter(x)) print_rich_table( df.head(top), headers=list(df.columns), show_index=False, title="Top NFT collections", ) console.print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "drnft", df, )
def display_unitroot(df: pd.DataFrame, target: str, fuller_reg: str, kpss_reg: str, export: str = ""): """Show unit root test calculations Parameters ---------- df : pd.DataFrame DataFrame target : str Column of data to look at fuller_reg : str Type of regression of ADF test kpss_reg : str Type of regression for KPSS test export : str Format for exporting data """ df = df[target] data = qa_model.get_unitroot(df, fuller_reg, kpss_reg) print_rich_table( data, show_index=True, headers=list(data.columns), title="[bold]Unit Root Calculation[/bold]", floatfmt=".4f", ) console.print("") export_data( export, os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"), "unitroot", data, )
def orders_view(num: int, export: str): """Prints last N orders by Fidelity customers. [Source: Fidelity] Parameters ---------- num: int Number of stocks to display export : str Export dataframe data to csv,json,xlsx file """ order_header, df_orders = fidelity_model.get_orders() pd.set_option("display.max_colwidth", None) if gtff.USE_COLOR: df_orders["Buy / Sell Ratio"] = df_orders["Buy / Sell Ratio"].apply( lambda_buy_sell_ratio_color_red_green) df_orders["Price Change"] = df_orders["Price Change"].apply( lambda_price_change_color_red_green) df_orders = df_orders.head(n=num).iloc[:, :-1] print_rich_table( df_orders, headers=[x.title() for x in df_orders.columns], show_index=False, title=f"{order_header}:", ) console.print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "ford", df_orders, )
def estimates(ticker: str, export: str): """Display analysts' estimates for a given ticker. [Source: Business Insider] Parameters ---------- ticker : str Ticker to get analysts' estimates export : str Export dataframe data to csv,json,xlsx file """ ( df_year_estimates, df_quarter_earnings, df_quarter_revenues, ) = business_insider_model.get_estimates(ticker) print_rich_table( df_year_estimates, headers=list(df_year_estimates.columns), show_index=True, title="Annual Earnings Estimates", ) console.print("") print_rich_table( df_quarter_earnings, headers=list(df_quarter_earnings.columns), show_index=True, title="Quarterly Earnings Estimates", ) console.print("") print_rich_table( df_quarter_revenues, headers=list(df_quarter_revenues.columns), show_index=True, title="Quarterly Revenue Estimates", ) console.print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "pt_year", df_year_estimates, ) export_data( export, os.path.dirname(os.path.abspath(__file__)), "pt_qtr_earnings", df_quarter_earnings, ) export_data( export, os.path.dirname(os.path.abspath(__file__)), "pt_qtr_revenues", df_quarter_revenues, )
def display_earnings(ticker: str, limit: int, quarterly: bool = False): """Alpha Vantage earnings Parameters ---------- ticker : str Fundamental analysis ticker symbol limit:int Number of events to show quarterly: bool Flag to show quarterly instead of annual """ df_fa = av_model.get_earnings(ticker, quarterly) if df_fa.empty: console.print("No API calls left. Try me later", "\n") return print_rich_table( df_fa.head(limit), headers=list(df_fa.columns), show_index=False, title=f"{ticker} Earnings", ) console.print("")
def display_top_retail(n_days: int = 3, export: str = ""): """Display the top 10 retail traded stocks for last days Parameters ---------- n_days : int, optional Number of days to show by default 3 export : str, optional Format to export data, by default "" """ retails = nasdaq_model.get_retail_tickers() for date, df in retails.head(n_days * 10).groupby("Date"): df = df.drop(columns=["Date"]) df = df.reset_index(drop=True) print_rich_table( df, headers=[x.title() for x in df.columns], show_index=False, title=f"[bold]{date} Top Retail:[/bold]", ) console.print("") export_data(export, os.path.dirname(os.path.abspath(__file__)), "rtat", retails)
def display_top_dexes(top: int = 10, export: str = "", sortby: str = "") -> None: """Displays top decentralized exchanges [Source: https://dappradar.com/] Parameters ---------- top: int Number of records to display sortby: str Key by which to sort data export : str Export dataframe data to csv,json,xlsx file """ df = dappradar_model.get_top_dexes() if df.empty: console.print("Failed to fetch data from DappRadar\n") return if sortby in dappradar_model.DEX_COLUMNS: df = df.sort_values(by=sortby, ascending=False) for col in ["Daily Users", "Daily Volume [$]"]: if col in df.columns: df[col] = df[col].apply(lambda x: very_long_number_formatter(x)) print_rich_table( df.head(top), headers=list(df.columns), show_index=False, title="Top Decentralized Exchanges", ) console.print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "drdex", df, )
def display_allocation(fund_name: str, focus: str): """Displays the allocation of the selected swedish fund Parameters ---------- fund_name: str Full name of the fund focus: str The focus of the displayed allocation/exposure of the fund """ # Code mostly taken from: https://github.com/northern-64bit/Portfolio-Report-Generator/tree/main fund_data = avanza_model.get_data(fund_name.upper()) if focus in ["holding", "all"]: table_row = [] console.print("") for data in fund_data["holdingChartData"]: table_row_temp = [] table_row_temp.append(data["name"]) table_row_temp.append(str(data["y"])) table_row_temp.append(data["countryCode"]) table_row.append(table_row_temp) header = ["Holding", "Allocation in %", "Country"] holding_data = pd.DataFrame(table_row, columns=header) print_rich_table(holding_data, title=f"{fund_name}'s Holdings", headers=header) if focus in ["sector", "all"]: table_row = [] console.print("") for data in fund_data["sectorChartData"]: table_row_temp = [] table_row_temp.append(sector_dict[data["name"]]) table_row_temp.append(str(data["y"])) table_row.append(table_row_temp) header = ["Sector", "Allocation in %"] sector_data = pd.DataFrame(table_row, columns=header) print_rich_table(sector_data, title=f"{fund_name}'s Sector Weighting", headers=header) if focus in ["country", "all"]: table_row = [] console.print("") for data in fund_data["countryChartData"]: table_row_temp = [] table_row_temp.append(data["countryCode"]) table_row_temp.append(str(data["y"])) table_row.append(table_row_temp) header = ["Country", "Allocation in %"] country_data = pd.DataFrame(table_row, columns=header) print_rich_table(country_data, title=f"{fund_name}'s Country Weighting", headers=header) console.print("")
def print_prediction_kpis(real: np.ndarray, pred: np.ndarray): """Print prediction statistics""" kpis = { "MAPE": f"{mean_absolute_percentage_error(real, pred) :.3f} %", "R2": f"{r2_score(real, pred) :.3f}", "MAE": f"{mean_absolute_error(real, pred):.3f}", "MSE": f"{mean_squared_error(real, pred):.3f}", "RMSE": f"{mean_squared_error(real, pred, squared=False):.3f}", } df = pd.DataFrame.from_dict(kpis, orient="index") console.print( print_rich_table( df, show_index=True, title="KPIs", floatfmt=".2f", ) )
def display_last_contracts( past_transaction_days: int = 2, num: int = 20, sum_contracts: bool = False, export: str = "", external_axes: Optional[List[plt.Axes]] = None, ): """Last government contracts [Source: quiverquant.com] Parameters ---------- past_transaction_days: int Number of days to look back num: int Number of contracts to show sum_contracts: bool Flag to show total amount of contracts given out. export: str Format to export data external_axes : Optional[List[plt.Axes]], optional External axes (1 axis is expected in the list), by default None """ df_contracts = quiverquant_model.get_government_trading("contracts") if df_contracts.empty: console.print("No government contracts found\n") return df_contracts.sort_values("Date", ascending=False) df_contracts["Date"] = pd.to_datetime(df_contracts["Date"]) df_contracts.drop_duplicates(inplace=True) df = df_contracts.copy() df_contracts = df_contracts[df_contracts["Date"].isin( df_contracts["Date"].unique()[:past_transaction_days])] df_contracts = df_contracts[[ "Date", "Ticker", "Amount", "Description", "Agency" ]][:num] df_contracts["Description"] = df_contracts["Description"].apply( lambda x: "\n".join(textwrap.wrap(x, 50))) print_rich_table( df_contracts, headers=list(df_contracts.columns), show_index=False, title="Last Government Contracts", ) if sum_contracts: # This plot has 1 axis if not external_axes: _, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) else: if len(external_axes) != 1: console.print("[red]Expected list of one axis item./n[/red]") return (ax, ) = external_axes df["Date"] = pd.to_datetime(df["Date"]).dt.date df.groupby("Date").sum().div(1000).plot(kind="bar", rot=0, ax=ax) ax.set_ylabel("Amount ($1k)") ax.set_title("Total amount of government contracts given") theme.style_primary_axis(ax) if not external_axes: theme.visualize_output() console.print("") export_data(export, os.path.dirname(os.path.abspath(__file__)), "lastcontracts", df)
def display_government_sells( gov_type: str, past_transactions_months: int = 6, num: int = 10, raw: bool = False, export: str = "", external_axes: Optional[List[plt.Axes]] = None, ): """Top buy government trading [Source: quiverquant.com] Parameters ---------- gov_type: str Type of government data between: congress, senate and house past_transactions_months: int Number of months to get trading for num: int Number of tickers to show raw: bool Display raw data export: str Format to export data external_axes : Optional[List[plt.Axes]], optional External axes (1 axis is expected in the list), by default None """ df_gov = quiverquant_model.get_government_trading(gov_type) if df_gov.empty: console.print(f"No {gov_type} trading data found\n") return df_gov = df_gov.sort_values("TransactionDate", ascending=False) start_date = datetime.now() - timedelta(days=past_transactions_months * 30) df_gov["TransactionDate"] = pd.to_datetime(df_gov["TransactionDate"]) df_gov = df_gov[df_gov["TransactionDate"] > start_date].dropna() df_gov["Range"] = df_gov["Range"].apply(lambda x: "$5,000,001-$5,000,001" if x == ">$5,000,000" else x) df_gov["min"] = df_gov["Range"].apply(lambda x: x.split("-")[0].strip( "$").replace(",", "").strip().replace(">$", "").strip()) df_gov["max"] = df_gov["Range"].apply( lambda x: x.split("-")[1].replace(",", "").strip().strip("$").replace( ">$", "").strip() if "-" in x else x.strip("$").replace( ",", "").replace(">$", "").strip()) df_gov["lower"] = df_gov[["min", "max", "Transaction"]].apply( lambda x: float(x["min"]) if x["Transaction"] == "Purchase" else -float(x["max"]), axis=1, ) df_gov["upper"] = df_gov[["min", "max", "Transaction"]].apply( lambda x: float(x["max"]) if x["Transaction"] == "Purchase" else -float(x["min"]), axis=1, ) df_gov = df_gov.sort_values("TransactionDate", ascending=True) if raw: df = pd.DataFrame( df_gov.groupby("Ticker")["upper"].sum().div(1000).sort_values( ascending=True).abs().head(n=num)) print_rich_table(df, headers=["Amount ($1k)"], show_index=True, title="Top Government Trades") # This plot has 1 axis if not external_axes: _, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) else: if len(external_axes) != 1: console.print("[red]Expected list of one axis item./n[/red]") return (ax, ) = external_axes colors = theme.get_colors() df_gov.groupby("Ticker")["upper"].sum().div(1000).sort_values().abs().head( n=num).plot(kind="bar", rot=0, ax=ax, color=colors) ax.set_ylabel("Amount ($1k)") ax.set_title( f"{num} most sold stocks over last {past_transactions_months} months" f" (upper bound) for {gov_type}") theme.style_primary_axis(ax) if not external_axes: theme.visualize_output() console.print("") export_data(export, os.path.dirname(os.path.abspath(__file__)), "topsells", df_gov)
def fails_to_deliver( ticker: str, stock: pd.DataFrame, start: datetime, end: datetime, num: int, raw: bool, export: str = "", external_axes: Optional[List[plt.Axes]] = None, ): """Display fails-to-deliver data for a given ticker. [Source: SEC] Parameters ---------- ticker : str Stock ticker stock : pd.DataFrame Stock data start : datetime Start of data end : datetime End of data num : int Number of latest fails-to-deliver being printed raw : bool Print raw data export : str Export dataframe data to csv,json,xlsx file external_axes : Optional[List[plt.Axes]], optional External axes (2 axis is expected in the list), by default None """ ftds_data = sec_model.get_fails_to_deliver(ticker, start, end, num) # This plot has 2 axis if not external_axes: _, ax1 = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) ax2 = ax1.twinx() else: if len(external_axes) != 2: console.print("[red]Expected list of one axis item./n[/red]") return (ax1, ax2) = external_axes ax1.bar( ftds_data["SETTLEMENT DATE"], ftds_data["QUANTITY (FAILS)"] / 1000, label="Fail Quantity", ) ax1.set_ylabel("Shares [K]") ax1.set_title(f"Fails-to-deliver Data for {ticker}") ax1.legend(loc="lower right") if num > 0: stock_ftd = stock[stock.index > (datetime.now() - timedelta(days=num + 31))] else: stock_ftd = stock[stock.index > start] stock_ftd = stock_ftd[stock_ftd.index < end] ax2.plot(stock_ftd.index, stock_ftd["Adj Close"], color="orange", label="Share Price") ax2.set_ylabel("Share Price [$]") ax2.legend(loc="upper right") theme.style_twin_axes(ax1, ax2) if not external_axes: theme.visualize_output() if raw: print_rich_table( ftds_data, headers=list(ftds_data.columns), show_index=False, title="Fails-To-Deliver Data", ) console.print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "ftd", ftds_data.reset_index(), )
def display_sentiment_compare( similar: List[str], raw: bool = False, export: str = "", external_axes: Optional[List[plt.Axes]] = None, ): """Display sentiment for all ticker. [Source: FinBrain] Parameters ---------- similar : List[str] Similar companies to compare income with raw : bool, optional Output raw values, by default False export : str, optional Format to export data external_axes : Optional[List[plt.Axes]], optional External axes (1 axis is expected in the list), by default None """ df_sentiment = finbrain_model.get_sentiments(similar) if df_sentiment.empty: console.print("No sentiments found.") else: # This plot has 1 axis if not external_axes: _, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) else: if len(external_axes) != 1: console.print("[red]Expected list of one axis item./n[/red]") return (ax,) = external_axes for idx, tick in enumerate(similar): offset = 2 * idx ax.axhline(y=offset, color="white", linestyle="--", lw=1) ax.axhline(y=offset + 1, color="white", linestyle="--", lw=1) senValues = np.array(pd.to_numeric(df_sentiment[tick].values)) senNone = np.array(0 * len(df_sentiment)) ax.fill_between( df_sentiment.index, pd.to_numeric(df_sentiment[tick].values) + offset, offset, where=(senValues < senNone), color=theme.down_color, interpolate=True, ) ax.fill_between( df_sentiment.index, pd.to_numeric(df_sentiment[tick].values) + offset, offset, where=(senValues >= senNone), color=theme.up_color, interpolate=True, ) ax.set_ylabel("Sentiment") ax.axhline(y=-1, color="white", linestyle="--", lw=1) ax.set_yticks(np.arange(len(similar)) * 2) ax.set_yticklabels(similar) ax.set_xlim(df_sentiment.index[0], df_sentiment.index[-1]) ax.set_title(f"FinBrain's Sentiment Analysis since {df_sentiment.index[0]}") theme.style_primary_axis(ax) if not external_axes: theme.visualize_output() if raw: print_rich_table( df_sentiment, headers=list(df_sentiment.columns), title="Ticker Sentiment", ) console.print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "sentiment", df_sentiment, ) console.print("")
def display_hist_contracts( ticker: str, raw: bool = False, export: str = "", external_axes: Optional[List[plt.Axes]] = None, ): """Show historical quarterly government contracts [Source: quiverquant.com] Parameters ---------- ticker: str Ticker to get congress trading data from raw: bool Flag to display raw data export: str Format to export data external_axes : Optional[List[plt.Axes]], optional External axes (1 axis is expected in the list), by default None """ df_contracts = quiverquant_model.get_government_trading( "quarter-contracts", ticker=ticker) if df_contracts.empty: console.print("No quarterly government contracts found\n") return amounts = df_contracts.sort_values(by=["Year", "Qtr"])["Amount"].values qtr = df_contracts.sort_values(by=["Year", "Qtr"])["Qtr"].values year = df_contracts.sort_values(by=["Year", "Qtr"])["Year"].values quarter_ticks = [ f"{quarter[0]}" if quarter[1] == 1 else "" for quarter in zip(year, qtr) ] if raw: print_rich_table( df_contracts, headers=list(df_contracts.columns), title="Historical Quarterly Government Contracts", ) else: # This plot has 1 axis if not external_axes: _, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) else: if len(external_axes) != 1: console.print("[red]Expected list of one axis item./n[/red]") return (ax, ) = external_axes ax.plot( np.arange(0, len(amounts)), amounts / 1000, marker=".", markerfacecolor=theme.down_color, lw=2, ms=15, ) ax.set_xlim([-0.5, len(amounts) - 0.5]) ax.set_xticks(np.arange(0, len(amounts))) ax.set_xticklabels(quarter_ticks) ax.set_title( f"Historical Quarterly Government Contracts for {ticker.upper()}") ax.set_ylabel("Amount ($1k)") theme.style_primary_axis(ax) if not external_axes: theme.visualize_output() export_data(export, os.path.dirname(os.path.abspath(__file__)), "histcont") console.print("")
def display_contracts( ticker: str, past_transaction_days: int, raw: bool, export: str = "", external_axes: Optional[List[plt.Axes]] = None, ): """Show government contracts for ticker [Source: quiverquant.com] Parameters ---------- ticker: str Ticker to get congress trading data from past_transaction_days: int Number of days to get transactions for raw: bool Flag to display raw data export: str Format to export data external_axes : Optional[List[plt.Axes]], optional External axes (1 axis is expected in the list), by default None """ df_contracts = quiverquant_model.get_government_trading( "contracts", ticker) if df_contracts.empty: console.print("No government contracts found\n") return df_contracts["Date"] = pd.to_datetime(df_contracts["Date"]).dt.date df_contracts = df_contracts[df_contracts["Date"].isin( df_contracts["Date"].unique()[:past_transaction_days])] df_contracts.drop_duplicates(inplace=True) if raw: print_rich_table( df_contracts, headers=list(df_contracts.columns), show_index=False, title=f"Government Contracts for {ticker.upper()}", ) else: # This plot has 1 axis if not external_axes: _, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) else: if len(external_axes) != 1: console.print("[red]Expected list of one axis item./n[/red]") return (ax, ) = external_axes df_contracts.groupby("Date").sum().div(1000).plot(kind="bar", rot=0, ax=ax) ax.set_ylabel("Amount ($1k)") ax.set_title(f"Sum of latest government contracts to {ticker}") ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(4)) theme.style_primary_axis(ax) if not external_axes: theme.visualize_output() export_data(export, os.path.dirname(os.path.abspath(__file__)), "contracts", df_contracts) console.print("")
def display_last_government(gov_type: str, past_days: int = 5, representative: str = "", export: str = ""): """Display last government trading [Source: quiverquant.com] Parameters ---------- gov_type: str Type of government data between: congress, senate and house past_days: int Number of days to look back representative: str Specific representative to look at export: str Format to export data """ df_gov = quiverquant_model.get_government_trading(gov_type) if df_gov.empty: console.print(f"No {gov_type} trading data found\n") return console.print(f"\nLast transactions for {gov_type.upper()}\n") df_gov = df_gov.sort_values("TransactionDate", ascending=False) df_gov = df_gov[df_gov["TransactionDate"].isin( df_gov["TransactionDate"].unique()[:past_days])] if gov_type == "congress": df_gov = df_gov[[ "TransactionDate", "Ticker", "Representative", "Transaction", "Range", "House", "ReportDate", ]].rename(columns={ "TransactionDate": "Transaction Date", "ReportDate": "Report Date", }) else: df_gov = df_gov[[ "TransactionDate", "Ticker", "Representative", "Transaction", "Range", ]].rename(columns={"TransactionDate": "Transaction Date"}) if representative: df_gov_rep = df_gov[df_gov["Representative"].str.split().str[0] == representative] if df_gov_rep.empty: console.print( f"No representative {representative} found in the past {past_days}" f" days. The following are available: " f"{', '.join(df_gov['Representative'].str.split().str[0].unique())}" ) else: print_rich_table( df_gov_rep, headers=list(df_gov_rep.columns), show_index=False, title="Representative Trading", ) else: print_rich_table( df_gov, headers=list(df_gov.columns), show_index=False, title="Representative Trading", ) console.print("") export_data(export, os.path.dirname(os.path.abspath(__file__)), "lasttrades", df_gov)
def display_government_trading( ticker: str, gov_type: str, past_transactions_months: int = 6, raw: bool = False, export: str = "", external_axes: Optional[List[plt.Axes]] = None, ): """Government trading for specific ticker [Source: quiverquant.com] Parameters ---------- ticker: str Ticker to get congress trading data from gov_type: str Type of government data between: congress, senate and house past_transactions_months: int Number of months to get transactions for raw: bool Show raw output of trades export: str Format to export data external_axes : Optional[List[plt.Axes]], optional External axes (1 axis is expected in the list), by default None """ df_gov = quiverquant_model.get_government_trading(gov_type, ticker) if df_gov.empty: console.print(f"No {gov_type} trading data found\n") return df_gov = df_gov.sort_values("TransactionDate", ascending=False) start_date = datetime.now() - timedelta(days=past_transactions_months * 30) df_gov["TransactionDate"] = pd.to_datetime(df_gov["TransactionDate"]) df_gov = df_gov[df_gov["TransactionDate"] > start_date] if df_gov.empty: console.print(f"No recent {gov_type} trading data found\n") return df_gov["min"] = df_gov["Range"].apply( lambda x: x.split("-")[0].strip("$").replace(",", "").strip()) df_gov["max"] = df_gov["Range"].apply( lambda x: x.split("-")[1].replace(",", "").strip().strip("$") if "-" in x else x.strip("$").replace(",", "").split("\n")[0]) df_gov["lower"] = df_gov[["min", "max", "Transaction"]].apply( lambda x: int(float(x["min"])) if x["Transaction"] == "Purchase" else -int(float(x["max"])), axis=1, ) df_gov["upper"] = df_gov[["min", "max", "Transaction"]].apply( lambda x: int(float(x["max"])) if x["Transaction"] == "Purchase" else -1 * int(float(x["min"])), axis=1, ) df_gov = df_gov.sort_values("TransactionDate", ascending=True) if raw: print_rich_table( df_gov, headers=list(df_gov.columns), show_index=False, title=f"Government Trading for {ticker.upper()}", ) else: plot_government(df_gov, ticker, gov_type, external_axes) export_data(export, os.path.dirname(os.path.abspath(__file__)), "gtrades", df_gov) console.print("")
def display_categories(sortby: str, top: int, export: str, pie: bool) -> None: """Shows top cryptocurrency categories by market capitalization The cryptocurrency category ranking is based on market capitalization. [Source: CoinGecko] Parameters ---------- top: int Number of records to display sortby: str Key by which to sort data export : str Export dataframe data to csv,json,xlsx file """ df = gecko.get_top_crypto_categories(sortby) df_data = df if not df.empty: if pie: df_data[f"% relative to top {top}"] = ( df_data["Market Cap"] / df_data["Market Cap"].sum()) * 100 stables_to_display = df_data[ df_data[f"% relative to top {top}"] >= 1] other_stables = df_data[df_data[f"% relative to top {top}"] < 1] values_list = list( stables_to_display[f"% relative to top {top}"].values) values_list.append(other_stables[f"% relative to top {top}"].sum()) labels_list = list(stables_to_display["Name"].values) labels_list.append("Others") _, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) ax.pie( values_list, labels=labels_list, wedgeprops={ "linewidth": 0.5, "edgecolor": "white" }, autopct="%1.0f%%", startangle=90, ) ax.set_title( f"Market Cap distribution of top {top} crypto categories") if gtff.USE_ION: plt.ion() plt.show() df = df.applymap( lambda x: lambda_long_number_format_with_type_check(x)) print_rich_table( df.head(top), headers=list(df.columns), floatfmt=".2f", show_index=False, ) console.print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "cgcategories", df_data, ) else: console.print("\nUnable to retrieve data from CoinGecko.\n")
def display_qtr_contracts( analysis: str, num: int, raw: bool = False, export: str = "", external_axes: Optional[List[plt.Axes]] = None, ): """Quarterly contracts [Source: quiverquant.com] Parameters ---------- analysis: str Analysis to perform. Either 'total', 'upmom' 'downmom' num: int Number to show raw: bool Flag to display raw data export: str Format to export data external_axes : Optional[List[plt.Axes]], optional External axes (1 axis is expected in the list), by default None """ df_contracts = quiverquant_model.get_government_trading( "quarter-contracts") if df_contracts.empty: console.print("No quarterly government contracts found\n") return tickers = quiverquant_model.analyze_qtr_contracts(analysis, num) if analysis in ("upmom", "downmom"): if raw: print_rich_table( pd.DataFrame(tickers.values), headers=["tickers"], show_index=False, title="Quarterly Contracts", ) else: # This plot has 1 axis if not external_axes: _, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) else: if len(external_axes) != 1: console.print( "[red]Expected list of one axis item./n[/red]") return (ax, ) = external_axes max_amount = 0 quarter_ticks = [] for symbol in tickers: amounts = ( df_contracts[df_contracts["Ticker"] == symbol].sort_values( by=["Year", "Qtr"])["Amount"].values) qtr = ( df_contracts[df_contracts["Ticker"] == symbol].sort_values( by=["Year", "Qtr"])["Qtr"].values) year = ( df_contracts[df_contracts["Ticker"] == symbol].sort_values( by=["Year", "Qtr"])["Year"].values) ax.plot(np.arange(0, len(amounts)), amounts / 1_000_000, "-*", lw=2, ms=15) if len(amounts) > max_amount: max_amount = len(amounts) quarter_ticks = [ f"{quarter[0]} - Q{quarter[1]} " for quarter in zip(year, qtr) ] ax.set_xlim([-0.5, max_amount - 0.5]) ax.set_xticks(np.arange(0, max_amount)) ax.set_xticklabels(quarter_ticks) ax.legend(tickers) titles = { "upmom": "Highest increasing quarterly Government Contracts", "downmom": "Highest decreasing quarterly Government Contracts", } ax.set_title(titles[analysis]) ax.set_ylabel("Amount ($1M)") if not external_axes: theme.visualize_output() elif analysis == "total": print_rich_table(tickers, headers=["Total"], title="Quarterly Contracts") export_data(export, os.path.dirname(os.path.abspath(__file__)), "qtrcontracts", df_contracts) console.print("")
def display_cramer_ticker( ticker: str, raw: bool = True, export: str = "", external_axes: Optional[List[plt.Axes]] = None, ): """Display ticker close with Cramer recommendations Parameters ---------- ticker: str Stock ticker raw: bool Display raw data export: str Format to export data external_axes: Optional[List[plt.Axes]] = None, External axes to plot on """ df = cramer_model.get_cramer_ticker(ticker) if df.empty: console.print(f"No recommendations found for {ticker}.\n") return df["Date"] = pd.to_datetime(df["Date"].apply(lambda x: x + "/2022")) if external_axes is None: _, ax = plt.subplots(figsize=plot_autoscale(), dpi=cfp.PLOT_DPI) else: if len(external_axes) != 1: logger.error("Expected list of one axis item.") console.print("[red]Expected list of one axis item./n[/red]") return (ax,) = external_axes close_prices = yfinance.download(ticker, start="2022-01-01", progress=False)[ "Adj Close" ] ax.plot(close_prices) color_map = {"Buy": theme.up_color, "Sell": theme.down_color} for name, group in df.groupby("Recommendation"): ax.scatter(group.Date, group.Price, color=color_map[name], s=150, label=name) ax.set_title(f"{ticker.upper()} Close With Cramer Recommendations") theme.style_primary_axis(ax) ax.legend(loc="best", scatterpoints=1) # Overwrite default dote formatting ax.xaxis.set_major_formatter(DateFormatter("%m/%d")) ax.set_xlabel("Date") if external_axes is None: theme.visualize_output() if raw: df["Date"] = df["Date"].apply(lambda x: x.strftime("%Y-%m-%d")) print_rich_table(df, title=f"Jim Cramer Recommendations for {ticker}") console.print() export_data(export, os.path.dirname(os.path.abspath(__file__)), df, "jctr")
def display_top_lobbying( num: int, raw: bool = False, export: str = "", external_axes: Optional[List[plt.Axes]] = None, ): """Top lobbying tickers based on total spent Parameters ---------- num: int Number of tickers to show raw: bool Show raw data export: Format to export data external_axes : Optional[List[plt.Axes]], optional External axes (1 axis is expected in the list), by default None """ df_lobbying = quiverquant_model.get_government_trading( "corporate-lobbying") if df_lobbying.empty: console.print("No corporate lobbying found\n") return df_lobbying["Amount"] = df_lobbying.Amount.astype(float).fillna( 0) / 100_000 lobbying_by_ticker = pd.DataFrame( df_lobbying.groupby("Ticker")["Amount"].agg("sum")).sort_values( by="Amount", ascending=False) if raw: print_rich_table( lobbying_by_ticker.head(num), headers=["Amount ($100k)"], show_index=True, title="Top Lobbying Tickers", ) else: # This plot has 1 axis if not external_axes: _, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) else: if len(external_axes) != 1: console.print("[red]Expected list of one axis item./n[/red]") return (ax, ) = external_axes colors = theme.get_colors() lobbying_by_ticker.head(num).plot(kind="bar", ax=ax, color=colors) ax.set_xlabel("Ticker") ax.set_ylabel("Total Amount ($100k)") ax.set_title( f"Corporate Lobbying Spent since {df_lobbying['Date'].min()}") theme.style_primary_axis(ax) if not external_axes: theme.visualize_output() console.print("") export_data(export, os.path.dirname(os.path.abspath(__file__)), "lobbying", df_lobbying)
def display_sentiment_correlation( similar: List[str], raw: bool = False, export: str = "", external_axes: Optional[List[plt.Axes]] = None, ): """Plot correlation sentiments heatmap across similar companies. [Source: FinBrain] Parameters ---------- similar : List[str] Similar companies to compare income with raw : bool, optional Output raw values, by default False export : str, optional Format to export data external_axes : Optional[List[plt.Axes]], optional External axes (1 axis is expected in the list), by default None """ df_sentiment = finbrain_model.get_sentiments(similar) corrs = df_sentiment.corr() if df_sentiment.empty: console.print("No sentiments found.") else: # This plot has 1 axis if not external_axes: _, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) else: if len(external_axes) != 1: console.print("[red]Expected list of one axis item./n[/red]") return (ax,) = external_axes mask = np.zeros((len(similar), len(similar)), dtype=bool) mask[np.triu_indices(len(mask))] = True sns.heatmap( corrs, cbar_kws={"ticks": [-1.0, -0.5, 0.0, 0.5, 1.0]}, cmap="RdYlGn", linewidths=1, annot=True, vmin=-1, vmax=1, mask=mask, ax=ax, ) similar_string = ",".join(similar) ax.set_title( f"Sentiment correlation heatmap across \n{similar_string}", fontsize=11 ) if not external_axes: theme.visualize_output() if raw: print_rich_table( corrs, headers=list(corrs.columns), show_index=True, title="Correlation Sentiments", ) export_data( export, os.path.dirname(os.path.abspath(__file__)), "scorr", corrs, ) console.print("")