def shareholders(l_args, s_ticker): parser = argparse.ArgumentParser( add_help=False, prog="shrs", description="""Print Major, institutional and mutualfunds shareholders. [Source: Yahoo Finance]""", ) try: ns_parser = parse_known_args_and_warn(parser, l_args) if not ns_parser: return stock = yf.Ticker(s_ticker) pd.set_option("display.max_colwidth", None) # Major holders print("Major holders") df_major_holders = stock.major_holders df_major_holders[1] = df_major_holders[1].apply( lambda x: x.replace("%", "Percentage")) print(df_major_holders.to_string(index=False, header=False)) print("") # Institutional holders print("Institutional holders") df_institutional_shareholders = stock.institutional_holders df_institutional_shareholders.columns = ( df_institutional_shareholders.columns.str.replace( "% Out", "Stake")) df_institutional_shareholders[ "Shares"] = df_institutional_shareholders["Shares"].apply( lambda x: long_number_format(x)) df_institutional_shareholders["Value"] = df_institutional_shareholders[ "Value"].apply(lambda x: long_number_format(x)) df_institutional_shareholders["Stake"] = df_institutional_shareholders[ "Stake"].apply(lambda x: str(f"{100 * x:.2f}") + " %") print(df_institutional_shareholders.to_string(index=False)) print("") # Mutualfunds holders print("Mutualfunds holders") df_mutualfund_shareholders = stock.mutualfund_holders df_mutualfund_shareholders.columns = ( df_mutualfund_shareholders.columns.str.replace("% Out", "Stake")) df_mutualfund_shareholders["Shares"] = df_mutualfund_shareholders[ "Shares"].apply(lambda x: long_number_format(x)) df_mutualfund_shareholders["Value"] = df_mutualfund_shareholders[ "Value"].apply(lambda x: long_number_format(x)) df_mutualfund_shareholders["Stake"] = df_mutualfund_shareholders[ "Stake"].apply(lambda x: str(f"{100 * x:.2f}") + " %") print(df_mutualfund_shareholders.to_string(index=False)) print("") except Exception as e: print(e) print("") return
def get_shareholders(ticker: str) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]: """Get shareholders from yahoo Parameters ---------- ticker : str Stock ticker Returns ------- pd.DataFrame Major holders pd.DataFrame Institutional holders pd.DataFrame Mutual Fund holders """ stock = yf.Ticker(ticker) # Major holders df_major_holders = stock.major_holders df_major_holders[1] = df_major_holders[1].apply( lambda x: x.replace("%", "Percentage") ) # Institutional holders df_institutional_shareholders = stock.institutional_holders df_institutional_shareholders.columns = ( df_institutional_shareholders.columns.str.replace("% Out", "Stake") ) df_institutional_shareholders["Shares"] = df_institutional_shareholders[ "Shares" ].apply(lambda x: long_number_format(x)) df_institutional_shareholders["Value"] = df_institutional_shareholders[ "Value" ].apply(lambda x: long_number_format(x)) df_institutional_shareholders["Stake"] = df_institutional_shareholders[ "Stake" ].apply(lambda x: str(f"{100 * x:.2f}") + " %") # Mutualfunds holders df_mutualfund_shareholders = stock.mutualfund_holders df_mutualfund_shareholders.columns = df_mutualfund_shareholders.columns.str.replace( "% Out", "Stake" ) df_mutualfund_shareholders["Shares"] = df_mutualfund_shareholders["Shares"].apply( lambda x: long_number_format(x) ) df_mutualfund_shareholders["Value"] = df_mutualfund_shareholders["Value"].apply( lambda x: long_number_format(x) ) df_mutualfund_shareholders["Stake"] = df_mutualfund_shareholders["Stake"].apply( lambda x: str(f"{100 * x:.2f}") + " %" ) return df_major_holders, df_institutional_shareholders, df_mutualfund_shareholders
def quote(other_args: List[str], ticker: str): """Financial Modeling Prep ticker quote Parameters ---------- other_args : List[str] argparse other args ticker : str Fundamental analysis ticker symbol """ parser = argparse.ArgumentParser( add_help=False, prog="quote", description=""" Prints actual information about the company which is, among other things, the day high, market cap, open and close price and price-to-equity ratio. The following fields are expected: Avg volume, Change, Changes percentage, Day high, Day low, Earnings announcement, Eps, Exchange, Market cap, Name, Open, Pe, Previous close, Price, Price avg200, Price avg50, Shares outstanding, Symbol, Timestamp, Volume, Year high, and Year low. [Source: Financial Modeling Prep] """, ) try: ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return df_fa = fa.quote(ticker, cfg.API_KEY_FINANCIALMODELINGPREP) clean_df_index(df_fa) df_fa.loc["Market cap"][0] = long_number_format( df_fa.loc["Market cap"][0]) df_fa.loc["Shares outstanding"][0] = long_number_format( df_fa.loc["Shares outstanding"][0]) df_fa.loc["Volume"][0] = long_number_format(df_fa.loc["Volume"][0]) # Check if there is a valid earnings announcement if df_fa.loc["Earnings announcement"][0]: earning_announcement = datetime.strptime( df_fa.loc["Earnings announcement"][0][0:19], "%Y-%m-%dT%H:%M:%S") df_fa.loc["Earnings announcement"][ 0] = f"{earning_announcement.date()} {earning_announcement.time()}" print(df_fa.to_string(header=False)) print("") except Exception as e: print(e) print("") return
def get_calendar_earnings(ticker: str) -> pd.DataFrame: """Get calendar earnings for ticker Parameters ---------- ticker : [type] Stock ticker Returns ------- pd.DataFrame Dataframe of calendar earnings """ stock = yf.Ticker(ticker) df_calendar = stock.calendar if df_calendar.empty: return pd.DataFrame() df_calendar.iloc[0, :] = df_calendar.iloc[0, :].apply( lambda x: x.date().strftime("%m/%d/%Y")) df_calendar.iloc[1:, :] = df_calendar.iloc[1:, :].applymap( lambda x: long_number_format(x)) return df_calendar
def clean_metrics_df(df_fa: pd.DataFrame, num: int, mask: bool = True) -> pd.DataFrame: """Clean metrics data frame Parameters ---------- df_fa : pd.DataFrame Metrics data frame num : int Number of columns to clean mask : bool, optional Apply mask, by default True Returns ------- pd.DataFrame Cleaned metrics data frame """ df_fa = df_fa.iloc[:, 0:num] if mask: df_fa = df_fa.mask(df_fa.astype(object).eq(num * ["None"])).dropna() df_fa = df_fa.mask(df_fa.astype(object).eq(num * ["0"])).dropna() df_fa = df_fa.applymap(lambda x: long_number_format(x)) clean_df_index(df_fa) df_fa.columns.name = "Fiscal Date Ending" df_fa = df_fa.rename( index={ "Enterprise value over e b i t d a": "Enterprise value over EBITDA", "Net debt to e b i t d a": "Net debt to EBITDA", "D c f": "DCF", "Net income per e b t": "Net income per EBT", } ) return df_fa
def display_defi_protocols(top: int, sortby: str, descend: bool, description: bool, export: str = "") -> None: """Display information about listed DeFi protocols, their current TVL and changes to it in the last hour/day/week. [Source: https://docs.llama.fi/api] Parameters ---------- top: int Number of records to display sortby: str Key by which to sort data descend: bool Flag to sort data descending description: bool Flag to display description of protocol export : str Export dataframe data to csv,json,xlsx file """ df = llama_model.get_defi_protocols() df_data = df.copy() df = df.sort_values(by=sortby, ascending=descend) df["tvl"] = df["tvl"].apply(lambda x: long_number_format(x)) if not description: df.drop(["description", "url"], axis=1, inplace=True) else: df = df[[ "name", "symbol", "category", "description", "url", ]] if gtff.USE_TABULATE_DF: print( tabulate( df.head(top), headers=df.columns, floatfmt=".2f", showindex=False, tablefmt="fancy_grid", ), "\n", ) else: print(df.to_string, "\n") export_data( export, os.path.dirname(os.path.abspath(__file__)), "llama", df_data, )
def clean_fundamentals_df(df_fa: pd.DataFrame, num: int) -> pd.DataFrame: """Clean fundamentals dataframe Parameters ---------- df_fa : pd.DataFrame Fundamentals dataframe num : int Number of data rows to display Returns ---------- pd.DataFrame Clean dataframe to output """ # pylint: disable=no-member df_fa = df_fa.set_index("fiscalDateEnding") df_fa = df_fa.head(n=num).T df_fa = df_fa.mask(df_fa.astype(object).eq(num * ["None"])).dropna() df_fa = df_fa.mask(df_fa.astype(object).eq(num * ["0"])).dropna() df_fa = df_fa.applymap(lambda x: long_number_format(x)) clean_df_index(df_fa) df_fa.columns.name = "Fiscal Date Ending" return df_fa
def display_whales_transactions( min_value: int = 800000, top: int = 100, sortby: str = "date", descend: bool = False, show_address: bool = False, export: str = "", ) -> None: """Display huge value transactions from major blockchains. [Source: https://docs.whale-alert.io/] Parameters ---------- min_value: int Minimum value of trade to track. top: int Limit of transactions. Maximum 100 sortby: str Key to sort by. descend: str Sort in descending order. show_address: bool Flag to show addresses of transactions. export : str Export dataframe data to csv,json,xlsx file """ df = whale_alert_model.get_whales_transactions(min_value) df_data = df.copy() df = df.sort_values(by=sortby, ascending=descend) if not show_address: df = df.drop(["from_address", "to_address"], axis=1) else: df = df.drop(["from", "to", "blockchain"], axis=1) for col in ["amount_usd", "amount"]: df[col] = df[col].apply(lambda x: long_number_format(x)) if gtff.USE_TABULATE_DF: print( tabulate( df.head(top), headers=df.columns, floatfmt=".0f", showindex=False, tablefmt="fancy_grid", ), "\n", ) else: print(df.to_string, "\n") export_data( export, os.path.dirname(os.path.abspath(__file__)), "whales", df_data, )
def get_quote(ticker) -> pd.DataFrame: """Gets ticker quote from FMP""" df_fa = fa.quote(ticker, cfg.API_KEY_FINANCIALMODELINGPREP) clean_df_index(df_fa) df_fa.loc["Market cap"][0] = long_number_format(df_fa.loc["Market cap"][0]) df_fa.loc["Shares outstanding"][0] = long_number_format( df_fa.loc["Shares outstanding"][0]) df_fa.loc["Volume"][0] = long_number_format(df_fa.loc["Volume"][0]) # Check if there is a valid earnings announcement if df_fa.loc["Earnings announcement"][0]: earning_announcement = datetime.strptime( df_fa.loc["Earnings announcement"][0][0:19], "%Y-%m-%dT%H:%M:%S") df_fa.loc["Earnings announcement"][ 0] = f"{earning_announcement.date()} {earning_announcement.time()}" return df_fa
def display_account_growth( kind: str = "total", cumulative: bool = False, top: int = 90, export: str = "" ) -> None: """Display terra blockchain account growth history [Source: https://fcd.terra.dev/swagger] Parameters ---------- top: int Number of records to display kind: str display total account count or active account count. One from list [active, total] cumulative: bool Flag to show cumulative or discrete values. For active accounts only discrete value are available. export : str Export dataframe data to csv,json,xlsx file """ df = terramoney_fcd_model.get_account_growth(cumulative) if kind not in ["active", "total"]: kind = "total" options = {"total": "Total accounts", "active": "Active accounts"} opt = options[kind] label = "Cumulative" if cumulative and opt == "total" else "Daily" fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) df = df.sort_values("date", ascending=False).head(top) df = df.set_index("date") start, end = df.index[-1], df.index[0] if cumulative: ax.plot(df[opt], label=df[opt]) else: ax.bar(x=df.index, height=df[opt], label=df[opt]) ax.set_ylabel(f"{opt}") ax.set_xlabel("Date") dateFmt = mdates.DateFormatter("%m/%d/%Y") ax.xaxis.set_major_formatter(dateFmt) ax.get_yaxis().set_major_formatter( ticker.FuncFormatter(lambda x, _: long_number_format(x)) ) fig.tight_layout(pad=8) ax.set_title(f"{label} number of {opt.lower()} in period from {start} to {end}") ax.grid(alpha=0.5) ax.tick_params(axis="x", labelrotation=45) if gtff.USE_ION: plt.ion() plt.show() print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "gacc", df, )
def calendar_earnings(other_args: List[str], ticker: str): """Yahoo Finance ticker calendar earnings Parameters ---------- other_args : List[str] argparse other args ticker : str Fundamental analysis ticker symbol """ parser = argparse.ArgumentParser( add_help=False, prog="cal", description=""" Calendar earnings of the company. Including revenue and earnings estimates. [Source: Yahoo Finance] """, ) try: ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return stock = yf.Ticker(ticker) df_calendar = stock.calendar if df_calendar.empty: print(f"No earnings calendar information in Yahoo for {ticker}") print("") return df_calendar.iloc[0, 0] = df_calendar.iloc[0, 0].date().strftime("%d/%m/%Y") df_calendar.iloc[:, 0] = df_calendar.iloc[:, 0].apply( lambda x: long_number_format(x)) print(f"Earnings Date: {df_calendar.iloc[:, 0]['Earnings Date']}") avg = df_calendar.iloc[:, 0]["Earnings Average"] low = df_calendar.iloc[:, 0]["Earnings Low"] high = df_calendar.iloc[:, 0]["Earnings High"] print(f"Earnings Estimate Avg: {avg} [{low}, {high}]") print( f"Revenue Estimate Avg: {df_calendar.iloc[:, 0]['Revenue Average']} \ [{df_calendar.iloc[:, 0]['Revenue Low']}, {df_calendar.iloc[:, 0]['Revenue High']}]" ) print("") except Exception as e: print(e) print("") return
def clean_fundamentals_df(df_fa: pd.DataFrame, num: int) -> pd.DataFrame: # pylint: disable=no-member df_fa = df_fa.set_index("fiscalDateEnding") df_fa = df_fa.head(n=num).T df_fa = df_fa.mask(df_fa.astype(object).eq(num * ["None"])).dropna() df_fa = df_fa.mask(df_fa.astype(object).eq(num * ["0"])).dropna() df_fa = df_fa.applymap(lambda x: long_number_format(x)) clean_df_index(df_fa) df_fa.columns.name = "Fiscal Date Ending" return df_fa
def get_overview(ticker: str) -> pd.DataFrame: """Get alpha vantage company overview Parameters ---------- ticker : str Stock ticker Returns ------- pd.DataFrame Dataframe of fundamentals """ # Request OVERVIEW data from Alpha Vantage API s_req = f"https://www.alphavantage.co/query?function=OVERVIEW&symbol={ticker}&apikey={cfg.API_KEY_ALPHAVANTAGE}" result = requests.get(s_req, stream=True) # If the returned data was successful if result.status_code == 200: # Parse json data to dataframe if "Note" in result.json(): print(result.json()["Note"], "\n") return pd.DataFrame() df_fa = pd.json_normalize(result.json()) # Keep json data sorting in dataframe df_fa = df_fa[list(result.json().keys())].T df_fa.iloc[5:] = df_fa.iloc[5:].applymap(lambda x: long_number_format(x)) clean_df_index(df_fa) df_fa = df_fa.rename( index={ "E b i t d a": "EBITDA", "P e ratio": "PE ratio", "P e g ratio": "PEG ratio", "E p s": "EPS", "Revenue per share t t m": "Revenue per share TTM", "Operating margin t t m": "Operating margin TTM", "Return on assets t t m": "Return on assets TTM", "Return on equity t t m": "Return on equity TTM", "Revenue t t m": "Revenue TTM", "Gross profit t t m": "Gross profit TTM", "Diluted e p s t t m": "Diluted EPS TTM", "Quarterly earnings growth y o y": "Quarterly earnings growth YOY", "Quarterly revenue growth y o y": "Quarterly revenue growth YOY", "Trailing p e": "Trailing PE", "Forward p e": "Forward PE", "Price to sales ratio t t m": "Price to sales ratio TTM", "E v to revenue": "EV to revenue", "E v to e b i t d a": "EV to EBITDA", } ) return df_fa return pd.DataFrame()
def long_number_format_with_type_check( x: Union[int, float]) -> Union[str, Any]: """Helper which checks if type of x is int or float and it's smaller then 10^18. If yes it apply long_num_format Parameters ---------- x: int/float number to apply long_number_format method Returns ------- """ if isinstance(x, (int, float)) and x < 10**18: return long_number_format(x) return x
def get_key_metrics(ticker: str) -> pd.DataFrame: """Get key metrics from overview Parameters ---------- ticker : str Stock ticker Returns ------- pd.DataFrame Dataframe of key metrics """ # Request OVERVIEW data s_req = f"https://www.alphavantage.co/query?function=OVERVIEW&symbol={ticker}&apikey={cfg.API_KEY_ALPHAVANTAGE}" result = requests.get(s_req, stream=True) # If the returned data was successful if result.status_code == 200: df_fa = pd.json_normalize(result.json()) df_fa = df_fa[list(result.json().keys())].T df_fa = df_fa.applymap(lambda x: long_number_format(x)) clean_df_index(df_fa) df_fa = df_fa.rename( index={ "E b i t d a": "EBITDA", "P e ratio": "PE ratio", "P e g ratio": "PEG ratio", "E p s": "EPS", "Return on equity t t m": "Return on equity TTM", "Price to sales ratio t t m": "Price to sales ratio TTM", } ) as_key_metrics = [ "Market capitalization", "EBITDA", "EPS", "PE ratio", "PEG ratio", "Price to book ratio", "Return on equity TTM", "Price to sales ratio TTM", "Dividend yield", "50 day moving average", "Analyst target price", "Beta", ] return df_fa.loc[as_key_metrics] return pd.DataFrame()
def display_trading_pairs(top: int, sortby: str, descend: bool, export: str) -> None: """Displays a list of available currency pairs for trading. [Source: Coinbase] Parameters ---------- top: int Top n of pairs sortby: str Key to sortby data descend: bool Sort descending flag export : str Export dataframe data to csv,json,xlsx file """ df = coinbase_model.get_trading_pairs() df_data = df.copy() for col in [ "base_min_size", "base_max_size", "min_market_funds", "max_market_funds", ]: df[col] = df[col].apply(lambda x: long_number_format(x)) df = df.sort_values(by=sortby, ascending=descend).head(top) if gtff.USE_TABULATE_DF: print( tabulate( df, headers=df.columns, floatfmt=".2f", showindex=False, tablefmt="fancy_grid", ), "\n", ) else: print(df.to_string, "\n") export_data( export, os.path.dirname(os.path.abspath(__file__)), "pairs", df_data, )
def display_historical_tvl(dapps: str = "", export: str = ""): """Displays historical TVL of different dApps [Source: https://docs.llama.fi/api] Parameters ---------- dapps: str dApps to search historical TVL. Should be split by , e.g.: anchor,sushiswap,pancakeswap export : str Export dataframe data to csv,json,xlsx file """ fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) available_protocols = read_data_file("defillama_dapps.json") if isinstance(available_protocols, dict): for dapp in dapps.split(","): if dapp in available_protocols.keys(): df = llama_model.get_defi_protocol(dapp) if not df.empty: ax.plot(df, label=available_protocols[dapp]) else: print(f"{dapp} not found\n") ax.set_ylabel("Total Value Locked ($)") ax.set_xlabel("Time") dateFmt = mdates.DateFormatter("%m/%d/%Y") ax.xaxis.set_major_formatter(dateFmt) ax.get_yaxis().set_major_formatter( ticker.FuncFormatter(lambda x, _: long_number_format(x))) ax.legend() ax.set_title("TVL in dApps") ax.grid(alpha=0.5) ax.tick_params(axis="x", labelrotation=45) fig.tight_layout(pad=2) if gtff.USE_ION: plt.ion() plt.show() print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "dtvl", None, )
def display_defi_tvl(top: int, export: str = "") -> None: """Displays historical values of the total sum of TVLs from all listed protocols. [Source: https://docs.llama.fi/api] Parameters ---------- top: int Number of records to display export : str Export dataframe data to csv,json,xlsx file """ df = llama_model.get_defi_tvl() df_data = df.copy() df = df.tail(top) fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) ax.plot(df["date"], df["totalLiquidityUSD"], "-ok", ms=2) ax.set_xlabel("Time") ax.set_xlim(df["date"].iloc[0], df["date"].iloc[-1]) dateFmt = mdates.DateFormatter("%m/%d/%Y") ax.xaxis.set_major_formatter(dateFmt) ax.tick_params(axis="x", labelrotation=45) ax.set_ylabel("Total Value Locked ($)") ax.grid(b=True, which="major", color="#666666", linestyle="-") ax.minorticks_on() ax.grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2) ax.set_title("Total Value Locked in DeFi") ax.get_yaxis().set_major_formatter( ticker.FuncFormatter(lambda x, _: long_number_format(x))) fig.tight_layout(pad=2) if gtff.USE_ION: plt.ion() plt.show() console.print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "stvl", df_data, )
def display_terra_asset_history(asset: str = "", address: str = "", export: str = "") -> None: """Displays the 30-day history of specified asset in terra address [Source: https://docs.llama.fi/api] Parameters ---------- asset : str Terra asset {ust,luna,sdt} address : str Terra address. Valid terra addresses start with 'terra' export : str Export dataframe data to csv,json,xlsx file """ df = terraengineer_model.get_history_asset_from_terra_address( address=address, asset=asset) fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) ax.plot(df["x"], df["y"]) ax.set_xlabel("Time") ax.tick_params(axis="x", labelrotation=45) ax.set_xlim(df["x"].iloc[0], df["x"].iloc[-1]) dateFmt = mdates.DateFormatter("%m/%d/%Y") fig.tight_layout(pad=4) ax.xaxis.set_major_formatter(dateFmt) ax.set_ylabel(f"{asset.upper()} Amount") ax.grid(alpha=0.5) ax.set_title(f"{asset.upper()} Amount in Address {address}") ax.get_yaxis().set_major_formatter( ticker.FuncFormatter(lambda x, _: long_number_format(x))) if gtff.USE_ION: plt.ion() plt.show() print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "aterra", df, )
def display_btc_confirmed_transactions(since: int, until: int, export: str) -> None: """Returns BTC confirmed transactions [Source: https://api.blockchain.info/] Parameters ---------- since : int Initial date timestamp (e.g., 1_609_459_200) until : int End date timestamp (e.g., 1_641_588_030) export : str Export dataframe data to csv,json,xlsx file """ df = blockchain_model.get_btc_confirmed_transactions() df = df[(df["x"] > datetime.fromtimestamp(since)) & (df["x"] < datetime.fromtimestamp(until))] fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) ax.plot(df["x"], df["y"], lw=0.8) ax.set_xlabel("Time") ax.tick_params(axis="x", labelrotation=45) ax.set_xlim(df["x"].iloc[0], df["x"].iloc[-1]) dateFmt = mdates.DateFormatter("%m/%d/%Y") fig.tight_layout(pad=4) ax.xaxis.set_major_formatter(dateFmt) ax.set_ylabel("Transactions") ax.grid(alpha=0.5) ax.set_title("BTC Confirmed Transactions") ax.get_yaxis().set_major_formatter( ticker.FuncFormatter(lambda x, _: long_number_format(x))) if gtff.USE_ION: plt.ion() plt.show() print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "btcct", df, )
def calendar_earnings(l_args, s_ticker): parser = argparse.ArgumentParser( prog="cal", description=""" Calendar earnings of the company. Including revenue and earnings estimates. [Source: Yahoo Finance] """, ) try: parse_known_args_and_warn(parser, l_args) stock = yf.Ticker(s_ticker) df_calendar = stock.calendar if df_calendar.empty: print(f"No earnings calendar information in Yahoo for {s_ticker}") print("") return df_calendar.iloc[0, 0] = df_calendar.iloc[0, 0].date().strftime("%d/%m/%Y") df_calendar.iloc[:, 0] = df_calendar.iloc[:, 0].apply( lambda x: long_number_format(x)) print(f"Earnings Date: {df_calendar.iloc[:, 0]['Earnings Date']}") avg = df_calendar.iloc[:, 0]["Earnings Average"] low = df_calendar.iloc[:, 0]["Earnings Low"] high = df_calendar.iloc[:, 0]["Earnings High"] print(f"Earnings Estimate Avg: {avg} [{low}, {high}]") print( f"Revenue Estimate Avg: {df_calendar.iloc[:, 0]['Revenue Average']} \ [{df_calendar.iloc[:, 0]['Revenue Low']}, {df_calendar.iloc[:, 0]['Revenue High']}]" ) print("") except Exception as e: print(e) print("") return
def get_info(ticker: str) -> pd.DataFrame: """Gets ticker info Parameters ---------- ticker : str Stock ticker Returns ------- pd.DataFrame DataFrame of yfinance information """ stock = yf.Ticker(ticker) df_info = pd.DataFrame(stock.info.items(), columns=["Metric", "Value"]) df_info = df_info.set_index("Metric") clean_df_index(df_info) if "Last split date" in df_info.index and df_info.loc[ "Last split date"].values[0]: df_info.loc["Last split date"].values[0] = datetime.fromtimestamp( df_info.loc["Last split date"].values[0]).strftime("%d/%m/%Y") df_info = df_info.mask(df_info["Value"].astype(str).eq("[]")).dropna() df_info[df_info.index != "Zip"] = df_info[df_info.index != "Zip"].applymap( lambda x: long_number_format(x)) df_info = df_info.rename( index={ "Address1": "Address", "Average daily volume10 day": "Average daily volume 10 day", "Average volume10days": "Average volume 10 days", "Price to sales trailing12 months": "Price to sales trailing 12 months", }) df_info.index = df_info.index.str.replace("eps", "EPS") df_info.index = df_info.index.str.replace("p e", "PE") df_info.index = df_info.index.str.replace("Peg", "PEG") return df_info
def clean_metrics_df(df_fa: pd.DataFrame, num: int, mask: bool = True) -> pd.DataFrame: df_fa = df_fa.iloc[:, 0:num] if mask: df_fa = df_fa.mask(df_fa.astype(object).eq(num * ["None"])).dropna() df_fa = df_fa.mask(df_fa.astype(object).eq(num * ["0"])).dropna() df_fa = df_fa.applymap(lambda x: long_number_format(x)) clean_df_index(df_fa) df_fa.columns.name = "Fiscal Date Ending" df_fa = df_fa.rename( index={ "Enterprise value over e b i t d a": "Enterprise value over EBITDA", "Net debt to e b i t d a": "Net debt to EBITDA", "D c f": "DCF", "Net income per e b t": "Net income per EBT", }) return df_fa
def display_grouped_defi_protocols(num: int = 50, export: str = "") -> None: """Display top dApps (in terms of TVL) grouped by chain. [Source: https://docs.llama.fi/api] Parameters ---------- num: int Number of top dApps to display export : str Export dataframe data to csv,json,xlsx file """ df = llama_model.get_defi_protocols() fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) df = df.sort_values("tvl", ascending=False).head(num) df = df.set_index("name") chains = df.groupby("chain").size().index.values.tolist() for chain in chains: chain_filter = df.loc[df.chain == chain] ax.bar(x=chain_filter.index, height=chain_filter.tvl, label=chain) ax.set_ylabel("Total Value Locked ($)") ax.set_xlabel("dApp name") ax.get_yaxis().set_major_formatter( ticker.FuncFormatter(lambda x, _: long_number_format(x))) fig.tight_layout(pad=8) ax.legend(ncol=2) ax.set_title(f"Top {num} dApp TVL grouped by chain") ax.grid(alpha=0.5) ax.tick_params(axis="x", labelrotation=90) if gtff.USE_ION: plt.ion() plt.show() print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "gdapps", df, )
def display_anchor_yield_reserve(export: str = "") -> None: """Displays the 30-day history of the Anchor Yield Reserve. [Source: https://docs.llama.fi/api] Parameters ---------- export : str Export dataframe data to csv,json,xlsx file """ df = terraengineer_model.get_history_asset_from_terra_address( address="terra1tmnqgvg567ypvsvk6rwsga3srp7e3lg6u0elp8") fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) ax.plot(df["x"], df["y"]) ax.set_xlabel("Time") ax.tick_params(axis="x", labelrotation=45) ax.set_xlim(df["x"].iloc[0], df["x"].iloc[-1]) dateFmt = mdates.DateFormatter("%m/%d/%Y") fig.tight_layout(pad=4) ax.xaxis.set_major_formatter(dateFmt) ax.set_ylabel("UST Amount") ax.grid(alpha=0.5) ax.set_title("Anchor UST Yield Reserve") ax.get_yaxis().set_major_formatter( ticker.FuncFormatter(lambda x, _: long_number_format(x))) if gtff.USE_ION: plt.ion() plt.show() print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "ayr", df, )
def get_balance_sheet( ticker: str, number: int, quarterly: bool = False ) -> pd.DataFrame: """Get balance sheets for company Parameters ---------- ticker : str Stock ticker number : int Number of past to get quarterly : bool, optional Flag to get quarterly instead of annual, by default False Returns ------- pd.DataFrame Dataframe of income statements """ url = f"https://www.alphavantage.co/query?function=BALANCE_SHEET&symbol={ticker}&apikey={cfg.API_KEY_ALPHAVANTAGE}" r = requests.get(url) if r.status_code == 200: statements = r.json() df_fa = pd.DataFrame() if quarterly: if "quarterlyReports" in statements: df_fa = pd.DataFrame(statements["quarterlyReports"]) else: if "annualReports" in statements: df_fa = pd.DataFrame(statements["annualReports"]) if df_fa.empty: return pd.DataFrame() df_fa = df_fa.set_index("fiscalDateEnding") df_fa = df_fa.head(number) df_fa = df_fa.applymap(lambda x: long_number_format(x)) return df_fa[::-1].T return pd.DataFrame()
def overview(other_args: List[str], ticker: str): """Alpha Vantage stock ticker overview Parameters ---------- other_args : List[str] argparse other args ticker : str Fundamental analysis ticker symbol """ parser = argparse.ArgumentParser( add_help=False, prog="overview", description=""" Prints an overview about the company. The following fields are expected: Symbol, Asset type, Name, Description, Exchange, Currency, Country, Sector, Industry, Address, Full time employees, Fiscal year end, Latest quarter, Market capitalization, EBITDA, PE ratio, PEG ratio, Book value, Dividend per share, Dividend yield, EPS, Revenue per share TTM, Profit margin, Operating margin TTM, Return on assets TTM, Return on equity TTM, Revenue TTM, Gross profit TTM, Diluted EPS TTM, Quarterly earnings growth YOY, Quarterly revenue growth YOY, Analyst target price, Trailing PE, Forward PE, Price to sales ratio TTM, Price to book ratio, EV to revenue, EV to EBITDA, Beta, 52 week high, 52 week low, 50 day moving average, 200 day moving average, Shares outstanding, Shares float, Shares short, Shares short prior month, Short ratio, Short percent outstanding, Short percent float, Percent insiders, Percent institutions, Forward annual dividend rate, Forward annual dividend yield, Payout ratio, Dividend date, Ex dividend date, Last split factor, and Last split date. [Source: Alpha Vantage] """, ) try: ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return # Request OVERVIEW data from Alpha Vantage API s_req = f"https://www.alphavantage.co/query?function=OVERVIEW&symbol={ticker}&apikey={cfg.API_KEY_ALPHAVANTAGE}" result = requests.get(s_req, stream=True) # If the returned data was successful if result.status_code == 200: # Parse json data to dataframe df_fa = pd.json_normalize(result.json()) # Keep json data sorting in dataframe df_fa = df_fa[list(result.json().keys())].T df_fa = df_fa.applymap(lambda x: long_number_format(x)) clean_df_index(df_fa) df_fa = df_fa.rename( index={ "E b i t d a": "EBITDA", "P e ratio": "PE ratio", "P e g ratio": "PEG ratio", "E p s": "EPS", "Revenue per share t t m": "Revenue per share TTM", "Operating margin t t m": "Operating margin TTM", "Return on assets t t m": "Return on assets TTM", "Return on equity t t m": "Return on equity TTM", "Revenue t t m": "Revenue TTM", "Gross profit t t m": "Gross profit TTM", "Diluted e p s t t m": "Diluted EPS TTM", "Quarterly earnings growth y o y": "Quarterly earnings growth YOY", "Quarterly revenue growth y o y": "Quarterly revenue growth YOY", "Trailing p e": "Trailing PE", "Forward p e": "Forward PE", "Price to sales ratio t t m": "Price to sales ratio TTM", "E v to revenue": "EV to revenue", "E v to e b i t d a": "EV to EBITDA", }) pd.set_option("display.max_colwidth", None) print(df_fa.drop(index=["Description"]).to_string(header=False)) print(f"Description: {df_fa.loc['Description'][0]}") print("") else: print(f"Error: {result.status_code}") print("") except Exception as e: print(e) print("") return
def key(other_args: List[str], ticker: str): """Alpha Vantage key metrics Parameters ---------- other_args : List[str] argparse other args ticker : str Fundamental analysis ticker symbol """ parser = argparse.ArgumentParser( add_help=False, prog="key", description=""" Gives main key metrics about the company (it's a subset of the Overview data from Alpha Vantage API). The following fields are expected: Market capitalization, EBITDA, EPS, PE ratio, PEG ratio, Price to book ratio, Return on equity TTM, Payout ratio, Price to sales ratio TTM, Dividend yield, 50 day moving average, Analyst target price, Beta [Source: Alpha Vantage API] """, ) try: ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return # Request OVERVIEW data s_req = f"https://www.alphavantage.co/query?function=OVERVIEW&symbol={ticker}&apikey={cfg.API_KEY_ALPHAVANTAGE}" result = requests.get(s_req, stream=True) # If the returned data was successful if result.status_code == 200: df_fa = pd.json_normalize(result.json()) df_fa = df_fa[list(result.json().keys())].T df_fa = df_fa.applymap(lambda x: long_number_format(x)) clean_df_index(df_fa) df_fa = df_fa.rename( index={ "E b i t d a": "EBITDA", "P e ratio": "PE ratio", "P e g ratio": "PEG ratio", "E p s": "EPS", "Return on equity t t m": "Return on equity TTM", "Price to sales ratio t t m": "Price to sales ratio TTM", }) as_key_metrics = [ "Market capitalization", "EBITDA", "EPS", "PE ratio", "PEG ratio", "Price to book ratio", "Return on equity TTM", "Payout ratio", "Price to sales ratio TTM", "Dividend yield", "50 day moving average", "Analyst target price", "Beta", ] print(df_fa.loc[as_key_metrics].to_string(header=False)) print("") else: print(f"Error: {result.status_code}") print("") except Exception as e: print(e) print("") return
def short_interest(l_args, s_ticker, s_start): parser = argparse.ArgumentParser( prog="short", description=""" Plots the short interest of a stock. This corresponds to the number of shares that have been sold short but have not yet been covered or closed out. Either NASDAQ or NYSE [Source: Quandl] """, ) parser.add_argument( "-n", "--nyse", action="store_true", default=False, dest="b_nyse", help="data from NYSE flag.", ) parser.add_argument( "-d", "--days", action="store", dest="n_days", type=check_positive, default=10, help="number of latest days to print data.", ) try: ns_parser = parse_known_args_and_warn(parser, l_args) quandl.ApiConfig.api_key = cfg.API_KEY_QUANDL if ns_parser.b_nyse: df_short_interest = quandl.get(f"FINRA/FNYX_{s_ticker}") else: df_short_interest = quandl.get(f"FINRA/FNSQ_{s_ticker}") df_short_interest = df_short_interest[s_start:] df_short_interest.columns = [ "".join( " " + char if char.isupper() else char.strip() for char in idx ).strip() for idx in df_short_interest.columns.tolist() ] df_short_interest["% of Volume Shorted"] = round( 100 * df_short_interest["Short Volume"] / df_short_interest["Total Volume"], 2, ) _, ax = plt.subplots() ax.bar( df_short_interest.index, df_short_interest["Short Volume"], 0.3, color="r" ) ax.bar( df_short_interest.index, df_short_interest["Total Volume"] - df_short_interest["Short Volume"], 0.3, bottom=df_short_interest["Short Volume"], color="b", ) ax.set_ylabel("Shares") ax.set_xlabel("Date") if s_start: ax.set_title( f"{('NASDAQ', 'NYSE')[ns_parser.b_nyse]} Short Interest on {s_ticker} from {s_start.date()}" ) else: ax.set_title( f"{('NASDAQ', 'NYSE')[ns_parser.b_nyse]} Short Interest on {s_ticker}" ) ax.legend(labels=["Short Volume", "Total Volume"]) ax.tick_params(axis="both", which="major") ax.yaxis.set_major_formatter(ticker.EngFormatter()) ax_twin = ax.twinx() ax_twin.tick_params(axis="y", colors="green") ax_twin.set_ylabel("Percentage of Volume Shorted", color="green") ax_twin.plot( df_short_interest.index, df_short_interest["% of Volume Shorted"], color="green", ) ax_twin.tick_params(axis="y", which="major", color="green") ax_twin.yaxis.set_major_formatter(ticker.FormatStrFormatter("%.0f%%")) plt.xlim([df_short_interest.index[0], df_short_interest.index[-1]]) df_short_interest["% of Volume Shorted"] = df_short_interest[ "% of Volume Shorted" ].apply(lambda x: f"{x/100:.2%}") df_short_interest = df_short_interest.applymap( lambda x: long_number_format(x) ).sort_index(ascending=False) pd.set_option("display.max_colwidth", 70) print(df_short_interest.head(n=ns_parser.n_days).to_string()) print("") plt.show() except Exception as e: print(e) print("") return
def info(l_args, s_ticker): parser = argparse.ArgumentParser( prog="info", description=""" Print information about the company. The following fields are expected: Zip, Sector, Full time employees, Long business summary, City, Phone, State, Country, Website, Max age, Address, Industry, Previous close, Regular market open, Two hundred day average, Payout ratio, Regular market day high, Average daily volume 10 day, Regular market previous close, Fifty day average, Open, Average volume 10 days, Beta, Regular market day low, Price hint, Currency, Trailing PE, Regular market volume, Market cap, Average volume, Price to sales trailing 12 months, Day low, Ask, Ask size, Volume, Fifty two week high, Forward PE, Fifty two week low, Bid, Tradeable, Bid size, Day high, Exchange, Short name, Long name, Exchange timezone name, Exchange timezone short name, Is esg populated, Gmt off set milliseconds, Quote type, Symbol, Message board id, Market, Enterprise to revenue, Profit margins, Enterprise to ebitda, 52 week change, Forward EPS, Shares outstanding, Book value, Shares short, Shares percent shares out, Last fiscal year end, Held percent institutions, Net income to common, Trailing EPS, Sand p52 week change, Price to book, Held percent insiders, Next fiscal year end, Most recent quarter, Short ratio, Shares short previous month date, Float shares, Enterprise value, Last split date, Last split factor, Earnings quarterly growth, Date short interest, PEG ratio, Short percent of float, Shares short prior month, Regular market price, Logo_url. [Source: Yahoo Finance] """, ) try: parse_known_args_and_warn(parser, l_args) stock = yf.Ticker(s_ticker) df_info = pd.DataFrame(stock.info.items(), columns=["Metric", "Value"]) df_info = df_info.set_index("Metric") clean_df_index(df_info) if ("Last split date" in df_info.index and df_info.loc["Last split date"].values[0]): df_info.loc["Last split date"].values[0] = datetime.fromtimestamp( df_info.loc["Last split date"].values[0]).strftime("%d/%m/%Y") df_info = df_info.mask(df_info["Value"].astype(str).eq("[]")).dropna() df_info = df_info.applymap(lambda x: long_number_format(x)) df_info = df_info.rename( index={ "Address1": "Address", "Average daily volume10 day": "Average daily volume 10 day", "Average volume10days": "Average volume 10 days", "Price to sales trailing12 months": "Price to sales trailing 12 months", }) df_info.index = df_info.index.str.replace("eps", "EPS") df_info.index = df_info.index.str.replace("p e", "PE") df_info.index = df_info.index.str.replace("Peg", "PEG") pd.set_option("display.max_colwidth", -1) if "Long business summary" in df_info.index: print( df_info.drop(index=["Long business summary"]).to_string( header=False)) print("") print(df_info.loc["Long business summary"].values[0]) print("") else: print(df_info.to_string(header=False)) print("") except Exception as e: print(e) print("") return