def currencies_command(): """Currencies overview [Wall St. Journal]""" # Debug user input if imps.DEBUG: logger.debug("econ-currencies") # Retrieve data df = wsj_model.global_currencies() df = df.fillna("") # Check for argument if df.empty: raise Exception("No available data found") df["Last Price"] = pd.to_numeric(df["Last"].astype(float)) df["Change"] = pd.to_numeric(df["Chng"].astype(float)) df["%Chng"] = pd.to_numeric(df["%Chng"].astype(float)) # Debug user output if imps.DEBUG: logger.debug(df.to_string()) formats = { "Last Price": "${:.2f}", "Change": "${:.2f}", "%Chng": "<b>{:.2f}%</b>", } for col, value in formats.items(): df[col] = df[col].map(lambda x: value.format(x)) # pylint: disable=W0640 df["Change"] = df.apply(lambda x: f"{x['Change']} (<b>{x['%Chng']}</b>)", axis=1) df.set_index(" ", inplace=True) font_color = ["white"] * 2 + [[ "#e4003a" if boolv else "#00ACFF" for boolv in df["%Chng"].str.contains("-") ]] df = df.drop(columns=["Last", "Chng", "%Chng"]) fig = imps.plot_df( df, fig_size=(620, (40 + (40 * len(df.index)))), col_width=[4.2, 2.4, 3], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict( align=["center", "right"], font=dict(color=font_color), ))) imagefile = imps.save_image("econ-currencies.png", fig) return { "title": "Economy: [WSJ] Currencies", "imagefile": imagefile, }
def quote_command(ticker: str = None): """Ticker Quote""" # Debug if imps.DEBUG: logger.debug("quote %s", ticker) # Check for argument if ticker is None: raise Exception("Stock ticker is required") df = imps.quote(ticker) fig = imps.plot_df( df, fig_size=(600, 1500), col_width=[2, 3], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict(align="left"))) imagefile = imps.save_image("quote.png", fig) return { "title": f"{ticker.upper()} Quote", "imagefile": imagefile, }
def iv_command(ticker: str = None): """Options IV""" # Debug if imps.DEBUG: logger.debug("opt info %s", ticker) # Check for argument if ticker is None: raise Exception("Stock ticker is required") df = barchart_model.get_options_info(ticker) df = df.fillna("") df = df.set_axis( [ " ", "", ], axis="columns", ) df[""] = df[""].str.lstrip() font_color = [["white"]] + [["#e4003a" if "-" in df[""][0] else "#00ACFF"] + ["white"]] df.set_index(" ", inplace=True) fig = imps.plot_df( df, fig_size=(600, 1500), col_width=[3, 3], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces( header=(dict( values=[[f"<b>{ticker.upper()}</b>"]], align="center", )), cells=(dict( align="left", font=dict(color=font_color), )), ) imagefile = imps.save_image("opt-info.png", fig) return { "title": f"{ticker.upper()} Options: IV", "imagefile": imagefile, }
def analyst_command(ticker=""): """Displays analyst recommendations [Finviz]""" # Debug if imps.DEBUG: logger.debug("dd analyst %s", ticker) # Check for argument if not ticker: raise Exception("Stock ticker is required") df = finviz_model.get_analyst_data(ticker) df = df.replace(np.nan, 0) df.index.names = ["Date"] df = df.rename( columns={ "category": "Category", "analyst": "Analyst", "rating": "Rating", "target": "Target", "target_from": "Target From", "target_to": "Target To", }) dindex = len(df.index) fig = imps.plot_df( df, fig_size=(900, (40 + (40 * dindex))), col_width=[5, 5, 9, 8, 5, 6, 5], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) imagefile = imps.save_image("dd-analyst.png", fig) return { "title": f"Stocks: [Finviz] Analyst Recommendations {ticker.upper()}", "imagefile": imagefile, }
def chain_command( ticker: str = None, expiry: str = None, opt_type: str = None, min_sp: float = None, max_sp: float = None, ): """Show calls/puts for given ticker and expiration""" # Debug if imps.DEBUG: logger.debug("opt chain %s %s %s %s %s", ticker, expiry, opt_type, min_sp, max_sp) # Check for argument if not ticker: raise Exception("Stock ticker is required") dates = yfinance_model.option_expirations(ticker) if not dates: raise Exception("Stock ticker is invalid") options = yfinance_model.get_option_chain(ticker, str(expiry)) calls_df = options.calls.fillna(0) puts_df = options.puts.fillna(0) column_map = { "openInterest": "oi", "volume": "vol", "impliedVolatility": "iv" } columns = [ "strike", "bid", "ask", "volume", "openInterest", "impliedVolatility", ] if opt_type == "Calls": df = calls_df[columns].rename(columns=column_map) if opt_type == "Puts": df = puts_df[columns].rename(columns=column_map) min_strike = np.percentile(df["strike"], 1) max_strike = np.percentile(df["strike"], 100) if min_sp: min_strike = min_sp if max_sp: max_strike = max_sp if min_sp > max_sp: # type: ignore min_sp, max_sp = max_strike, min_strike df = df[df["strike"] >= min_strike] df = df[df["strike"] <= max_strike] df["iv"] = pd.to_numeric(df["iv"].astype(float)) formats = {"iv": "{:.2f}"} for col, f in formats.items(): df[col] = df[col].map(lambda x: f.format(x)) # pylint: disable=W0640 df.columns = df.columns.str.capitalize() df.set_index("Strike", inplace=True) title = ( f"Stocks: {opt_type} Option Chain for {ticker.upper()} on\n{expiry} [yfinance]" ) embeds: list = [] # Output i, i2, end = 0, 0, 20 df_pg, embeds_img, images_list = [], [], [] while i < len(df.index): df_pg = df.iloc[i:end] df_pg.append(df_pg) fig = imps.plot_df( df_pg, fig_size=(570, (40 + (40 * 20))), col_width=[3.1, 3.1, 3.1, 3.5], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict(align=["center", "right"]))) imagefile = "opt-chain.png" imagefile = imps.save_image(imagefile, fig) if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE: image_link = imps.multi_image(imagefile) images_list.append(imagefile) else: image_link = imps.multi_image(imagefile) embeds_img.append(f"{image_link}", ) embeds.append(disnake.Embed( title=title, colour=imps.COLOR, ), ) i2 += 1 i += 20 end += 20 # Author/Footer for i in range(0, i2): embeds[i].set_author( name=imps.AUTHOR_NAME, url=imps.AUTHOR_URL, icon_url=imps.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=imps.AUTHOR_NAME, icon_url=imps.AUTHOR_ICON_URL, ) i = 0 for i in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f"Page 1 of {len(embeds)}") choices = [ disnake.SelectOption(label="Home", value="0", emoji="🟢"), ] return { "view": imps.Menu, "title": title, "embed": embeds, "choices": choices, "embeds_img": embeds_img, "images_list": images_list, }
def reverse_repo_command(days: int = 50): """Displays Reverse Repo [Stocksera.com]""" # Debug user input if imps.DEBUG: logger.debug("dd repo %s", days) df = pd.DataFrame( requests.get( f"https://stocksera.pythonanywhere.com/api/reverse_repo/?days={str(days)}" ).json() ) if df.empty: raise Exception("No Data Found") title = "Reverse Repo [Stocksera]" df["Difference"] = df["Amount"].diff().fillna(0) formats = { "Amount": "${:.2f}B", "Average": "${:.2f}B", "Difference": "<b>${:.2f}B</b>", } for col, value in formats.items(): df[col] = df[col].map(lambda x: value.format(x)) # pylint: disable=W0640 df = df.drop(columns="Moving Avg") df = df.sort_values(by="Date", ascending=False) font_color = ["white"] * 4 + [ [ "#e4003a" if boolv else "#00ACFF" for boolv in df["Difference"].str.contains("-") ] # type: ignore ] df.set_index("Date", inplace=True) df.columns = df.columns.str.capitalize() dindex = len(df.index) if dindex > 15: embeds: list = [] # Output i, i2, end = 0, 0, 15 df_pg, embeds_img, images_list = pd.DataFrame(), [], [] while i < dindex: df_pg = df.iloc[i:end] font_color = ["white"] * 4 + [ [ "#e4003a" if boolv else "#00ACFF" for boolv in df_pg["Difference"].str.contains("-") ] # type: ignore ] df_pg.append(df_pg) fig = imps.plot_df( df_pg, fig_size=(650, (40 + (40 * len(df.index)))), col_width=[1.8, 1.5, 1.7, 1.3, 1.8], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces( cells=( dict( align=["center", "right", "center", "right"], font=dict(color=font_color), ) ) ) imagefile = "dd_r_repo.png" imagefile = imps.save_image(imagefile, fig) if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE: image_link = imps.multi_image(imagefile) images_list.append(imagefile) else: image_link = imps.multi_image(imagefile) embeds_img.append( f"{image_link}", ) embeds.append( disnake.Embed( title=title, colour=imps.COLOR, ), ) i2 += 1 i += 15 end += 15 # Author/Footer for i in range(0, i2): embeds[i].set_author( name=imps.AUTHOR_NAME, url=imps.AUTHOR_URL, icon_url=imps.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=imps.AUTHOR_NAME, icon_url=imps.AUTHOR_ICON_URL, ) i = 0 for i in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f"Page 1 of {len(embeds)}") choices = [ disnake.SelectOption(label="Home", value="0", emoji="🟢"), ] output = { "view": imps.Menu, "title": title, "embed": embeds, "choices": choices, "embeds_img": embeds_img, "images_list": images_list, } else: fig = imps.plot_df( df, fig_size=(650, (40 + (40 * len(df.index)))), col_width=[1.8, 1.5, 1.7, 1.3, 1.8], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces( cells=( dict( align=["center", "right", "center", "right"], font=dict(color=font_color), ) ) ) imagefile = "dd_r_repo.png" imagefile = imps.save_image(imagefile, fig) output = { "title": title, "imagefile": imagefile, } return output
def pos_command(sort="dpp_dollar", ascending: bool = False, num: int = 10): """Dark pool short position [Stockgrid]""" # Debug user input if imps.DEBUG: logger.debug("dps-pos %s %s", sort, num) # Check for argument possible_sorts = ("sv", "sv_pct", "nsv", "nsv_dollar", "dpp", "dpp_dollar") if sort not in possible_sorts: raise Exception(f"The possible sorts are: {', '.join(possible_sorts)}") if num < 0: raise Exception("Number has to be above 0") # Retrieve data df = stockgrid_model.get_dark_pool_short_positions(sort, ascending) if df.empty: raise Exception("No available data found") df = df.iloc[:num] # Debug user output if imps.DEBUG: logger.debug(df.to_string()) # Output data title = "Stocks: [Stockgrid] Dark Pool Short Position" df = df.applymap(lambda x: lambda_long_number_format(x, 2)) df = df.drop(columns=["Date"]) formats = { "Short Volume %": "{}%", "Net Short Volume $": "${}", "Dark Pools Position $": "${}", } for col, f in formats.items(): df[col] = df[col].map(lambda x: f.format(x)) # pylint: disable=W0640 df["Short Volume"] = df.apply( lambda x: f"{x['Short Volume']} (<b>{x['Short Volume %']}</b>)", axis=1) df["Net Short Volume"] = df.apply( lambda x: f"{x['Net Short Volume']:>9} (<b>{x['Net Short Volume $']:>9}</b>)", axis=1, ) df["Dark Pools Position"] = df.apply( lambda x: f"{x['Dark Pools Position']:>9} (<b>{x['Dark Pools Position $']:>9}</b>)", axis=1, ) df = df.drop(columns=[ "Short Volume %", "Net Short Volume $", "Dark Pools Position $" ]) df.columns = [ "Ticker", "Short Vol.", "Net Short Vol.", "DP Position", ] df.set_index("Ticker", inplace=True) dindex = len(df.index) if dindex > 15: embeds: list = [] # Output i, i2, end = 0, 0, 15 df_pg, embeds_img, images_list = [], [], [] while i < dindex: df_pg = df.iloc[i:end] df_pg.append(df_pg) fig = imps.plot_df( df_pg, fig_size=(720, (40 * dindex)), col_width=[2, 4, 4, 4], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict(align=["center", "right"]))) imagefile = "dps-pos.png" imagefile = imps.save_image(imagefile, fig) if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE: image_link = imps.multi_image(imagefile) images_list.append(imagefile) else: image_link = imps.multi_image(imagefile) embeds_img.append(f"{image_link}", ) embeds.append(disnake.Embed( title=title, colour=imps.COLOR, ), ) i2 += 1 i += 15 end += 15 # Author/Footer for i in range(0, i2): embeds[i].set_author( name=imps.AUTHOR_NAME, url=imps.AUTHOR_URL, icon_url=imps.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=imps.AUTHOR_NAME, icon_url=imps.AUTHOR_ICON_URL, ) i = 0 for i in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f"Page 1 of {len(embeds)}") choices = [ disnake.SelectOption(label="Home", value="0", emoji="🟢"), ] output = { "view": imps.Menu, "title": title, "embed": embeds, "choices": choices, "embeds_img": embeds_img, "images_list": images_list, } else: fig = imps.plot_df( df, fig_size=(720, (40 * dindex)), col_width=[2, 4, 4, 4], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict(align=["center", "right"]))) imagefile = imps.save_image("dps-pos.png", fig) output = { "title": title, "imagefile": imagefile, } return output
def futures_command(): """Futures [Yahoo Finance]""" # Debug user input if imps.DEBUG: logger.debug("futures") # Retrieve data req = pd.read_html( requests.get( "https://finance.yahoo.com/commodities", headers={ "User-Agent": get_user_agent() }, ).text) df = req[0] # Check for argument if df.empty: raise Exception("No available data found") title = "Futures [yfinance]" df["Last Price"] = pd.to_numeric(df["Last Price"].astype(float)) df["Change"] = pd.to_numeric(df["Change"].astype(float)) formats = { "Last Price": "${:.2f}", "Change": "${:.2f}", } for col, value in formats.items(): df[col] = df[col].map(lambda x: value.format(x)) # pylint: disable=W0640 df = df.fillna("") df["Change"] = df.apply( lambda x: f"{x['Change']} (<b>{x['% Change']}</b>)", axis=1) df.drop(columns="Symbol") df = df.rename(columns={"Name": " "}) df.set_index(" ", inplace=True) df = df[["Last Price", "Change"]] font_color = ["white"] * 2 + [[ "#e4003a" if boolv else "#00ACFF" for boolv in df["Change"].str.contains("-") ]] dindex = len(df.index) if dindex > 15: embeds: list = [] # Output i, i2, end = 0, 0, 15 df_pg, embeds_img, images_list = pd.DataFrame(), [], [] while i < dindex: df_pg = df[["Last Price", "Change"]].iloc[i:end] df_pg.append(df_pg) font_color = ["white"] * 2 + [[ "#e4003a" if boolv else "#00ACFF" for boolv in df_pg["Change"].str.contains("-") ]] fig = imps.plot_df( df_pg, fig_size=(620, (40 + (45 * len(df.index)))), col_width=[4.2, 1.8, 2.5], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict( align=["center", "right"], font=dict(color=font_color), ))) imagefile = "econ-futures.png" imagefile = imps.save_image(imagefile, fig) if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE: image_link = imps.multi_image(imagefile) images_list.append(imagefile) else: image_link = imps.multi_image(imagefile) embeds_img.append(f"{image_link}", ) embeds.append(disnake.Embed( title=title, colour=imps.COLOR, ), ) i2 += 1 i += 15 end += 15 # Author/Footer for i in range(0, i2): embeds[i].set_author( name=imps.AUTHOR_NAME, url=imps.AUTHOR_URL, icon_url=imps.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=imps.AUTHOR_NAME, icon_url=imps.AUTHOR_ICON_URL, ) i = 0 for i in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f"Page 1 of {len(embeds)}") choices = [ disnake.SelectOption(label="Home", value="0", emoji="🟢"), ] output = { "view": imps.Menu, "title": title, "embed": embeds, "choices": choices, "embeds_img": embeds_img, "images_list": images_list, } else: fig = imps.plot_df( df, fig_size=(620, (40 + (45 * len(df.index)))), col_width=[4.2, 1.8, 2.5], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict( align=["center", "right"], font=dict(color=font_color), ))) imagefile = "econ-futures.png" imagefile = imps.save_image(imagefile, fig) output = { "title": title, "imagefile": imagefile, } return output
def lins_command(ticker: str = "", num: int = 30): """Display insider activity for a given stock ticker. [Source: Finviz] Parameters ---------- ticker : Stock Ticker num : Number of latest insider activity to display """ # Debug if imps.DEBUG: logger.debug("disc-lins %s", num) d_finviz_insider = finviz_model.get_last_insider_activity(ticker) df = pd.DataFrame.from_dict(d_finviz_insider) df.set_index("Date", inplace=True) df = df[[ "Relationship", "Transaction", "#Shares", "Cost", "Value ($)", "#Shares Total", "Insider Trading", "SEC Form 4", ]] df = df.head(num) df = df.replace(to_replace="Option Exercise", value="Opt Ex.", regex=True) title = f"Insider Trading for {ticker.upper()}" embeds: list = [] i, i2, end = 0, 0, 15 df_pg, embeds_img, images_list = [], [], [] while i < len(df.index): df_pg = df.iloc[i:end] df_pg.append(df_pg) fig = imps.plot_df( df_pg, fig_size=(1400, (40 + (45 * 20))), col_width=[4, 10, 4, 4, 3.5, 5.3, 6, 8, 7], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict(align=[ "center", "center", "center", "right", "right", "right", "right", "center", ]))) imagefile = imps.save_image("disc-insider.png", fig) if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE: image_link = imps.multi_image(imagefile) images_list.append(imagefile) else: image_link = imps.multi_image(imagefile) embeds_img.append(f"{image_link}", ) embeds.append(disnake.Embed( title=title, colour=imps.COLOR, ), ) i2 += 1 i += 15 end += 15 # Author/Footer for i in range(0, i2): embeds[i].set_author( name=imps.AUTHOR_NAME, url=imps.AUTHOR_URL, icon_url=imps.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=imps.AUTHOR_NAME, icon_url=imps.AUTHOR_ICON_URL, ) i = 0 for i in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f"Page 1 of {len(embeds)}") choices = [ disnake.SelectOption(label="Home", value="0", emoji="🟢"), ] return { "view": imps.Menu, "title": title, "embed": embeds, "choices": choices, "embeds_img": embeds_img, "images_list": images_list, }
def by_ticker_command(ticker="", sort="fund_percent", num: int = 15): """Display ETF Holdings. [Source: StockAnalysis]""" # Debug if imps.DEBUG: logger.debug("etfs") options = uc.ChromeOptions() options.headless = True options.add_argument("--headless") options.add_argument("--incognito") driver = uc.Chrome(options=options, version_main=98) driver.set_window_size(1920, 1080) driver.get(f"http://etf.com/stock/{ticker.upper()}/") time.sleep(2) driver.find_element(By.XPATH, "(//div[@id='inactiveResult'])[3]").click() soup5 = bs4.BeautifulSoup(driver.page_source, "html.parser") r_ticker, r_holdings, r_name, r_market = [], [], [], [] table1 = soup5.find("table", id="StockTable") table = table1.find("tbody") for x in table.find_all("tr"): r_ticker.append(x.find("td").text) r_name.append(x.find("td").findNext("td").text) r_holdings.append( x.find("td").findNext("td").findNext("td").findNext("td").text) r_market.append( x.find("td").findNext("td").findNext("td").findNext("td").findNext( "td").text) driver.quit() df = pd.DataFrame({ "Ticker": r_ticker, "Name": r_name, "Holdings": r_holdings, "Market Value": r_market, }) if df.empty: raise Exception("No company holdings found!\n") if sort == "mkt_value": key = imps.natsort.index_natsorted( df["Market Value"], key=lambda x: imps.unit_finder.sub(imps.unit_replacer, x), reverse=True, ) df = df.reindex(key) df = df.iloc[:num] df.set_index("Ticker", inplace=True) title = f"ETF's Holding {ticker.upper()}" dindex = len(df.index) if dindex > 15: embeds: list = [] # Output i, i2, end = 0, 0, 15 df_pg, embeds_img, images_list = [], [], [] while i < dindex: df_pg = df.iloc[i:end] df_pg.append(df_pg) fig = imps.plot_df( df_pg, fig_size=(800, (40 * dindex)), col_width=[0.6, 3.5, 0.65, 1.1], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict( align=["center", "center", "center", "right"]))) imagefile = "etf-byticker.png" imagefile = imps.save_image(imagefile, fig) if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE: image_link = imps.multi_image(imagefile) images_list.append(imagefile) else: image_link = imps.multi_image(imagefile) embeds_img.append(f"{image_link}", ) embeds.append(disnake.Embed( title=title, colour=imps.COLOR, ), ) i2 += 1 i += 15 end += 15 # Author/Footer for i in range(0, i2): embeds[i].set_author( name=imps.AUTHOR_NAME, url=imps.AUTHOR_URL, icon_url=imps.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=imps.AUTHOR_NAME, icon_url=imps.AUTHOR_ICON_URL, ) i = 0 for i in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f"Page 1 of {len(embeds)}") choices = [ disnake.SelectOption(label="Home", value="0", emoji="🟢"), ] output = { "view": imps.Menu, "title": title, "embed": embeds, "choices": choices, "embeds_img": embeds_img, "images_list": images_list, } else: fig = imps.plot_df( df, fig_size=(800, (40 * dindex)), col_width=[0.6, 3.5, 0.65, 1.1], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict( align=["center", "center", "center", "right"]))) imagefile = imps.save_image("etf-holdings.png", fig) output = { "title": title, "imagefile": imagefile, } return output
def holdings_command(etf="", num: int = 15): """Display ETF Holdings. [Source: StockAnalysis]""" if imps.DEBUG: logger.debug("etfs") holdings = stockanalysis_model.get_etf_holdings(etf.upper()) holdings = holdings.iloc[:num] if holdings.empty: raise Exception("No company holdings found!\n") title = f"ETF: {etf.upper()} Holdings" dindex = len(holdings.index) if dindex > 15: embeds: list = [] # Output i, i2, end = 0, 0, 15 df_pg, embeds_img, images_list = [], [], [] while i < dindex: df_pg = holdings.iloc[i:end] df_pg.append(df_pg) fig = imps.plot_df( df_pg, fig_size=(500, (40 + (40 * dindex))), col_width=[1, 2, 2], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict(align=["center", "right"]))) imagefile = "etf-holdings.png" imagefile = imps.save_image(imagefile, fig) if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE: image_link = imps.multi_image(imagefile) images_list.append(imagefile) else: image_link = imps.multi_image(imagefile) embeds_img.append(f"{image_link}", ) embeds.append(disnake.Embed( title=title, colour=imps.COLOR, ), ) i2 += 1 i += 15 end += 15 # Author/Footer for i in range(0, i2): embeds[i].set_author( name=imps.AUTHOR_NAME, url=imps.AUTHOR_URL, icon_url=imps.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=imps.AUTHOR_NAME, icon_url=imps.AUTHOR_ICON_URL, ) i = 0 for i in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f"Page 1 of {len(embeds)}") choices = [ disnake.SelectOption(label="Home", value="0", emoji="🟢"), ] output = { "view": imps.Menu, "title": title, "embed": embeds, "choices": choices, "embeds_img": embeds_img, "images_list": images_list, } else: fig = imps.plot_df( holdings, fig_size=(500, (40 + (40 * dindex))), col_width=[1, 2, 2], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict(align=["center", "right"]))) imagefile = imps.save_image("etf-holdings.png", fig) output = { "title": title, "imagefile": imagefile, } return output
def softs_command(): """Displays softs futures data [Finviz]""" # Debug user input if imps.DEBUG: logger.debug("econ-softs") # Retrieve data d_futures = finviz_model.get_futures() df = pd.DataFrame(d_futures["Softs"]) # Check for argument if df.empty: raise Exception("No available data found") formats = { "last": "${:.2f}", "prevClose": "${:.2f}", "change": "<b>{:.2f}%</b>" } for col, value in formats.items(): df[col] = df[col].map(lambda x: value.format(x)) # pylint: disable=W0640 # Debug user output if imps.DEBUG: logger.debug(df) df = df.sort_values(by="ticker", ascending=False) df = df.fillna("") df.set_index("label", inplace=True) df = df[[ "prevClose", "last", "change", ]] df.index.names = [""] df = df.rename(columns={ "prevClose": "PrevClose", "last": "Last", "change": "Change" }) font_color = ["white"] * 3 + [[ "#e4003a" if boolv else "#00ACFF" for boolv in df["Change"].str.contains("-") ]] fig = imps.plot_df( df, fig_size=(550, (40 + (40 * len(df.index)))), col_width=[5, 3, 3], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict( align=["center", "right"], font=dict(color=font_color), ))) imagefile = imps.save_image("econ-softs.png", fig) return { "title": "Economy: [Finviz] Softs Futures", "imagefile": imagefile, }
def ford_command(): """Display Orders by Fidelity Customers. [Source: Fidelity]""" # Debug if imps.DEBUG: logger.debug("disc ford") order_header, df_orders = fidelity_model.get_orders() # pylint: disable=W0612 df_orders = df_orders.head(n=30).iloc[:, :-1] df_orders = df_orders.applymap(str) font_color = (["white"] * 2 + [[ "#e4003a" if boolv else "#00ACFF" for boolv in df_orders["Price Change"].str.contains("-") ]] + [["white"] * 3]) df_orders = df_orders.rename(columns={ "# Buy Orders": "# Buy's", "# Sell Orders": "# Sell's" }) df_orders.set_index("Symbol", inplace=True) df_orders = df_orders.apply(lambda x: x.str.slice(0, 30)) title = "Fidelity Customer Orders" dindex = len(df_orders.index) embeds: list = [] # Output i, i2, end = 0, 0, 15 df_pg, embeds_img, images_list = [], [], [] while i < dindex: df_pg = df_orders.iloc[i:end] df_pg.append(df_pg) fig = imps.plot_df( df_pg, fig_size=(900, (40 + (40 * dindex))), col_width=[1, 2.4, 2.35, 4, 1.5, 1.5], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict( align=["center", "center", "center", "center", "right"], font=dict(color=font_color), ))) imagefile = "disc-ford.png" imagefile = imps.save_image(imagefile, fig) if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE: image_link = imps.multi_image(imagefile) images_list.append(imagefile) else: image_link = imps.multi_image(imagefile) embeds_img.append(f"{image_link}", ) embeds.append(disnake.Embed( title=title, colour=imps.COLOR, ), ) i2 += 1 i += 15 end += 15 # Author/Footer for i in range(0, i2): embeds[i].set_author( name=imps.AUTHOR_NAME, url=imps.AUTHOR_URL, icon_url=imps.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=imps.AUTHOR_NAME, icon_url=imps.AUTHOR_ICON_URL, ) i = 0 for i in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f"Page 1 of {len(embeds)}") choices = [ disnake.SelectOption(label="Home", value="0", emoji="🟢"), ] return { "view": imps.Menu, "title": title, "embed": embeds, "choices": choices, "embeds_img": embeds_img, "images_list": images_list, }
def arktrades_command(ticker: str = "", num: int = 30): """Displays trades made by ark [cathiesark.com]""" # Debug user input if imps.DEBUG: logger.debug("dd arktrades %s", ticker) if ticker: ark_holdings = ark_model.get_ark_trades_by_ticker(ticker) if ark_holdings.empty: raise Exception( "Issue getting data from cathiesark.com. Likely no trades found.\n" ) ark_holdings["Total"] = ark_holdings["Total"] / 1_000_000 ark_holdings.rename( columns={ "shares": "Shares", "direction": "B/S", "weight": "Weight", "fund": "Fund", }, inplace=True, ) ark_holdings = ark_holdings.drop( columns=["ticker", "everything.profile.companyName"]) ark_holdings.index = pd.Series( ark_holdings.index).apply(lambda x: x.strftime("%Y-%m-%d")) df = ark_holdings.head(num) df = df.fillna(0) formats = {"Weight": "{:.2f}", "Close": "${:.2f}", "Total": "{:.2f}M"} for col, f in formats.items(): df[col] = df[col].map(lambda x: f.format(x)) # pylint: disable=W0640 title = f"Stocks: [cathiesark.com] {ticker.upper()} Trades by Ark" embeds: list = [] i, i2, end = 0, 0, 15 df_pg, embeds_img, images_list = [], [], [] while i < len(df.index): df_pg = df.iloc[i:end] df_pg.append(df_pg) fig = imps.plot_df( df_pg, fig_size=(900, (40 + (40 * 20))), col_width=[5, 8, 4, 4, 3, 5, 5], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) imagefile = imps.save_image("dd-arktrades.png", fig) if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE: image_link = imps.multi_image(imagefile) images_list.append(imagefile) else: image_link = imps.multi_image(imagefile) embeds_img.append(f"{image_link}", ) embeds.append(disnake.Embed( title=title, colour=imps.COLOR, ), ) i2 += 1 i += 15 end += 15 # Author/Footer for i in range(0, i2): embeds[i].set_author( name=imps.AUTHOR_NAME, url=imps.AUTHOR_URL, icon_url=imps.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=imps.AUTHOR_NAME, icon_url=imps.AUTHOR_ICON_URL, ) i = 0 for i in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f"Page 1 of {len(embeds)}") choices = [ disnake.SelectOption(label="Home", value="0", emoji="🟢"), ] return { "view": imps.Menu, "title": title, "embed": embeds, "choices": choices, "embeds_img": embeds_img, "images_list": images_list, }
def etfs_disc_command(sort="gainers"): """Displays ETF's Top Gainers/Decliners, Most Active [Wall Street Journal]""" # Debug if imps.DEBUG: logger.debug("etfs") df_etfs = wsj_model.etf_movers(sort, export=True) if df_etfs.empty: raise Exception("No available data found") prfx = "Most" if sort == "active" else "Top" title = f"ETF Movers ({prfx} {sort.capitalize()})" df_etfs["Price"] = pd.to_numeric(df_etfs["Price"].astype(float)) df_etfs["Price"] = df_etfs.apply(lambda x: f"${x['Price']:.2f}", axis=1) df_etfs["Change"] = df_etfs.apply( lambda x: f"${x['Chg']:.2f} (<b>{x['%Chg']:.2f}%</b>)", axis=1 ) df_etfs.set_index(" ", inplace=True) df_etfs = df_etfs.drop(columns=["Chg", "%Chg"]) df_etfs = df_etfs[ [ "Name", "Price", "Change", "Vol", ] ] dindex = len(df_etfs.index) if dindex > 15: embeds: list = [] # Output i, i2, end = 0, 0, 15 df_pg, embeds_img, images_list = [], [], [] while i < dindex: df_pg = df_etfs.iloc[i:end] df_pg.append(df_pg) fig = imps.plot_df( df_pg, fig_size=(820, (40 + (40 * dindex))), col_width=[1.1, 9, 1.5, 3, 1.5], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict(align=["center", "center", "right"]))) imagefile = "disc-etfs.png" imagefile = imps.save_image(imagefile, fig) if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE: image_link = imps.multi_image(imagefile) images_list.append(imagefile) else: image_link = imps.multi_image(imagefile) embeds_img.append( f"{image_link}", ) embeds.append( disnake.Embed( title=title, colour=imps.COLOR, ), ) i2 += 1 i += 15 end += 15 # Author/Footer for i in range(0, i2): embeds[i].set_author( name=imps.AUTHOR_NAME, url=imps.AUTHOR_URL, icon_url=imps.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=imps.AUTHOR_NAME, icon_url=imps.AUTHOR_ICON_URL, ) i = 0 for i in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f"Page 1 of {len(embeds)}") choices = [ disnake.SelectOption(label="Home", value="0", emoji="🟢"), ] output = { "view": imps.Menu, "title": title, "embed": embeds, "choices": choices, "embeds_img": embeds_img, "images_list": images_list, } else: fig = imps.plot_df( df_etfs, fig_size=(820, (40 + (40 * dindex))), col_width=[1, 9, 1.5, 3, 1.5], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict(align=["center", "center", "right"]))) imagefile = imps.save_image("disc-etfs.png", fig) output = { "title": title, "imagefile": imagefile, } return output
def shorted_command(num: int = 10): """Show most shorted stocks [Yahoo Finance]""" # Debug user input if imps.DEBUG: logger.debug("dps shorted %s", num) # Check for argument if num < 0: raise Exception("Number has to be above 0") # Retrieve data df = yahoofinance_model.get_most_shorted().head(num) if df.empty: raise Exception("No available data found") # Debug user output if imps.DEBUG: logger.debug(df.to_string()) # Output data title = "Stocks: [Yahoo Finance] Most Shorted" df.dropna(how="all", axis=1, inplace=True) df = df.replace(float("NaN"), "") # Convert and format: str into float for col in ["Volume", "Avg Vol (3 month)"]: df[col] = [ imps.unit_finder.sub(imps.unit_replacer, x) for x in df[col] ] df[col] = pd.to_numeric(df[col].astype(float)) df[col] = df[col].map(lambda x: lambda_long_number_format(x, 2)) for col in ["Price (Intraday)", "Change"]: df[col] = df[col].apply(lambda x: f"${x:.2f}") # Format "%% Change" columns then combine it into "Change" df["% Change"] = df.apply(lambda x: f"(<b>{x['% Change']}</b>)", axis=1) df["Change"] = df.apply(lambda x: f"{x['Change']} {x['% Change']}", axis=1) # Combine "Volume" columns df["Volume"] = df.apply( lambda x: f"{x['Volume']:>8} (<b>{x['Avg Vol (3 month)']:>8}</b>)", axis=1, ) df = df.drop(columns=["% Change", "Avg Vol (3 month)", "PE Ratio (TTM)"]) df.columns = [ "Ticker", "Name", "Price", "Change", "Volume (Avg)", "Mkt Cap", ] df.set_index("Ticker", inplace=True) dindex = len(df.index) if dindex > 15: embeds: list = [] # Output i, i2, end = 0, 0, 15 df_pg, embeds_img, images_list = [], [], [] while i < dindex: df_pg = df.iloc[i:end] df_pg.append(df_pg) fig = imps.plot_df( df_pg, fig_size=(950, (45 * dindex)), col_width=[2.1, 10, 2.5, 5, 5.2, 3], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict( align=["center", "center", "right"]))) imagefile = "etf-holdings.png" imagefile = imps.save_image(imagefile, fig) if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE: image_link = imps.multi_image(imagefile) images_list.append(imagefile) else: image_link = imps.multi_image(imagefile) embeds_img.append(f"{image_link}", ) embeds.append(disnake.Embed( title=title, colour=imps.COLOR, ), ) i2 += 1 i += 15 end += 15 # Author/Footer for i in range(0, i2): embeds[i].set_author( name=imps.AUTHOR_NAME, url=imps.AUTHOR_URL, icon_url=imps.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=imps.AUTHOR_NAME, icon_url=imps.AUTHOR_ICON_URL, ) i = 0 for i in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f"Page 1 of {len(embeds)}") choices = [ disnake.SelectOption(label="Home", value="0", emoji="🟢"), ] output = { "view": imps.Menu, "title": title, "embed": embeds, "choices": choices, "embeds_img": embeds_img, "images_list": images_list, } else: fig = imps.plot_df( df, fig_size=(950, (45 * dindex)), col_width=[2.1, 10, 2.5, 5, 5.2, 3], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict(align=["center", "center", "right"]))) imagefile = imps.save_image("etf-holdings.png", fig) output = { "title": title, "imagefile": imagefile, } return output
def glbonds_command(): """Global bonds overview [Wall St. Journal]""" # Debug user input if imps.DEBUG: logger.debug("econ-glbonds") # Retrieve data df = wsj_model.global_bonds() # Check for argument if df.empty: raise Exception("No available data found") df["Rate (%)"] = pd.to_numeric(df["Rate (%)"].astype(float)) df["Yld (%)"] = pd.to_numeric(df["Yld (%)"].astype(float)) df["Yld Chg (%)"] = pd.to_numeric(df["Yld Chg (%)"].astype(float)) formats = { "Rate (%)": "{:.2f}%", "Yld (%)": "{:.2f}%", "Yld Chg (%)": "<b>{:.2f}%</b>", } for col, value in formats.items(): df[col] = df[col].map(lambda x: value.format(x)) # pylint: disable=W0640 # Debug user output if imps.DEBUG: logger.debug(df.to_string()) df = df.fillna("") df = df.replace(("Government Bond", "10 Year"), ("Gov .Bond", "10yr"), regex=True) df.set_index(" ", inplace=True) df = df.set_axis( [ "Rate", "Yld", "Yld Chg", ], axis="columns", ) font_color = ["white"] * 3 + [[ "#e4003a" if boolv else "#00ACFF" for boolv in df["Yld Chg"].str.contains("-") ]] fig = imps.plot_df( df, fig_size=(500, (40 + (40 * len(df.index)))), col_width=[8, 3, 3], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict( align=["center", "right"], font=dict(color=font_color), ))) imagefile = imps.save_image("econ-glbonds.png", fig) return {"title": "Economy: [WSJ] Global Bonds", "imagefile": imagefile}
def unu_command(num: int = 20): """Unusual Options""" # Debug if imps.DEBUG: logger.debug("opt unu %s", num) pages = np.arange(0, num // 20 + 1) data_list = [] for page_num in pages: r = requests.get( f"https://app.fdscanner.com/api2/unusualvolume?p=0&page_size=20&page={int(page_num)}", headers={"User-Agent": get_user_agent()}, ) if r.status_code != 200: logger.debug("Error in fdscanner request") return pd.DataFrame(), "request error" data_list.append(r.json()) ticker, expiry, option_strike, option_type, ask, bid, oi, vol, voi = ( [], [], [], [], [], [], [], [], [], ) for data in data_list: for entry in data["data"]: ticker.append(entry["tk"]) expiry.append(entry["expiry"]) option_strike.append(float(entry["s"])) option_type.append("Put" if entry["t"] == "P" else "Call") ask.append(entry["a"]) bid.append(entry["b"]) oi.append(entry["oi"]) vol.append(entry["v"]) voi.append(entry["vol/oi"]) df = pd.DataFrame({ "Ticker": ticker, "Exp": expiry, "Strike": option_strike, "Type": option_type, "Vol/OI": voi, "Vol": vol, "OI": oi, }) if df.empty: raise Exception("No data found!\n") title = "Unusual Options" df.set_index("Ticker", inplace=True) dindex = len(df.index) if dindex > 15: embeds: list = [] # Output i, i2, end = 0, 0, 20 df_pg, embeds_img, images_list = [], [], [] while i < dindex: df_pg = df.iloc[i:end] df_pg.append(df_pg) fig = imps.plot_df( df_pg, fig_size=(650, (40 + (40 * dindex))), col_width=[3, 4, 3, 2.5, 2.5, 2, 2], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict( align=["center", "center", "right", "center", "right"]))) imagefile = "opt-unu.png" imagefile = imps.save_image(imagefile, fig) if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE: image_link = imps.multi_image(imagefile) images_list.append(imagefile) else: image_link = imps.multi_image(imagefile) embeds_img.append(f"{image_link}", ) embeds.append(disnake.Embed( title=title, colour=imps.COLOR, ), ) i2 += 1 i += 20 end += 20 # Author/Footer for i in range(0, i2): embeds[i].set_author( name=imps.AUTHOR_NAME, url=imps.AUTHOR_URL, icon_url=imps.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=imps.AUTHOR_NAME, icon_url=imps.AUTHOR_ICON_URL, ) i = 0 for i in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f"Page 1 of {len(embeds)}") choices = [ disnake.SelectOption(label="Home", value="0", emoji="🟢"), ] output = { "view": imps.Menu, "title": title, "embed": embeds, "choices": choices, "embeds_img": embeds_img, "images_list": images_list, } else: fig = imps.plot_df( df, fig_size=(650, (40 + (40 * dindex))), col_width=[3, 4, 3, 2.5, 2.5, 2, 2], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict( align=["center", "center", "right", "center", "right"]))) imagefile = imps.save_image("opt-unu.png", fig) output = { "title": "Unusual Options", "imagefile": imagefile, } return output
def borrowed_command(ticker: str = ""): """Displays borrowed shares available and fee [Stocksera.com]""" # Debug user input if imps.DEBUG: logger.debug("dd borrowed %s", ticker) # Check for argument if ticker == "": raise Exception("Stock ticker is required") df = pd.DataFrame( requests.get( f"https://stocksera.pythonanywhere.com/api/borrowed_shares/{ticker}" ).json() ) if df.empty: raise Exception("No Data Found") title = f"{ticker.upper()} Shares Available to Borrow [Stocksera]" df = df.head(200) df["changed"] = df["available"].astype(int).diff() df = df[df["changed"] != 0.0] df = df.drop(columns="changed") formats = {"fee": "{:.2f}%", "available": "{:,}"} for col, value in formats.items(): df[col] = df[col].map(lambda x: value.format(x)) # pylint: disable=W0640 df = df.rename(columns={"ticker": " ", "date_updated": "Updated"}) df.set_index(" ", inplace=True) df.columns = df.columns.str.capitalize() dindex = len(df.index) if dindex > 15: embeds: list = [] # Output i, i2, end = 0, 0, 15 df_pg, embeds_img, images_list = pd.DataFrame(), [], [] while i < dindex: df_pg = df.iloc[i:end] df_pg.append(df_pg) fig = imps.plot_df( df_pg, fig_size=(550, (40 + (40 * len(df.index)))), col_width=[1, 1, 1.5, 2], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces( cells=(dict(align=["center", "right", "right", "center"])) ) imagefile = "dd_borrowed.png" imagefile = imps.save_image(imagefile, fig) if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE: image_link = imps.multi_image(imagefile) images_list.append(imagefile) else: image_link = imps.multi_image(imagefile) embeds_img.append( f"{image_link}", ) embeds.append( disnake.Embed( title=title, colour=imps.COLOR, ), ) i2 += 1 i += 15 end += 15 # Author/Footer for i in range(0, i2): embeds[i].set_author( name=imps.AUTHOR_NAME, url=imps.AUTHOR_URL, icon_url=imps.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=imps.AUTHOR_NAME, icon_url=imps.AUTHOR_ICON_URL, ) i = 0 for i in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f"Page 1 of {len(embeds)}") choices = [ disnake.SelectOption(label="Home", value="0", emoji="🟢"), ] output = { "view": imps.Menu, "title": title, "embed": embeds, "choices": choices, "embeds_img": embeds_img, "images_list": images_list, } else: fig = imps.plot_df( df, fig_size=(550, (40 + (40 * len(df.index)))), col_width=[1, 1, 1.5, 2], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict(align=["center", "right", "right", "center"]))) imagefile = "dd_borrowed.png" imagefile = imps.save_image(imagefile, fig) output = { "title": title, "imagefile": imagefile, } return output
def performance_command(economy_group="sector"): """Performance of sectors, industry, country [Finviz]""" d_economy_group = { "sector": "Sector", "industry": "Industry", "basic_materials": "Industry (Basic Materials)", "communication_services": "Industry (Communication Services)", "consumer_cyclical": "Industry (Consumer Cyclical)", "consumer_defensive": "Industry (Consumer Defensive)", "energy": "Industry (Energy)", "financial": "Industry (Financial)", "healthcare": "Industry (Healthcare)", "industrials": "Industry (Industrials)", "real_estate": "Industry (Real Estate)", "technology": "Industry (Technology)", "utilities": "Industry (Utilities)", "country": "Country (U.S. listed stocks only)", "capitalization": "Capitalization", } # Debug user input if imps.DEBUG: logger.debug("econ-performance %s", economy_group) # Select default group if not economy_group: if imps.DEBUG: logger.debug("Use default economy_group: 'sector'") economy_group = "sector" # Check for argument possible_groups = list(d_economy_group.keys()) if economy_group not in possible_groups: possible_group_list = ", ".join(possible_groups) raise Exception(f"Select a valid group from {possible_group_list}") # nosec group = d_economy_group[economy_group] # Retrieve data df_group = finviz_model.get_valuation_performance_data(group, "performance") # Check for argument if df_group.empty: raise Exception("No available data found") # Output data df = pd.DataFrame(df_group) df["Volume"] = df["Volume"] / 1_000_000 df["Avg Volume"] = df["Avg Volume"] / 1_000_000 formats = { "Perf Month": "{:.2f}", "Perf Quart": "{:.2f}%", "Perf Half": "{:.2f}%", "Perf Year": "{:.2f}%", "Perf YTD": "{:.2f}%", "Avg Volume": "{:.0f}M", "Change": "{:.2f}%", "Volume": "{:.0f}M", } for col, value in formats.items(): df[col] = df[col].map(lambda x: value.format(x)) # pylint: disable=W0640 df = df.set_axis( [ "Name", "Week", "Month", "3 Mouth", "6 Mouth", "1 Year", "YTD", "Recom", "Avg Volume", "Rel Volume", "Change", "Volume", ], axis="columns", ) df.set_index("Name", inplace=True) df = df.fillna("-") df = df.applymap(lambda x: lambda_long_number_format(x, 2)) title = f"Economy: [WSJ] Performance {group}" dindex = len(df.index) if dindex > 2: embeds: list = [] # Output i, i2, end = 0, 0, 2 df_pg, embeds_img, images_list = pd.DataFrame(), [], [] while i < dindex: df_pg = df.iloc[i:end] df_pg.append(df_pg) fig = imps.plot_df( df_pg.transpose(), fig_size=(800, 720), col_width=[6, 10], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict(align=["center", "right"]))) imagefile = "econ_performance.png" imagefile = imps.save_image(imagefile, fig) if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE: image_link = imps.multi_image(imagefile) images_list.append(imagefile) else: image_link = imps.multi_image(imagefile) embeds_img.append( f"{image_link}", ) embeds.append( disnake.Embed( title=title, colour=imps.COLOR, ), ) i2 += 1 i += 2 end += 2 # Author/Footer for i in range(0, i2): embeds[i].set_author( name=imps.AUTHOR_NAME, url=imps.AUTHOR_URL, icon_url=imps.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=imps.AUTHOR_NAME, icon_url=imps.AUTHOR_ICON_URL, ) i = 0 for i in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f"Page 1 of {len(embeds)}") choices = [ disnake.SelectOption(label="Home", value="0", emoji="🟢"), ] output = { "view": imps.Menu, "title": title, "embed": embeds, "choices": choices, "embeds_img": embeds_img, "images_list": images_list, } else: fig = imps.plot_df( df.transpose(), fig_size=(800, 720), col_width=[6, 10], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict(align=["center", "right"]))) imagefile = imps.save_image("econ_performance.png", fig) output = { "title": title, "imagefile": imagefile, } return output
def options_run( ticker, url, expiry, dates, df_bcinfo, calls, puts, df_opt, current_price, min_strike, max_strike, min_strike2, max_strike2, max_pain, ): """Options Overview""" titles, reports, embeds, embeds_img, choices, images_list = [], [], [], [], [], [] fig = go.Figure() dmax = df_opt[["OI_call", "OI_put"]].values.max() dmin = df_opt[["OI_call", "OI_put"]].values.min() fig.add_trace( go.Scatter( x=df_opt.index, y=df_opt["OI_call"], name="Calls", mode="lines+markers", line=dict(color="#00ACFF", width=3), )) fig.add_trace( go.Scatter( x=df_opt.index, y=df_opt["OI_put"], name="Puts", mode="lines+markers", line=dict(color="#e4003a", width=3), )) fig.add_trace( go.Scatter( x=[current_price, current_price], y=[dmin, dmax], mode="lines", line=dict(color="gold", width=2), name="Current Price", )) fig.add_trace( go.Scatter( x=[max_pain, max_pain], y=[dmin, dmax], mode="lines", line=dict(color="grey", width=3, dash="dash"), name=f"Max Pain: {max_pain}", )) if imps.PLT_WATERMARK: fig.add_layout_image(imps.PLT_WATERMARK) fig.update_xaxes( range=[min_strike, max_strike], constrain="domain", ) fig.update_layout( margin=dict(l=0, r=0, t=60, b=20), template=imps.PLT_SCAT_STYLE_TEMPLATE, title=f"Open Interest for {ticker.upper()} expiring {expiry}", title_x=0.5, legend_title="", xaxis_title="Strike", yaxis_title="Open Interest (1k)", xaxis=dict(rangeslider=dict(visible=False), ), font=imps.PLT_FONT, legend=dict(yanchor="top", y=0.99, xanchor="left", x=0.01), dragmode="pan", ) imagefile = "opt-oi.png" plt_link = "" if imps.INTERACTIVE: plt_link = imps.inter_chart(fig, imagefile, callback=False) reports.append(plt_link) fig.update_layout( width=800, height=500, ) imagefile = imps.image_border(imagefile, fig=fig) if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE: image_link_oi = imps.multi_image(imagefile) images_list.append(imagefile) else: image_link_oi = imps.multi_image(imagefile) calls_df = calls[columns].rename(columns=column_map) calls_df = calls_df[calls_df["strike"] >= min_strike2] calls_df = calls_df[calls_df["strike"] <= max_strike2] calls_df["iv"] = pd.to_numeric(calls_df["iv"].astype(float)) formats = {"iv": "{:.2f}"} for col, f in formats.items(): calls_df[col] = calls_df[col].map(lambda x: f.format(x)) calls_df = calls_df.fillna("") calls_df.set_index("strike", inplace=True) if "^" not in ticker: if "-" in df_bcinfo.iloc[0, 1]: iv = f"```diff\n- {df_bcinfo.iloc[0, 1]}\n```" else: iv = f"```yaml\n {df_bcinfo.iloc[0, 1]}\n```" pfix, sfix = f"{ticker.upper()} ", f" expiring {expiry}" if expiry == dates[0]: pfix = f"{ticker.upper()} Weekly " sfix = "" titles.append(f"{ticker.upper()} Overview", ) titles.append(f"{pfix}Open Interest{sfix}", ) embeds.append( disnake.Embed( title=f"{ticker.upper()} Overview", color=imps.COLOR, ), ) embeds.append( disnake.Embed( title=f"{pfix}Open Interest{sfix}", description=plt_link, colour=imps.COLOR, ), ) choices.append( disnake.SelectOption(label=f"{ticker.upper()} Overview", value="0", emoji="🟢"), ) choices.append( disnake.SelectOption(label=f"{pfix}Open Interest{sfix}", value="1", emoji="🟢"), ) i, i2, end = 0, 0, 20 df_calls = [] dindex = len(calls_df.index) while i < dindex: df_calls = calls_df.iloc[i:end] df_calls.append(df_calls) figc = imps.plot_df( df_calls, fig_size=(1000, (40 + (40 * 20))), col_width=[3, 3, 3, 3], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) imagefile = "opt-calls.png" imagefile = imps.save_image(imagefile, figc) if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE: image_link = imps.multi_image(imagefile) images_list.append(imagefile) else: image_link = imps.multi_image(imagefile) embeds_img.append(f"{image_link}", ) titles.append(f"{pfix}Calls{sfix}", ) embeds.append( disnake.Embed( title=f"{pfix}Calls{sfix}", colour=imps.COLOR, ), ) i2 += 1 i += 20 end += 20 # Add Calls page field i, page, puts_page = 2, 0, 3 i3 = i2 + 2 choices.append( disnake.SelectOption(label="Calls Page 1", value="2", emoji="🟢"), ) for i in range(2, i3): page += 1 puts_page += 1 embeds[i].add_field(name=f"Calls Page {page}", value="_ _", inline=True) puts_df = puts[columns].rename(columns=column_map) puts_df = puts_df[puts_df["strike"] >= min_strike2] puts_df = puts_df[puts_df["strike"] <= max_strike2] puts_df["iv"] = pd.to_numeric(puts_df["iv"].astype(float)) formats = {"iv": "{:.2f}"} for col, f in formats.items(): puts_df[col] = puts_df[col].map(lambda x: f.format(x)) # pylint: disable=W0640 puts_df = puts_df.fillna("") puts_df.set_index("strike", inplace=True) pfix, sfix = f"{ticker.upper()} ", f" expiring {expiry}" if expiry == dates[0]: pfix = f"{ticker.upper()} Weekly " sfix = "" # Puts Pages i, end = 0, 20 df_puts = [] dindex = len(puts_df.index) while i < dindex: df_puts = puts_df.iloc[i:end] df_puts.append(df_puts) figp = imps.plot_df( df_puts, fig_size=(1000, (40 + (40 * 20))), col_width=[3, 3, 3, 3], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) imagefile = "opt-puts.png" imagefile = imps.save_image(imagefile, figp) if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE: image_link = imps.multi_image(imagefile) images_list.append(imagefile) else: image_link = imps.multi_image(imagefile) embeds_img.append(f"{image_link}", ) titles.append(f"{pfix}Puts{sfix}", ) embeds.append( disnake.Embed( title=f"{pfix}Puts{sfix}", colour=imps.COLOR, ), ) i2 += 1 i += 20 end += 20 # Add Puts page field i, page = 0, 0 puts_page -= 1 i2 += 2 choices.append( disnake.SelectOption(label="Puts Page 1", value=f"{puts_page}", emoji="🟢"), ) for i in range(puts_page, i2): page += 1 embeds[i].add_field(name=f"Puts Page {page}", value="_ _", inline=True) # Author/Footer for i in range(0, i2): embeds[i].set_author( name=imps.AUTHOR_NAME, url=imps.AUTHOR_URL, icon_url=imps.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=imps.AUTHOR_NAME, icon_url=imps.AUTHOR_ICON_URL, ) # Set images to Pages i = 0 img_i = 0 embeds[1].set_image(url=image_link_oi) for i in range(2, i2): embeds[i].set_image(url=embeds_img[img_i]) img_i += 1 i += 1 if url: embeds[0].set_thumbnail(url=f"{url}") else: embeds[0].set_thumbnail(url=imps.AUTHOR_ICON_URL) # Overview Section if "^" not in ticker: reports.append( f"{'':^5}*{df_bcinfo.iloc[0, 0]:^25}*{'':^5}*{df_bcinfo.iloc[1, 0]:^25}*{'':^5}\n" ) reports.append( f"{'':^8}{df_bcinfo.iloc[0, 1]:^25}{'':^5}{df_bcinfo.iloc[1, 1]:^25}\n" ) i, i2 = 2, 3 while i < 11: text = ( f"{'':^5}*{df_bcinfo.iloc[i, 0]:^25}*{'':^5}*{df_bcinfo.iloc[i2, 0]:^25}*{'':^5}\n" f"{'':^5}{df_bcinfo.iloc[i, 1]:^30}{'':^5}{df_bcinfo.iloc[i2, 1]:^25}{'':^10}\n" ) reports.append(text) i += 1 i2 += 1 embeds[0].add_field(name=f"{df_bcinfo.iloc[0, 0]}", value=iv, inline=False) embeds[0].add_field( name=f"•{df_bcinfo.iloc[1, 0]}", value=f"```css\n{df_bcinfo.iloc[1, 1]}\n```", inline=True, ) for N in range(2, 6): embeds[0].add_field( name=f"_ _ _ _ _ _ _ _ _ _ •{df_bcinfo.iloc[N, 0]}", value=f"```css\n{df_bcinfo.iloc[N, 1]}\n```", inline=True, ) embeds[0].add_field(name="_ _", value="_ _", inline=False) for N in range(6, 8): embeds[0].add_field( name=f"_ _ _ _ _ _ _ _ _ _ •{df_bcinfo.iloc[N, 0]}", value=f"```css\n{df_bcinfo.iloc[N, 1]}\n```", inline=True, ) embeds[0].add_field(name="_ _", value="_ _", inline=False) for N in range(8, 10): embeds[0].add_field( name=f"_ _ _ _ _ _ _ _ _ _ •{df_bcinfo.iloc[N, 0]}", value=f"```css\n{df_bcinfo.iloc[N, 1]}\n```", inline=True, ) embeds[0].add_field(name="_ _", value="_ _", inline=False) for N in range(10, 12): embeds[0].add_field( name=f"_ _ _ _ _ _ _ _ _ _ •{df_bcinfo.iloc[N, 0]}", value=f"```css\n{df_bcinfo.iloc[N, 1]}\n```", inline=True, ) embeds[0].set_footer(text=f"Page 1 of {len(embeds)}") return titles, reports, embeds, choices, embeds_img, images_list
def earnings_command(): """Display Upcoming Earnings. [Source: Seeking Alpha]""" # Debug if imps.DEBUG: logger.debug("earnings") df_earnings = seeking_alpha_model.get_next_earnings(2) for n_days, earning_date in enumerate(df_earnings.index.unique()): df_earn = df_earnings[earning_date == df_earnings.index][[ "Ticker", "Name" ]].dropna() df_earn.index = df_earn["Ticker"].values df_earn.drop(columns=["Ticker"], inplace=True) title = f"Earnings on {earning_date.date()}" dindex = len(df_earn.index) if dindex > 15: embeds: list = [] # Output i, i2, end = 0, 0, 15 df_pg, embeds_img, images_list = [], [], [] while i < dindex: df_pg = df_earn.iloc[i:end] df_pg.append(df_pg) fig = imps.plot_df( df_pg, fig_size=(800, (40 + (40 * dindex))), col_width=[1, 5], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict(align=["center", "left"]))) imagefile = "disc-upcoming.png" imagefile = imps.save_image(imagefile, fig) if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE: image_link = imps.multi_image(imagefile) images_list.append(imagefile) else: image_link = imps.multi_image(imagefile) embeds_img.append(f"{image_link}", ) embeds.append(disnake.Embed( title=title, colour=imps.COLOR, ), ) i2 += 1 i += 15 end += 15 # Author/Footer for i in range(0, i2): embeds[i].set_author( name=imps.AUTHOR_NAME, url=imps.AUTHOR_URL, icon_url=imps.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=imps.AUTHOR_NAME, icon_url=imps.AUTHOR_ICON_URL, ) i = 0 for i in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f"Page 1 of {len(embeds)}") choices = [ disnake.SelectOption(label="Home", value="0", emoji="🟢"), ] output = { "view": imps.Menu, "title": title, "embed": embeds, "choices": choices, "embeds_img": embeds_img, "images_list": images_list, } else: fig = imps.plot_df( df_earn, fig_size=(800, (40 + (40 * dindex))), col_width=[1, 5], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict(align=["center", "left"]))) imagefile = imps.save_image("disc-upcoming.png", fig) output = { "title": title, "imagefile": imagefile, } return output
def ownership_command( preset: str = "template", sort: str = "", limit: int = 5, ascend: bool = False ): """Displays stocks based on own share float and ownership data [Finviz]""" # Check for argument if preset == "template" or preset not in so.all_presets: raise Exception("Invalid preset selected!") # Debug if imps.DEBUG: logger.debug("scr-ownership %s %s %s %s", preset, sort, limit, ascend) # Check for argument if limit < 0: raise Exception("Number has to be above 0") # Output Data df_screen = get_screener_data( preset, "ownership", limit, ascend, ) title = "Stocks: [Finviz] Ownership Screener" if isinstance(df_screen, pd.DataFrame): if df_screen.empty: raise Exception("No data found.") df_screen = df_screen.dropna(axis="columns", how="all") if sort: if sort in so.d_cols_to_sort["ownership"]: df_screen = df_screen.sort_values( by=sort, ascending=ascend, na_position="last", ) else: similar_cmd = difflib.get_close_matches( " ".join(sort), so.d_cols_to_sort["ownership"], n=1, cutoff=0.7, ) if similar_cmd: df_screen = df_screen.sort_values( by=[similar_cmd[0]], ascending=ascend, na_position="last", ) else: raise ValueError( f"Wrong sort column provided! Select from: {', '.join(so.d_cols_to_sort['ownership'])}" ) df_screen.set_index("Ticker", inplace=True) df_screen = df_screen.head(n=limit) df_screen = df_screen.fillna("-") dindex = len(df_screen.index) df_screen = df_screen.applymap(lambda x: lambda_long_number_format(x, 2)) if dindex > 5: embeds: list = [] # Output i, i2, end = 0, 0, 5 df_pg, embeds_img, images_list = pd.DataFrame(), [], [] while i < dindex: df_pg = df_screen.iloc[i:end] df_pg.append(df_pg) fig = imps.plot_df( df_pg.transpose(), fig_size=(800, 720), col_width=[2, 1.5], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict(align=["center", "right"]))) imagefile = "scr_ownership.png" imagefile = imps.save_image(imagefile, fig) if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE: image_link = imps.multi_image(imagefile) images_list.append(imagefile) else: image_link = imps.multi_image(imagefile) embeds_img.append( f"{image_link}", ) embeds.append( disnake.Embed( title=title, colour=imps.COLOR, ), ) i2 += 1 i += 5 end += 5 # Author/Footer for i in range(0, i2): embeds[i].set_author( name=imps.AUTHOR_NAME, url=imps.AUTHOR_URL, icon_url=imps.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=imps.AUTHOR_NAME, icon_url=imps.AUTHOR_ICON_URL, ) i = 0 for i in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f"Page 1 of {len(embeds)}") choices = [ disnake.SelectOption(label="Home", value="0", emoji="🟢"), ] output = { "view": imps.Menu, "title": title, "embed": embeds, "choices": choices, "embeds_img": embeds_img, "images_list": images_list, } else: fig = imps.plot_df( df_screen.transpose(), fig_size=(800, 720), col_width=[2, 1.5], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) fig.update_traces(cells=(dict(align=["center", "right"]))) imagefile = imps.save_image("scr_ownership.png", fig) output = { "title": title, "imagefile": imagefile, } return output
def est_command(ticker: str = ""): """Displays earning estimates [Business Insider]""" # Debug if imps.DEBUG: logger.debug("dd est %s", ticker) # Check for argument if ticker == "": raise Exception("Stock ticker is required") ( df_year_estimates, df_quarter_earnings, df_quarter_revenues, ) = business_insider_model.get_estimates(ticker) if (df_quarter_revenues.empty and df_year_estimates.empty and df_quarter_earnings.empty): raise Exception("Enter a valid ticker") # Debug user output if imps.DEBUG: logger.debug(df_year_estimates.to_string()) logger.debug(df_quarter_earnings.to_string()) logger.debug(df_quarter_revenues.to_string()) images_list = [] dindex = len(df_year_estimates.index) fig = imps.plot_df( df_year_estimates, fig_size=(900, (40 + (60 * dindex))), col_width=[9, 4, 4, 4, 4], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) imagefile = imps.save_image("estimates.png", fig) if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE: link_estimates = imps.multi_image(imagefile) images_list.append(imagefile) else: link_estimates = imps.multi_image(imagefile) fig = imps.plot_df( df_quarter_earnings, fig_size=(900, (40 + (40 * 20))), col_width=[5, 5, 4, 4, 5, 4], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) imagefile = imps.save_image("earnings.png", fig) if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE: link_earnings = imps.multi_image(imagefile) images_list.append(imagefile) else: link_earnings = imps.multi_image(imagefile) fig = imps.plot_df( df_quarter_revenues, fig_size=(900, (40 + (40 * 20))), col_width=[5, 5, 4, 4, 5, 4], tbl_header=imps.PLT_TBL_HEADER, tbl_cells=imps.PLT_TBL_CELLS, font=imps.PLT_TBL_FONT, row_fill_color=imps.PLT_TBL_ROW_COLORS, paper_bgcolor="rgba(0, 0, 0, 0)", ) imagefile = imps.save_image("revenues.png", fig) if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE: link_revenues = imps.multi_image(imagefile) images_list.append(imagefile) else: link_revenues = imps.multi_image(imagefile) embeds = [ disnake.Embed( title=f"**{ticker.upper()} Year Estimates**", color=imps.COLOR, ), disnake.Embed( title=f"**{ticker.upper()} Quarter Earnings**", colour=imps.COLOR, ), disnake.Embed( title=f"**{ticker.upper()} Quarter Revenues**", colour=imps.COLOR, ), ] embeds[0].set_image(url=link_estimates) embeds[1].set_image(url=link_earnings) embeds[2].set_image(url=link_revenues) titles = [ f"**{ticker.upper()} Year Estimates**", f"**{ticker.upper()} Quarter Earnings**", f"**{ticker.upper()} Quarter Revenues**", ] embeds_img = [ f"{link_estimates}", f"{link_earnings}", f"{link_revenues}", ] # Output data choices = [ disnake.SelectOption(label=f"{ticker.upper()} Year Estimates", value="0", emoji="🟢"), disnake.SelectOption(label=f"{ticker.upper()} Quarter Earnings", value="1", emoji="🟢"), disnake.SelectOption(label=f"{ticker.upper()} Quarter Revenues", value="2", emoji="🟢"), ] return { "view": imps.Menu, "titles": titles, "embed": embeds, "choices": choices, "embeds_img": embeds_img, "images_list": images_list, }