dragon-bot/app/stock.py
2023-09-29 09:05:01 -07:00

155 lines
4.3 KiB
Python
Executable File

import discord
import requests
import yfinance as yf
import os
def parse_message(symbols, verbose):
embeds = []
bad_tickers = []
for s in symbols.split():
try:
embeds.append(get_stock(s, verbose=verbose))
except Exception as e:
bad_tickers.append(s)
if bad_tickers:
embeds.append(_make_error_embed(bad_tickers))
return embeds
def _make_error_embed(symbols):
embed = discord.Embed(
title="Errors when querying symbol data",
description="I was unable to find information from Yahoo's API for the following symbols:",
)
embed.add_field(
name="Invalid symbols",
value=", ".join(symbols),
inline=False,
)
return embed
def _add_verbose_fields(embed, request):
"""
Helper function to add verbose fields.
"""
embed.add_field(
name="Previous Close",
value="$%s" % request["regularMarketPreviousClose"],
inline=False,
)
embed.add_field(
name="Change since prev. close (as %)",
value="$%.2f (%s%%)"
% (
request["regularMarketChange"],
request["regularMarketChangePercent"],
),
inline=False,
)
if "bid" in request and "ask" in request:
embed.add_field(
name="Current bid price",
value="$%s" % request["bid"],
inline=False,
)
embed.add_field(
name="Current ask price",
value="$%s" % request["ask"],
inline=False,
)
embed.add_field(
name="Current bid-ask spread",
value="$%.2f" % (request["bid"] - request["ask"]),
inline=False,
)
embed.add_field(
name="Day's Range", value=request["regularMarketDayRange"], inline=False
)
if "marketCap" in request:
embed.add_field(
name="Market Cap", value="{:,}".format(request["marketCap"]), inline=False
)
if "sharesOutstanding" in request:
embed.add_field(
name="Shares Outstanding",
value="{:,}".format(request["sharesOutstanding"]),
inline=False,
)
return embed
def get_stock(share_name, verbose=False):
share_name = share_name.upper()
try:
os.mkdir("/root/.cache/py-yfinance")
except OSError as error:
pass
try:
request = yf.Ticker(share_name).info
except requests.exceptions.HTTPError:
raise ValueError("Invalid symbol %s: empty response from Yahoo" % share_name)
change_symbol = "+"
embed_color = 2067276
meme_url = "https://i.ytimg.com/vi/if-2M3K1tqk/hqdefault.jpg"
# If stock price has gone down since open, use red and a sad stonk meme
current_change = request["currentPrice"] - request["regularMarketOpen"]
if current_change < 0:
change_symbol = "-"
embed_color = 15158332
meme_url = "https://i.kym-cdn.com/photos/images/facebook/002/021/567/635.png"
embed = discord.Embed(description="-------", color=embed_color, type="rich")
embed.set_thumbnail(url=meme_url)
embed.set_author(name=request["shortName"])
embed.add_field(
name="Current price",
value="$%s" % request["currentPrice"],
inline=False,
)
embed.add_field(
name="Opening price",
value="$%s" % request["regularMarketOpen"],
inline=False,
)
embed.add_field(
name="Change since day open (as %)",
value="$%.2f (%.7f%%)"
% (
current_change,
current_change * 100 / request["regularMarketOpen"],
),
inline=False,
)
if verbose:
embed = _add_verbose_fields(embed, request)
chart_url = "https://www.marketwatch.com/investing/stock"
if "-" in share_name:
chart_url = "https://coinmarketcap.com/currencies"
share_name = request["shortName"].split()[0].lower()
embed.add_field(
name="Link to stock price",
value="%s/%s" % (chart_url, share_name),
inline=False,
)
embed.set_footer(
text="Pulled from https://finance.yahoo.com\nRemember, stocks can go up 10000%, but they can only go down 100%",
icon_url="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/emojidex/112/chart-with-downwards-trend_1f4c9.png",
)
return embed