dragon-bot/app/stock.py

168 lines
4.9 KiB
Python
Executable File

import discord
import requests
def parse_message(symbols, verbose):
embeds = []
bad_tickers = []
for s in symbols.split():
try:
embeds.append(get_stock(s, verbose=verbose))
except:
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"]["raw"],
inline=False,
)
embed.add_field(
name="Change since prev. close (as %)",
value="$%.2f (%s%%)"
% (
request["regularMarketChange"]["raw"],
request["regularMarketChangePercent"]["raw"],
),
inline=False,
)
if "bid" in request and "ask" in request:
embed.add_field(
name="Current bid price",
value="$%s" % request["bid"]["raw"],
inline=False,
)
embed.add_field(
name="Current ask price",
value="$%s" % request["ask"]["raw"],
inline=False,
)
embed.add_field(
name="Current bid-ask spread",
value="$%.2f" % (request["bid"]["raw"] - request["ask"]["raw"]),
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()
# Fake headers to make yahoo happy
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"
}
request_string = (
"https://query2.finance.yahoo.com/v11/finance/quoteSummary/%s?modules=price"
% share_name
)
response = requests.get(request_string, headers=headers).json()["quoteSummary"][
"result"
]
if not response:
raise ValueError("Invalid symbol %s: empty response from Yahoo" % share_name)
request = response[0]["price"]
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["regularMarketPrice"]["raw"] - request["regularMarketOpen"]["raw"]
)
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"])
if "postMarketPrice" in request:
embed.add_field(
name="After Hours price",
value="$%s" % request["postMarketPrice"]["raw"],
inline=False,
)
embed.add_field(
name="Current price",
value="$%s" % request["regularMarketPrice"]["raw"],
inline=False,
)
embed.add_field(
name="Opening price",
value="$%s" % request["regularMarketOpen"]["raw"],
inline=False,
)
embed.add_field(
name="Change since day open (as %)",
value="$%.2f (%.7f%%)"
% (
current_change,
current_change * 100 / request["regularMarketOpen"]["raw"],
),
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 100000%, 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