def display_last_contracts( past_transaction_days: int = 2, num: int = 20, sum_contracts: bool = False, export: str = "", ): """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 """ 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: fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) 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") if gtff.USE_ION: plt.ion() fig.tight_layout() plt.show() console.print("") export_data(export, os.path.dirname(os.path.abspath(__file__)), "lastcontracts", df)
def display_contracts( ticker: str, past_transaction_days: int, raw: bool, export: str = "" ): """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 """ df_contracts = quiverquant_model.get_government_trading("contracts", ticker) if df_contracts.empty: 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: if gtff.USE_TABULATE_DF: print( tabulate( df_contracts, headers=df_contracts.columns, tablefmt="fancy_grid", showindex=False, floatfmt=".2f", ) ) else: print(df_contracts.to_string()) else: fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) 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}") plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%Y/%m/%d")) plt.gcf().autofmt_xdate() fig.tight_layout() if gtff.USE_ION: plt.ion() plt.show() export_data( export, os.path.dirname(os.path.abspath(__file__)), "contracts", df_contracts ) print("")
def toplobbying_command(num: int = 10, raw: bool = False): """Displays top lobbying firms [quiverquant.com]""" # Debug user input if cfg.DEBUG: logger.debug("gov-toplobbying %s %s", num, raw) # Retrieve Data df_lobbying = quiverquant_model.get_government_trading( "corporate-lobbying") if df_lobbying.empty: raise Exception("No corporate lobbying found") 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) fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) lobbying_by_ticker.head(num).plot(kind="bar", ax=ax) ax.set_xlabel("Ticker") ax.set_ylabel("Total Amount ($100k)") ax.set_title(f"Corporate Lobbying Spent since {df_lobbying['Date'].min()}") fig.tight_layout() plt.savefig("ta_toplobbying.png") imagefile = "ta_toplobbying.png" imagefile = image_border(imagefile) return { "title": "Stocks: [quiverquant.com] Top Lobbying Firms", "imagefile": imagefile, }
def display_lobbying(ticker: str, num: int = 10): """Corporate lobbying details Parameters ---------- ticker: str Ticker to get corporate lobbying data from num: int Number of events to show """ df_lobbying = quiverquant_model.get_government_trading( "corporate-lobbying", ticker=ticker) if df_lobbying.empty: console.print("No corporate lobbying found\n") return for _, row in (df_lobbying.sort_values( by=["Date"], ascending=False).head(num).iterrows()): amount = ("$" + str(int(float(row["Amount"]))) if row["Amount"] is not None else "N/A") console.print(f"{row['Date']}: {row['Client']} {amount}") if row["Amount"] is not None: console.print( "\t" + row["Specific_Issue"].replace("\n", " ").replace("\r", "")) console.print("") console.print("")
def qtr_contracts_hist(other_args: List[str], ticker: str): """Quarter contracts Parameters ---------- other_args : List[str] Command line arguments to be processed with argparse ticker: str Ticker to get congress trading data from """ parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="qtr_contracts_hist", description= "Quarterly-contracts historical [Source: www.quiverquant.com]", ) try: ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return df_contracts = quiverquant_model.get_government_trading( "quarter-contracts", ticker=ticker) if df_contracts.empty: print("No quarterly government contracts found\n") return plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI) 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) ] plt.plot(np.arange(0, len(amounts)), amounts / 1000, "-*", lw=2, ms=15) plt.xlim([-0.5, len(amounts) - 0.5]) plt.xticks(np.arange(0, len(amounts)), quarter_ticks) plt.grid() plt.title( f"Quarterly Government Contracts Historical on {ticker.upper()}") plt.xlabel("Date") plt.ylabel("Amount [1k $]") if gtff.USE_ION: plt.ion() plt.show() print("") except Exception as e: print(e, "\n")
def display_hist_contracts(ticker: str, raw: bool = False, export: str = ""): """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 """ 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: fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) ax.plot(np.arange(0, len(amounts)), amounts / 1000, "-*", 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.grid() ax.set_title(f"Historical Quarterly Government Contracts for {ticker.upper()}") ax.set_xlabel("Date") ax.set_ylabel("Amount ($1k)") fig.tight_layout() if gtff.USE_ION: plt.ion() plt.show() export_data(export, os.path.dirname(os.path.abspath(__file__)), "histcont") console.print("")
def raw_contracts(other_args: List[str], ticker: str): """Raw contracts Parameters ---------- other_args : List[str] Command line arguments to be processed with argparse ticker: str Ticker to get congress trading data from """ parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="raw_contracts", description="Raw contracts. [Source: www.quiverquant.com]", ) parser.add_argument( "-p", "--past_transactions_days", action="store", dest="past_transactions_days", type=check_positive, default=10, help="Past transaction days", ) try: if other_args: if "-" not in other_args[0]: other_args.insert(0, "-p") ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return df_contracts = quiverquant_model.get_government_trading( "contracts", ticker) if df_contracts.empty: print("No government contracts found\n") return df_contracts["Date"] = pd.to_datetime(df_contracts["Date"]).dt.date df_contracts.drop_duplicates(inplace=True) df_contracts = df_contracts[df_contracts["Date"].isin( df_contracts["Date"].unique()[:ns_parser.past_transactions_days])] df_contracts.drop_duplicates(inplace=True) print(df_contracts.to_string(index=False)) print("") except Exception as e: print(e, "\n")
def histcont_command(ticker=""): """Displays historical quarterly-contracts [quiverquant.com]""" # Debug user input if imps.DEBUG: logger.debug("gov histcont %s", ticker) if ticker == "": raise Exception("A ticker is required") # Retrieve Data df_contracts = quiverquant_model.get_government_trading( "quarter-contracts", ticker=ticker) if df_contracts.empty: logger.debug("No quarterly government contracts found") raise Exception("No quarterly government contracts found") # Output Data 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) ] fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) ax.plot(np.arange(0, len(amounts)), amounts / 1000, "-*", 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.grid() ax.set_title( f"Historical Quarterly Government Contracts for {ticker.upper()}") ax.set_xlabel("Date") ax.set_ylabel("Amount ($1k)") fig.tight_layout() imagefile = "gov_histcont.png" dataBytesIO = io.BytesIO() plt.savefig(dataBytesIO) dataBytesIO.seek(0) plt.close("all") imagefile = imps.image_border(imagefile, base64=dataBytesIO) return { "title": "Stocks: Historical Quarterly Government Contract ", "imagefile": imagefile, }
def display_top_lobbying(num: int, raw: bool = False, export: str = ""): """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 """ df_lobbying = quiverquant_model.get_government_trading("corporate-lobbying") if df_lobbying.empty: 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: if gtff.USE_TABULATE_DF: print( tabulate( lobbying_by_ticker.head(num), headers=["Amount ($100k)"], tablefmt="fancy_grid", showindex=True, floatfmt=".2f", ) ) else: print(lobbying_by_ticker.head(num).to_string()) else: fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) lobbying_by_ticker.head(num).plot(kind="bar", ax=ax) ax.set_xlabel("Ticker") ax.set_ylabel("Total Amount ($100k)") ax.set_title(f"Corporate Lobbying Spent since {df_lobbying['Date'].min()}") fig.tight_layout() if gtff.USE_ION: plt.ion() plt.show() print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "lobbying", df_lobbying )
def lobbying(other_args: List[str], ticker: str): """Corporate lobbying details Parameters ---------- other_args : List[str] Command line arguments to be processed with argparse ticker: str Ticker to get corporate lobbying data from """ parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="lobbying", description="Lobbying details [Source: www.quiverquant.com]", ) parser.add_argument( "-l", "--last", action="store", dest="last", type=check_positive, default=10, help="Last corporate lobbying details", ) try: ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return df_lobbying = quiverquant_model.get_government_trading( "corporate-lobbying", ticker=ticker) if df_lobbying.empty: print("No corporate lobbying found\n") return for _, row in (df_lobbying.sort_values( by=["Date"], ascending=False).head(ns_parser.last).iterrows()): amount = ("$" + str(int(float(row["Amount"]))) if row["Amount"] is not None else "N/A") print(f"{row['Date']}: {row['Client']} {amount}") if row["Amount"] is not None: print( "\t" + row["Specific_Issue"].replace("\n", " ").replace("\r", "")) print("") print("") except Exception as e: print(e, "\n")
def contracts_command(ticker: str = "", past_transaction_days: Union[int, str] = 10, raw: bool = False): """Displays contracts associated with tickers [quiverquant.com]""" past_transaction_days = int(past_transaction_days) # Debug user input if imps.DEBUG: logger.debug("gov contracts %s %s %s", ticker, past_transaction_days, raw) if ticker == "": raise Exception("A ticker is required") # Retrieve Data df_contracts = quiverquant_model.get_government_trading( "contracts", ticker) if df_contracts.empty: return { "title": f"Stocks: [quiverquant.com] Contracts by {ticker}", "description": f"{ticker} does not have any contracts", } # Output Data 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) fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) 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}") fig.tight_layout() imagefile = "gov_contracts.png" dataBytesIO = io.BytesIO() plt.savefig(dataBytesIO) plt.close("all") dataBytesIO.seek(0) imagefile = imps.image_border(imagefile, base64=dataBytesIO) return { "title": f"Stocks: [quiverquant.com] Contracts by {ticker}", "imagefile": imagefile, }
def sum_contracts(other_args: List[str]): """Sum contracts Parameters ---------- other_args : List[str] Command line arguments to be processed with argparse """ parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="sum_contracts", description="Sum latest contracts. [Source: www.quiverquant.com]", ) try: if other_args: if "-" not in other_args[0]: other_args.insert(0, "-p") ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return df_contracts = quiverquant_model.get_government_trading("contracts") if df_contracts.empty: print("No government contracts found\n") return df_contracts["Date"] = pd.to_datetime(df_contracts["Date"]).dt.date df_contracts.drop_duplicates(inplace=True) plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI) df_contracts.groupby("Date").sum().div(1000).plot(kind="bar", rot=0, ax=plt.gca()) plt.ylabel("Amount [1k $]") plt.title("Sum of latest government contracts") if gtff.USE_ION: plt.ion() plt.show() print("") except Exception as e: print(e, "\n")
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_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_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_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 raw_government(other_args: List[str], ticker: str, gov_type: str): """Raw government trading Parameters ---------- other_args : List[str] Command line arguments to be processed with argparse ticker: str Ticker to get congress trading data from gov_type: str Type of government data between: congress, senate and house """ parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog=gov_type, description=f"Raw {gov_type} trading. [Source: www.quiverquant.com]", ) parser.add_argument( "-p", "--past_transactions_days", action="store", dest="past_transactions_days", type=check_positive, default=10, help="Past transaction days", ) try: if other_args: if "-" not in other_args[0]: other_args.insert(0, "-p") ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return df_gov = quiverquant_model.get_government_trading(gov_type, ticker) if df_gov.empty: print(f"No {gov_type} trading data found\n") return df_gov = df_gov.sort_values("TransactionDate", ascending=False) if gov_type == "congress": df_gov = df_gov[[ "TransactionDate", "Representative", "House", "Transaction", "Range" ]] else: df_gov = df_gov[[ "TransactionDate", "Representative", "Transaction", "Range" ]] df_gov = df_gov[df_gov["TransactionDate"].isin( df_gov["TransactionDate"].unique() [:ns_parser.past_transactions_days])].rename( columns={ "TransactionDate": "Transaction Date", }) print(df_gov.to_string(index=False)) print("") except Exception as e: print(e, "\n")
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)
async def lasttrades_command(ctx, gov_type="", past_transactions_days="", representative=""): """Displays trades made by the congress/senate/house [quiverquant.com]""" try: # Debug user input if cfg.DEBUG: print( f"!stocks.gov.lasttrades {gov_type} {past_transactions_days} {representative}" ) if past_transactions_days == "": past_days = 5 else: if not past_transactions_days.lstrip("-").isnumeric(): raise Exception("Number has to be an integer") past_days = int(past_transactions_days) possible_args = ["congress", "senate", "house"] if gov_type == "": gov_type = "congress" elif gov_type not in possible_args: raise Exception( "Enter a valid government argument, options are: congress, senate and house" ) # Retrieve Data df_gov = quiverquant_model.get_government_trading(gov_type) # Output Data if df_gov.empty: raise Exception(f"No {gov_type} trading data found") 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: raise Exception( 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())}" ) initial_str = "Page 0: Overview" i = 1 for col_name in df_gov_rep["Ticker"].values: initial_str += f"\nPage {i}: {col_name}" i += 1 columns = [] df_gov_rep = df_gov_rep.T columns.append( discord.Embed( title= f"Stocks: [quiverquant.com] Trades by {representative}", description=initial_str, colour=cfg.COLOR, ).set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, )) for column in df_gov_rep.columns.values: columns.append( discord.Embed( description="```" + df_gov_rep[column].fillna("").to_string() + "```", colour=cfg.COLOR, ).set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, )) await pagination(columns, ctx) else: initial_str = "Page 0: Overview" i = 1 for col_name in df_gov["Ticker"].values: initial_str += f"\nPage {i}: {col_name}" i += 1 columns = [] df_gov = df_gov.T columns.append( discord.Embed( title= f"Stocks: [quiverquant.com] Trades for {gov_type.upper()}", description=initial_str, colour=cfg.COLOR, ).set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, )) for column in df_gov.columns.values: columns.append( discord.Embed( description="```" + df_gov[column].fillna("").to_string() + "```", colour=cfg.COLOR, ).set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, )) await pagination(columns, ctx) except Exception as e: embed = discord.Embed( title= f"ERROR Stocks: [quiverquant.com] Trades by {gov_type.upper()}", colour=cfg.COLOR, description=e, ) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) await ctx.send(embed=embed)
def qtr_contracts(other_args: List[str]): """Quarter contracts Parameters ---------- other_args : List[str] Command line arguments to be processed with argparse """ parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="qtr_contracts", description= "Quarterly-contracts, best regression slope. [Source: www.quiverquant.com]", ) parser.add_argument( "-t", "--top", action="store", dest="top", type=check_positive, default=5, help="Top promising stocks with best quarterly-contracts momentum", ) try: ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return df_contracts = quiverquant_model.get_government_trading( "quarter-contracts") if df_contracts.empty: print("No quarterly government contracts found\n") return df_coef = pd.DataFrame(columns=["Ticker", "Coef"]) for symbol in df_contracts["Ticker"].unique(): # Create linear regression object regr = linear_model.LinearRegression() amounts = ( df_contracts[df_contracts["Ticker"] == symbol].sort_values( by=["Year", "Qtr"])["Amount"].values) # Train the model using the training sets regr.fit(np.arange(0, len(amounts)).reshape(-1, 1), amounts) df_coef = df_coef.append({ "Ticker": symbol, "Coef": regr.coef_[0] }, ignore_index=True) plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI) tickers = df_coef.sort_values(by=["Coef"], ascending=False).head( ns_parser.top)["Ticker"] 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) plt.plot(np.arange(0, len(amounts)), amounts / 1000, "-*", lw=2, ms=15) if len(amounts) > max_amount: max_amount = len(amounts) quarter_ticks = [ f"{quarter[0]} - {quarter[1]} Qtr" for quarter in zip(year, qtr) ] plt.xlim([-0.5, max_amount - 0.5]) plt.xticks(np.arange(0, max_amount), quarter_ticks) plt.grid() plt.legend(tickers) plt.title("Quarterly Government Contracts - Top promising stocks") plt.xlabel("Date") plt.ylabel("Amount [1k $]") if gtff.USE_ION: plt.ion() plt.show() print("") except Exception as e: print(e, "\n")
def contracts(other_args: List[str], ticker: str): """Contracts Parameters ---------- other_args : List[str] Command line arguments to be processed with argparse ticker: str Ticker to get congress trading data from """ parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="contracts", description= "Contracts associated with ticker. [Source: www.quiverquant.com]", ) parser.add_argument( "-p", "--past_transactions_days", action="store", dest="past_transactions_days", type=check_positive, default=10, help="Past transaction days", ) try: if other_args: if "-" not in other_args[0]: other_args.insert(0, "-p") ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return df_contracts = quiverquant_model.get_government_trading( "contracts", ticker) if df_contracts.empty: 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()[:ns_parser.past_transactions_days])] df_contracts.drop_duplicates(inplace=True) plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI) df_contracts.groupby("Date").sum().div(1000).plot(kind="bar", rot=0, ax=plt.gca()) plt.ylabel("Amount [1k $]") plt.title(f"Sum of latest government contracts to {ticker}") if gtff.USE_ION: plt.ion() plt.show() print("") except Exception as e: print(e, "\n")
def sell_government(other_args: List[str], gov_type: str): """Top sell government trading Parameters ---------- other_args : List[str] Command line arguments to be processed with argparse gov_type: str Type of government data between: congress, senate and house """ parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="sell_" + gov_type, description= f"Top sell {gov_type} trading. [Source: www.quiverquant.com]", ) parser.add_argument( "-p", "--past_transactions_months", action="store", dest="past_transactions_months", type=check_positive, default=6, help="Past transaction months", ) parser.add_argument( "-t", "--top", action="store", dest="top_num", type=check_positive, default=10, help="Number of top tickers", ) try: ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return df_gov = quiverquant_model.get_government_trading(gov_type) if df_gov.empty: 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=ns_parser.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["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(",", "")) 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) plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI) df_gov.groupby("Ticker")["lower"].sum().div( 1000).sort_values().abs().head(n=ns_parser.top_num).plot( kind="bar", rot=0) plt.ylabel("Amount [1k $]") plt.title( f"Top {ns_parser.top_num} most sold stocks since last {ns_parser.past_transactions_months} months" " (upper bound)") plt.gcf().axes[0].yaxis.get_major_formatter().set_scientific(False) if gtff.USE_ION: plt.ion() plt.show() print("") except Exception as e: print(e, "\n")
def last_contracts(other_args: List[str]): """Last contracts Parameters ---------- other_args : List[str] Command line arguments to be processed with argparse """ parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="last_contracts", description="Last contracts. [Source: www.quiverquant.com]", ) parser.add_argument( "-p", "--past_transactions_days", action="store", dest="past_transactions_days", type=check_positive, default=2, help="Past transaction days", ) parser.add_argument( "-l", "--limit", action="store", dest="limit_contracts", type=check_positive, default=20, help="Limit of contracts to display", ) try: if other_args: if "-" not in other_args[0]: other_args.insert(0, "-p") ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return df_contracts = quiverquant_model.get_government_trading("contracts") if df_contracts.empty: 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_contracts = df_contracts[df_contracts["Date"].isin( df_contracts["Date"].unique()[:ns_parser.past_transactions_days])] df_contracts = df_contracts[[ "Date", "Ticker", "Amount", "Description", "Agency" ]][:ns_parser.limit_contracts] print(df_contracts.to_string(index=False)) print("") except Exception as e: print(e, "\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 top_lobbying(other_args: List[str]): """Top lobbying based on tickers that have biggest amounts for the past couple months Parameters ---------- other_args : List[str] Command line arguments to be processed with argparse """ parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="top_lobbying", description="Top lobbying. [Source: www.quiverquant.com]", ) parser.add_argument( "-t", "--top", action="store", dest="top", type=check_positive, default=10, help="Top corporate lobbying tickers with biggest amounts", ) try: ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return df_lobbying = quiverquant_model.get_government_trading( "corporate-lobbying") if df_lobbying.empty: print("No corporate lobbying found\n") return d_lobbying = {} for symbol in df_lobbying["Ticker"].unique(): d_lobbying[symbol] = sum( float(amount) for amount in df_lobbying[df_lobbying["Ticker"] == symbol]. replace(np.nan, 0)["Amount"].values) df_amount = pd.DataFrame.from_dict(d_lobbying, orient="index", columns=["Amount"]).sort_values( by=["Amount"], ascending=False) plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI) plt.bar( df_amount.head(ns_parser.top).index, df_amount.head(ns_parser.top).values.flatten() / 1000, ) plt.xlabel("Ticker") plt.ylabel("Sum Amount [1k $]") plt.title( f"Total amount spent on corporate lobbying since {df_lobbying['Date'].min()}" ) if gtff.USE_ION: plt.ion() plt.show() print("") except Exception as e: print(e, "\n")
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 last_government(other_args: List[str], gov_type: str): """Last government trading Parameters ---------- other_args : List[str] Command line arguments to be processed with argparse gov_type: str Type of government data between: congress, senate and house """ parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="last_" + gov_type, description=f"Last {gov_type} trading. [Source: www.quiverquant.com]", ) parser.add_argument( "-p", "--past_transactions_days", action="store", dest="past_transactions_days", type=check_positive, default=5, help="Past transaction days", ) parser.add_argument( "-r", "--representative", action="store", dest="representative", type=str, default="", help="Representative", ) try: if other_args: if "-" not in other_args[0]: other_args.insert(0, "-p") ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return df_gov = quiverquant_model.get_government_trading(gov_type) if df_gov.empty: print(f"No {gov_type} trading data found\n") return df_gov = df_gov.sort_values("TransactionDate", ascending=False) df_gov = df_gov[df_gov["TransactionDate"].isin( df_gov["TransactionDate"].unique() [:ns_parser.past_transactions_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 ns_parser.representative: df_gov_rep = df_gov[df_gov["Representative"].str.split().str[0] == ns_parser.representative] if df_gov_rep.empty: print( f"No representative {ns_parser.representative} found in the past {ns_parser.past_transactions_days}" f" days. The following are available: " f"{', '.join(df_gov['Representative'].str.split().str[0].unique())}" ) else: print(df_gov_rep.to_string(index=False)) else: print(df_gov.to_string(index=False)) print("") except Exception as e: print(e, "\n")
async def qtrcontracts_command(ctx, num="", analysis=""): """Displays a look at government contracts [quiverquant.com]""" try: # Debug user input if cfg.DEBUG: print(f"!stocks.gov.qtrcontracts {num} {analysis}") if num == "": num = 20 else: if not num.lstrip("-").isnumeric(): raise Exception("Number has to be an integer") num = int(num) possible_args = ["total", "upmom", "downmom"] if analysis == "": analysis = "total" elif analysis not in possible_args: raise Exception( "Enter a valid analysis argument, options are: total, upmom and downmom" ) # Retrieve Data df_contracts = quiverquant_model.get_government_trading( "quarter-contracts") if df_contracts.empty: raise Exception("No quarterly government contracts found") tickers = quiverquant_model.analyze_qtr_contracts(analysis, num) # Output Data if analysis in {"upmom", "downmom"}: description = tickers.to_string() fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) 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.grid() ax.legend(tickers) titles = { "upmom": "Highest increasing quarterly Government Contracts", "downmom": "Highest decreasing quarterly Government Contracts", } ax.set_title(titles[analysis]) ax.set_xlabel("Date") ax.set_ylabel("Amount ($1M)") fig.tight_layout() plt.savefig("gov_qtrcontracts.png") uploaded_image = gst_imgur.upload_image("gov_qtrcontracts.png", title="something") image_link = uploaded_image.link if cfg.DEBUG: print(f"Image URL: {image_link}") title = "Stocks: [quiverquant.com] Government contracts" embed = discord.Embed(title=title, description=description, colour=cfg.COLOR) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) embed.set_image(url=image_link) os.remove("gov_qtrcontracts.png") await ctx.send(embed=embed) elif analysis == "total": tickers.index = [ ind + " " * (7 - len(ind)) for ind in tickers.index ] tickers[:] = [ str(round(val[0] / 1e9, 2)) for val in tickers.values ] tickers.columns = ["Amount [M]"] tickers_str = tabulate( tickers, headers=tickers.columns, showindex=True, numalign="right", stralign="center", ) embed = discord.Embed( title="Stocks: [quiverquant.com] Government contracts", description=tickers_str, colour=cfg.COLOR, ) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) await ctx.send(embed=embed) except Exception as e: embed = discord.Embed( title="ERROR Stocks: [quiverquant.com] Government contracts", colour=cfg.COLOR, description=e, ) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) await ctx.send(embed=embed)
def government_trading(other_args: List[str], ticker: str, gov_type: str): """Government trading Parameters ---------- other_args : List[str] Command line arguments to be processed with argparse ticker: str Ticker to get congress trading data from gov_type: str Type of government data between: congress, senate and house """ parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog=gov_type, description=f"{gov_type} trading. [Source: www.quiverquant.com]", ) parser.add_argument( "-p", "--past_transactions_months", action="store", dest="past_transactions_months", type=check_positive, default=6, help="Past transaction months", ) try: if other_args: if "-" not in other_args[0]: other_args.insert(0, "-p") ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return df_gov = quiverquant_model.get_government_trading(gov_type, ticker) if df_gov.empty: 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=ns_parser.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: 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(",", "")) df_gov["lower"] = df_gov[["min", "max", "Transaction"]].apply( lambda x: int(x["min"]) if x["Transaction"] == "Purchase" else -int(x["max"]), axis=1, ) df_gov["upper"] = df_gov[["min", "max", "Transaction"]].apply( lambda x: int(x["max"]) if x["Transaction"] == "Purchase" else -int(x["min"]), axis=1, ) df_gov = df_gov.sort_values("TransactionDate", ascending=True) plot_government(df_gov, ticker, gov_type) print("") except Exception as e: print(e, "\n")