1
0
mirror of https://gitlab.com/simple-stock-bots/simple-discord-stock-bot.git synced 2025-06-15 14:56:40 +00:00

Merge branch '23-pull-in-changes-from-telegram-bot' into 'master'

Resolve "Pull in changes from Telegram bot"

Closes #23

See merge request simple-stock-bots/simple-discord-stock-bot!6
This commit is contained in:
Anson Biggs 2023-04-16 21:57:33 +00:00
commit 3d453115fe
19 changed files with 832 additions and 1544 deletions

View File

@ -1,23 +1,21 @@
FROM python:3.9-buster AS builder
FROM python:3.11-buster AS builder
COPY requirements.txt /requirements.txt
RUN pip install --user -r requirements.txt
COPY dev-reqs.txt /dev-reqs.txt
RUN pip install --user -r dev-reqs.txt
FROM python:3.9-slim
FROM python:3.11-slim
ENV MPLBACKEND=Agg
COPY --from=builder /root/.local /root/.local
# Formatting
RUN pip install --no-cache-dir black
# Jupyter Notebooks
RUN pip install --no-cache-dir ipykernel
ENV DISCORD=TOKEN
ENV IEX=TOKEN
ENV MPLBACKEND=Agg
ENV DISCORD=NTMyMDQ1MjAwODIzMDI1NjY2.XDQftA.Px-arL5wDMB4XKcoPOS1r4gCGmA
ENV MARKETDATA=a01mVUZ4cW1sUUFOVWlEZ3NNTHFNeHYzS2diUUhTUVJZbzNxVVEwTUxVMD0
COPY . .

4
.gitignore vendored
View File

@ -1 +1,3 @@
__pycache__
__pycache__
.mypy_cache
nextcord.log

View File

@ -1,96 +1,34 @@
#Following instructions (as of 2020-04-01): https://docs.gitlab.com/ee/ci/docker/using_kaniko.html
#Kaniko docs are here: https://github.com/GoogleContainerTools/kaniko
#While this example shows building to multiple registries for all branches, with a few modifications
# it can be used to build non-master branches to a "dev" container registry and only build master to
# a production container registry
image:
name: gcr.io/kaniko-project/executor:debug
entrypoint: [""]
variables:
#More Information on Kaniko Caching: https://cloud.google.com/build/docs/kaniko-cache
KANIKO_CACHE_ARGS: "--cache=true --cache-copy-layers=true --cache-ttl=24h"
VERSIONLABELMETHOD: "OnlyIfThisCommitHasVersion" # options: "OnlyIfThisCommitHasVersion","LastVersionTagInGit"
IMAGE_LABELS: >
--label org.opencontainers.image.vendor=$CI_SERVER_URL/$GITLAB_USER_LOGIN
--label org.opencontainers.image.authors=$CI_SERVER_URL/$GITLAB_USER_LOGIN
--label org.opencontainers.image.revision=$CI_COMMIT_SHA
--label org.opencontainers.image.source=$CI_PROJECT_URL
--label org.opencontainers.image.documentation=$CI_PROJECT_URL
--label org.opencontainers.image.licenses=$CI_PROJECT_URL
--label org.opencontainers.image.url=$CI_PROJECT_URL
--label vcs-url=$CI_PROJECT_URL
--label com.gitlab.ci.user=$CI_SERVER_URL/$GITLAB_USER_LOGIN
--label com.gitlab.ci.email=$GITLAB_USER_EMAIL
--label com.gitlab.ci.tagorbranch=$CI_COMMIT_REF_NAME
--label com.gitlab.ci.pipelineurl=$CI_PIPELINE_URL
--label com.gitlab.ci.commiturl=$CI_PROJECT_URL/commit/$CI_COMMIT_SHA
--label com.gitlab.ci.cijoburl=$CI_JOB_URL
--label com.gitlab.ci.mrurl=$CI_PROJECT_URL/-/merge_requests/$CI_MERGE_REQUEST_ID
get-latest-git-version:
black:
stage: .pre
image:
name: alpine/git
entrypoint: [""]
rules:
- if: '$VERSIONLABELMETHOD == "LastVersionTagInGit"'
image: registry.gitlab.com/pipeline-components/black:latest
script:
- |
echo "the google kaniko container does not have git and does not have a packge manager to install it"
git clone https://github.com/GoogleContainerTools/kaniko.git
cd kaniko
echo "$(git describe --abbrev=0 --tags)" > ../VERSIONTAG.txt
echo "VERSIONTAG.txt contains $(cat ../VERSIONTAG.txt)"
artifacts:
paths:
- VERSIONTAG.txt
- black --check --verbose -- .
.build_with_kaniko:
#Hidden job to use as an "extends" template
build:master:
stage: build
image:
name: gcr.io/kaniko-project/executor:v1.9.0-debug
entrypoint: [""]
script:
- |
echo "Building and shipping image to $CI_REGISTRY_IMAGE"
#Build date for opencontainers
BUILDDATE="'$(date '+%FT%T%z' | sed -E -n 's/(\+[0-9]{2})([0-9]{2})$/\1:\2/p')'" #rfc 3339 date
IMAGE_LABELS="$IMAGE_LABELS --label org.opencontainers.image.created=$BUILDDATE --label build-date=$BUILDDATE"
#Description for opencontainers
BUILDTITLE=$(echo $CI_PROJECT_TITLE | tr " " "_")
IMAGE_LABELS="$IMAGE_LABELS --label org.opencontainers.image.title=$BUILDTITLE --label org.opencontainers.image.description=$BUILDTITLE"
#Add ref.name for opencontainers
IMAGE_LABELS="$IMAGE_LABELS --label org.opencontainers.image.ref.name=$CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME"
#Build Version Label and Tag from git tag, LastVersionTagInGit was placed by a previous job artifact
if [[ "$VERSIONLABELMETHOD" == "LastVersionTagInGit" ]]; then VERSIONLABEL=$(cat VERSIONTAG.txt); fi
if [[ "$VERSIONLABELMETHOD" == "OnlyIfThisCommitHasVersion" ]]; then VERSIONLABEL=$CI_COMMIT_TAG; fi
if [[ ! -z "$VERSIONLABEL" ]]; then
IMAGE_LABELS="$IMAGE_LABELS --label org.opencontainers.image.version=$VERSIONLABEL"
ADDITIONALTAGLIST="$ADDITIONALTAGLIST $VERSIONLABEL"
fi
ADDITIONALTAGLIST="$ADDITIONALTAGLIST $CI_COMMIT_REF_NAME $CI_COMMIT_SHORT_SHA"
if [[ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]]; then ADDITIONALTAGLIST="$ADDITIONALTAGLIST latest"; fi
if [[ -n "$ADDITIONALTAGLIST" ]]; then
for TAG in $ADDITIONALTAGLIST; do
FORMATTEDTAGLIST="${FORMATTEDTAGLIST} --tag $CI_REGISTRY_IMAGE:$TAG ";
done;
fi
#Reformat Docker tags to kaniko's --destination argument:
FORMATTEDTAGLIST=$(echo "${FORMATTEDTAGLIST}" | sed s/\-\-tag/\-\-destination/g)
echo "Kaniko arguments to run: --context $CI_PROJECT_DIR --dockerfile $CI_PROJECT_DIR/Dockerfile $KANIKO_CACHE_ARGS $FORMATTEDTAGLIST $IMAGE_LABELS"
mkdir -p /kaniko/.docker
echo "{\"auths\":{\"$CI_REGISTRY\":{\"auth\":\"$(echo -n $CI_REGISTRY_USER:$CI_REGISTRY_PASSWORD | base64)\"}}}" > /kaniko/.docker/config.json
/kaniko/executor --context $CI_PROJECT_DIR --dockerfile $CI_PROJECT_DIR/Dockerfile $KANIKO_CACHE_ARGS $FORMATTEDTAGLIST $IMAGE_LABELS
- /kaniko/executor
--context "${CI_PROJECT_DIR}"
--dockerfile "${CI_PROJECT_DIR}/Dockerfile"
--destination "${CI_REGISTRY_IMAGE}:latest"
rules:
- if: '$CI_COMMIT_BRANCH == "master"'
build-for-gitlab-project-registry:
extends: .build_with_kaniko
environment:
#This is only here for completeness, since there are no CI CD Variables with this scope, the project defaults are used
# to push to this projects docker registry
name: push-to-gitlab-project-registry
build:branch:
stage: build
image:
name: gcr.io/kaniko-project/executor:v1.9.0-debug
entrypoint: [""]
script:
- /kaniko/executor
--context "${CI_PROJECT_DIR}"
--dockerfile "${CI_PROJECT_DIR}/Dockerfile"
--destination "${CI_REGISTRY_IMAGE}:${CI_COMMIT_SHORT_SHA}"
--destination "${CI_REGISTRY_IMAGE}:${CI_COMMIT_BRANCH}"
rules:
- if: '$CI_COMMIT_BRANCH != "master"'

7
.vscode/launch.json vendored
View File

@ -1,15 +1,12 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Discord Bot",
"type": "python",
"request": "launch",
"program": "bot.py",
"console": "integratedTerminal"
"console": "integratedTerminal",
"python": "python3.11"
}
]
}

12
.vscode/settings.json vendored
View File

@ -1,13 +1,5 @@
{
"workbench.iconTheme": "vscode-icons",
"editor.suggestSelection": "first",
"vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
"python.languageServer": "Pylance",
"git.autofetch": true,
"editor.formatOnSave": true,
"files.associations": {
"DockerDev": "dockerfile",
},
"python.formatting.provider": "black",
"python.showStartPage": false,
"python.linting.mypyEnabled": true,
"python.linting.flake8Enabled": true,
}

View File

@ -1,4 +1,4 @@
"""Functions and Info specific to the Telegram Bot
"""Functions and Info specific to the discord Bot
"""
import re
@ -10,15 +10,15 @@ class D_info:
license = re.sub(
r"\b\n",
" ",
r.get(
"https://gitlab.com/simple-stock-bots/simple-discord-stock-bot/-/raw/master/LICENSE"
).text,
r.get("https://gitlab.com/simple-stock-bots/simple-discord-stock-bot/-/raw/master/LICENSE").text,
)
help_text = """
Thanks for using this bot, consider supporting it by [buying me a beer.](https://www.buymeacoffee.com/Anson)
Keep up with the latest news for the bot in its Telegram Channel: https://t.me/simplestockbotnews
If you are interested in stock market data, or want to host your own bot, be sure to use my affiliate link so that the bot can stay free: [marketdata.app](https://dashboard.marketdata.app/marketdata/aff/go/misterbiggs?keyword=discord)
Keep up with the latest news for the bot in its discord Channel: https://t.me/simplestockbotnews
Full documentation on using and running your own stock bot can be found on the bots [docs.](https://docs.simplestockbot.com)
@ -28,18 +28,15 @@ Simply calling a symbol in any message that the bot can see will also return the
**Commands**
- `/donate [amount in USD]` to donate. 🎗
- `/dividend $[symbol]` Dividend information for the symbol. 📅
- `/intra $[symbol]` Plot of the stocks movement since the last market open. 📈
- `/chart $[symbol]` Plot of the stocks movement for the past 1 month. 📊
- `/news $[symbol]` News about the symbol. 📰
- `/info $[symbol]` General information about the symbol.
- `/stat $[symbol]` Key statistics about the symbol. 🔢
- `/cap $[symbol]` Market Capitalization of symbol. 💰
- `/trending` Trending Stocks and Cryptos. 💬
- `/help` Get some help using the bot. 🆘
Market data is provided by [IEX Cloud](https://iexcloud.io)
**Inline Features**
You can type @SimpleStockBot `[search]` in any chat or direct message to search for the stock bots full list of stock and crypto symbols and return the price. Then once you select the ticker want the bot will send a message as you in that chat with the latest stock price. Prices may be delayed by up to an hour.
Market data is provided by [marketdata.app](https://dashboard.marketdata.app/marketdata/aff/go/misterbiggs?keyword=discord)
If you believe the bot is not behaving properly run `/status` or [get in touch](https://docs.simplestockbot.com/contact).
"""
@ -47,7 +44,7 @@ Simply calling a symbol in any message that the bot can see will also return the
donate_text = """
Simple Stock Bot is run entirely on donations[.](https://www.buymeacoffee.com/Anson)
All donations go directly towards paying for servers, and market data is provided by
[IEX Cloud](https://iexcloud.io/).
[marketdata.app](https://dashboard.marketdata.app/marketdata/aff/go/misterbiggs?keyword=discord).
The easiest way to donate is to run the `/donate [amount in USD]` command with US dollars you would like to donate.
@ -59,15 +56,10 @@ If you have any questions see the [website](https://docs.simplestockbot.com)
"""
commands = """
commands = """ # Not used by the bot but for updating commands with BotFather
donate - Donate to the bot 🎗
help - Get some help using the bot. 🆘
info - $[symbol] General information about the symbol.
news - $[symbol] News about the symbol. 📰
stat - $[symbol] Key statistics about the symbol. 🔢
cap - $[symbol] Market Capitalization of symbol. 💰
dividend - $[symbol] Dividend info 📅
trending - Trending Stocks and Cryptos. 💬
intra - $[symbol] Plot since the last market open. 📈
chart - $[chart] Plot of the past month. 📊
""" # Not used by the bot but for updaing commands with BotFather
"""

View File

@ -1,11 +1,11 @@
FROM python:3.9-buster AS builder
FROM python:3.11-buster AS builder
COPY requirements.txt /requirements.txt
RUN pip install --user -r requirements.txt
FROM python:3.9-slim
FROM python:3.11-slim
ENV MPLBACKEND=Agg

View File

@ -1,497 +0,0 @@
"""Class with functions for running the bot with IEX Cloud.
"""
import logging
import os
from datetime import datetime
from logging import warning
from typing import List, Optional, Tuple
import pandas as pd
import requests as r
import schedule
from Symbol import Stock
class IEX_Symbol:
"""
Functions for finding stock market information about symbols.
"""
SYMBOL_REGEX = "[$]([a-zA-Z]{1,4})"
searched_symbols = {}
otc_list = []
charts = {}
trending_cache = None
def __init__(self) -> None:
"""Creates a Symbol Object
Parameters
----------
IEX_TOKEN : str
IEX API Token
"""
try:
self.IEX_TOKEN = os.environ["IEX"]
if self.IEX_TOKEN == "TOKEN":
self.IEX_TOKEN = ""
except KeyError:
self.IEX_TOKEN = ""
warning(
"Starting without an IEX Token will not allow you to get market data!"
)
if self.IEX_TOKEN != "":
self.get_symbol_list()
schedule.every().day.do(self.get_symbol_list)
schedule.every().day.do(self.clear_charts)
def get(self, endpoint, params: dict = {}, timeout=5) -> dict:
url = "https://cloud.iexapis.com/stable" + endpoint
# set token param if it wasn't passed.
params["token"] = params.get("token", self.IEX_TOKEN)
resp = r.get(url, params=params, timeout=timeout)
# Make sure API returned a proper status code
try:
resp.raise_for_status()
except r.exceptions.HTTPError as e:
logging.error(e)
return {}
# Make sure API returned valid JSON
try:
resp_json = resp.json()
# IEX uses backtick ` as apostrophe which breaks telegram markdown parsing
if type(resp_json) is dict:
resp_json["companyName"] = resp_json.get("companyName", "").replace(
"`", "'"
)
return resp_json
except r.exceptions.JSONDecodeError as e:
logging.error(e)
return {}
def clear_charts(self) -> None:
"""
Clears cache of chart data.
Charts are cached so that only 1 API call per 24 hours is needed since the
chart data is expensive and a large download.
"""
self.charts = {}
def get_symbol_list(
self, return_df=False
) -> Optional[Tuple[pd.DataFrame, datetime]]:
"""Gets list of all symbols supported by IEX
Parameters
----------
return_df : bool, optional
return the dataframe of all stock symbols, by default False
Returns
-------
Optional[Tuple[pd.DataFrame, datetime]]
If `return_df` is set to `True` returns a dataframe, otherwise returns `None`.
"""
reg_symbols = self.get("/ref-data/symbols")
otc_symbols = self.get("/ref-data/otc/symbols")
reg = pd.DataFrame(data=reg_symbols)
otc = pd.DataFrame(data=otc_symbols)
self.otc_list = set(otc["symbol"].to_list())
symbols = pd.concat([reg, otc])
# IEX uses backtick ` as apostrophe which breaks telegram markdown parsing
symbols["name"] = symbols["name"].str.replace("`", "'")
symbols["description"] = "$" + symbols["symbol"] + ": " + symbols["name"]
symbols["id"] = symbols["symbol"]
symbols["type_id"] = "$" + symbols["symbol"].str.lower()
symbols = symbols[["id", "symbol", "name", "description", "type_id"]]
self.symbol_list = symbols
if return_df:
return symbols, datetime.now()
def status(self) -> str:
"""Checks IEX Status dashboard for any current API issues.
Returns
-------
str
Human readable text on status of IEX API
"""
if self.IEX_TOKEN == "":
return "The `IEX_TOKEN` is not set so Stock Market data is not available."
resp = r.get(
"https://pjmps0c34hp7.statuspage.io/api/v2/status.json",
timeout=15,
)
if resp.status_code == 200:
status = resp.json()["status"]
else:
return "IEX Cloud did not respond. Please check their status page for more information. https://status.iexapis.com"
if status["indicator"] == "none":
return "IEX Cloud is currently not reporting any issues with its API."
else:
return (
f"{status['indicator']}: {status['description']}."
+ " Please check the status page for more information. https://status.iexapis.com"
)
def price_reply(self, symbol: Stock) -> str:
"""Returns price movement of Stock for the last market day, or after hours.
Parameters
----------
symbol : Stock
Returns
-------
str
Formatted markdown
"""
if IEXData := self.get(f"/stock/{symbol.id}/quote"):
if symbol.symbol.upper() in self.otc_list:
return f"OTC - {symbol.symbol.upper()}, {IEXData['companyName']} most recent price is: $**{IEXData['latestPrice']}**"
keys = (
"extendedChangePercent",
"extendedPrice",
"companyName",
"latestPrice",
"changePercent",
)
if set(keys).issubset(IEXData):
if change := IEXData.get("changePercent", 0):
change = round(change * 100, 2)
else:
change = 0
if (
IEXData.get("isUSMarketOpen", True)
or (IEXData["extendedChangePercent"] is None)
or (IEXData["extendedPrice"] is None)
): # Check if market is open.
message = f"The current stock price of {IEXData['companyName']} is $**{IEXData['latestPrice']}**"
else:
message = (
f"{IEXData['companyName']} closed at $**{IEXData['latestPrice']}** with a change of {change}%,"
+ f" after hours _(15 minutes delayed)_ the stock price is $**{IEXData['extendedPrice']}**"
)
if change := IEXData.get("extendedChangePercent", 0):
change = round(change * 100, 2)
else:
change = 0
# Determine wording of change text
if change > 0:
message += f", the stock is currently **up {change}%**"
elif change < 0:
message += f", the stock is currently **down {change}%**"
else:
message += ", the stock hasn't shown any movement today."
else:
message = (
f"The symbol: {symbol} encountered and error. This could be due to "
)
else:
message = f"The symbol: {symbol} was not found."
return message
def dividend_reply(self, symbol: Stock) -> str:
"""Returns the most recent, or next dividend date for a stock symbol.
Parameters
----------
symbol : Stock
Returns
-------
str
Formatted markdown
"""
if symbol.symbol.upper() in self.otc_list:
return "OTC stocks do not currently support any commands."
if resp := self.get(f"/stock/{symbol.id}/dividends/next"):
try:
IEXData = resp[0]
except IndexError as e:
logging.info(e)
return f"Getting dividend information for ${symbol.id.upper()} encountered an error. The provider for upcoming dividend information has been having issues recently which has likely caused this error. It is also possible that the stock has no dividend or does not exist."
keys = (
"amount",
"currency",
"declaredDate",
"exDate",
"frequency",
"paymentDate",
"flag",
)
if set(keys).issubset(IEXData):
if IEXData["currency"] == "USD":
price = f"${IEXData['amount']}"
else:
price = f"{IEXData['amount']} {IEXData['currency']}"
# Pattern IEX uses for dividend date.
pattern = "%Y-%m-%d"
declared = datetime.strptime(IEXData["declaredDate"], pattern).strftime(
"%A, %B %w"
)
ex = datetime.strptime(IEXData["exDate"], pattern).strftime("%A, %B %w")
payment = datetime.strptime(IEXData["paymentDate"], pattern).strftime(
"%A, %B %w"
)
daysDelta = (
datetime.strptime(IEXData["paymentDate"], pattern) - datetime.now()
).days
return (
"The next dividend for "
+ f"{self.symbol_list[self.symbol_list['symbol']==symbol.id.upper()]['description'].item()}" # Get full name without api call
+ f" is on {payment} which is in {daysDelta} days."
+ f" The dividend is for {price} per share."
+ f"\n\nThe dividend was declared on {declared} and the ex-dividend date is {ex}"
)
return f"Getting dividend information for ${symbol.id.upper()} encountered an error. The provider for upcoming dividend information has been having issues recently which has likely caused this error. It is also possible that the stock has no dividend or does not exist."
def news_reply(self, symbol: Stock) -> str:
"""Gets most recent, english, non-paywalled news
Parameters
----------
symbol : Stock
Returns
-------
str
Formatted markdown
"""
if symbol.symbol.upper() in self.otc_list:
return "OTC stocks do not currently support any commands."
if data := self.get(f"/stock/{symbol.id}/news/last/15"):
line = []
for news in data:
if news["lang"] == "en" and not news["hasPaywall"]:
line.append(
f"*{news['source']}*: [{news['headline']}]({news['url']})"
)
return f"News for **{symbol.id.upper()}**:\n" + "\n".join(line[:5])
else:
return f"No news found for: {symbol.id}\nEither today is boring or the symbol does not exist."
def info_reply(self, symbol: Stock) -> str:
"""Gets description for Stock
Parameters
----------
symbol : Stock
Returns
-------
str
Formatted text
"""
if symbol.symbol.upper() in self.otc_list:
return "OTC stocks do not currently support any commands."
if data := self.get(f"/stock/{symbol.id}/company"):
[data.pop(k) for k in list(data) if data[k] == ""]
if "description" in data:
return data["description"]
return f"No information found for: {symbol}\nEither today is boring or the symbol does not exist."
def stat_reply(self, symbol: Stock) -> str:
"""Key statistics on a Stock
Parameters
----------
symbol : Stock
Returns
-------
str
Formatted markdown
"""
if symbol.symbol.upper() in self.otc_list:
return "OTC stocks do not currently support any commands."
if data := self.get(f"/stock/{symbol.id}/stats"):
[data.pop(k) for k in list(data) if data[k] == ""]
m = ""
if "companyName" in data:
m += f"Company Name: {data['companyName']}\n"
if "marketcap" in data:
m += f"Market Cap: ${data['marketcap']:,}\n"
if "week52high" in data:
m += f"52 Week (high-low): {data['week52high']:,} "
if "week52low" in data:
m += f"- {data['week52low']:,}\n"
if "employees" in data:
m += f"Number of Employees: {data['employees']:,}\n"
if "nextEarningsDate" in data:
m += f"Next Earnings Date: {data['nextEarningsDate']}\n"
if "peRatio" in data:
m += f"Price to Earnings: {data['peRatio']:.3f}\n"
if "beta" in data:
m += f"Beta: {data['beta']:.3f}\n"
return m
else:
return f"No information found for: {symbol}\nEither today is boring or the symbol does not exist."
def cap_reply(self, symbol: Stock) -> str:
"""Get the Market Cap of a stock"""
if data := self.get(f"/stock/{symbol.id}/stats"):
try:
cap = data["marketcap"]
except KeyError:
return f"{symbol.id} returned an error."
message = f"The current market cap of {symbol.name} is $**{cap:,.2f}**"
else:
message = f"The Stock: {symbol.name} was not found or returned and error."
return message
def intra_reply(self, symbol: Stock) -> pd.DataFrame:
"""Returns price data for a symbol since the last market open.
Parameters
----------
symbol : str
Stock symbol.
Returns
-------
pd.DataFrame
Returns a timeseries dataframe with high, low, and volume data if its available. Otherwise returns empty pd.DataFrame.
"""
if symbol.symbol.upper() in self.otc_list:
return pd.DataFrame()
if symbol.id.upper() not in list(self.symbol_list["symbol"]):
return pd.DataFrame()
if data := self.get(f"/stock/{symbol.id}/intraday-prices"):
df = pd.DataFrame(data)
df.dropna(inplace=True, subset=["date", "minute", "high", "low", "volume"])
df["DT"] = pd.to_datetime(df["date"] + "T" + df["minute"])
df = df.set_index("DT")
return df
return pd.DataFrame()
def chart_reply(self, symbol: Stock) -> pd.DataFrame:
"""Returns price data for a symbol of the past month up until the previous trading days close.
Also caches multiple requests made in the same day.
Parameters
----------
symbol : str
Stock symbol.
Returns
-------
pd.DataFrame
Returns a timeseries dataframe with high, low, and volume data if its available. Otherwise returns empty pd.DataFrame.
"""
schedule.run_pending()
if symbol.symbol.upper() in self.otc_list:
return pd.DataFrame()
if symbol.id.upper() not in list(self.symbol_list["symbol"]):
return pd.DataFrame()
try: # https://stackoverflow.com/a/3845776/8774114
return self.charts[symbol.id.upper()]
except KeyError:
pass
if data := self.get(
f"/stock/{symbol.id}/chart/1mm",
params={"chartInterval": 3, "includeToday": "false"},
):
df = pd.DataFrame(data)
df.dropna(inplace=True, subset=["date", "minute", "high", "low", "volume"])
df["DT"] = pd.to_datetime(df["date"] + "T" + df["minute"])
df = df.set_index("DT")
self.charts[symbol.id.upper()] = df
return df
return pd.DataFrame()
def spark_reply(self, symbol: Stock) -> str:
quote = self.get(f"/stock/{symbol.id}/quote")
open_change = quote.get("changePercent", 0)
after_change = quote.get("extendedChangePercent", 0)
change = 0
if open_change:
change = change + open_change
if after_change:
change = change + after_change
change = change * 100
return f"`{symbol.tag}`: {quote['companyName']}, {change:.2f}%"
def trending(self) -> list[str]:
"""Gets current coins trending on IEX. Only returns when market is open.
Returns
-------
list[str]
list of $ID: NAME, CHANGE%
"""
if data := self.get(f"/stock/market/list/mostactive"):
self.trending_cache = [
f"`${s['symbol']}`: {s['companyName']}, {100*s['changePercent']:.2f}%"
for s in data
]
return self.trending_cache

194
LICENSE
View File

@ -1,173 +1,21 @@
## creative commons
# Attribution-ShareAlike 4.0 International
Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
### Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
* __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors).
* __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensors permission is not necessary for any reasonfor example, because of any applicable exception or limitation to copyrightthen that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
## Creative Commons Attribution-ShareAlike 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
### Section 1 Definitions.
a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
c. __BY-SA Compatible License__ means a license listed at [creativecommons.org/compatiblelicenses](http://creativecommons.org/compatiblelicenses), approved by Creative Commons as essentially the equivalent of this Public License.
d. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
e. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
f. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
g. __License Elements__ means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike.
h. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
i. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
j. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
k. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
l. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
m. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
### Section 2 Scope.
a. ___License grant.___
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
A. reproduce and Share the Licensed Material, in whole or in part; and
B. produce, reproduce, and Share Adapted Material.
2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
3. __Term.__ The term of this Public License is specified in Section 6(a).
4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
5. __Downstream recipients.__
A. __Offer from the Licensor Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
B. __Additional offer from the Licensor Adapted Material.__ Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapters License You apply.
C. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
b. ___Other rights.___
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties.
### Section 3 License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
a. ___Attribution.___
1. If You Share the Licensed Material (including in modified form), You must:
A. retain the following if it is supplied by the Licensor with the Licensed Material:
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
b. ___ShareAlike.___
In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
1. The Adapters License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
### Section 4 Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
### Section 5 Disclaimer of Warranties and Limitation of Liability.
a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__
b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
### Section 6 Term and Termination.
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
### Section 7 Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
### Section 8 Interpretation.
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
> Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” The text of the Creative Commons public licenses is dedicated to the public domain under the [CC0 Public Domain Dedication](https://creativecommons.org/publicdomain/zero/1.0/legalcode). Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
>
> Creative Commons may be contacted at creativecommons.org.
MIT License
Copyright (c) 2019 Anson Biggs
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

263
MarketData.py Normal file
View File

@ -0,0 +1,263 @@
import datetime as dt
import logging
import os
from typing import Dict
import pandas as pd
import pytz
import requests as r
import schedule
from Symbol import Stock
log = logging.getLogger(__name__)
class MarketData:
"""
Functions for finding stock market information about symbols from MarkData.app
"""
SYMBOL_REGEX = "[$]([a-zA-Z]{1,4})"
charts: Dict[Stock, pd.DataFrame] = {}
openTime = dt.time(hour=9, minute=30, second=0)
marketTimeZone = pytz.timezone("US/Eastern")
def __init__(self) -> None:
"""Creates a Symbol Object
Parameters
----------
MARKETDATA_TOKEN : str
MarketData.app API Token
"""
try:
self.MARKETDATA_TOKEN = os.environ["MARKETDATA"]
if self.MARKETDATA_TOKEN == "TOKEN":
self.MARKETDATA_TOKEN = ""
except KeyError:
self.MARKETDATA_TOKEN = ""
log.warning("Starting without an MarketData.app Token will not allow you to get market data!")
log.warning("Use this affiliate link so that the bot can stay free:")
log.warning("https://dashboard.marketdata.app/marketdata/aff/go/misterbiggs?keyword=repo")
if self.MARKETDATA_TOKEN != "":
schedule.every().day.do(self.clear_charts)
def get(self, endpoint, params: dict = {}, timeout=10) -> dict:
url = "https://api.marketdata.app/v1/" + endpoint
# set token param if it wasn't passed.
params["token"] = self.MARKETDATA_TOKEN
# Undocumented query variable that ensures bot usage can be
# monitored even if someone doesn't make it through an affiliate link.
params["application"] = "simplestockbot"
resp = r.get(url, params=params, timeout=timeout)
# Make sure API returned a proper status code
try:
resp.raise_for_status()
except r.exceptions.HTTPError as e:
logging.error(e)
return {}
# Make sure API returned valid JSON
try:
resp_json = resp.json()
match resp_json["s"]:
case "ok":
return resp_json
case "no_data":
return resp_json
case "error":
logging.error("MarketData Error:\n" + resp_json["errmsg"])
return {}
except r.exceptions.JSONDecodeError as e:
logging.error(e)
return {}
def clear_charts(self) -> None:
"""
Clears cache of chart data.
Charts are cached so that only 1 API call per 24 hours is needed since the
chart data is expensive and a large download.
"""
self.charts = {}
def status(self) -> str:
# TODO: At the moment this API is poorly documented, this function likely needs to be revisited later.
try:
status = r.get(
"https://stats.uptimerobot.com/api/getMonitorList/6Kv3zIow0A",
timeout=5,
)
status.raise_for_status()
except r.HTTPError:
return f"API returned an HTTP error code {status.status_code} in {status.elapsed.total_seconds()} Seconds."
except r.Timeout:
return "API timed out before it was able to give status. This is likely due to a surge in usage or a complete outage."
statusJSON = status.json()
if statusJSON["status"] == "ok":
return (
f"CoinGecko API responded that it was OK with a {status.status_code} in {status.elapsed.total_seconds()} Seconds."
)
else:
return f"MarketData.app is currently reporting the following status: {statusJSON['status']}"
def price_reply(self, symbol: Stock) -> str:
"""Returns price movement of Stock for the last market day, or after hours.
Parameters
----------
symbol : Stock
Returns
-------
str
Formatted markdown
"""
if quoteResp := self.get(f"stocks/quotes/{symbol}/"):
price = round(quoteResp["last"][0], 2)
changePercent = round(quoteResp["changepct"][0], 2)
message = f"The current price of {symbol.name} is ${price} and "
if changePercent > 0.0:
message += f"is currently up {changePercent}% for the day."
elif changePercent < 0.0:
message += f"is currently down {changePercent}% for the day."
else:
message += "hasn't shown any movement for the day."
return message
else:
return f"Getting a quote for {symbol} encountered an error."
def spark_reply(self, symbol: Stock) -> str:
if quoteResp := self.get(f"stocks/quotes/{symbol}/"):
changePercent = round(quoteResp["changepct"][0], 2)
return f"`{symbol.tag}`: {changePercent}%"
else:
logging.warning(f"{symbol} did not have 'changepct' field.")
return f"`{symbol.tag}`"
def intra_reply(self, symbol: Stock) -> pd.DataFrame:
"""Returns price data for a symbol of the past month up until the previous trading days close.
Also caches multiple requests made in the same day.
Parameters
----------
symbol : str
Stock symbol.
Returns
-------
pd.DataFrame
Returns a timeseries dataframe with high, low, and volume data if its available. Otherwise returns empty pd.DataFrame.
"""
schedule.run_pending()
try:
return self.charts[symbol.id.upper()]
except KeyError:
pass
resolution = "15" # minutes
now = dt.datetime.now(self.marketTimeZone)
if self.openTime < now.time():
startTime = now.replace(hour=9, minute=30)
else:
startTime = now - dt.timedelta(days=1)
if data := self.get(
f"stocks/candles/{resolution}/{symbol}",
params={"from": startTime.timestamp(), "to": now.timestamp(), "extended": True},
):
data.pop("s")
df = pd.DataFrame(data)
df["t"] = pd.to_datetime(df["t"], unit="s", utc=True)
df.set_index("t", inplace=True)
df.rename(
columns={
"o": "Open",
"h": "High",
"l": "Low",
"c": "Close",
"v": "Volume",
},
inplace=True,
)
self.charts[symbol.id.upper()] = df
return df
return pd.DataFrame()
def chart_reply(self, symbol: Stock) -> pd.DataFrame:
"""Returns price data for a symbol of the past month up until the previous trading days close.
Also caches multiple requests made in the same day.
Parameters
----------
symbol : str
Stock symbol.
Returns
-------
pd.DataFrame
Returns a timeseries dataframe with high, low, and volume data if its available. Otherwise returns empty pd.DataFrame.
"""
schedule.run_pending()
try:
return self.charts[symbol.id.upper()]
except KeyError:
pass
to_date = dt.datetime.today().strftime("%Y-%m-%d")
from_date = (dt.datetime.today() - dt.timedelta(days=30)).strftime("%Y-%m-%d")
resultion = "daily"
if data := self.get(
f"stocks/candles/{resultion}/{symbol}",
params={
"from": from_date,
"to": to_date,
},
):
data.pop("s")
df = pd.DataFrame(data)
df["t"] = pd.to_datetime(df["t"], unit="s")
df.set_index("t", inplace=True)
df.rename(
columns={
"o": "Open",
"h": "High",
"l": "Low",
"c": "Close",
"v": "Volume",
},
inplace=True,
)
self.charts[symbol.id.upper()] = df
return df
return pd.DataFrame()

175
README.md
View File

@ -1,176 +1,33 @@
<div align="center">
<p align="center">
<a href="" rel="noopener">
<img width=200px height=200px src="https://assets.gitlab-static.net/uploads/-/system/project/avatar/10273693/logo.jpg" alt="Simple Discord Stock Bot"></a>
</p>
# Simple Discord Stock Bot
<h3 align="center">Simple Discord Stock Bot</h3>
<a href="https://www.buymeacoffee.com/Anson" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Beer" style="height: 51px !important;width: 217px !important;" ></a>
[![Status](https://img.shields.io/badge/status-active-success.svg)]()
[![Platform](https://img.shields.io/badge/platform-Discord-blue.svg)]()
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](/LICENSE)
[![Author](https://img.shields.io/badge/Maintainer-Anson-blue)](https://ansonbiggs.com)
</div>
## Docs
---
https://docs.simplestockbot.com/
<p align="center"> Discord Bot 🤖 that provides Stock Market information.
<br>
</p>
## Usage
## 📝 Table of Contents
https://docs.simplestockbot.com/commands/
- [About](#about)
- [How it works](#working)
- [Usage](#usage)
- [Getting Started](#getting_started)
- [Deploying your own bot](#deployment)
- [Built Using](#built_using)
- [Contributing](../CONTRIBUTING.md)
- [author](#author)
- [Acknowledgments](#acknowledgement)
## Donate
## 🧐 About <a name = "about"></a>
Simple Stock Bot is run entirely on donations, and costs about $420 a year to run. All donations go directly towards paying for servers, and premium market data provided by [marketdata.app](https://dashboard.marketdata.app/marketdata/aff/go/misterbiggs?keyword=repo).
This bot aims to be as simple as possible while providing all the information you need on the stock market. The motivation of this bot is to provide similar stock market functionality that the Google Assistant provided in [Google Allo](https://gcemetery.co/google-allo/) before the project was sunset.
The best way to donate is through [Buy Me A Coffee](https://www.buymeacoffee.com/Anson) which accepts Paypal or Credit card.
## 💭 How it works <a name = "working"></a>
If you have any questions get in [touch.](contact.md)
This bot works by using the [IEX API 2.0](https://iexcloud.io/docs/api/). Using various endpoints provided by the API, the bot can take either take commands from users or check any messages for stock symbols as detailed in [Usage](#usage).
## Other Ways to Help:
## 🎈 Usage <a name = "usage"></a>
### Basic Usage
The simplest way to use the bot is just by sending a message either as a direct message or in a group chat with the bot active. The bot will search every message for text with a dollar sign followed by a stock symbol, and it will return the full name of the company and the current trading price.
```
$tsla
```
The symbols can be anywhere in the message, and you can post as many as you like so commands such as:
```
I wonder if $aapl is down as much as $msft is today.
```
would return the stock price of both Apple and Microsoft like so:
```
The current stock price of Microsoft Corp. is $131.4, the stock is currently up 2.8%
The current stock price of Apple, Inc. is $190.15, the stock is currently up 2.66%
```
### /search `query`
This command takes any query and searches all tickers and company names that the bot supports and returns matches. The bot uses IEX Cloud so market information is limited to what they support, which is still about ~15,000 tickers so anything in a United States exchange should have support.
### /dividend \$ticker
To get information about the dividend of a stock type `/dividend` followed by any text that has symbols with a dollar sign in front of them. So, the following command:
```
/dividend $psec
```
Would return information about Prospect Capitals dividend:
```
Prospect Capital Corp. Declares June 2019 Dividend of $0.06 Per Share
The dividend is in: 38 Days 3 Hours 53 Minutes 22 Seconds.
```
💡 you can also call the dividend command using /div
### /news \$ticker
To get the latest news about a stock symbol use `/news` followed by any text that has symbols with a dollar sign in front of them. So, the following command:
```
/news $psec
```
Would return news for Prospect Capital:
News for PSEC:
[Yield-Starved Investors Still Accumulating BDCs Paying More Than 10% Annually](https://cloud.iexapis.com/v1/news/article/d994b8b5-9fbf-4ceb-afbe-e6defcfc6352)
[Assessing Main Street Capital's Results For Q1 2019 (Includes Updated Price Target And Investment Ratings Analysis)](https://cloud.iexapis.com/v1/news/article/e60899bc-5230-4388-a609-fc2b8736a7d4)
[Fully Assessing Prospect Capital's Fiscal Q3 2019 (Includes Current Recommendation And Price Target)](https://cloud.iexapis.com/v1/news/article/08881160-72c5-4f5d-885b-1751187d24eb)
### /info \$ticker
To get information about a stock type `/info` followed by any text that has symbols with a dollar sign in front of them. So, the following command:
```
/info $psec
```
Would return information about Prospect Capitals:
Company Name: [Prospect Capital Corp.](http://www.prospectstreet.com/)
Industry: Investment Managers
Sector: Finance
CEO: John Francis Barry
Description: Prospect Capital Corp. is a business development company, which engages in lending to and investing in private businesses. It also involves in generating current income and long-term capital appreciation through debt and equity investments. The company was founded on April 13, 2004 and is headquartered in New York, NY.
## 🏁 Getting Started <a name = "getting_started"></a>
You can either choose to use the hosted version of the bot by [clicking here](https://discordapp.com/oauth2/authorize?client_id=532045200823025666&permissions=2048&scope=bot) or you can host your own bot with the instructions below.
### Self Hosted Bot
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See [deployment](#deployment) for notes on how to deploy the project on a live system.
### Prerequisites
This project runs neatly in a docker container, so all that you need to run it yourself is [Docker](https://hub.docker.com/?overlay=onboarding) installed on your system.
You will also need a Discord API key which can be obtained [here.](https://discordapp.com/developers/)
Finally, you will need and IEX Cloud API key. They offer a free tier that should be enough for any private groups, more details [here.](https://iexcloud.io/)
### Installing
Once Docker is installed and you have your API keys for Discord and IEX Cloud getting the bot running on any platform is extremely easy.
Download or clone the repository to your machine and open a terminal in the project and build the Docker container.
```
docker build -t simple-discord-bot .
```
Then run the bot using your API keys.
```
docker run --detach \
-e DISCORD=DISCORD_TOKEN \
-e IEX=IEX_TOKEN \
simple-discord-bot
```
Your bot should be running! If you are new to Docker, I would recommend checking out its documentation for full control over your bot.
## 🚀 Deploying your own bot <a name = "deployment"></a>
I recommend Digital Ocean for small projects like this because it is straightforward to use and affordable. [Sign up with my referral code, and we both get some free hosting.](https://m.do.co/c/6b5df7ef55b6)
## ⛏️ Built Using <a name = "built_using"></a>
- [discord.py](https://github.com/Rapptz/discord.py) - Python Discord API Wrapper
- [Digital Ocean](https://www.digitalocean.com/) - IaaS hosting platform
## ✍️ author <a name = "author"></a>
- [Anson Biggs](https://blog.ansonbiggs.com/author/anson/) - The one and only
## 🎉 Acknowledgements <a name = "acknowledgement"></a>
- Discord for having a great bot API
- IEX Cloud for offering a free tier
- Viewers like you ♥
- Follow me on [twitter](https://twitter.com/AnsonBiggs)
- Contribute to the project on [GitLab](https://gitlab.com/simple-stock-bots) or just leave a star
- Using my referral links to host your own Bot
- [DigitalOcean](https://m.do.co/c/6b5df7ef55b6)
- [marketdata.app](https://dashboard.marketdata.app/marketdata/aff/go/misterbiggs?keyword=repo)

View File

@ -27,17 +27,13 @@ class Symbol:
class Stock(Symbol):
"""Stock Market Object. Gets data from IEX Cloud"""
"""Stock Market Object. Gets data from MarketData"""
def __init__(self, symbol: pd.DataFrame) -> None:
if len(symbol) > 1:
logging.info(f"Crypto with shared id:\n\t{symbol.id}")
symbol = symbol.head(1)
self.symbol = symbol.symbol.values[0]
self.id = symbol.id.values[0]
self.name = symbol.name.values[0]
self.tag = symbol.type_id.values[0].upper()
def __init__(self, symbol: str) -> None:
self.symbol = symbol
self.id = symbol
self.name = "$" + symbol.upper()
self.tag = "$" + symbol.lower()
class Coin(Symbol):

76
bot.py
View File

@ -3,10 +3,9 @@ import io
import logging
import os
import discord
import mplfinance as mpf
from discord.ext import commands
from discord.flags import Intents
import nextcord
from nextcord.ext import commands
from D_info import D_info
from symbol_router import Router
@ -17,17 +16,17 @@ s = Router()
d = D_info()
client = discord.Client()
intents = nextcord.Intents.default()
bot = commands.Bot(
command_prefix="/", description=d.help_text, intents=Intents.default()
)
client = nextcord.Client(intents=intents)
bot = commands.Bot(command_prefix="/", description=d.help_text, intents=intents)
logger = logging.getLogger("discord")
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger("nextcord")
logger.setLevel(logging.INFO)
handler = logging.FileHandler(filename="nextcord.log", encoding="utf-8", mode="w")
handler.setFormatter(logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s"))
logger.addHandler(handler)
@bot.event
@ -43,9 +42,7 @@ async def status(ctx: commands):
message = ""
try:
message = "Contact MisterBiggs#0465 if you need help.\n"
message += (
s.status(f"Bot recieved your message in: {bot.latency*1000:.4f}ms") + "\n"
)
message += s.status(f"Bot recieved your message in: {bot.latency*1000:.4f}ms") + "\n"
except Exception as ex:
logging.critical(ex)
@ -68,46 +65,6 @@ async def donate(ctx: commands):
await ctx.send(d.donate_text)
@bot.command()
async def stat(ctx: commands, *, sym: str):
"""Get statistics on a list of stock symbols."""
symbols = s.find_symbols(sym)
if symbols:
for reply in s.stat_reply(symbols):
await ctx.send(reply)
@bot.command()
async def dividend(ctx: commands, *, sym: str):
"""Get dividend information on a stock symbol."""
symbols = s.find_symbols(sym)
if symbols:
for reply in s.dividend_reply(symbols):
await ctx.send(reply)
@bot.command()
async def news(ctx: commands, *, sym: str):
"""Get recent english news on a stock symbol."""
symbols = s.find_symbols(sym)
if symbols:
for reply in s.news_reply(symbols):
await ctx.send(reply)
@bot.command()
async def info(ctx: commands, *, sym: str):
"""Get information of a stock ticker."""
symbols = s.find_symbols(sym)
if symbols:
for reply in s.info_reply(symbols):
await ctx.send(reply[0:1900])
@bot.command()
async def search(ctx: commands, *, query: str):
"""Search for a stock symbol using either symbol of company name."""
@ -122,9 +79,7 @@ async def search(ctx: commands, *, query: str):
@bot.command()
async def crypto(ctx: commands, _: str):
"""Get the price of a cryptocurrency using in USD."""
await ctx.send(
"Crypto now has native support. Any crypto can be called using two dollar signs: `$$eth` `$$btc` `$$doge`"
)
await ctx.send("Crypto now has native support. Any crypto can be called using two dollar signs: `$$eth` `$$btc` `$$doge`")
@bot.command()
@ -143,7 +98,6 @@ async def intra(ctx: commands, sym: str):
await ctx.send("Invalid symbol please see `/help` for usage details.")
return
with ctx.channel.typing():
buf = io.BytesIO()
mpf.plot(
df,
@ -159,7 +113,7 @@ async def intra(ctx: commands, sym: str):
# Get price so theres no request lag after the image is sent
price_reply = s.price_reply([symbol])[0]
await ctx.send(
file=discord.File(
file=nextcord.File(
buf,
filename=f"{symbol.name}:intra{datetime.date.today().strftime('%S%M%d%b%Y')}.png",
),
@ -186,7 +140,6 @@ async def chart(ctx: commands, sym: str):
await ctx.send("Invalid symbol please see `/help` for usage details.")
return
with ctx.channel.typing():
buf = io.BytesIO()
mpf.plot(
df,
@ -201,7 +154,7 @@ async def chart(ctx: commands, sym: str):
# Get price so theres no request lag after the image is sent
price_reply = s.price_reply([symbol])[0]
await ctx.send(
file=discord.File(
file=nextcord.File(
buf,
filename=f"{symbol.name}:1M{datetime.date.today().strftime('%d%b%Y')}.png",
),
@ -230,7 +183,6 @@ async def trending(ctx: commands):
@bot.event
async def on_message(message):
if message.author.id == bot.user.id:
return
if message.content:

View File

@ -1,388 +1,367 @@
"""Class with functions for running the bot with IEX Cloud.
"""
import logging
from datetime import datetime
from logging import critical, debug, error, info, warning
from typing import List, Optional, Tuple
import pandas as pd
import requests as r
import schedule
from markdownify import markdownify
from Symbol import Coin
class cg_Crypto:
"""
Functions for finding crypto info
"""
vs_currency = "usd" # simple/supported_vs_currencies for list of options
searched_symbols = {}
trending_cache = None
def __init__(self) -> None:
"""Creates a Symbol Object
Parameters
----------
IEX_TOKEN : str
IEX Token
"""
self.get_symbol_list()
schedule.every().day.do(self.get_symbol_list)
def get(self, endpoint, params: dict = {}, timeout=10) -> dict:
url = "https://api.coingecko.com/api/v3" + endpoint
resp = r.get(url, params=params, timeout=timeout)
# Make sure API returned a proper status code
try:
resp.raise_for_status()
except r.exceptions.HTTPError as e:
logging.error(e)
return {}
# Make sure API returned valid JSON
try:
resp_json = resp.json()
return resp_json
except r.exceptions.JSONDecodeError as e:
logging.error(e)
return {}
def symbol_id(self, symbol) -> str:
try:
return self.symbol_list[self.symbol_list["symbol"] == symbol]["id"].values[
0
]
except KeyError:
return ""
def get_symbol_list(
self, return_df=False
) -> Optional[Tuple[pd.DataFrame, datetime]]:
raw_symbols = self.get("/coins/list")
symbols = pd.DataFrame(data=raw_symbols)
# Removes all binance-peg symbols
symbols = symbols[~symbols["id"].str.contains("binance-peg")]
symbols["description"] = (
"$$" + symbols["symbol"].str.upper() + ": " + symbols["name"]
)
symbols = symbols[["id", "symbol", "name", "description"]]
symbols["type_id"] = "$$" + symbols["symbol"]
self.symbol_list = symbols
if return_df:
return symbols, datetime.now()
def status(self) -> str:
"""Checks CoinGecko /ping endpoint for API issues.
Returns
-------
str
Human readable text on status of CoinGecko API
"""
status = r.get(
"https://api.coingecko.com/api/v3/ping",
timeout=5,
)
try:
status.raise_for_status()
return f"CoinGecko API responded that it was OK with a {status.status_code} in {status.elapsed.total_seconds()} Seconds."
except:
return f"CoinGecko API returned an error code {status.status_code} in {status.elapsed.total_seconds()} Seconds."
def price_reply(self, coin: Coin) -> str:
"""Returns current market price or after hours if its available for a given coin symbol.
Parameters
----------
symbols : list
List of coin symbols.
Returns
-------
Dict[str, str]
Each symbol passed in is a key with its value being a human readable
markdown formatted string of the symbols price and movement.
"""
if resp := self.get(
"/simple/price",
params={
"ids": coin.id,
"vs_currencies": self.vs_currency,
"include_24hr_change": "true",
},
):
try:
data = resp[coin.id]
price = data[self.vs_currency]
change = data[self.vs_currency + "_24h_change"]
if change is None:
change = 0
except KeyError:
return f"{coin.id} returned an error."
message = f"The current price of {coin.name} is $**{price:,}**"
# Determine wording of change text
if change > 0:
message += f", the coin is currently **up {change:.3f}%** for today"
elif change < 0:
message += f", the coin is currently **down {change:.3f}%** for today"
else:
message += ", the coin hasn't shown any movement today."
else:
message = f"The price for {coin.name} is not available. If you suspect this is an error run `/status`"
return message
def intra_reply(self, symbol: Coin) -> pd.DataFrame:
"""Returns price data for a symbol since the last market open.
Parameters
----------
symbol : str
Stock symbol.
Returns
-------
pd.DataFrame
Returns a timeseries dataframe with high, low, and volume data if its available. Otherwise returns empty pd.DataFrame.
"""
if resp := self.get(
f"/coins/{symbol.id}/ohlc",
params={"vs_currency": self.vs_currency, "days": 1},
):
df = pd.DataFrame(
resp, columns=["Date", "Open", "High", "Low", "Close"]
).dropna()
df["Date"] = pd.to_datetime(df["Date"], unit="ms")
df = df.set_index("Date")
return df
return pd.DataFrame()
def chart_reply(self, symbol: Coin) -> pd.DataFrame:
"""Returns price data for a symbol of the past month up until the previous trading days close.
Also caches multiple requests made in the same day.
Parameters
----------
symbol : str
Stock symbol.
Returns
-------
pd.DataFrame
Returns a timeseries dataframe with high, low, and volume data if its available. Otherwise returns empty pd.DataFrame.
"""
if resp := self.get(
f"/coins/{symbol.id}/ohlc",
params={"vs_currency": self.vs_currency, "days": 30},
):
df = pd.DataFrame(
resp, columns=["Date", "Open", "High", "Low", "Close"]
).dropna()
df["Date"] = pd.to_datetime(df["Date"], unit="ms")
df = df.set_index("Date")
return df
return pd.DataFrame()
def stat_reply(self, symbol: Coin) -> str:
"""Gathers key statistics on coin. Mostly just CoinGecko scores.
Parameters
----------
symbol : Coin
Returns
-------
str
Preformatted markdown.
"""
if data := self.get(
f"/coins/{symbol.id}",
params={
"localization": "false",
},
):
return f"""
[{data['name']}]({data['links']['homepage'][0]}) Statistics:
Market Cap: ${data['market_data']['market_cap'][self.vs_currency]:,}
Market Cap Ranking: {data.get('market_cap_rank',"Not Available")}
CoinGecko Scores:
Overall: {data.get('coingecko_score','Not Available')}
Development: {data.get('developer_score','Not Available')}
Community: {data.get('community_score','Not Available')}
Public Interest: {data.get('public_interest_score','Not Available')}
"""
else:
return f"{symbol.symbol} returned an error."
def cap_reply(self, coin: Coin) -> str:
"""Gets market cap for Coin
Parameters
----------
coin : Coin
Returns
-------
str
Preformatted markdown.
"""
if resp := self.get(
f"/simple/price",
params={
"ids": coin.id,
"vs_currencies": self.vs_currency,
"include_market_cap": "true",
},
):
debug(resp)
try:
data = resp[coin.id]
price = data[self.vs_currency]
cap = data[self.vs_currency + "_market_cap"]
except KeyError:
return f"{coin.id} returned an error."
if cap == 0:
return f"The market cap for {coin.name} is not available for unknown reasons."
message = f"The current price of {coin.name} is $**{price:,}** and its market cap is $**{cap:,.2f}** {self.vs_currency.upper()}"
else:
message = f"The Coin: {coin.name} was not found or returned and error."
return message
def info_reply(self, symbol: Coin) -> str:
"""Gets coin description
Parameters
----------
symbol : Coin
Returns
-------
str
Preformatted markdown.
"""
if data := self.get(
f"/coins/{symbol.id}",
params={"localization": "false"},
):
try:
return markdownify(data["description"]["en"])
except KeyError:
return f"{symbol} does not have a description available."
return f"No information found for: {symbol}\nEither today is boring or the symbol does not exist."
def spark_reply(self, symbol: Coin) -> str:
change = self.get(
f"/simple/price",
params={
"ids": symbol.id,
"vs_currencies": self.vs_currency,
"include_24hr_change": "true",
},
)[symbol.id]["usd_24h_change"]
return f"`{symbol.tag}`: {symbol.name}, {change:.2f}%"
def trending(self) -> list[str]:
"""Gets current coins trending on coingecko
Returns
-------
list[str]
list of $$ID: NAME, CHANGE%
"""
coins = self.get("/search/trending")
try:
trending = []
for coin in coins["coins"]:
c = coin["item"]
sym = c["symbol"].upper()
name = c["name"]
change = self.get(
f"/simple/price",
params={
"ids": c["id"],
"vs_currencies": self.vs_currency,
"include_24hr_change": "true",
},
)[c["id"]]["usd_24h_change"]
msg = f"`$${sym}`: {name}, {change:.2f}%"
trending.append(msg)
except Exception as e:
logging.warning(e)
return self.trending_cache
self.trending_cache = trending
return trending
def batch_price(self, coins: list[Coin]) -> list[str]:
"""Gets price of a list of coins all in one API call
Parameters
----------
coins : list[Coin]
Returns
-------
list[str]
returns preformatted list of strings detailing price movement of each coin passed in.
"""
query = ",".join([c.id for c in coins])
prices = self.get(
f"/simple/price",
params={
"ids": query,
"vs_currencies": self.vs_currency,
"include_24hr_change": "true",
},
)
replies = []
for coin in coins:
if coin.id in prices:
p = prices[coin.id]
if p.get("usd_24h_change") is None:
p["usd_24h_change"] = 0
replies.append(
f"{coin.name}: ${p.get('usd',0):,} and has moved {p.get('usd_24h_change',0.0):.2f}% in the past 24 hours."
)
return replies
import logging
from typing import List
import pandas as pd
import requests as r
import schedule
from markdownify import markdownify
from Symbol import Coin
log = logging.getLogger(__name__)
class cg_Crypto:
"""
Functions for finding crypto info
"""
vs_currency = "usd" # simple/supported_vs_currencies for list of options
trending_cache: List[str] = []
def __init__(self) -> None:
self.get_symbol_list()
schedule.every().day.do(self.get_symbol_list)
def get(self, endpoint, params: dict = {}, timeout=10) -> dict:
url = "https://api.coingecko.com/api/v3" + endpoint
resp = r.get(url, params=params, timeout=timeout)
# Make sure API returned a proper status code
try:
resp.raise_for_status()
except r.exceptions.HTTPError as e:
log.error(e)
return {}
# Make sure API returned valid JSON
try:
resp_json = resp.json()
return resp_json
except r.exceptions.JSONDecodeError as e:
log.error(e)
return {}
def symbol_id(self, symbol) -> str:
try:
return self.symbol_list[self.symbol_list["symbol"] == symbol]["id"].values[0]
except KeyError:
return ""
def get_symbol_list(self):
raw_symbols = self.get("/coins/list")
symbols = pd.DataFrame(data=raw_symbols)
# Removes all binance-peg symbols
symbols = symbols[~symbols["id"].str.contains("binance-peg")]
symbols["description"] = "$$" + symbols["symbol"].str.upper() + ": " + symbols["name"]
symbols = symbols[["id", "symbol", "name", "description"]]
symbols["type_id"] = "$$" + symbols["symbol"]
self.symbol_list = symbols
def status(self) -> str:
"""Checks CoinGecko /ping endpoint for API issues.
Returns
-------
str
Human readable text on status of CoinGecko API
"""
status = r.get(
"https://api.coingecko.com/api/v3/ping",
timeout=5,
)
try:
status.raise_for_status()
return (
f"CoinGecko API responded that it was OK with a {status.status_code} in {status.elapsed.total_seconds()} Seconds."
)
except r.HTTPError:
return f"CoinGecko API returned an error code {status.status_code} in {status.elapsed.total_seconds()} Seconds."
def price_reply(self, coin: Coin) -> str:
"""Returns current market price or after hours if its available for a given coin symbol.
Parameters
----------
symbols : list
List of coin symbols.
Returns
-------
Dict[str, str]
Each symbol passed in is a key with its value being a human readable
markdown formatted string of the symbols price and movement.
"""
if resp := self.get(
"/simple/price",
params={
"ids": coin.id,
"vs_currencies": self.vs_currency,
"include_24hr_change": "true",
},
):
try:
data = resp[coin.id]
price = data[self.vs_currency]
change = data[self.vs_currency + "_24h_change"]
if change is None:
change = 0
except KeyError:
return f"{coin.id} returned an error."
message = f"The current price of {coin.name} is $**{price:,}**"
# Determine wording of change text
if change > 0:
message += f", the coin is currently **up {change:.3f}%** for today"
elif change < 0:
message += f", the coin is currently **down {change:.3f}%** for today"
else:
message += ", the coin hasn't shown any movement today."
else:
message = f"The price for {coin.name} is not available. If you suspect this is an error run `/status`"
return message
def intra_reply(self, symbol: Coin) -> pd.DataFrame:
"""Returns price data for a symbol since the last market open.
Parameters
----------
symbol : str
Stock symbol.
Returns
-------
pd.DataFrame
Returns a timeseries dataframe with high, low, and volume data if its available. Otherwise returns empty pd.DataFrame.
"""
if resp := self.get(
f"/coins/{symbol.id}/ohlc",
params={"vs_currency": self.vs_currency, "days": 1},
):
df = pd.DataFrame(resp, columns=["Date", "Open", "High", "Low", "Close"]).dropna()
df["Date"] = pd.to_datetime(df["Date"], unit="ms")
df = df.set_index("Date")
return df
return pd.DataFrame()
def chart_reply(self, symbol: Coin) -> pd.DataFrame:
"""Returns price data for a symbol of the past month up until the previous trading days close.
Also caches multiple requests made in the same day.
Parameters
----------
symbol : str
Stock symbol.
Returns
-------
pd.DataFrame
Returns a timeseries dataframe with high, low, and volume data if its available. Otherwise returns empty pd.DataFrame.
"""
if resp := self.get(
f"/coins/{symbol.id}/ohlc",
params={"vs_currency": self.vs_currency, "days": 30},
):
df = pd.DataFrame(resp, columns=["Date", "Open", "High", "Low", "Close"]).dropna()
df["Date"] = pd.to_datetime(df["Date"], unit="ms")
df = df.set_index("Date")
return df
return pd.DataFrame()
def stat_reply(self, symbol: Coin) -> str:
"""Gathers key statistics on coin. Mostly just CoinGecko scores.
Parameters
----------
symbol : Coin
Returns
-------
str
Preformatted markdown.
"""
if data := self.get(
f"/coins/{symbol.id}",
params={
"localization": "false",
},
):
return f"""
[{data['name']}]({data['links']['homepage'][0]}) Statistics:
Market Cap: ${data['market_data']['market_cap'][self.vs_currency]:,}
Market Cap Ranking: {data.get('market_cap_rank',"Not Available")}
CoinGecko Scores:
Overall: {data.get('coingecko_score','Not Available')}
Development: {data.get('developer_score','Not Available')}
Community: {data.get('community_score','Not Available')}
Public Interest: {data.get('public_interest_score','Not Available')}
"""
else:
return f"{symbol.symbol} returned an error."
def cap_reply(self, coin: Coin) -> str:
"""Gets market cap for Coin
Parameters
----------
coin : Coin
Returns
-------
str
Preformatted markdown.
"""
if resp := self.get(
"/simple/price",
params={
"ids": coin.id,
"vs_currencies": self.vs_currency,
"include_market_cap": "true",
},
):
log.debug(resp)
try:
data = resp[coin.id]
price = data[self.vs_currency]
cap = data[self.vs_currency + "_market_cap"]
except KeyError:
return f"{coin.id} returned an error."
if cap == 0:
return f"The market cap for {coin.name} is not available for unknown reasons."
message = (
f"The current price of {coin.name} is $**{price:,}** and"
+ " its market cap is $**{cap:,.2f}** {self.vs_currency.upper()}"
)
else:
message = f"The Coin: {coin.name} was not found or returned and error."
return message
def info_reply(self, symbol: Coin) -> str:
"""Gets coin description
Parameters
----------
symbol : Coin
Returns
-------
str
Preformatted markdown.
"""
if data := self.get(
f"/coins/{symbol.id}",
params={"localization": "false"},
):
try:
return markdownify(data["description"]["en"])
except KeyError:
return f"{symbol} does not have a description available."
return f"No information found for: {symbol}\nEither today is boring or the symbol does not exist."
def spark_reply(self, symbol: Coin) -> str:
change = self.get(
"/simple/price",
params={
"ids": symbol.id,
"vs_currencies": self.vs_currency,
"include_24hr_change": "true",
},
)[symbol.id]["usd_24h_change"]
return f"`{symbol.tag}`: {symbol.name}, {change:.2f}%"
def trending(self) -> list[str]:
"""Gets current coins trending on coingecko
Returns
-------
list[str]
list of $$ID: NAME, CHANGE%
"""
coins = self.get("/search/trending")
try:
trending = []
for coin in coins["coins"]:
c = coin["item"]
sym = c["symbol"].upper()
name = c["name"]
change = self.get(
"/simple/price",
params={
"ids": c["id"],
"vs_currencies": self.vs_currency,
"include_24hr_change": "true",
},
)[c["id"]]["usd_24h_change"]
msg = f"`$${sym}`: {name}, {change:.2f}%"
trending.append(msg)
except Exception as e:
log.warning(e)
return self.trending_cache
self.trending_cache = trending
return trending
def batch_price(self, coins: list[Coin]) -> list[str]:
"""Gets price of a list of coins all in one API call
Parameters
----------
coins : list[Coin]
Returns
-------
list[str]
returns preformatted list of strings detailing price movement of each coin passed in.
"""
query = ",".join([c.id for c in coins])
prices = self.get(
"/simple/price",
params={
"ids": query,
"vs_currencies": self.vs_currency,
"include_24hr_change": "true",
},
)
replies = []
for coin in coins:
if coin.id in prices:
p = prices[coin.id]
if p.get("usd_24h_change") is None:
p["usd_24h_change"] = 0
replies.append(
f"{coin.name}: ${p.get('usd',0):,} and has moved {p.get('usd_24h_change',0.0):.2f}% in the past 24 hours."
)
return replies

8
dev-reqs.txt Normal file
View File

@ -0,0 +1,8 @@
-r requirements.txt
black==23.3.0
flake8==5.0.4
Flake8-pyproject==1.2.3
pylama==8.4.1
mypy==1.2.0
types-cachetools==5.3.0.5
types-pytz==2023.3.0.0

8
pyproject.toml Normal file
View File

@ -0,0 +1,8 @@
[tool.black]
line-length = 130
[tool.flake8]
max-line-length = 130
[tool.pycodestyle]
max_line_length = 130

View File

@ -1,6 +1,6 @@
nextcord==2.0.0a5
nextcord==2.4.2
requests==2.25.1
pandas==1.2.1
pandas==2.0.0
schedule==1.0.0
mplfinance==0.12.7a5
markdownify==0.6.5

View File

@ -5,24 +5,27 @@ import datetime
import logging
import random
import re
from logging import critical, debug, error, info, warning
import pandas as pd
import schedule
from cachetools import TTLCache, cached
from cg_Crypto import cg_Crypto
from IEX_Symbol import IEX_Symbol
from MarketData import MarketData
from Symbol import Coin, Stock, Symbol
from typing import Dict
log = logging.getLogger(__name__)
class Router:
STOCK_REGEX = "(?:^|[^\\$])\\$([a-zA-Z.]{1,6})"
CRYPTO_REGEX = "[$]{2}([a-zA-Z]{1,20})"
trending_count = {}
trending_count: Dict[str, float] = {}
def __init__(self):
self.stock = IEX_Symbol()
self.stock = MarketData()
self.crypto = cg_Crypto()
schedule.every().hour.do(self.trending_decay)
@ -43,9 +46,9 @@ class Router:
t_copy.pop(dead)
self.trending_count = t_copy.copy()
info("Decayed trending symbols.")
log.info("Decayed trending symbols.")
def find_symbols(self, text: str, *, trending_weight: int = 1) -> list[Symbol]:
def find_symbols(self, text: str, *, trending_weight: int = 1) -> list[Stock | Symbol]:
"""Finds stock tickers starting with a dollar sign, and cryptocurrencies with two dollar signs
in a blob of text and returns them in a list.
@ -61,37 +64,25 @@ class Router:
"""
schedule.run_pending()
symbols = []
symbols: list[Symbol] = []
stocks = set(re.findall(self.STOCK_REGEX, text))
for stock in stocks:
sym = self.stock.symbol_list[
self.stock.symbol_list["symbol"].str.fullmatch(stock, case=False)
]
if ~sym.empty:
print(sym)
symbols.append(Stock(sym))
else:
info(f"{stock} is not in list of stocks")
# Market data lacks tools to check if a symbol is valid.
symbols.append(Stock(stock))
coins = set(re.findall(self.CRYPTO_REGEX, text))
for coin in coins:
sym = self.crypto.symbol_list[
self.crypto.symbol_list["symbol"].str.fullmatch(
coin.lower(), case=False
)
]
if ~sym.empty:
symbols.append(Coin(sym))
sym = self.crypto.symbol_list[self.crypto.symbol_list["symbol"].str.fullmatch(coin.lower(), case=False)]
if sym.empty:
log.info(f"{coin} is not in list of coins")
else:
info(f"{coin} is not in list of coins")
symbols.append(Coin(sym))
if symbols:
info(symbols)
for symbol in symbols:
self.trending_count[symbol.tag] = (
self.trending_count.get(symbol.tag, 0) + trending_weight
)
self.trending_count[symbol.tag] = self.trending_count.get(symbol.tag, 0) + trending_weight
log.debug(self.trending_count)
return symbols
return symbols
def status(self, bot_resp) -> str:
"""Checks for any issues with APIs.
@ -113,7 +104,7 @@ class Router:
{self.crypto.status()}
"""
warning(stats)
log.warning(stats)
return stats
@ -134,9 +125,9 @@ class Router:
df = pd.concat([self.stock.symbol_list, self.crypto.symbol_list])
df = df[
df["description"].str.contains(search, regex=False, case=False)
].sort_values(by="type_id", key=lambda x: x.str.len())
df = df[df["description"].str.contains(search, regex=False, case=False)].sort_values(
by="type_id", key=lambda x: x.str.len()
)
symbols = df.head(matches)
symbols["price_reply"] = symbols["type_id"].apply(
@ -162,67 +153,13 @@ class Router:
replies = []
for symbol in symbols:
info(symbol)
log.info(symbol)
if isinstance(symbol, Stock):
replies.append(self.stock.price_reply(symbol))
elif isinstance(symbol, Coin):
replies.append(self.crypto.price_reply(symbol))
else:
info(f"{symbol} is not a Stock or Coin")
return replies
def dividend_reply(self, symbols: list) -> list[str]:
"""Returns the most recent, or next dividend date for a stock symbol.
Parameters
----------
symbols : list
List of stock symbols.
Returns
-------
Dict[str, str]
Each symbol passed in is a key with its value being a human readable
formatted string of the symbols div dates.
"""
replies = []
for symbol in symbols:
if isinstance(symbol, Stock):
replies.append(self.stock.dividend_reply(symbol))
elif isinstance(symbol, Coin):
replies.append("Cryptocurrencies do no have Dividends.")
else:
debug(f"{symbol} is not a Stock or Coin")
return replies
def news_reply(self, symbols: list) -> list[str]:
"""Gets recent english news on stock symbols.
Parameters
----------
symbols : list
List of stock symbols.
Returns
-------
Dict[str, str]
Each symbol passed in is a key with its value being a human
readable markdown formatted string of the symbols news.
"""
replies = []
for symbol in symbols:
if isinstance(symbol, Stock):
replies.append(self.stock.news_reply(symbol))
elif isinstance(symbol, Coin):
# replies.append(self.crypto.news_reply(symbol))
replies.append(
"News is not yet supported for cryptocurrencies. If you have any suggestions for news sources please contatct @MisterBiggs"
)
else:
debug(f"{symbol} is not a Stock or Coin")
log.info(f"{symbol} is not a Stock or Coin")
return replies
@ -248,7 +185,7 @@ class Router:
elif isinstance(symbol, Coin):
replies.append(self.crypto.info_reply(symbol))
else:
debug(f"{symbol} is not a Stock or Coin")
log.debug(f"{symbol} is not a Stock or Coin")
return replies
@ -272,7 +209,7 @@ class Router:
elif isinstance(symbol, Coin):
return self.crypto.intra_reply(symbol)
else:
debug(f"{symbol} is not a Stock or Coin")
log.debug(f"{symbol} is not a Stock or Coin")
return pd.DataFrame()
def chart_reply(self, symbol: Symbol) -> pd.DataFrame:
@ -295,7 +232,7 @@ class Router:
elif isinstance(symbol, Coin):
return self.crypto.chart_reply(symbol)
else:
debug(f"{symbol} is not a Stock or Coin")
log.debug(f"{symbol} is not a Stock or Coin")
return pd.DataFrame()
def stat_reply(self, symbols: list[Symbol]) -> list[str]:
@ -320,7 +257,7 @@ class Router:
elif isinstance(symbol, Coin):
replies.append(self.crypto.stat_reply(symbol))
else:
debug(f"{symbol} is not a Stock or Coin")
log.debug(f"{symbol} is not a Stock or Coin")
return replies
@ -346,7 +283,7 @@ class Router:
elif isinstance(symbol, Coin):
replies.append(self.crypto.cap_reply(symbol))
else:
debug(f"{symbol} is not a Stock or Coin")
log.debug(f"{symbol} is not a Stock or Coin")
return replies
@ -371,7 +308,7 @@ class Router:
elif isinstance(symbol, Coin):
replies.append(self.crypto.spark_reply(symbol))
else:
debug(f"{symbol} is not a Stock or Coin")
log.debug(f"{symbol} is not a Stock or Coin")
return replies
@ -385,29 +322,21 @@ class Router:
List of preformatted strings to be sent to user.
"""
stocks = self.stock.trending()
# stocks = self.stock.trending()
coins = self.crypto.trending()
reply = ""
log.warning(self.trending_count)
if self.trending_count:
reply += "🔥Trending on the Stock Bot:\n`"
reply += "" * len("Trending on the Stock Bot:") + "`\n"
sorted_trending = [
s[0]
for s in sorted(self.trending_count.items(), key=lambda item: item[1])
][::-1][0:5]
sorted_trending = [s[0] for s in sorted(self.trending_count.items(), key=lambda item: item[1])][::-1][0:5]
log.warning(sorted_trending)
for t in sorted_trending:
reply += self.spark_reply(self.find_symbols(t))[0] + "\n"
if stocks:
reply += "\n\n💵Trending Stocks:\n`"
reply += "" * len("Trending Stocks:") + "`\n"
for stock in stocks:
reply += stock + "\n"
if coins:
reply += "\n\n🦎Trending Crypto:\n`"
reply += "" * len("Trending Crypto:") + "`\n"
@ -420,18 +349,12 @@ class Router:
if reply:
return reply
else:
warning("Failed to collect trending data.")
log.warning("Failed to collect trending data.")
return "Trending data is not currently available."
def random_pick(self) -> str:
choice = random.choice(
list(self.stock.symbol_list["description"])
+ list(self.crypto.symbol_list["description"])
)
hold = (
datetime.date.today() + datetime.timedelta(random.randint(1, 365))
).strftime("%b %d, %Y")
choice = random.choice(list(self.stock.symbol_list["description"]) + list(self.crypto.symbol_list["description"]))
hold = (datetime.date.today() + datetime.timedelta(random.randint(1, 365))).strftime("%b %d, %Y")
return f"{choice}\nBuy and hold until: {hold}"
@ -459,10 +382,9 @@ class Router:
elif isinstance(symbol, Coin):
coins.append(symbol)
else:
debug(f"{symbol} is not a Stock or Coin")
log.debug(f"{symbol} is not a Stock or Coin")
if stocks:
# IEX batch endpoint doesnt seem to be working right now
for stock in stocks:
replies.append(self.stock.price_reply(stock))
if coins:

33
tests.py Normal file
View File

@ -0,0 +1,33 @@
import keyboard
import time
tests = """$$xno
/info $tsla
/info $$btc
/news $tsla
/news $$btc
/stat $tsla
/stat $$btc
/cap $tsla
/cap $$btc
/dividend $tsla
/dividend $msft
/dividend $$btc
/intra $tsla
/intra $$btc
/chart $tsla
/chart $$btc
/help
/trending""".split(
"\n"
)
print("press enter to start")
keyboard.wait("enter")
for test in tests:
print(test)
keyboard.write(test)
time.sleep(1)
keyboard.press_and_release("enter")