mirror of
https://gitlab.com/simple-stock-bots/simple-stock-bot.git
synced 2026-06-03 21:00:26 +00:00
Compare commits
282 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 262ae7c534 | |||
| 4ed8c59828 | |||
| 86349deba4 | |||
| 22ed74d194 | |||
| e63dc7f46b | |||
| 928a23c8c6 | |||
| 580fcbb84d | |||
| 322dffa2f2 | |||
| a2a4556c0d | |||
| c2d73815f6 | |||
| 06e1f62fff | |||
| 633cc5bb41 | |||
| ccc44bfa21 | |||
| 2bb825d721 | |||
| 78d3447439 | |||
| a9b157cb4d | |||
| 6d269c7466 | |||
| d26a3cfc78 | |||
| 579421f4ab | |||
| 727e08a309 | |||
| f67cb398ac | |||
| c34af4cd40 | |||
| 8919e945f0 | |||
| e59dbf005c | |||
| 465e60e016 | |||
| 4f7aff9db2 | |||
| 9d510fc104 | |||
| d533c2c4a2 | |||
| 87aeafc77f | |||
| 2f3cef4ec4 | |||
| 7785e153f4 | |||
| e1c714f6ce | |||
| 2a06251ac7 | |||
| 0577018284 | |||
| a9eaf7c6db | |||
| 0374f5b789 | |||
| 29e9221970 | |||
| e36082334c | |||
| 9bb732a261 | |||
| c81e4ffb00 | |||
| 621e8a75c3 | |||
| 20ec52fc22 | |||
| e08573ff7c | |||
| e8aeba478c | |||
| e9639f3538 | |||
| 2cf0adcb22 | |||
| 28a3ff2960 | |||
| 553b958cc1 | |||
| 82469f1034 | |||
| e5013d8c69 | |||
| 3901c1ae73 | |||
| da4731e349 | |||
| cf25a7b9dc | |||
| 88a9b3aa63 | |||
| 4f5c558588 | |||
| 6e21565f2b | |||
| a583cad741 | |||
| dcce2cb95a | |||
| 0877949a89 | |||
| 0649789bf8 | |||
| c7f083b2b1 | |||
| 99fdd6e8be | |||
| e56679f29f | |||
| 42bb17dd40 | |||
| 082c42c39f | |||
| f34fd37597 | |||
| 0bac96cbd7 | |||
| dc75b7948c | |||
| c5b56bb345 | |||
| ccc8326495 | |||
| ec5d1fa195 | |||
| 46ddef206c | |||
| 7a20d8d6a3 | |||
| edb9dad961 | |||
| 5ec26f48a1 | |||
| 1bbbaa5f4e | |||
| 0eab043e09 | |||
| 89e8566427 | |||
| a09f8aec24 | |||
| bea03c73e3 | |||
| 9e72b8d834 | |||
| 55e4fe5d70 | |||
| 6d2b9309d7 | |||
| 390a6199ad | |||
| bd8a992de3 | |||
| 5f09744914 | |||
| 2e9bf6e673 | |||
| 24220cd0cc | |||
| bfeb28833a | |||
| 71c0272445 | |||
| cb92127ecd | |||
| 371b4505eb | |||
| 43976e873a | |||
| acc0ebdd28 | |||
| baf45e09c8 | |||
| ae0075b986 | |||
| 6baf893823 | |||
| 55bf78a57b | |||
| 3435ac1528 | |||
| 08f140af8e | |||
| 14c50deb82 | |||
| 2fa26c4662 | |||
| aba7120889 | |||
| c082761990 | |||
| e6ebd81928 | |||
| 15a62b7989 | |||
| a07d29cbfe | |||
| fcd6afec60 | |||
| d8bbfb057f | |||
| f9b8921ba8 | |||
| 610dbc3492 | |||
| 8e6425e756 | |||
| 0b44321754 | |||
| e7fa0ced5c | |||
| 1d884110e6 | |||
| f5195700a6 | |||
| 6df703bd1e | |||
| fc454d8623 | |||
| 26ddc267ff | |||
| 75355309bc | |||
| 7f9080d887 | |||
| 3e4945cffd | |||
| a4948fd566 | |||
| 85b8101cf6 | |||
| 26a838c000 | |||
| 6d955e8fb9 | |||
| 144dd1d218 | |||
| 8dd3ef772f | |||
| 1e60827a66 | |||
| a979de2272 | |||
| 0bef01450f | |||
| 00b17501ab | |||
| e061eb20cc | |||
| f4adfb1915 | |||
| a4befde8ce | |||
| f1838ba012 | |||
| 2844fd2a55 | |||
| 2e8cefcbfd | |||
| 042e50cc26 | |||
| 15fcf64caf | |||
| bd64742c39 | |||
| ff3083a8e5 | |||
| cb2f214096 | |||
| f65704b0be | |||
| 621de911cd | |||
| b2c325bddb | |||
| 367fab669f | |||
| 6ab7f2c25d | |||
| e1ed5fbf57 | |||
| 1c02980e69 | |||
| ee406fcf88 | |||
| 089e3344d4 | |||
| 30f4f190df | |||
| d8884bce13 | |||
| c2cb853db0 | |||
| cb8a7ccad8 | |||
| 2f1eb6dcd6 | |||
| f7dc433ec7 | |||
| 19c2daa9f9 | |||
| e08f3c4275 | |||
| 6e37e541d6 | |||
| 487ab10933 | |||
| 728f433fe1 | |||
| 2422489bba | |||
| 96321d7c07 | |||
| b10517e025 | |||
| bbb73c8405 | |||
| 9b100f4926 | |||
| a44008234a | |||
| 15be601a38 | |||
| cbb2c6b422 | |||
| 0368834159 | |||
| 78218834e4 | |||
| bff2e40411 | |||
| d99e7bc84a | |||
| 0b887b7042 | |||
| e6438ab89d | |||
| 554928db7e | |||
| a5505ab30c | |||
| 19c84c1cd6 | |||
| 3c9e1200d4 | |||
| 1e60528a08 | |||
| 0b01ddea15 | |||
| fa67a62b5f | |||
| fb9ff6b651 | |||
| 1e3ebbb71b | |||
| b5f1976d9e | |||
| 7d018b78b5 | |||
| ecbbfcd9d6 | |||
| 6dd033b7c2 | |||
| 72e912319f | |||
| 19655f02de | |||
| ba1f43b593 | |||
| f02ab0d14b | |||
| 71db661d72 | |||
| 11d64ab413 | |||
| 6c1c9ac420 | |||
| 4ab1750634 | |||
| 38853582d1 | |||
| d68b65d9e1 | |||
| 4578ad43f1 | |||
| 2016fba6b9 | |||
| dc2d1648ac | |||
| 0098432514 | |||
| 81c42000d8 | |||
| 4de494d1d2 | |||
| bce583fcf6 | |||
| f184fbe51d | |||
| c4d984a751 | |||
| ee58fb186e | |||
| 0f20486fae | |||
| 85d5cc9a30 | |||
| 28f2ba2320 | |||
| 78b412ebff | |||
| b3e628023b | |||
| 6cfbbeb992 | |||
| 7090da8fea | |||
| e603c5345a | |||
| 4cc4a2cda6 | |||
| df68df5e20 | |||
| c76784647c | |||
| 7ec1c02a8b | |||
| 68d66b833f | |||
| 463b2f1c3b | |||
| fdf338a9c3 | |||
| f90aa14f24 | |||
| fb4990c96c | |||
| d495932cf8 | |||
| 9c0abb0946 | |||
| 7e7fbbceb2 | |||
| c994afddf6 | |||
| 5fea3efee5 | |||
| 9552ef169f | |||
| 28a90b2472 | |||
| 1a7cfb71b6 | |||
| 3b96fdf4ed | |||
| 3c22fe4d5c | |||
| f213f1e7e7 | |||
| e1ff4a3d56 | |||
| e7c94d51c8 | |||
| c48c53746d | |||
| e647cbc8ac | |||
| 3a454083a5 | |||
| aab4a4354e | |||
| 53d655fa48 | |||
| c7634967f6 | |||
| 63e5344e86 | |||
| 3c506e124f | |||
| baf3757206 | |||
| a180e9f360 | |||
| 33c80bd75b | |||
| 38fcf6d054 | |||
| b716ef3bfb | |||
| 11f2146b7b | |||
| 685e4b94e6 | |||
| de2b3e5398 | |||
| 211fd0e2a9 | |||
| fd1baad811 | |||
| 99f0bf68d1 | |||
| d341c7b1bb | |||
| 6fcceab32e | |||
| 381ecf3bf1 | |||
| 6183ce33d3 | |||
| 7775bdc70a | |||
| 4f5f56f874 | |||
| da5d071f34 | |||
| 4da5d9933f | |||
| 230f6fdeac | |||
| a195c87b6e | |||
| c49a2c321e | |||
| bc09be8ea4 | |||
| 14ced9682a | |||
| 6b679963dd | |||
| 3113c17efb | |||
| bfca21f176 | |||
| d5533909a0 | |||
| 9f87a86bde | |||
| 74e63bb697 | |||
| 8589082439 | |||
| 369f6d9efa | |||
| 1f474dca46 | |||
| d7d0962eea |
@@ -0,0 +1,20 @@
|
|||||||
|
FROM python:3.11-buster AS builder
|
||||||
|
|
||||||
|
|
||||||
|
COPY requirements.txt /requirements.txt
|
||||||
|
RUN pip install --user -r requirements.txt
|
||||||
|
|
||||||
|
|
||||||
|
FROM python:3.11-slim
|
||||||
|
|
||||||
|
ENV MPLBACKEND=Agg
|
||||||
|
|
||||||
|
COPY --from=builder /root/.local /root/.local
|
||||||
|
|
||||||
|
RUN pip install --no-cache-dir black
|
||||||
|
ENV TELEGRAM=TOKEN
|
||||||
|
ENV IEX=TOKEN
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# CMD [ "python", "./bot.py" ]
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
|
||||||
|
// https://github.com/microsoft/vscode-dev-containers/tree/v0.191.0/containers/docker-existing-dockerfile
|
||||||
|
{
|
||||||
|
"name": "DockerDev",
|
||||||
|
// Sets the run context to one level up instead of the .devcontainer folder.
|
||||||
|
"context": "..",
|
||||||
|
// Update the 'dockerFile' property if you aren't using the standard 'Dockerfile' filename.
|
||||||
|
"dockerFile": "Dockerfile",
|
||||||
|
// Set *default* container specific settings.json values on container create.
|
||||||
|
"settings": {},
|
||||||
|
// Add the IDs of extensions you want installed when the container is created.
|
||||||
|
"extensions": [
|
||||||
|
"ms-python.python",
|
||||||
|
"ms-azuretools.vscode-docker"
|
||||||
|
]
|
||||||
|
// Use 'forwardPorts' to make a list of ports inside the container available locally.
|
||||||
|
// "forwardPorts": [],
|
||||||
|
// Uncomment the next line to run commands after the container is created - for example installing curl.
|
||||||
|
// "postCreateCommand": "apt-get update && apt-get install -y curl",
|
||||||
|
// Uncomment when using a ptrace-based debugger like C++, Go, and Rust
|
||||||
|
// "runArgs": [ "--cap-add=SYS_PTRACE", "--security-opt", "seccomp=unconfined" ],
|
||||||
|
// Uncomment to use the Docker CLI from inside the container. See https://aka.ms/vscode-remote/samples/docker-from-docker.
|
||||||
|
// "mounts": [ "source=/var/run/docker.sock,target=/var/run/docker.sock,type=bind" ],
|
||||||
|
// Uncomment to connect as a non-root user if you've added one. See https://aka.ms/vscode-remote/containers/non-root.
|
||||||
|
// "remoteUser": "vscode"
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
__pycache__
|
||||||
+33
-20
@@ -1,21 +1,34 @@
|
|||||||
stages:
|
black:
|
||||||
- docs
|
stage: .pre
|
||||||
|
image: registry.gitlab.com/pipeline-components/black:latest
|
||||||
pages:
|
|
||||||
stage: docs
|
|
||||||
image: python:alpine
|
|
||||||
|
|
||||||
before_script:
|
|
||||||
- pip install mkdocs
|
|
||||||
- pip install mkdocs-material
|
|
||||||
|
|
||||||
script:
|
script:
|
||||||
- cd ./web
|
- black --check --verbose -- .
|
||||||
- mkdocs build
|
|
||||||
- mv site ../public
|
|
||||||
- cd ../
|
build:master:
|
||||||
artifacts:
|
stage: build
|
||||||
paths:
|
image:
|
||||||
- public
|
name: gcr.io/kaniko-project/executor:v1.9.0-debug
|
||||||
only:
|
entrypoint: [""]
|
||||||
- documentation
|
script:
|
||||||
|
- /kaniko/executor
|
||||||
|
--context "${CI_PROJECT_DIR}"
|
||||||
|
--dockerfile "${CI_PROJECT_DIR}/Dockerfile"
|
||||||
|
--destination "${CI_REGISTRY_IMAGE}:latest"
|
||||||
|
rules:
|
||||||
|
- if: '$CI_COMMIT_BRANCH == "master"'
|
||||||
|
|
||||||
|
|
||||||
|
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"'
|
||||||
Vendored
+12
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"name": "Telegram Bot",
|
||||||
|
"type": "python",
|
||||||
|
"request": "launch",
|
||||||
|
"program": "bot.py",
|
||||||
|
"console": "integratedTerminal",
|
||||||
|
"python": "python3.11"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
Vendored
+5
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"python.formatting.provider": "black",
|
||||||
|
"python.linting.mypyEnabled": true,
|
||||||
|
"python.linting.flake8Enabled": true,
|
||||||
|
}
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
FROM python:3.11-buster AS builder
|
||||||
|
|
||||||
|
|
||||||
|
COPY requirements.txt /requirements.txt
|
||||||
|
RUN pip install --user -r requirements.txt
|
||||||
|
|
||||||
|
|
||||||
|
FROM python:3.11-slim
|
||||||
|
|
||||||
|
ENV MPLBACKEND=Agg
|
||||||
|
|
||||||
|
COPY --from=builder /root/.local /root/.local
|
||||||
|
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
CMD [ "python", "./bot.py" ]
|
||||||
+223
@@ -0,0 +1,223 @@
|
|||||||
|
"""Class with functions for running the bot with IEX Cloud.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import datetime as dt
|
||||||
|
from logging import warning
|
||||||
|
from typing import Dict
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
import requests as r
|
||||||
|
import schedule
|
||||||
|
|
||||||
|
from Symbol import Stock
|
||||||
|
|
||||||
|
|
||||||
|
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] = {}
|
||||||
|
|
||||||
|
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 = ""
|
||||||
|
warning("Starting without an MarketData.app Token will not allow you to get market data!")
|
||||||
|
|
||||||
|
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"] = params.get("token", self.MARKETDATA_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()
|
||||||
|
|
||||||
|
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:
|
||||||
|
return "status isnt implemented by marketdata.app"
|
||||||
|
|
||||||
|
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 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 = "5" # minutes
|
||||||
|
|
||||||
|
if data := self.get(
|
||||||
|
f"stocks/candles/{resolution}/{symbol}",
|
||||||
|
params={
|
||||||
|
"from": dt.datetime.now().strftime("%Y-%m-%d"),
|
||||||
|
"to": dt.datetime.now().isoformat(),
|
||||||
|
},
|
||||||
|
):
|
||||||
|
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()
|
||||||
|
|
||||||
|
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()
|
||||||
@@ -1,5 +1,32 @@
|
|||||||
# simple-telegram-bot
|
# Simple Telegram Stock Bot
|
||||||
|
|
||||||
## A Telegram Bot for stock market Data.
|
|
||||||
|
|
||||||
## Full documentation [here.](https://misterbiggs.gitlab.io/simple-telegram-bot)
|
[](https://t.me/SimpleStockBot)
|
||||||
|
[](/LICENSE)
|
||||||
|
[](https://ansonbiggs.com)
|
||||||
|
|
||||||
|
## Docs
|
||||||
|
|
||||||
|
https://docs.simplestockbot.com/
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
https://docs.simplestockbot.com/commands/
|
||||||
|
|
||||||
|
## Donate
|
||||||
|
|
||||||
|
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 [IEX Cloud](https://iexcloud.io/).
|
||||||
|
|
||||||
|
The best way to donate is through [Buy Me A Coffee](https://www.buymeacoffee.com/Anson) which accepts Paypal or Credit card.
|
||||||
|
|
||||||
|
Alternatively, you can donate on Telegram with the `/donate` [command](commands.md#donate-amount-in-usd).
|
||||||
|
|
||||||
|
If you have any questions get in [touch.](contact.md)
|
||||||
|
|
||||||
|
## Other Ways to Help:
|
||||||
|
|
||||||
|
- 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)
|
||||||
|
- [IEX Cloud](https://iexcloud.io/s/62c8503e)
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import pandas as pd
|
||||||
|
import logging
|
||||||
|
|
||||||
|
|
||||||
|
class Symbol:
|
||||||
|
"""
|
||||||
|
symbol: What the user calls it. ie tsla or btc
|
||||||
|
id: What the api expects. ie tsla or bitcoin
|
||||||
|
name: Human readable. ie Tesla or Bitcoin
|
||||||
|
tag: Uppercase tag to call the symbol. ie $TSLA or $$BTC
|
||||||
|
"""
|
||||||
|
|
||||||
|
currency = "usd"
|
||||||
|
pass
|
||||||
|
|
||||||
|
def __init__(self, symbol) -> None:
|
||||||
|
self.symbol = symbol
|
||||||
|
self.id = symbol
|
||||||
|
self.name = symbol
|
||||||
|
self.tag = "$" + symbol
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
return f"<{self.__class__.__name__} instance of {self.id} at {id(self)}>"
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return self.id
|
||||||
|
|
||||||
|
|
||||||
|
class Stock(Symbol):
|
||||||
|
"""Stock Market Object. Gets data from MarketData"""
|
||||||
|
|
||||||
|
def __init__(self, symbol: str) -> None:
|
||||||
|
self.symbol = symbol
|
||||||
|
self.id = symbol
|
||||||
|
self.name = "$" + symbol.upper()
|
||||||
|
self.tag = "$" + symbol.lower()
|
||||||
|
|
||||||
|
|
||||||
|
class Coin(Symbol):
|
||||||
|
"""Cryptocurrency Object. Gets data from CoinGecko."""
|
||||||
|
|
||||||
|
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()
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
"""Functions and Info specific to the Telegram Bot
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
|
import requests as r
|
||||||
|
|
||||||
|
|
||||||
|
class T_info:
|
||||||
|
license = re.sub(
|
||||||
|
r"\b\n",
|
||||||
|
" ",
|
||||||
|
r.get("https://gitlab.com/simple-stock-bots/simple-telegram-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
|
||||||
|
|
||||||
|
Full documentation on using and running your own stock bot can be found on the bots [docs.](https://docs.simplestockbot.com)
|
||||||
|
|
||||||
|
The bot detects _"Symbols"_ using either one `$` or two `$$` dollar signs before the symbol. One dollar sign is for a stock market ticker, while two is for a cryptocurrency coin. `/chart $$eth` would return a chart of the past month of data for Ethereum, while `/dividend $psec` returns dividend information for Prospect Capital stock.
|
||||||
|
|
||||||
|
Simply calling a symbol in any message that the bot can see will also return the price. So a message like: `I wonder if $$btc will go to the Moon now that $tsla accepts it as payment` would return the current price for both Bitcoin and Tesla.
|
||||||
|
|
||||||
|
**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. 🆘
|
||||||
|
|
||||||
|
**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 [IEX Cloud](https://iexcloud.io)
|
||||||
|
|
||||||
|
If you believe the bot is not behaving properly run `/status` or [get in touch](https://docs.simplestockbot.com/contact).
|
||||||
|
"""
|
||||||
|
|
||||||
|
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/).
|
||||||
|
|
||||||
|
The easiest way to donate is to run the `/donate [amount in USD]` command with US dollars you would like to donate.
|
||||||
|
|
||||||
|
Example: `/donate 2` would donate 2 USD.
|
||||||
|
|
||||||
|
An alternative way to donate is through https://www.buymeacoffee.com/Anson which requires no account and accepts Paypal or Credit card.
|
||||||
|
If you have any questions see the [website](https:docs.simplestockbot.com)
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
commands = """
|
||||||
|
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
|
||||||
@@ -0,0 +1,449 @@
|
|||||||
|
# Works with Python 3.8
|
||||||
|
import datetime
|
||||||
|
import html
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
import string
|
||||||
|
import traceback
|
||||||
|
import logging as log
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import mplfinance as mpf
|
||||||
|
import telegram
|
||||||
|
from telegram import (
|
||||||
|
InlineQueryResultArticle,
|
||||||
|
InputTextMessageContent,
|
||||||
|
LabeledPrice,
|
||||||
|
Update,
|
||||||
|
)
|
||||||
|
from telegram.ext import (
|
||||||
|
CallbackContext,
|
||||||
|
CommandHandler,
|
||||||
|
Filters,
|
||||||
|
InlineQueryHandler,
|
||||||
|
MessageHandler,
|
||||||
|
PreCheckoutQueryHandler,
|
||||||
|
Updater,
|
||||||
|
)
|
||||||
|
|
||||||
|
from symbol_router import Router
|
||||||
|
from T_info import T_info
|
||||||
|
|
||||||
|
TELEGRAM_TOKEN = os.environ["TELEGRAM"]
|
||||||
|
|
||||||
|
try:
|
||||||
|
STRIPE_TOKEN = os.environ["STRIPE"]
|
||||||
|
except KeyError:
|
||||||
|
STRIPE_TOKEN = ""
|
||||||
|
log.warning("Starting without a STRIPE Token will not allow you to accept Donations!")
|
||||||
|
|
||||||
|
s = Router()
|
||||||
|
t = T_info()
|
||||||
|
|
||||||
|
# Enable logging
|
||||||
|
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
log.info("Bot script started.")
|
||||||
|
|
||||||
|
|
||||||
|
def start(update: Update, context: CallbackContext):
|
||||||
|
"""Send help text when the command /start is issued."""
|
||||||
|
log.info(f"Start command ran by {update.message.chat.username}")
|
||||||
|
update.message.reply_text(
|
||||||
|
text=t.help_text,
|
||||||
|
parse_mode=telegram.ParseMode.MARKDOWN,
|
||||||
|
disable_notification=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def help(update: Update, context: CallbackContext):
|
||||||
|
"""Send help text when the command /help is issued."""
|
||||||
|
log.info(f"Help command ran by {update.message.chat.username}")
|
||||||
|
update.message.reply_text(
|
||||||
|
text=t.help_text,
|
||||||
|
parse_mode=telegram.ParseMode.MARKDOWN,
|
||||||
|
disable_notification=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def license(update: Update, context: CallbackContext):
|
||||||
|
"""Send bots license when the /license command is issued."""
|
||||||
|
log.info(f"License command ran by {update.message.chat.username}")
|
||||||
|
update.message.reply_text(
|
||||||
|
text=t.license,
|
||||||
|
parse_mode=telegram.ParseMode.MARKDOWN,
|
||||||
|
disable_notification=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def status(update: Update, context: CallbackContext):
|
||||||
|
"""Gather status of bot and dependant services and return important status updates."""
|
||||||
|
log.warning(f"Status command ran by {update.message.chat.username}")
|
||||||
|
bot_resp_time = datetime.datetime.now(update.message.date.tzinfo) - update.message.date
|
||||||
|
|
||||||
|
bot_status = s.status(f"It took {bot_resp_time.total_seconds()} seconds for the bot to get your message.")
|
||||||
|
|
||||||
|
update.message.reply_text(
|
||||||
|
text=bot_status,
|
||||||
|
parse_mode=telegram.ParseMode.MARKDOWN,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def donate(update: Update, context: CallbackContext):
|
||||||
|
"""Sets up donation."""
|
||||||
|
log.info(f"Donate command ran by {update.message.chat.username}")
|
||||||
|
chat_id = update.message.chat_id
|
||||||
|
|
||||||
|
if update.message.text.strip() == "/donate" or "/donate@" in update.message.text:
|
||||||
|
update.message.reply_text(
|
||||||
|
text=t.donate_text,
|
||||||
|
parse_mode=telegram.ParseMode.MARKDOWN,
|
||||||
|
disable_notification=True,
|
||||||
|
)
|
||||||
|
amount = 1.0
|
||||||
|
else:
|
||||||
|
amount = float(update.message.text.replace("/donate", "").replace("$", "").strip())
|
||||||
|
|
||||||
|
try:
|
||||||
|
price = int(amount * 100)
|
||||||
|
except ValueError:
|
||||||
|
update.message.reply_text(f"{amount} is not a valid donation amount or number.")
|
||||||
|
return
|
||||||
|
log.info(f"Donation amount: {price} by {update.message.chat.username}")
|
||||||
|
|
||||||
|
context.bot.send_invoice(
|
||||||
|
chat_id=chat_id,
|
||||||
|
title="Simple Stock Bot Donation",
|
||||||
|
description=f"Simple Stock Bot Donation of ${amount} by {update.message.chat.username}",
|
||||||
|
payload=f"simple-stock-bot-{chat_id}",
|
||||||
|
provider_token=STRIPE_TOKEN,
|
||||||
|
currency="USD",
|
||||||
|
prices=[LabeledPrice("Donation:", price)],
|
||||||
|
start_parameter="",
|
||||||
|
# suggested_tip_amounts=[100, 500, 1000, 2000],
|
||||||
|
photo_url="https://simple-stock-bots.gitlab.io/docs/img/Telegram.png",
|
||||||
|
photo_width=500,
|
||||||
|
photo_height=500,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def precheckout_callback(update: Update, context: CallbackContext):
|
||||||
|
"""Approves donation"""
|
||||||
|
log.info("precheckout_callback queried")
|
||||||
|
query = update.pre_checkout_query
|
||||||
|
|
||||||
|
query.answer(ok=True)
|
||||||
|
# I dont think I need to check since its only donations.
|
||||||
|
# if query.invoice_payload == "simple-stock-bot":
|
||||||
|
# # answer False pre_checkout_query
|
||||||
|
# query.answer(ok=True)
|
||||||
|
# else:
|
||||||
|
# query.answer(ok=False, error_message="Something went wrong...")
|
||||||
|
|
||||||
|
|
||||||
|
def successful_payment_callback(update: Update, context: CallbackContext):
|
||||||
|
"""Thanks user for donation"""
|
||||||
|
log.info("Successful payment!")
|
||||||
|
update.message.reply_text("Thank you for your donation! It goes a long way to keeping the bot free!")
|
||||||
|
|
||||||
|
|
||||||
|
def symbol_detect_image(update: Update, context: CallbackContext):
|
||||||
|
"""
|
||||||
|
Makes image captions into text then passes the `update` and `context`
|
||||||
|
to symbol detect so that it can reply cashtags in image captions.
|
||||||
|
"""
|
||||||
|
if update.message.caption:
|
||||||
|
update.message.text = update.message.caption
|
||||||
|
symbol_detect(update, context)
|
||||||
|
|
||||||
|
|
||||||
|
def symbol_detect(update: Update, context: CallbackContext):
|
||||||
|
"""
|
||||||
|
Runs on any message that doesn't have a command and searches for cashtags,
|
||||||
|
then returns the prices of any symbols found.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
message = update.message.text
|
||||||
|
chat_id = update.message.chat_id
|
||||||
|
if "$" in message:
|
||||||
|
symbols = s.find_symbols(message)
|
||||||
|
log.info("Looking for Symbols")
|
||||||
|
else:
|
||||||
|
return
|
||||||
|
except AttributeError as ex:
|
||||||
|
log.info(ex)
|
||||||
|
return
|
||||||
|
if symbols:
|
||||||
|
# Let user know bot is working
|
||||||
|
context.bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
|
||||||
|
log.info(f"Symbols found: {symbols}")
|
||||||
|
|
||||||
|
for reply in s.price_reply(symbols):
|
||||||
|
update.message.reply_text(
|
||||||
|
text=reply,
|
||||||
|
parse_mode=telegram.ParseMode.MARKDOWN,
|
||||||
|
disable_notification=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def intra(update: Update, context: CallbackContext):
|
||||||
|
"""returns a chart of intraday data for a symbol"""
|
||||||
|
log.info(f"Intra command ran by {update.message.chat.username}")
|
||||||
|
|
||||||
|
message = update.message.text
|
||||||
|
chat_id = update.message.chat_id
|
||||||
|
|
||||||
|
if message.strip().split("@")[0] == "/intra":
|
||||||
|
update.message.reply_text(
|
||||||
|
"This command returns a chart of the stocks movement since the most recent market open.\nExample: /intra $tsla"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
symbols = s.find_symbols(message, trending_weight=5)
|
||||||
|
symbol = symbols[0]
|
||||||
|
|
||||||
|
if len(symbols):
|
||||||
|
symbol = symbols[0]
|
||||||
|
else:
|
||||||
|
update.message.reply_text("No symbols or coins found.")
|
||||||
|
return
|
||||||
|
|
||||||
|
df = s.intra_reply(symbol)
|
||||||
|
if df.empty:
|
||||||
|
update.message.reply_text(
|
||||||
|
text="Invalid symbol please see `/help` for usage details.",
|
||||||
|
parse_mode=telegram.ParseMode.MARKDOWN,
|
||||||
|
disable_notification=True,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
context.bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.UPLOAD_PHOTO)
|
||||||
|
|
||||||
|
buf = io.BytesIO()
|
||||||
|
mpf.plot(
|
||||||
|
df,
|
||||||
|
type="renko",
|
||||||
|
title=f"\n{symbol.name}",
|
||||||
|
volume="Volume" in df.keys(),
|
||||||
|
style="yahoo",
|
||||||
|
savefig=dict(fname=buf, dpi=400, bbox_inches="tight"),
|
||||||
|
)
|
||||||
|
buf.seek(0)
|
||||||
|
|
||||||
|
update.message.reply_photo(
|
||||||
|
photo=buf,
|
||||||
|
caption=f"\nIntraday chart for {symbol.name} from {df.first_valid_index().strftime('%d %b at %H:%M')} to"
|
||||||
|
+ f" {df.last_valid_index().strftime('%d %b at %H:%M')}"
|
||||||
|
+ f"\n\n{s.price_reply([symbol])[0]}",
|
||||||
|
parse_mode=telegram.ParseMode.MARKDOWN,
|
||||||
|
disable_notification=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def chart(update: Update, context: CallbackContext):
|
||||||
|
"""returns a chart of the past month of data for a symbol"""
|
||||||
|
log.info(f"Chart command ran by {update.message.chat.username}")
|
||||||
|
|
||||||
|
message = update.message.text
|
||||||
|
chat_id = update.message.chat_id
|
||||||
|
|
||||||
|
if message.strip().split("@")[0] == "/chart":
|
||||||
|
update.message.reply_text(
|
||||||
|
"This command returns a chart of the stocks movement for the past month.\nExample: /chart $tsla"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
symbols = s.find_symbols(message, trending_weight=10)
|
||||||
|
|
||||||
|
if len(symbols):
|
||||||
|
symbol = symbols[0]
|
||||||
|
else:
|
||||||
|
update.message.reply_text("No symbols or coins found.")
|
||||||
|
return
|
||||||
|
|
||||||
|
df = s.chart_reply(symbol)
|
||||||
|
if df.empty:
|
||||||
|
update.message.reply_text(
|
||||||
|
text="Invalid symbol please see `/help` for usage details.",
|
||||||
|
parse_mode=telegram.ParseMode.MARKDOWN,
|
||||||
|
disable_notification=True,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
context.bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.UPLOAD_PHOTO)
|
||||||
|
|
||||||
|
buf = io.BytesIO()
|
||||||
|
mpf.plot(
|
||||||
|
df,
|
||||||
|
type="candle",
|
||||||
|
title=f"\n{symbol.name}",
|
||||||
|
volume="Volume" in df.keys(),
|
||||||
|
style="yahoo",
|
||||||
|
savefig=dict(fname=buf, dpi=400, bbox_inches="tight"),
|
||||||
|
)
|
||||||
|
buf.seek(0)
|
||||||
|
|
||||||
|
update.message.reply_photo(
|
||||||
|
photo=buf,
|
||||||
|
caption=f"\n1 Month chart for {symbol.name} from {df.first_valid_index().strftime('%d, %b %Y')}"
|
||||||
|
+ f" to {df.last_valid_index().strftime('%d, %b %Y')}\n\n{s.price_reply([symbol])[0]}",
|
||||||
|
parse_mode=telegram.ParseMode.MARKDOWN,
|
||||||
|
disable_notification=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def trending(update: Update, context: CallbackContext):
|
||||||
|
"""returns currently trending symbols and how much they've moved in the past trading day."""
|
||||||
|
log.info(f"Trending command ran by {update.message.chat.username}")
|
||||||
|
|
||||||
|
chat_id = update.message.chat_id
|
||||||
|
|
||||||
|
context.bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
|
||||||
|
|
||||||
|
trending_list = s.trending()
|
||||||
|
log.info(trending_list)
|
||||||
|
|
||||||
|
update.message.reply_text(
|
||||||
|
text=trending_list,
|
||||||
|
parse_mode=telegram.ParseMode.MARKDOWN,
|
||||||
|
disable_notification=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def inline_query(update: Update, context: CallbackContext):
|
||||||
|
"""
|
||||||
|
Handles inline query. Searches by looking if query is contained
|
||||||
|
in the symbol and returns matches in alphabetical order.
|
||||||
|
"""
|
||||||
|
# info(f"Inline command ran by {update.message.chat.username}")
|
||||||
|
log.info(f"Query: {update.inline_query.query}")
|
||||||
|
|
||||||
|
ignored_queries = {"$", "$$", " ", ""}
|
||||||
|
|
||||||
|
if update.inline_query.query.strip() in ignored_queries:
|
||||||
|
default_message = """
|
||||||
|
You can type:\n@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.
|
||||||
|
"""
|
||||||
|
|
||||||
|
update.inline_query.answer(
|
||||||
|
[
|
||||||
|
InlineQueryResultArticle(
|
||||||
|
str(uuid4()),
|
||||||
|
title="Please enter a query. It can be a ticker or a name of a company.",
|
||||||
|
input_message_content=InputTextMessageContent(default_message, parse_mode=telegram.ParseMode.MARKDOWN),
|
||||||
|
)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
matches = s.inline_search(update.inline_query.query)
|
||||||
|
|
||||||
|
results = []
|
||||||
|
for _, row in matches.iterrows():
|
||||||
|
results.append(
|
||||||
|
InlineQueryResultArticle(
|
||||||
|
str(uuid4()),
|
||||||
|
title=row["description"],
|
||||||
|
input_message_content=InputTextMessageContent(row["price_reply"], parse_mode=telegram.ParseMode.MARKDOWN),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
if len(results) == 5:
|
||||||
|
update.inline_query.answer(results, cache_time=60 * 60)
|
||||||
|
log.info("Inline Command was successful")
|
||||||
|
return
|
||||||
|
update.inline_query.answer(results)
|
||||||
|
|
||||||
|
|
||||||
|
def rand_pick(update: Update, context: CallbackContext):
|
||||||
|
"""For the gamblers. Returns a random symbol to buy and a sell date"""
|
||||||
|
log.info(f"Someone is gambling! Random_pick command ran by {update.message.chat.username}")
|
||||||
|
|
||||||
|
update.message.reply_text(
|
||||||
|
text=s.random_pick(),
|
||||||
|
parse_mode=telegram.ParseMode.MARKDOWN,
|
||||||
|
disable_notification=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def error(update: Update, context: CallbackContext):
|
||||||
|
"""Log Errors caused by Updates."""
|
||||||
|
log.warning('Update "%s" caused error "%s"', update, error)
|
||||||
|
|
||||||
|
tb_list = traceback.format_exception(None, context.error, context.error.__traceback__)
|
||||||
|
tb_string = "".join(tb_list)
|
||||||
|
|
||||||
|
err_code = "".join([random.choice(string.ascii_lowercase) for i in range(5)])
|
||||||
|
log.warning(f"Logging error: {err_code}")
|
||||||
|
|
||||||
|
if update:
|
||||||
|
message = (
|
||||||
|
f"An exception was raised while handling an update\n"
|
||||||
|
f"<pre>update = {html.escape(json.dumps(update.to_dict(), indent=2, ensure_ascii=False))}"
|
||||||
|
"</pre>\n\n"
|
||||||
|
f"<pre>context.chat_data = {html.escape(str(context.chat_data))}</pre>\n\n"
|
||||||
|
f"<pre>context.user_data = {html.escape(str(context.user_data))}</pre>\n\n"
|
||||||
|
f"<pre>{html.escape(tb_string)}</pre>"
|
||||||
|
)
|
||||||
|
log.warning(message)
|
||||||
|
else:
|
||||||
|
log.warning(tb_string)
|
||||||
|
|
||||||
|
update.message.reply_text(
|
||||||
|
text=f"An error has occured. Please inform @MisterBiggs if the error persists. Error Code: `{err_code}`",
|
||||||
|
parse_mode=telegram.ParseMode.MARKDOWN,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""Start the context.bot."""
|
||||||
|
# Create the EventHandler and pass it your bot's token.
|
||||||
|
updater = Updater(TELEGRAM_TOKEN)
|
||||||
|
|
||||||
|
# Get the dispatcher to register handlers
|
||||||
|
dp = updater.dispatcher
|
||||||
|
|
||||||
|
# on different commands - answer in Telegram
|
||||||
|
dp.add_handler(CommandHandler("start", start))
|
||||||
|
dp.add_handler(CommandHandler("help", help))
|
||||||
|
dp.add_handler(CommandHandler("license", license))
|
||||||
|
dp.add_handler(CommandHandler("trending", trending))
|
||||||
|
dp.add_handler(CommandHandler("random", rand_pick))
|
||||||
|
dp.add_handler(CommandHandler("donate", donate))
|
||||||
|
dp.add_handler(CommandHandler("status", status))
|
||||||
|
dp.add_handler(CommandHandler("inline", inline_query))
|
||||||
|
|
||||||
|
# Charting can be slow so they run async.
|
||||||
|
dp.add_handler(CommandHandler("intra", intra, run_async=True))
|
||||||
|
dp.add_handler(CommandHandler("intraday", intra, run_async=True))
|
||||||
|
dp.add_handler(CommandHandler("day", intra, run_async=True))
|
||||||
|
dp.add_handler(CommandHandler("chart", chart, run_async=True))
|
||||||
|
dp.add_handler(CommandHandler("month", chart, run_async=True))
|
||||||
|
|
||||||
|
# on noncommand i.e message - echo the message on Telegram
|
||||||
|
dp.add_handler(MessageHandler(Filters.text, symbol_detect))
|
||||||
|
dp.add_handler(MessageHandler(Filters.photo, symbol_detect_image))
|
||||||
|
|
||||||
|
# Inline Bot commands
|
||||||
|
dp.add_handler(InlineQueryHandler(inline_query))
|
||||||
|
|
||||||
|
# Pre-checkout handler to final check
|
||||||
|
dp.add_handler(PreCheckoutQueryHandler(precheckout_callback))
|
||||||
|
|
||||||
|
# Payment success
|
||||||
|
dp.add_handler(MessageHandler(Filters.successful_payment, successful_payment_callback))
|
||||||
|
|
||||||
|
# log all errors
|
||||||
|
dp.add_error_handler(error)
|
||||||
|
|
||||||
|
# Start the Bot
|
||||||
|
updater.start_polling()
|
||||||
|
|
||||||
|
updater.idle()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
FROM python:3.7-slim
|
|
||||||
|
|
||||||
COPY requirements.txt ./
|
|
||||||
RUN pip install --no-cache-dir -r requirements.txt
|
|
||||||
|
|
||||||
COPY . .
|
|
||||||
|
|
||||||
CMD [ "python", "./stockBot.py" ]
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
secrets = {
|
|
||||||
"TELEGRAM_TOKEN": "TELEGRAM_API_TOKEN",
|
|
||||||
"TWITTER_CONSUMER_API": "CONSUMER_API",
|
|
||||||
"TWITTER_CONSUMER_SECRET": "CONSUMER_SECRET",
|
|
||||||
"TWITTER_ACCESS_TOKEN": "ACCESS_TOKEN",
|
|
||||||
"TWITTER_ACCESS_SECRET": "ACCESS_SECRET",
|
|
||||||
}
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
telegram==0.0.1
|
|
||||||
python-telegram-bot==11.1.0
|
|
||||||
-182
@@ -1,182 +0,0 @@
|
|||||||
# Work with Python 3.7
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
import re
|
|
||||||
import urllib.request
|
|
||||||
|
|
||||||
import telegram
|
|
||||||
from telegram.ext import CommandHandler, Filters, MessageHandler, Updater
|
|
||||||
|
|
||||||
import credentials
|
|
||||||
import tickerInfo
|
|
||||||
|
|
||||||
TOKEN = credentials.secrets["TELEGRAM_TOKEN"]
|
|
||||||
TICKER_REGEX = "[$]([a-zA-Z]{1,4})"
|
|
||||||
|
|
||||||
# Enable logging
|
|
||||||
logging.basicConfig(
|
|
||||||
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
|
|
||||||
)
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
print("Bot Online")
|
|
||||||
|
|
||||||
|
|
||||||
# Define a few command handlers. These usually take the two arguments bot and
|
|
||||||
# update. Error handlers also receive the raised TelegramError object in error.
|
|
||||||
def start(bot, update):
|
|
||||||
"""Send a message when the command /start is issued."""
|
|
||||||
update.message.reply_text("I am started and ready to go!")
|
|
||||||
|
|
||||||
|
|
||||||
def help(bot, update):
|
|
||||||
"""Send link to docs when the command /help is issued."""
|
|
||||||
message = "[Please see the docs for Bot information](https://misterbiggs.gitlab.io/simple-telegram-bot)"
|
|
||||||
update.message.reply_text(text=message, parse_mode=telegram.ParseMode.MARKDOWN)
|
|
||||||
|
|
||||||
|
|
||||||
def news(bot, update):
|
|
||||||
"""Send a message when the /news command is issued."""
|
|
||||||
message = update.message.text
|
|
||||||
chat_id = update.message.chat_id
|
|
||||||
|
|
||||||
try:
|
|
||||||
# regex to find tickers in messages, looks for up to 4 word characters following a dollar sign and captures the 4 word characters
|
|
||||||
tickers = re.findall(TICKER_REGEX, message)
|
|
||||||
bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
|
|
||||||
|
|
||||||
## Checks if a ticker was passed in
|
|
||||||
if tickers == []:
|
|
||||||
message = "No Ticker, showing Market News:"
|
|
||||||
news = tickerInfo.stockNews("market")
|
|
||||||
for i in range(len(news["title"])):
|
|
||||||
message = f"{message}\n\n[{news['title'][i]}]({news['link'][i]})"
|
|
||||||
update.message.reply_text(
|
|
||||||
text=message, parse_mode=telegram.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
tickerData = tickerInfo.tickerQuote(tickers)
|
|
||||||
for ticker in tickers:
|
|
||||||
ticker = ticker.upper()
|
|
||||||
# Makes sure ticker exists
|
|
||||||
if tickerData[ticker] == 1:
|
|
||||||
name = tickerData[ticker + "Name"]
|
|
||||||
price = tickerData[ticker + "Price"]
|
|
||||||
change = tickerData[ticker + "Change"]
|
|
||||||
|
|
||||||
message = f"The current stock price of {name} is $**{price}**"
|
|
||||||
if change > 0:
|
|
||||||
message = f"{message}, the stock is currently **up {change}%**"
|
|
||||||
elif change < 0:
|
|
||||||
message = (
|
|
||||||
f"{message}, the stock is currently **down {change}%**"
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
message = (
|
|
||||||
f"{message}, the stock hasn't shown any movement today."
|
|
||||||
)
|
|
||||||
|
|
||||||
news = tickerInfo.stockNews(ticker)
|
|
||||||
for i in range(len(news["title"])):
|
|
||||||
message = (
|
|
||||||
f"{message}\n\n[{news['title'][i]}]({news['link'][i]})"
|
|
||||||
)
|
|
||||||
|
|
||||||
update.message.reply_text(
|
|
||||||
text=message, parse_mode=telegram.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
update.message.reply_text(ticker + " Does not exist.")
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def stockInfo(bot, update):
|
|
||||||
message = update.message.text
|
|
||||||
chat_id = update.message.chat_id
|
|
||||||
|
|
||||||
try:
|
|
||||||
# regex to find tickers in messages, looks for up to 4 word characters following a dollar sign and captures the 4 word characters
|
|
||||||
tickers = re.findall(TICKER_REGEX, message)
|
|
||||||
|
|
||||||
if len(tickers) > 0:
|
|
||||||
tickerData = tickerInfo.tickerQuote(tickers)
|
|
||||||
bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
|
|
||||||
|
|
||||||
for ticker in tickers:
|
|
||||||
ticker = ticker.upper()
|
|
||||||
# Makes sure ticker exists
|
|
||||||
if tickerData[ticker] == 1:
|
|
||||||
name = tickerData[ticker + "Name"]
|
|
||||||
price = tickerData[ticker + "Price"]
|
|
||||||
change = tickerData[ticker + "Change"]
|
|
||||||
message = f"The current stock price of {name} is $**{price}**"
|
|
||||||
if change > 0:
|
|
||||||
message = f"{message}, the stock is currently **up {change}%**"
|
|
||||||
elif change < 0:
|
|
||||||
message = f"{message}, the stock is currently **down {change}%**"
|
|
||||||
else:
|
|
||||||
message = f"{message}, the stock hasn't shown any movement today."
|
|
||||||
update.message.reply_text(
|
|
||||||
text=message, parse_mode=telegram.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
update.message.reply_text(ticker + " Does not exist.")
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def dividend(bot, update):
|
|
||||||
message = update.message.text
|
|
||||||
chat_id = update.message.chat_id
|
|
||||||
try:
|
|
||||||
# regex to find tickers in messages, looks for up to 4 word characters following a dollar sign and captures the 4 word characters
|
|
||||||
tickers = re.findall(TICKER_REGEX, message)
|
|
||||||
bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
|
|
||||||
|
|
||||||
for ticker in tickers:
|
|
||||||
message = tickerInfo.stockDividend(ticker)
|
|
||||||
update.message.reply_text(
|
|
||||||
text=message, parse_mode=telegram.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def error(bot, update, error):
|
|
||||||
"""Log Errors caused by Updates."""
|
|
||||||
logger.warning('Update "%s" caused error "%s"', update, error)
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
"""Start the bot."""
|
|
||||||
# Create the EventHandler and pass it your bot's token.
|
|
||||||
updater = Updater(TOKEN)
|
|
||||||
|
|
||||||
# Get the dispatcher to register handlers
|
|
||||||
dp = updater.dispatcher
|
|
||||||
|
|
||||||
# on different commands - answer in Telegram
|
|
||||||
dp.add_handler(CommandHandler("start", start))
|
|
||||||
dp.add_handler(CommandHandler("help", help))
|
|
||||||
dp.add_handler(CommandHandler("news", news))
|
|
||||||
dp.add_handler(CommandHandler("dividend", dividend))
|
|
||||||
|
|
||||||
# on noncommand i.e message - echo the message on Telegram
|
|
||||||
dp.add_handler(MessageHandler(Filters.text, stockInfo))
|
|
||||||
|
|
||||||
# log all errors
|
|
||||||
dp.add_error_handler(error)
|
|
||||||
|
|
||||||
# Start the Bot
|
|
||||||
updater.start_polling()
|
|
||||||
|
|
||||||
# Run the bot until you press Ctrl-C or the process receives SIGINT,
|
|
||||||
# SIGTERM or SIGABRT. This should be used most of the time, since
|
|
||||||
# start_polling() is non-blocking and will stop the bot gracefully.
|
|
||||||
updater.idle()
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -1,105 +0,0 @@
|
|||||||
import urllib.request
|
|
||||||
import json
|
|
||||||
from datetime import datetime
|
|
||||||
import time
|
|
||||||
|
|
||||||
|
|
||||||
def tickerQuote(tickers):
|
|
||||||
"""Gathers information from IEX api on stock"""
|
|
||||||
stockData = {}
|
|
||||||
IEXURL = (
|
|
||||||
"https://api.iextrading.com/1.0/stock/market/batch?symbols="
|
|
||||||
+ ",".join(tickers)
|
|
||||||
+ "&types=quote"
|
|
||||||
)
|
|
||||||
print("Gathering Quote from " + IEXURL)
|
|
||||||
with urllib.request.urlopen(IEXURL) as url:
|
|
||||||
IEXData = json.loads(url.read().decode())
|
|
||||||
|
|
||||||
for ticker in tickers:
|
|
||||||
ticker = ticker.upper()
|
|
||||||
|
|
||||||
# Makes sure ticker exists before populating a dictionary
|
|
||||||
if ticker in IEXData:
|
|
||||||
stockData[ticker] = 1
|
|
||||||
stockData[ticker + "Name"] = IEXData[ticker]["quote"]["companyName"]
|
|
||||||
stockData[ticker + "Price"] = IEXData[ticker]["quote"]["latestPrice"]
|
|
||||||
stockData[ticker + "Change"] = round(
|
|
||||||
(IEXData[ticker]["quote"]["changePercent"] * 100), 2
|
|
||||||
)
|
|
||||||
stockData[ticker + "Image"] = stockLogo(ticker)
|
|
||||||
print(ticker + " Quote Gathered")
|
|
||||||
else:
|
|
||||||
stockData[ticker] = 0
|
|
||||||
return stockData
|
|
||||||
|
|
||||||
|
|
||||||
def stockNews(ticker):
|
|
||||||
"""Makes a bunch of strings that are links to news websites for an input ticker"""
|
|
||||||
print("Gather News on " + ticker)
|
|
||||||
|
|
||||||
newsLink = f"https://api.iextrading.com/1.0/stock/{ticker}/news/last/5"
|
|
||||||
print(newsLink)
|
|
||||||
with urllib.request.urlopen(newsLink) as url:
|
|
||||||
data = json.loads(url.read().decode())
|
|
||||||
|
|
||||||
news = {"link": [], "title": []}
|
|
||||||
for i in range(len(data)):
|
|
||||||
news["link"].append(data[i]["url"])
|
|
||||||
news["title"].append(data[i]["headline"])
|
|
||||||
return news
|
|
||||||
|
|
||||||
|
|
||||||
def stockLogo(ticker):
|
|
||||||
"""returns a png of an input ticker"""
|
|
||||||
logoURL = f"https://g.foolcdn.com/art/companylogos/mark/{ticker}.png"
|
|
||||||
return logoURL
|
|
||||||
|
|
||||||
|
|
||||||
def stockInfo(ticker):
|
|
||||||
infoURL = f"https://api.iextrading.com/1.0/stock/{ticker}/stats"
|
|
||||||
|
|
||||||
with urllib.request.urlopen(infoURL) as url:
|
|
||||||
data = json.loads(url.read().decode())
|
|
||||||
|
|
||||||
info = {}
|
|
||||||
|
|
||||||
info["companyName"] = data["companyName"]
|
|
||||||
info["marketCap"] = data["marketcap"]
|
|
||||||
info["yearHigh"] = data["week52high"]
|
|
||||||
info["yearLow"] = data["week52low"]
|
|
||||||
info["divRate"] = data["dividendRate"]
|
|
||||||
info["divYield"] = data["dividendYield"]
|
|
||||||
info["divDate"] = data["exDividendDate"]
|
|
||||||
|
|
||||||
return info
|
|
||||||
|
|
||||||
|
|
||||||
def stockDividend(ticker):
|
|
||||||
data = stockInfo(ticker)
|
|
||||||
print(data["divDate"])
|
|
||||||
if data["divDate"] == 0:
|
|
||||||
return "{} has no dividend.".format(data["companyName"])
|
|
||||||
|
|
||||||
line1 = "{} current dividend yield is: {:.3f}%, or ${:.3f} per share.".format(
|
|
||||||
data["companyName"], data["divRate"], data["divYield"]
|
|
||||||
)
|
|
||||||
|
|
||||||
divDate = data["divDate"]
|
|
||||||
|
|
||||||
# Pattern IEX uses for dividend date.
|
|
||||||
pattern = "%Y-%m-%d %H:%M:%S.%f"
|
|
||||||
|
|
||||||
# Convert divDate to seconds, and subtract it from current time.
|
|
||||||
divSeconds = datetime.strptime(divDate, pattern).timestamp()
|
|
||||||
difference = divSeconds - int(time.time())
|
|
||||||
|
|
||||||
# Calculate (d)ays, (h)ours, (m)inutes, and (s)econds
|
|
||||||
d, h = divmod(difference, 86400)
|
|
||||||
h, m = divmod(h, 3600)
|
|
||||||
m, s = divmod(m, 60)
|
|
||||||
|
|
||||||
countdownMessage = f"\n\nThe dividend is in: {d:.0f} Days {h:.0f} Hours {m:.0f} Minutes {s:.0f} Seconds."
|
|
||||||
|
|
||||||
message = line1 + countdownMessage
|
|
||||||
return message
|
|
||||||
+375
@@ -0,0 +1,375 @@
|
|||||||
|
"""Class with functions for running the bot with IEX Cloud.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging as log
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
trending_cache: List[str] = []
|
||||||
|
|
||||||
|
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:
|
||||||
|
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
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
-r requirements.txt
|
||||||
|
black==23.3.0
|
||||||
|
flake8==5.0.4
|
||||||
|
Flake8-pyproject==1.2.3
|
||||||
|
pylama==8.4.1
|
||||||
|
mypy==1.2.0
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
[tool.black]
|
||||||
|
line-length = 130
|
||||||
|
|
||||||
|
[tool.flake8]
|
||||||
|
max-line-length = 130
|
||||||
|
|
||||||
|
[tool.pycodestyle]
|
||||||
|
max_line_length = 130
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
python-telegram-bot==13.5
|
||||||
|
requests==2.25.1
|
||||||
|
pandas==2.0.0
|
||||||
|
schedule==1.0.0
|
||||||
|
mplfinance==0.12.7a5
|
||||||
|
markdownify==0.6.5
|
||||||
|
cachetools==4.2.2
|
||||||
@@ -0,0 +1,399 @@
|
|||||||
|
"""Function that routes symbols to the correct API provider.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import datetime
|
||||||
|
import logging
|
||||||
|
import random
|
||||||
|
import re
|
||||||
|
import logging as log
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
import schedule
|
||||||
|
from cachetools import TTLCache, cached
|
||||||
|
|
||||||
|
from cg_Crypto import cg_Crypto
|
||||||
|
from MarketData import MarketData
|
||||||
|
from Symbol import Coin, Stock, Symbol
|
||||||
|
|
||||||
|
from typing import Dict
|
||||||
|
|
||||||
|
|
||||||
|
class Router:
|
||||||
|
STOCK_REGEX = "(?:^|[^\\$])\\$([a-zA-Z.]{1,6})"
|
||||||
|
CRYPTO_REGEX = "[$]{2}([a-zA-Z]{1,20})"
|
||||||
|
trending_count: Dict[str, float] = {}
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.stock = MarketData()
|
||||||
|
self.crypto = cg_Crypto()
|
||||||
|
|
||||||
|
schedule.every().hour.do(self.trending_decay)
|
||||||
|
|
||||||
|
def trending_decay(self, decay=0.5):
|
||||||
|
"""Decays the value of each trending stock by a multiplier"""
|
||||||
|
t_copy = {}
|
||||||
|
dead_keys = []
|
||||||
|
if self.trending_count:
|
||||||
|
t_copy = self.trending_count.copy()
|
||||||
|
for key in t_copy.keys():
|
||||||
|
if t_copy[key] < 0.01:
|
||||||
|
# This just makes sure were not keeping around keys that havent been called in a very long time.
|
||||||
|
dead_keys.append(key)
|
||||||
|
else:
|
||||||
|
t_copy[key] = t_copy[key] * decay
|
||||||
|
for dead in dead_keys:
|
||||||
|
t_copy.pop(dead)
|
||||||
|
|
||||||
|
self.trending_count = t_copy.copy()
|
||||||
|
log.info("Decayed trending symbols.")
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
text : str
|
||||||
|
Blob of text.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
list[Symbol]
|
||||||
|
List of stock symbols as Symbol objects
|
||||||
|
"""
|
||||||
|
schedule.run_pending()
|
||||||
|
|
||||||
|
symbols: list[Symbol] = []
|
||||||
|
stocks = set(re.findall(self.STOCK_REGEX, text))
|
||||||
|
for stock in 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:
|
||||||
|
log.info(f"{coin} is not in list of coins")
|
||||||
|
else:
|
||||||
|
symbols.append(Coin(sym))
|
||||||
|
if symbols:
|
||||||
|
log.info(symbols)
|
||||||
|
for symbol in symbols:
|
||||||
|
self.trending_count[symbol.tag] = self.trending_count.get(symbol.tag, 0) + trending_weight
|
||||||
|
|
||||||
|
return symbols
|
||||||
|
|
||||||
|
def status(self, bot_resp) -> str:
|
||||||
|
"""Checks for any issues with APIs.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
str
|
||||||
|
Human readable text on status of the bot and relevant APIs
|
||||||
|
"""
|
||||||
|
|
||||||
|
stats = f"""
|
||||||
|
Bot Status:
|
||||||
|
{bot_resp}
|
||||||
|
|
||||||
|
Stock Market Data:
|
||||||
|
{self.stock.status()}
|
||||||
|
|
||||||
|
Cryptocurrency Data:
|
||||||
|
{self.crypto.status()}
|
||||||
|
"""
|
||||||
|
|
||||||
|
log.warning(stats)
|
||||||
|
|
||||||
|
return stats
|
||||||
|
|
||||||
|
def inline_search(self, search: str, matches: int = 5) -> pd.DataFrame:
|
||||||
|
"""Searches based on the shortest symbol that contains the same string as the search.
|
||||||
|
Should be very fast compared to a fuzzy search.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
search : str
|
||||||
|
String used to match against symbols.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
list[tuple[str, str]]
|
||||||
|
Each tuple contains: (Symbol, Issue Name).
|
||||||
|
"""
|
||||||
|
|
||||||
|
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()
|
||||||
|
)
|
||||||
|
|
||||||
|
symbols = df.head(matches)
|
||||||
|
symbols["price_reply"] = symbols["type_id"].apply(
|
||||||
|
lambda sym: self.price_reply(self.find_symbols(sym, trending_weight=0))[0]
|
||||||
|
)
|
||||||
|
|
||||||
|
return symbols
|
||||||
|
|
||||||
|
def price_reply(self, symbols: list[Symbol]) -> list[str]:
|
||||||
|
"""Returns current market price or after hours if its available for a given 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
|
||||||
|
markdown formatted string of the symbols price and movement.
|
||||||
|
"""
|
||||||
|
replies = []
|
||||||
|
|
||||||
|
for symbol in symbols:
|
||||||
|
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:
|
||||||
|
log.info(f"{symbol} is not a Stock or Coin")
|
||||||
|
|
||||||
|
return replies
|
||||||
|
|
||||||
|
def info_reply(self, symbols: list) -> list[str]:
|
||||||
|
"""Gets information on stock symbols.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
symbols : list[str]
|
||||||
|
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 information.
|
||||||
|
"""
|
||||||
|
replies = []
|
||||||
|
|
||||||
|
for symbol in symbols:
|
||||||
|
if isinstance(symbol, Stock):
|
||||||
|
replies.append(self.stock.info_reply(symbol))
|
||||||
|
elif isinstance(symbol, Coin):
|
||||||
|
replies.append(self.crypto.info_reply(symbol))
|
||||||
|
else:
|
||||||
|
log.debug(f"{symbol} is not a Stock or Coin")
|
||||||
|
|
||||||
|
return replies
|
||||||
|
|
||||||
|
def intra_reply(self, symbol: Symbol) -> 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 isinstance(symbol, Stock):
|
||||||
|
return self.stock.intra_reply(symbol)
|
||||||
|
elif isinstance(symbol, Coin):
|
||||||
|
return self.crypto.intra_reply(symbol)
|
||||||
|
else:
|
||||||
|
log.debug(f"{symbol} is not a Stock or Coin")
|
||||||
|
return pd.DataFrame()
|
||||||
|
|
||||||
|
def chart_reply(self, symbol: Symbol) -> 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 isinstance(symbol, Stock):
|
||||||
|
return self.stock.chart_reply(symbol)
|
||||||
|
elif isinstance(symbol, Coin):
|
||||||
|
return self.crypto.chart_reply(symbol)
|
||||||
|
else:
|
||||||
|
log.debug(f"{symbol} is not a Stock or Coin")
|
||||||
|
return pd.DataFrame()
|
||||||
|
|
||||||
|
def stat_reply(self, symbols: list[Symbol]) -> list[str]:
|
||||||
|
"""Gets key statistics for each symbol in the list
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
symbols : list[str]
|
||||||
|
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 statistics.
|
||||||
|
"""
|
||||||
|
replies = []
|
||||||
|
|
||||||
|
for symbol in symbols:
|
||||||
|
if isinstance(symbol, Stock):
|
||||||
|
replies.append(self.stock.stat_reply(symbol))
|
||||||
|
elif isinstance(symbol, Coin):
|
||||||
|
replies.append(self.crypto.stat_reply(symbol))
|
||||||
|
else:
|
||||||
|
log.debug(f"{symbol} is not a Stock or Coin")
|
||||||
|
|
||||||
|
return replies
|
||||||
|
|
||||||
|
def cap_reply(self, symbols: list[Symbol]) -> list[str]:
|
||||||
|
"""Gets market cap for each symbol in the list
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
symbols : list[str]
|
||||||
|
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 market cap.
|
||||||
|
"""
|
||||||
|
replies = []
|
||||||
|
|
||||||
|
for symbol in symbols:
|
||||||
|
if isinstance(symbol, Stock):
|
||||||
|
replies.append(self.stock.cap_reply(symbol))
|
||||||
|
elif isinstance(symbol, Coin):
|
||||||
|
replies.append(self.crypto.cap_reply(symbol))
|
||||||
|
else:
|
||||||
|
log.debug(f"{symbol} is not a Stock or Coin")
|
||||||
|
|
||||||
|
return replies
|
||||||
|
|
||||||
|
def spark_reply(self, symbols: list[Symbol]) -> list[str]:
|
||||||
|
"""Gets change for each symbol and returns it in a compact format
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
symbols : list[str]
|
||||||
|
List of stock symbols
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
list[str]
|
||||||
|
List of human readable strings.
|
||||||
|
"""
|
||||||
|
replies = []
|
||||||
|
|
||||||
|
for symbol in symbols:
|
||||||
|
if isinstance(symbol, Stock):
|
||||||
|
replies.append("Command not supported for stocks.")
|
||||||
|
# replies.append(self.stock.spark_reply(symbol))
|
||||||
|
elif isinstance(symbol, Coin):
|
||||||
|
replies.append(self.crypto.spark_reply(symbol))
|
||||||
|
else:
|
||||||
|
log.debug(f"{symbol} is not a Stock or Coin")
|
||||||
|
|
||||||
|
return replies
|
||||||
|
|
||||||
|
@cached(cache=TTLCache(maxsize=1024, ttl=600))
|
||||||
|
def trending(self) -> str:
|
||||||
|
"""Checks APIs for trending symbols.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
list[str]
|
||||||
|
List of preformatted strings to be sent to user.
|
||||||
|
"""
|
||||||
|
|
||||||
|
stocks = self.stock.trending()
|
||||||
|
coins = self.crypto.trending()
|
||||||
|
|
||||||
|
reply = ""
|
||||||
|
|
||||||
|
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]
|
||||||
|
|
||||||
|
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"
|
||||||
|
for coin in coins:
|
||||||
|
reply += coin + "\n"
|
||||||
|
|
||||||
|
if "`$GME" in reply:
|
||||||
|
reply = reply.replace("🔥", "🦍")
|
||||||
|
|
||||||
|
if reply:
|
||||||
|
return reply
|
||||||
|
else:
|
||||||
|
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")
|
||||||
|
|
||||||
|
return f"{choice}\nBuy and hold until: {hold}"
|
||||||
|
|
||||||
|
def batch_price_reply(self, symbols: list[Symbol]) -> list[str]:
|
||||||
|
"""Returns current market price or after hours if its available for a given 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
|
||||||
|
markdown formatted string of the symbols price and movement.
|
||||||
|
"""
|
||||||
|
replies = []
|
||||||
|
stocks = []
|
||||||
|
coins = []
|
||||||
|
|
||||||
|
for symbol in symbols:
|
||||||
|
if isinstance(symbol, Stock):
|
||||||
|
stocks.append(symbol)
|
||||||
|
elif isinstance(symbol, Coin):
|
||||||
|
coins.append(symbol)
|
||||||
|
else:
|
||||||
|
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:
|
||||||
|
replies = replies + self.crypto.batch_price(coins)
|
||||||
|
|
||||||
|
return replies
|
||||||
@@ -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")
|
||||||
@@ -1,179 +0,0 @@
|
|||||||
# License
|
|
||||||
|
|
||||||
## Stock Market Data
|
|
||||||
|
|
||||||
Provided for free by [IEX](https://iextrading.com/developer). View IEX’s [Terms of Use](https://iextrading.com/api-exhibit-a/).
|
|
||||||
|
|
||||||
**This Website and the Associated Bot are Provided under the Following License**
|
|
||||||
|
|
||||||
## 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 licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then 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 Adapter’s 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 Adapter’s 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.
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
# Under Construction 🚧
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
# Telegram Bot Commands
|
|
||||||
|
|
||||||
## Getting a Stock Quote
|
|
||||||
|
|
||||||
Anytime the Bot is in your chat it will search all chats for `$` followed by a ticker. For example `$tsla` will return the following message for Tesla Motors:
|
|
||||||
|
|
||||||
```
|
|
||||||
The current stock price of Tesla Inc. is $321.35, the stock is currently up 2.7%
|
|
||||||
```
|
|
||||||
|
|
||||||
This works no matter where the ticker is in the message and you can have as many tickers as you want in the same message. For example:
|
|
||||||
|
|
||||||
```
|
|
||||||
I wonder how $aapl, $nflx, and $sono are performing today.
|
|
||||||
```
|
|
||||||
|
|
||||||
Will return:
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
## Commands
|
|
||||||
|
|
||||||
* [`/help`](#/help) - Create a new project.
|
|
||||||
* [`/news`](#/news) - Start the live-reloading docs server.
|
|
||||||
|
|
||||||
### /help
|
|
||||||
|
|
||||||
This command just displays a short description of what the bot does and a link to this page.
|
|
||||||
|
|
||||||
### /news
|
|
||||||
|
|
||||||
This command is intelligent enough to get any tickers in the ticker format: `$amzn`, and can handle as many tickers as you would like to enter. The bot will then return the price of the ticker, and links various websites that provide news about the ticker. Currently for Apple stock the Bot would return:
|
|
||||||
|
|
||||||
|
|
||||||
`The current stock price of Apple Inc. is **$174.18**, the stock is currently up **1.71%**`
|
|
||||||
[`Bravos`](https://bravos.co/AAPL)
|
|
||||||
[`Seeking Alpha`](https://seekingalpha.com/symbol/AAPL)
|
|
||||||
[`MSN Money`](https://www.msn.com/en-us/money/stockdetails?symbol=AAPL)
|
|
||||||
[`Yahoo Finance`](https://finance.yahoo.com/quote/AAPL)
|
|
||||||
[`Wall Street Journal`](https://quotes.wsj.com/AAPL)
|
|
||||||
[`The Street`](https://www.thestreet.com/quote/AAPL.html)
|
|
||||||
[`Zacks`](https://www.zacks.com/stock/quote/AAPL)
|
|
||||||
|
|
||||||
*This command needs updating, feel free to [open an issue](https://gitlab.com/MisterBiggs/simple-telegram-bot/issues) with suggestions.*
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 65 KiB |
@@ -1,82 +0,0 @@
|
|||||||
# Telegram Bot Commands
|
|
||||||
|
|
||||||
## About
|
|
||||||
|
|
||||||
If you aren't already, you can talk to this bot here: **[http://t.me/SimpleStockBot](http://t.me/SimpleStockBot)**
|
|
||||||
|
|
||||||
Simple Stock Bot is a bot for [Telegram](https://telegram.org/) that provides information about the stock market. You can view the source code [here.](https://gitlab.com/MisterBiggs/simple-telegram-bot). You can also build your own docker container to run [here.](#Build)
|
|
||||||
|
|
||||||
_Coded with ❤ by [@MisterBiggs](https://gitlab.com/MisterBiggs)_
|
|
||||||
|
|
||||||
## Getting a Stock Quote
|
|
||||||
|
|
||||||
Anytime the Bot is in your chat it will search all chats for `$` followed by a ticker. For example `$tsla` will return the following message for Tesla Motors:
|
|
||||||
|
|
||||||
```
|
|
||||||
The current stock price of Tesla Inc. is $321.35, the stock is currently up 2.7%
|
|
||||||
```
|
|
||||||
|
|
||||||
This works no matter where the ticker is in the message and you can have as many tickers as you want in the same message. For example:
|
|
||||||
|
|
||||||
```
|
|
||||||
I wonder how $aapl, $nflx, and $sono are performing today.
|
|
||||||
```
|
|
||||||
|
|
||||||
Will return:
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
As long as the bot is in your chat it will reply to any stock tickers in your messages.
|
|
||||||
|
|
||||||
## Commands
|
|
||||||
|
|
||||||
- [`/help`](#/help)
|
|
||||||
- [`/news`](#/news)
|
|
||||||
- [`/dividend`](#/dividend)
|
|
||||||
|
|
||||||
### /help
|
|
||||||
|
|
||||||
This command just displays a short description of what the bot does and a link to this page.
|
|
||||||
|
|
||||||
### /news
|
|
||||||
|
|
||||||
This command is intelligent enough to get any tickers in the ticker format: `$amzn`, and can handle as many tickers as you would like to enter. The bot will then return the price of the ticker, and links various websites that provide news about the ticker. Currently the command `/news $aapl` returns:
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
`The current stock price of Apple Inc. is $**170.89**, the stock is currently **up 0.86%**`
|
|
||||||
|
|
||||||
[`Apple: The 4 Biggest Risks`](https://api.iextrading.com/1.0/stock/aapl/article/7171544094325661)
|
|
||||||
|
|
||||||
[`Apple is getting so serious about health, it's started hosting heart-health events at Apple Stores`](https://api.iextrading.com/1.0/stock/aapl/article/6966979968162641)
|
|
||||||
|
|
||||||
[`You can now ask Siri to get you directions with Waze so you don't even have to open the app`](https://api.iextrading.com/1.0/stock/aapl/article/7672481171984085)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### /dividend
|
|
||||||
|
|
||||||
The dividend command will give you the `dividend yield`, `dividend rate`, and will tell you how long until the payout date for any tickers input. Currently the command `/dividend $psec` returns:
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
`Prospect Capital Corporation current dividend yield is: 0.720%, or $11.285 per share.`
|
|
||||||
|
|
||||||
`The dividend is in: 14 Days 1 Hours 54 Minutes 46 Seconds.`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Run your own bot using latest build
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
docker run --detach registry.gitlab.com/misterbiggs/simple-telegram-bot:latest
|
|
||||||
```
|
|
||||||
|
|
||||||
## Built and Run your own Bot
|
|
||||||
|
|
||||||
You can also run your own bot super easily in a [Docker](https://hub.docker.com/) Container.
|
|
||||||
|
|
||||||
1. Download the repository.
|
|
||||||
2. Change information in [Credentials.py]() with your own Telegram Bot key, which can be found [here.]()
|
|
||||||
3. Run stockBot.py
|
|
||||||
4. profit???
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
site_name: Simple Stock Bot
|
|
||||||
site_url: https://misterbiggs.gitlab.io/simple-telegram-bot
|
|
||||||
edit_uri: blob/master/web/docs/
|
|
||||||
nav:
|
|
||||||
- Home: index.md
|
|
||||||
# - Commands: commands.md
|
|
||||||
# - About: about.md
|
|
||||||
# - Author's Website: https://blog.ansonbiggs.com/
|
|
||||||
- LICENSE: LICENSE.md
|
|
||||||
theme: "material"
|
|
||||||
|
|
||||||
repo_url: https://gitlab.com/MisterBiggs/simple-telegram-bot
|
|
||||||
repo_name: Simple Telegram Bot
|
|
||||||
site_description: A Telegram Bot for stock market Data.
|
|
||||||
Reference in New Issue
Block a user