1
0
mirror of https://gitlab.com/simple-stock-bots/simple-stock-bot.git synced 2026-06-03 21:00:26 +00:00

Compare commits

..

159 Commits

Author SHA1 Message Date
Anson 262ae7c534 fixed typing in file 2023-04-08 18:56:01 -06:00
Anson 4ed8c59828 fixed control flow 2023-04-08 18:52:47 -06:00
Anson 86349deba4 Merge branch '93-add-change-percent-to-market-data' into 'master'
Resolve "Add change percent to Market Data"

Closes #93

See merge request simple-stock-bots/simple-telegram-stock-bot!41
2023-04-09 00:41:57 +00:00
Anson 22ed74d194 Resolve "Add change percent to Market Data" 2023-04-09 00:41:57 +00:00
Anson e63dc7f46b Update .gitlab-ci.yml file 2023-04-07 20:51:14 +00:00
Anson 928a23c8c6 fighting CI 2023-04-07 14:50:29 -06:00
Anson 580fcbb84d Merge branch '88-switch-to-marketdata-app-for-stock-market-data' into 'master'
Resolve "Switch to marketdata.app for stock market data"

Closes #88

See merge request simple-stock-bots/simple-telegram-stock-bot!40
2023-04-07 20:46:23 +00:00
Anson 322dffa2f2 Resolve "Switch to marketdata.app for stock market data" 2023-04-07 20:46:23 +00:00
Anson a2a4556c0d Merge branch '88-switch-to-marketdata-app-for-stock-market-data' into 'master'
Resolve "Switch to marketdata.app for stock market data"

Closes #88

See merge request simple-stock-bots/simple-telegram-stock-bot!39
2023-04-07 20:39:24 +00:00
Anson c2d73815f6 Resolve "Switch to marketdata.app for stock market data" 2023-04-07 20:39:24 +00:00
Anson 06e1f62fff Merge branch 'Canary' into 'master'
Canary

See merge request simple-stock-bots/simple-telegram-stock-bot!36
2022-01-05 07:27:39 +00:00
Anson 633cc5bb41 Merge branch '85-remove-binance-peg-crypto' into 'Canary'
Resolve "Remove binance-peg crypto"

See merge request simple-stock-bots/simple-telegram-stock-bot!35
2022-01-05 07:24:57 +00:00
Anson ccc44bfa21 Resolve "Remove binance-peg crypto" 2022-01-05 07:24:57 +00:00
Anson 2bb825d721 quick debug of trending error 2021-11-18 17:21:52 +00:00
Anson 78d3447439 closes #81 2021-11-07 12:02:06 -07:00
Anson a9b157cb4d remove debugging prints 2021-11-07 11:44:15 -07:00
Anson 6d269c7466 add weights to trending based on command #84 2021-11-07 11:43:42 -07:00
Anson d26a3cfc78 fixed markdown parsing bug 2021-11-07 11:35:36 -07:00
Anson 579421f4ab Merge branch 'Canary' into 'master'
Canary

Closes #76 and #78

See merge request simple-stock-bots/simple-telegram-stock-bot!34
2021-11-06 20:22:00 +00:00
Anson 727e08a309 finisheing touches on #82 2021-11-06 13:17:13 -07:00
Anson f67cb398ac closes #76 2021-11-06 13:00:00 -07:00
Anson c34af4cd40 added tokens to devcontainer 2021-11-06 12:40:07 -07:00
Anson 8919e945f0 added list of commands to help test bot 2021-11-06 12:39:12 -07:00
Anson e59dbf005c added warning about #83 2021-11-06 12:38:59 -07:00
Anson 465e60e016 left print statements in code 2021-11-06 11:57:35 -07:00
Anson 4f7aff9db2 hopefully fix #78 2021-11-05 23:54:26 -07:00
Anson 9d510fc104 fixed stock market cap bug 2021-11-05 23:31:24 -07:00
Anson d533c2c4a2 dev stuff 2021-11-05 23:29:02 -07:00
Anson 87aeafc77f fixed inline #82 2021-11-05 23:28:44 -07:00
Anson 2f3cef4ec4 Merge branch 'canary' into 'master'
Smaller Docker Image

See merge request simple-stock-bots/simple-telegram-stock-bot!33
2021-11-06 04:27:27 +00:00
Anson 7785e153f4 Smaller Docker Image 2021-11-06 04:27:27 +00:00
Anson e1c714f6ce formatting 2021-10-06 07:15:14 -07:00
Anson 2a06251ac7 should fix #77 2021-10-06 14:11:57 +00:00
Anson 0577018284 Update symbol_router.py 2021-10-06 14:08:11 +00:00
Anson a9eaf7c6db Merge branch 'canary' 2021-10-05 15:56:22 -07:00
Anson 0374f5b789 fix format error 2021-10-05 15:49:47 -07:00
Anson 29e9221970 Merge branch 'canary' of gitlab.com:simple-stock-bots/simple-telegram-stock-bot into canary 2021-10-05 15:48:45 -07:00
Anson e36082334c seeing what happens if formatting is incorrect 2021-10-05 15:48:40 -07:00
Anson 9bb732a261 Update .gitlab-ci.yml file 2021-10-05 22:47:12 +00:00
Anson c81e4ffb00 clean settings 2021-10-05 15:42:39 -07:00
Anson 621e8a75c3 add linting step 2021-10-05 15:41:49 -07:00
Anson 20ec52fc22 hopeful fix for #77 2021-10-05 15:37:39 -07:00
Anson e08573ff7c Only look at messages with a $ 2021-10-05 15:28:51 -07:00
Anson e8aeba478c stop decaying trending #77 2021-09-23 14:34:32 -07:00
Anson e9639f3538 Merge branch 'canary' of gitlab.com:simple-stock-bots/simple-telegram-stock-bot into canary 2021-09-16 19:04:59 -07:00
Anson 2cf0adcb22 cache trending command results 2021-09-16 19:04:41 -07:00
Anson 28a3ff2960 Turn off error messages until trending error is figured out 2021-09-02 21:50:40 +00:00
Anson 553b958cc1 cache trending command results 2021-09-01 23:52:53 -07:00
Anson 82469f1034 Merge branch 'canary' into 'master'
wrong token name

See merge request simple-stock-bots/simple-telegram-stock-bot!31
2021-09-02 06:26:29 +00:00
Anson e5013d8c69 wrong token name 2021-09-01 23:25:41 -07:00
Anson 3901c1ae73 Merge branch 'canary' into 'master'
accidentally pushed a key

See merge request simple-stock-bots/simple-telegram-stock-bot!30
2021-09-02 06:21:00 +00:00
Anson da4731e349 accidentally pushed a key 2021-09-01 23:19:29 -07:00
Anson cf25a7b9dc Bot is having sync issues and I believe this is related. 2021-09-01 21:45:57 +00:00
Anson 88a9b3aa63 Merge branch 'canary' into 'master'
Trending Update

Closes #73 and #74

See merge request simple-stock-bots/simple-telegram-stock-bot!29
2021-09-01 03:23:01 +00:00
Anson 4f5c558588 small easteregg 2021-09-01 03:11:58 +00:00
Anson 6e21565f2b #75 enough calls to justify making cmd async 2021-08-31 20:04:44 -07:00
Anson a583cad741 Mostly wrapped up #75 2021-08-31 20:03:59 -07:00
Anson dcce2cb95a #18 2021-09-01 01:51:18 +00:00
Anson 0877949a89 trending only returns if data was retrieved. #75 2021-08-30 13:46:12 -07:00
Anson 0649789bf8 bug in decay schedule #75 2021-08-30 20:35:04 +00:00
Anson c7f083b2b1 trending stocks now decay #75 2021-08-30 13:21:56 -07:00
Anson 99fdd6e8be documentation fix 2021-08-30 13:21:44 -07:00
Anson e56679f29f more idiomatic setup for Dockerfile 2021-08-30 12:52:46 -07:00
Anson 42bb17dd40 #18 2021-08-26 19:13:51 +00:00
Anson 082c42c39f Bot now keeps track of symbols for own trending 2021-08-26 19:12:38 +00:00
Anson f34fd37597 /close #74 2021-08-26 17:46:13 +00:00
Anson 0bac96cbd7 Closes #73 2021-08-26 10:26:14 -07:00
Anson dc75b7948c revert donation stuff 2021-08-26 08:35:00 -07:00
Anson c5b56bb345 clean up logs
(cherry picked from commit 1bbbaa5f4e)
2021-08-26 15:29:15 +00:00
Anson ccc8326495 Revert "clean up logs"
This reverts commit 1bbbaa5f4e
2021-08-26 15:28:37 +00:00
Anson ec5d1fa195 Stock needs a string to be passed to it 2021-08-26 08:14:11 -07:00
Anson 46ddef206c update links to go to donate message 2021-08-26 08:10:15 -07:00
Anson 7a20d8d6a3 Merge branch 'canary' into 'master'
Update to reflect that stock market data isnt working

See merge request simple-stock-bots/simple-telegram-stock-bot!28
2021-08-26 15:07:55 +00:00
Anson edb9dad961 The unfortunate im broke update 2021-08-26 08:06:27 -07:00
Anson 5ec26f48a1 Update to ask for donations 2021-08-26 14:39:41 +00:00
Anson 1bbbaa5f4e clean up logs 2021-08-15 20:07:32 -07:00
Anson 0eab043e09 Merge branch 'canary' into 'master'
bug fix

See merge request simple-stock-bots/simple-telegram-stock-bot!27
2021-08-16 02:54:29 +00:00
Anson 89e8566427 bug fix 2021-08-15 19:51:15 -07:00
Anson a09f8aec24 Merge branch 'canary' into 'master'
Change to API requests and small formatting changes

See merge request simple-stock-bots/simple-telegram-stock-bot!26
2021-08-16 02:35:39 +00:00
Anson bea03c73e3 embracing devcontainers 2021-08-15 19:21:06 -07:00
Anson 9e72b8d834 big where telegram auto command broke donations 2021-08-13 19:59:29 -07:00
Anson 55e4fe5d70 API requests are now made under one function 2021-08-13 15:45:30 -07:00
Anson 6d2b9309d7 small formatting change 2021-08-04 22:52:52 -07:00
Anson 390a6199ad ignore docker dev stuff 2021-08-04 02:54:16 -07:00
Anson bd8a992de3 After hours now mentions change for open hours 2021-08-04 02:53:56 -07:00
Anson 5f09744914 Merge branch 'canary' into 'master'
trending bugfix

See merge request simple-stock-bots/simple-telegram-stock-bot!25
2021-07-08 18:24:16 +00:00
Anson 2e9bf6e673 trending bugfix 2021-07-08 11:18:24 -07:00
Anson 24220cd0cc Merge branch 'canary' into 'master'
Canary

Closes #68, #70, and #69

See merge request simple-stock-bots/simple-telegram-stock-bot!24
2021-07-07 19:13:01 +00:00
Anson bfeb28833a updated info with new site and cap command 2021-07-07 12:00:25 -07:00
Anson 71c0272445 updated docs link 2021-07-05 03:08:38 -07:00
Anson cb92127ecd added error code #18 2021-07-05 03:08:04 -07:00
Anson 371b4505eb sorted imports 2021-07-05 02:54:09 -07:00
Anson 43976e873a updated all docstrings 2021-07-02 12:41:36 -07:00
Anson acc0ebdd28 start on #18 2021-06-23 21:28:13 -07:00
Anson baf45e09c8 Closes #69 2021-06-23 14:17:50 -07:00
Anson ae0075b986 improved performance of getting crypto prices 2021-06-23 13:46:11 -07:00
Anson 6baf893823 Closes #70 2021-06-22 00:08:04 -07:00
Anson 55bf78a57b Closes #68 2021-06-21 23:41:09 -07:00
Anson 3435ac1528 Merge branch 'canary' into 'master'
added support for stock symbols using '.'

See merge request simple-stock-bots/simple-telegram-stock-bot!23
2021-06-07 18:25:07 +00:00
Anson 08f140af8e added support for stock symbols using '.' 2021-06-07 18:20:52 +00:00
Anson 14c50deb82 Merge branch 'canary' into 'master'
May 2021 Update

Closes #66, #62, #60, and #55

See merge request simple-stock-bots/simple-telegram-stock-bot!22
2021-05-27 05:31:13 +00:00
Anson 2fa26c4662 Merge branch 'canaryCanary' into 'canary'
Fixes inline search functionality

See merge request simple-stock-bots/simple-telegram-stock-bot!21
2021-05-27 05:24:44 +00:00
Anson aba7120889 Fixes #55 2021-05-26 22:16:41 -07:00
Anson c082761990 Closes #60 2021-05-21 20:22:23 -07:00
Anson e6ebd81928 #56 added message when errors occur. 2021-05-21 20:16:36 -07:00
Anson 15a62b7989 #54 2021-05-21 20:01:07 -07:00
Anson a07d29cbfe #62 2021-05-21 19:58:56 -07:00
Anson fcd6afec60 Closes #62 2021-05-21 19:53:46 -07:00
Anson d8bbfb057f removed moving average from intra plot 2021-05-21 19:46:01 -07:00
Anson f9b8921ba8 Close #66 2021-05-21 16:50:29 -07:00
Anson 610dbc3492 Started #61 2021-05-05 20:48:25 -07:00
Anson 8e6425e756 Close #55 2021-05-05 20:46:18 -07:00
Anson 0b44321754 bandaid on #55 2021-04-24 11:42:47 -07:00
Anson e7fa0ced5c Fixes #60 Changed Date Formatting for intra reply 2021-04-24 11:36:02 -07:00
Anson 1d884110e6 Merge branch 'canary' into 'master'
Canary

See merge request simple-stock-bots/simple-telegram-stock-bot!20
2021-04-01 18:32:47 +00:00
Anson f5195700a6 fix price_reply again 2021-04-01 11:27:52 -07:00
Anson 6df703bd1e gave love to almost all stock commands 2021-04-01 10:47:14 -07:00
Anson fc454d8623 properly updated for OTC 2021-04-01 10:20:46 -07:00
Anson 26ddc267ff Broke Change% in recent update 2021-03-31 15:33:27 +00:00
Anson 75355309bc Bot now sends silent messages. 2021-03-30 22:04:59 -07:00
Anson 7f9080d887 typo on donation link 2021-03-31 03:06:04 +00:00
Anson 3e4945cffd update for OTC 2021-03-31 00:59:40 +00:00
Anson a4948fd566 copied a string wrong 2021-03-31 00:54:35 +00:00
Anson 85b8101cf6 add OTC support 2021-03-31 00:51:18 +00:00
Anson 26a838c000 Update searchindexer.ipynb 2021-03-30 19:32:51 +00:00
Anson 6d955e8fb9 testing indexing methods 2021-03-30 12:31:11 -07:00
Anson 144dd1d218 Fixed Inline #55 2021-03-30 11:36:52 -07:00
Anson 8dd3ef772f bug where some symbols return None for change 2021-03-30 09:36:54 -07:00
Anson 1e60827a66 Merge branch 'master' of gitlab.com:simple-stock-bots/simple-telegram-stock-bot 2021-03-30 08:50:00 -07:00
Anson a979de2272 added trending to list of commands 2021-03-30 08:49:56 -07:00
Anson 0bef01450f fix trending output 2021-03-29 12:58:37 -07:00
Anson 00b17501ab bug in searching 2021-03-29 12:52:35 -07:00
Anson e061eb20cc wasnt returning enough matches 2021-03-29 08:05:33 -07:00
Anson f4adfb1915 added /trending command 2021-03-28 23:31:21 -07:00
Anson a4befde8ce search now works with crypto 2021-03-28 22:37:09 -07:00
Anson f1838ba012 changed max length of symbol regexes 2021-03-28 15:30:19 -07:00
Anson 2844fd2a55 Close #37 2021-03-28 14:02:05 -07:00
Anson 2e8cefcbfd didnt merge correctly first time 2021-03-28 13:49:22 -07:00
Anson 042e50cc26 Merge branch 'crypto' 2021-03-28 13:38:40 -07:00
Anson 15fcf64caf Merge branch 'docker' into 'master'
Add Kaniko to CI

See merge request simple-stock-bots/simple-telegram-stock-bot!18
2021-03-28 20:28:58 +00:00
Anson bd64742c39 Add Kaniko to CI 2021-03-28 20:28:57 +00:00
Anson ff3083a8e5 added commands list to T_info 2021-03-28 01:07:10 -07:00
Anson cb2f214096 updated help text 2021-03-28 01:05:26 -07:00
Anson f65704b0be fixed status command 2021-03-27 19:10:51 -07:00
Anson 621de911cd close #48 2021-03-27 18:40:02 -07:00
Anson b2c325bddb grammar 2021-03-27 18:26:26 -07:00
Anson 367fab669f Coin formatting for price reply 2021-03-27 18:24:33 -07:00
Anson 6ab7f2c25d #31 just need to fix bugs from Main 2021-03-27 17:31:23 -07:00
Anson e1ed5fbf57 update to python3.9 2021-03-27 17:17:16 -07:00
Anson 1c02980e69 Delete .gitlab-ci.yml 2021-03-18 01:08:24 +00:00
Anson ee406fcf88 testing to see if ci/cd will just work with k8s runner 2021-03-18 00:44:59 +00:00
Anson 089e3344d4 disable error messages until crypto update is done 2021-03-11 15:06:30 -07:00
Anson f7dc433ec7 I think i wrangled the types 2021-02-28 13:54:46 -07:00
Anson 19c2daa9f9 I hate Typing 2021-02-28 00:44:31 -07:00
Anson e08f3c4275 so many changes 2021-02-27 17:14:55 -07:00
Anson 6e37e541d6 just need to smash bugs and the update is done 2021-02-25 21:37:13 -07:00
Anson 487ab10933 fix for symbols without a dividend 2021-02-25 11:21:59 -07:00
Anson 96321d7c07 mostly implemented router and IEX 2021-02-17 21:09:03 -07:00
Anson b10517e025 new file structure 2021-02-12 23:21:56 -07:00
20 changed files with 1518 additions and 1021 deletions
+20
View File
@@ -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" ]
+26
View File
@@ -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"
}
+1 -2
View File
@@ -1,2 +1 @@
__pycache__/
.vscode
__pycache__
+34
View File
@@ -0,0 +1,34 @@
black:
stage: .pre
image: registry.gitlab.com/pipeline-components/black:latest
script:
- black --check --verbose -- .
build:master:
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}: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"'
+12
View File
@@ -0,0 +1,12 @@
{
"configurations": [
{
"name": "Telegram Bot",
"type": "python",
"request": "launch",
"program": "bot.py",
"console": "integratedTerminal",
"python": "python3.11"
}
]
}
+5
View File
@@ -0,0 +1,5 @@
{
"python.formatting.provider": "black",
"python.linting.mypyEnabled": true,
"python.linting.flake8Enabled": true,
}
+10 -3
View File
@@ -1,9 +1,16 @@
FROM python:3.8-buster
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 requirements.txt ./
RUN pip install --no-cache-dir -U -r requirements.txt
COPY . .
+223
View File
@@ -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()
+18 -159
View File
@@ -1,173 +1,32 @@
<div align="center">
<p align="center">
<a href="" rel="noopener">
<img width=200px height=200px src="https://assets.gitlab-static.net/uploads/-/system/project/avatar/10295651/TelegramLogo.jpg?width=64" alt="Simple Telegram Stock Bot"></a>
</p>
# Simple Telegram Stock Bot
<h3 align="center">Simple Telegram Stock Bot</h3>
<a href="https://www.buymeacoffee.com/Anson" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Beer" style="height: 51px !important;width: 217px !important;" ></a>
[![Status](https://img.shields.io/badge/status-active-success.svg)]()
[![Platform](https://img.shields.io/badge/platform-Telegram-blue.svg)]()
[![Platform](https://img.shields.io/badge/platform-Telegram-blue.svg)](https://t.me/SimpleStockBot)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](/LICENSE)
[![Author](https://img.shields.io/badge/Maintainer-Anson-blue)](https://ansonbiggs.com)
</div>
## Docs
---
https://docs.simplestockbot.com/
<p align="center"> Telegram Bot 🤖 that provides Stock Market information.
<br>
</p>
## Usage
Message the bot on Telegram [@SimpleStockBot](https://t.me/SimpleStockBot)
## 📝 Table of Contents
https://docs.simplestockbot.com/commands/
- [About](#about)
- [How it works](#working)
- [Usage](#usage)
- [Getting Started](#getting_started)
- [Deploying your own bot](#deployment)
- [Built Using](#built_using)
- [Contributing](../CONTRIBUTING.md)
- [author](#author)
- [Acknowledgments](#acknowledgement)
## Donate
## 🧐 About <a name = "about"></a>
Simple Stock Bot is run entirely on donations, and costs about $420 a year to run. All donations go directly towards paying for servers, and premium market data provided by [IEX Cloud](https://iexcloud.io/).
This bot aims to be as simple as possible while providing all the information you need on the stock market. The motivation of this bot is to provide similar stock market functionality that the Google Assistant provided in [Google Allo](https://gcemetery.co/google-allo/) before the project was sunset.
The best way to donate is through [Buy Me A Coffee](https://www.buymeacoffee.com/Anson) which accepts Paypal or Credit card.
## 💭 How it works <a name = "working"></a>
Alternatively, you can donate on Telegram with the `/donate` [command](commands.md#donate-amount-in-usd).
This bot works by using the [IEX API 2.0](https://iexcloud.io/docs/api/). Using various endpoints provided by the API, the bot can take either take commands from users or check any messages for stock symbols as detailed in [Usage](#usage).
If you have any questions get in [touch.](contact.md)
## 🎈 Usage <a name = "usage"></a>
## Other Ways to Help:
### Basic Usage
The simplest way to use the bot is just by sending a message either as a direct message or in a group chat with the bot active. The bot will search every message for text with a dollar sign followed by a stock symbol, and it will return the full name of the company and the current trading price.
```
$tsla
```
The symbols can be anywhere in the message, and you can post as many as you like so commands such as:
```
I wonder if $aapl is down as much as $msft is today.
```
would return the stock price of both Apple and Microsoft like so:
```
The current stock price of Microsoft Corp. is $131.4, the stock is currently up 2.8%
The current stock price of Apple, Inc. is $190.15, the stock is currently up 2.66%
```
### /dividend
To get information about the dividend of a stock type `/dividend` followed by any text that has symbols with a dollar sign in front of them. So, the following command:
```
/dividend $psec
```
Would return information about Prospect Capitals dividend:
```
Prospect Capital Corp. Declares June 2019 Dividend of $0.06 Per Share
The dividend is in: 38 Days 3 Hours 53 Minutes 22 Seconds.
```
💡 you can also call the dividend command using /div
### /news
To get the latest news about a stock symbol use `/news` followed by any text that has symbols with a dollar sign in front of them. So, the following command:
```
/news $psec
```
Would return news for Prospect Capital:
News for PSEC:
[Yield-Starved Investors Still Accumulating BDCs Paying More Than 10% Annually](https://cloud.iexapis.com/v1/news/article/d994b8b5-9fbf-4ceb-afbe-e6defcfc6352)
[Assessing Main Street Capital's Results For Q1 2019 (Includes Updated Price Target And Investment Ratings Analysis)](https://cloud.iexapis.com/v1/news/article/e60899bc-5230-4388-a609-fc2b8736a7d4)
[Fully Assessing Prospect Capital's Fiscal Q3 2019 (Includes Current Recommendation And Price Target)](https://cloud.iexapis.com/v1/news/article/08881160-72c5-4f5d-885b-1751187d24eb)
### /info
To get information about a stock type `/info` followed by any text that has symbols with a dollar sign in front of them. So, the following command:
```
/info $psec
```
Would return information about Prospect Capitals:
Company Name: [Prospect Capital Corp.](http://www.prospectstreet.com/)
Industry: Investment Managers
Sector: Finance
CEO: John Francis Barry
Description: Prospect Capital Corp. is a business development company, which engages in lending to and investing in private businesses. It also involves in generating current income and long-term capital appreciation through debt and equity investments. The company was founded on April 13, 2004 and is headquartered in New York, NY.
## 🏁 Getting Started <a name = "getting_started"></a>
You can either choose to use the hosted version of the bot by [clicking here](https://t.me/SimpleStockBot) or you can host your own bot with the instructions below.
### Self Hosted Bot
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See [deployment](#deployment) for notes on how to deploy the project on a live system.
### Prerequisites
This project runs neatly in a docker container, so all that you need to run it yourself is [Docker](https://hub.docker.com/?overlay=onboarding) installed on your system.
You will also need a telegram API key which can be obtained for free by talking to [BotFather](https://telegram.me/botfather), more details [here.](https://core.telegram.org/bots#3-how-do-i-create-a-bot)
Finally, you will need and IEX Cloud API key. They offer a free tier that should be enough for any private groups, more details [here.](https://iexcloud.io/)
### Installing
Once Docker is installed and you have your API keys for Telegram and IEX Cloud getting the bot running on any platform is extremely easy.
Download or clone the repository to your machine and open a terminal in the project and build the Docker container.
```
docker build -t simple-telegram-bot .
```
Then run the bot using your API keys.
```
docker run --detach \
-e TELEGRAM=TELEGRAM_API \
-e IEX=IEX_API \
simple-telegram-bot
```
Your bot should be running! If you are new to Docker, I would recommend checking out its documentation for full control over your bot.
## 🚀 Deploying your own bot <a name = "deployment"></a>
I recommend Digital Ocean for small projects like this because it is straightforward to use and affordable. [Sign up with my referral code, and we both get some free hosting.](https://m.do.co/c/6b5df7ef55b6)
## ⛏️ Built Using <a name = "built_using"></a>
- [python-telegram-bot](https://python-telegram-bot.org/) - Python Telegram API Wrapper
- [Digital Ocean](https://www.digitalocean.com/) - IaaS hosting platform
## ✍️ author <a name = "author"></a>
- [Anson Biggs](https://blog.ansonbiggs.com/author/anson/) - The one and only
## 🎉 Acknowledgements <a name = "acknowledgement"></a>
- Telegram for having a great bot API
- IEX Cloud for offering a free tier
- Viewers like you ♥
- Follow me on [twitter](https://twitter.com/AnsonBiggs)
- Contribute to the project on [GitLab](https://gitlab.com/simple-stock-bots) or just leave a star
- Using my referral links to host your own Bot
- [DigitalOcean](https://m.do.co/c/6b5df7ef55b6)
- [IEX Cloud](https://iexcloud.io/s/62c8503e)
+50
View File
@@ -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()
+73
View File
@@ -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
+220 -291
View File
@@ -1,12 +1,15 @@
# Works with Python 3.8
import datetime
import html
import io
import json
import logging
import os
import random
import html
import json
import string
import traceback
import logging as log
from uuid import uuid4
import mplfinance as mpf
import telegram
@@ -17,323 +20,267 @@ from telegram import (
Update,
)
from telegram.ext import (
CallbackContext,
CommandHandler,
Filters,
InlineQueryHandler,
MessageHandler,
PreCheckoutQueryHandler,
Updater,
CallbackContext,
)
from functions import Symbol
from symbol_router import Router
from T_info import T_info
TELEGRAM_TOKEN = os.environ["TELEGRAM"]
try:
IEX_TOKEN = os.environ["IEX"]
except KeyError:
IEX_TOKEN = ""
print("Starting without an IEX Token will not allow you to get market data!")
try:
STRIPE_TOKEN = os.environ["STRIPE"]
except KeyError:
STRIPE_TOKEN = ""
print("Starting without a STRIPE Token will not allow you to accept Donations!")
log.warning("Starting without a STRIPE Token will not allow you to accept Donations!")
s = Router()
t = T_info()
s = Symbol(IEX_TOKEN)
# Enable logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO)
logger = logging.getLogger(__name__)
print("Bot Online")
log.info("Bot script started.")
def start(update: Update, context: CallbackContext):
"""Send a message when the command /start is issued."""
update.message.reply_text(text=s.help_text, parse_mode=telegram.ParseMode.MARKDOWN)
"""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 link to docs when the command /help is issued."""
update.message.reply_text(text=s.help_text, parse_mode=telegram.ParseMode.MARKDOWN)
"""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):
"""Return bots license agreement"""
update.message.reply_text(text=s.license, parse_mode=telegram.ParseMode.MARKDOWN)
"""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):
message = ""
try:
# Bot Status
bot_resp = (
datetime.datetime.now(update.message.date.tzinfo) - update.message.date
)
message += f"It took {bot_resp.total_seconds()} seconds for the bot to get your message.\n"
"""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
# IEX Status
message += s.iex_status() + "\n"
bot_status = s.status(f"It took {bot_resp_time.total_seconds()} seconds for the bot to get your message.")
# Message Status
message += s.message_status()
except Exception as ex:
message += (
f"*\n\nERROR ENCOUNTERED:*\n{ex}\n\n"
+ "*The bot encountered an error while attempting to find errors. Please contact the bot admin.*"
)
update.message.reply_text(text=message, parse_mode=telegram.ParseMode.MARKDOWN)
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":
if update.message.text.strip() == "/donate" or "/donate@" in update.message.text:
update.message.reply_text(
text=s.donate_text, parse_mode=telegram.ParseMode.MARKDOWN
text=t.donate_text,
parse_mode=telegram.ParseMode.MARKDOWN,
disable_notification=True,
)
return
amount = 1.0
else:
amount = update.message.text.replace("/donate", "").replace("$", "").strip()
title = "Simple Stock Bot Donation"
description = f"Simple Stock Bot Donation of ${amount}"
payload = "simple-stock-bot"
provider_token = STRIPE_TOKEN
start_parameter = str(chat_id)
print(start_parameter)
currency = "USD"
amount = float(update.message.text.replace("/donate", "").replace("$", "").strip())
try:
price = int(float(amount) * 100)
price = int(amount * 100)
except ValueError:
update.message.reply_text(f"{amount} is not a valid donation amount or number.")
return
print(price)
prices = [LabeledPrice("Donation:", price)]
log.info(f"Donation amount: {price} by {update.message.chat.username}")
context.bot.send_invoice(
chat_id,
title,
description,
payload,
provider_token,
start_parameter,
currency,
prices,
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
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...")
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):
update.message.reply_text("Thank you for your donation!")
"""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 symbols,
Runs on any message that doesn't have a command and searches for cashtags,
then returns the prices of any symbols found.
"""
message = update.message.text
chat_id = update.message.chat_id
symbols = s.find_symbols(message)
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).items():
for reply in s.price_reply(symbols):
update.message.reply_text(
text=reply[1], parse_mode=telegram.ParseMode.MARKDOWN
text=reply,
parse_mode=telegram.ParseMode.MARKDOWN,
disable_notification=True,
)
def dividend(update: Update, context: CallbackContext):
"""
waits for /dividend or /div command and then finds dividend info on that symbol.
"""
message = update.message.text
chat_id = update.message.chat_id
if message.strip() == "/dividend":
update.message.reply_text(
"This command gives info on the next dividend date for a symbol.\nExample: /dividend $tsla"
)
return
symbols = s.find_symbols(message)
if symbols:
context.bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
for symbol in symbols:
update.message.reply_text(
text=s.dividend_reply(symbol), parse_mode=telegram.ParseMode.MARKDOWN
)
def news(update: Update, context: CallbackContext):
"""
waits for /news command and then finds news info on that symbol.
"""
message = update.message.text
chat_id = update.message.chat_id
if message.strip() == "/news":
update.message.reply_text(
"This command gives the most recent english news for a symbol.\nExample: /news $tsla"
)
return
symbols = s.find_symbols(message)
if symbols:
context.bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
for reply in s.news_reply(symbols).items():
update.message.reply_text(
text=reply[1], parse_mode=telegram.ParseMode.MARKDOWN
)
def info(update: Update, context: CallbackContext):
"""
waits for /info command and then finds info on that symbol.
"""
message = update.message.text
chat_id = update.message.chat_id
if message.strip() == "/info":
update.message.reply_text(
"This command gives information on a symbol.\nExample: /info $tsla"
)
return
symbols = s.find_symbols(message)
if symbols:
context.bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
for reply in s.info_reply(symbols).items():
update.message.reply_text(
text=reply[1], parse_mode=telegram.ParseMode.MARKDOWN
)
def search(update: Update, context: CallbackContext):
message = update.message.text.replace("/search ", "")
chat_id = update.message.chat_id
if message.strip() == "/search":
update.message.reply_text(
"This command searches for symbols supported by the bot.\nExample: /search Tesla Motors or /search $tsla"
)
return
context.bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
queries = s.search_symbols(message)[:6]
if queries:
reply = "*Search Results:*\n`$ticker: Company Name`\n"
for query in queries:
reply += "`" + query[1] + "`\n"
update.message.reply_text(text=reply, parse_mode=telegram.ParseMode.MARKDOWN)
def intra(update: Update, context: CallbackContext):
# TODO: Document usage of this command. https://iexcloud.io/docs/api/#historical-prices
"""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() == "/intra":
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
symbol = s.find_symbols(message)[0]
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
)
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.upper()}",
volume=True,
title=f"\n{symbol.name}",
volume="Volume" in df.keys(),
style="yahoo",
mav=20,
savefig=dict(fname=buf, dpi=400, bbox_inches="tight"),
)
buf.seek(0)
update.message.reply_photo(
photo=buf,
caption=f"\nIntraday chart for ${symbol.upper()} from {df.first_valid_index().strftime('%I:%M')} to"
+ f" {df.last_valid_index().strftime('%I:%M')} ET on"
+ f" {datetime.date.today().strftime('%d, %b %Y')}\n\n{s.price_reply([symbol])[symbol]}",
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):
# TODO: Document usage of this command. https://iexcloud.io/docs/api/#historical-prices
"""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() == "/chart":
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
symbol = s.find_symbols(message)[0]
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
)
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.upper()}",
volume=True,
title=f"\n{symbol.name}",
volume="Volume" in df.keys(),
style="yahoo",
savefig=dict(fname=buf, dpi=400, bbox_inches="tight"),
)
@@ -341,126 +288,114 @@ def chart(update: Update, context: CallbackContext):
update.message.reply_photo(
photo=buf,
caption=f"\n1 Month chart for ${symbol.upper()} 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])[symbol]}",
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 stat(update: Update, context: CallbackContext):
"""
https://iexcloud.io/docs/api/#key-stats
"""
message = update.message.text
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
if message.strip() == "/stat":
update.message.reply_text(
"This command returns key statistics for a symbol.\nExample: /stat $tsla"
)
return
context.bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
symbols = s.find_symbols(message)
trending_list = s.trending()
log.info(trending_list)
if symbols:
context.bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
for reply in s.stat_reply(symbols).items():
update.message.reply_text(
text=reply[1], parse_mode=telegram.ParseMode.MARKDOWN
)
def crypto(update: Update, context: CallbackContext):
"""
https://iexcloud.io/docs/api/#cryptocurrency-quote
"""
context.bot.send_chat_action(
chat_id=update.message.chat_id, action=telegram.ChatAction.TYPING
update.message.reply_text(
text=trending_list,
parse_mode=telegram.ParseMode.MARKDOWN,
disable_notification=True,
)
message = update.message.text
if message.strip() == "/crypto":
update.message.reply_text(
"This command returns the current price in USD for a cryptocurrency.\nExample: /crypto eth"
)
return
reply = s.crypto_reply(message)
if reply:
update.message.reply_text(text=reply, parse_mode=telegram.ParseMode.MARKDOWN)
else:
update.message.reply_text(
text=f"Pair: {message} returned an error.",
parse_mode=telegram.ParseMode.MARKDOWN,
)
def inline_query(update: Update, context: CallbackContext):
"""
Handles inline query.
Does a fuzzy search on input and returns stocks that are close.
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}")
matches = s.search_symbols(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 match in matches:
try:
price = s.price_reply([match[0]])[match[0]]
results.append(
InlineQueryResultArticle(
match[0],
title=match[1],
input_message_content=InputTextMessageContent(
price, parse_mode=telegram.ParseMode.MARKDOWN
),
)
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),
)
except TypeError:
logging.warning(str(match))
pass
)
if len(results) == 5:
update.inline_query.answer(results)
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):
choice = random.choice(list(s.symbol_list["description"]))
hold = (
datetime.date.today() + datetime.timedelta(random.randint(1, 365))
).strftime("%b %d, %Y")
"""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=f"{choice}\nBuy and hold until: {hold}",
text=s.random_pick(),
parse_mode=telegram.ParseMode.MARKDOWN,
disable_notification=True,
)
def error(update: Update, context: CallbackContext):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
log.warning('Update "%s" caused error "%s"', update, error)
tb_list = traceback.format_exception(
None, context.error, context.error.__traceback__
)
tb_list = traceback.format_exception(None, context.error, context.error.__traceback__)
tb_string = "".join(tb_list)
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>"
)
err_code = "".join([random.choice(string.ascii_lowercase) for i in range(5)])
log.warning(f"Logging error: {err_code}")
# Finally, send the message
update.message.reply_text(text=message, parse_mode=telegram.ParseMode.HTML)
update.message.reply_text(text="Please inform the bot admin of this issue.")
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():
@@ -475,23 +410,22 @@ def main():
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("license", license))
dp.add_handler(CommandHandler("dividend", dividend))
dp.add_handler(CommandHandler("div", dividend))
dp.add_handler(CommandHandler("news", news))
dp.add_handler(CommandHandler("info", info))
dp.add_handler(CommandHandler("stat", stat))
dp.add_handler(CommandHandler("stats", stat))
dp.add_handler(CommandHandler("search", search))
dp.add_handler(CommandHandler("intraday", intra))
dp.add_handler(CommandHandler("intra", intra, run_async=True))
dp.add_handler(CommandHandler("chart", chart))
dp.add_handler(CommandHandler("crypto", crypto))
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))
@@ -500,9 +434,7 @@ def main():
dp.add_handler(PreCheckoutQueryHandler(precheckout_callback))
# Payment success
dp.add_handler(
MessageHandler(Filters.successful_payment, successful_payment_callback)
)
dp.add_handler(MessageHandler(Filters.successful_payment, successful_payment_callback))
# log all errors
dp.add_error_handler(error)
@@ -510,9 +442,6 @@ def main():
# 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()
+375
View File
@@ -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
-8
View File
@@ -1,8 +0,0 @@
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. 🔢
dividend - $[symbol] Dividend info 📅
intra - $[symbol] Plot since the last market open. 📈
chart - $[chart] Plot of the past month. 📊
+6
View File
@@ -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
-553
View File
@@ -1,553 +0,0 @@
import re
from datetime import datetime
from typing import Optional, List, Tuple, Dict
import pandas as pd
import requests as r
import schedule
from fuzzywuzzy import fuzz
class Symbol:
"""
Functions for finding stock market information about symbols.
"""
SYMBOL_REGEX = "[$]([a-zA-Z]{1,4})"
searched_symbols = {}
charts = {}
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 itsTelegram Channel: https://t.me/simplestockbotnews
Full documentation on using and running your own stock bot can be found [here.](https://simple-stock-bots.gitlab.io/site)
**Commands**
- /donate [amount in USD] to donate. 🎗️
- /dividend $[symbol] will return 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. 🔢
- /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 symbols and return the price of the ticker. Then once you select the ticker
want the bot will send a message as you in that chat with the latest stock price.
The bot also looks at every message in any chat it is in for stock symbols.Symbols start with a
`$` followed by the stock symbol. For example:$tsla would return price information for Tesla Motors.
Market data is provided by [IEX Cloud](https://iexcloud.io)
If you believe the bot is not behaving properly run `/status`.
"""
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 USdollars 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 accepts Paypal or Credit card.
If you have any questions get in touch: @MisterBiggs or[anson@ansonbiggs.com](http://mailto:anson@ansonbiggs.com/)
_Donations can only be made in a chat directly with @simplestockbot_
"""
def __init__(self, IEX_TOKEN: str) -> None:
"""Creates a Symbol Object
Parameters
----------
IEX_TOKEN : str
IEX Token
"""
self.IEX_TOKEN = IEX_TOKEN
if IEX_TOKEN != "":
self.get_symbol_list()
schedule.every().day.do(self.get_symbol_list)
schedule.every().day.do(self.clear_charts)
def clear_charts(self) -> None:
"""Clears cache of chart data."""
self.charts = {}
def get_symbol_list(self, return_df=False) -> Optional[pd.DataFrame]:
raw_symbols = r.get(
f"https://cloud.iexapis.com/stable/ref-data/symbols?token={self.IEX_TOKEN}"
).json()
symbols = pd.DataFrame(data=raw_symbols)
symbols["description"] = symbols["symbol"] + ": " + symbols["name"]
self.symbol_list = symbols
if return_df:
return symbols, datetime.now()
def iex_status(self) -> str:
"""Checks IEX Status dashboard for any current API issues.
Returns
-------
str
Human readable text on status of IEX API
"""
status = r.get("https://pjmps0c34hp7.statuspage.io/api/v2/status.json").json()[
"status"
]
if status["indicator"] == "none":
return "IEX Cloud is currently not reporting any issues with its API."
else:
return (
f"{status['indicator']}: {status['description']}."
+ " Please check the status page for more information. https://status.iexapis.com"
)
def message_status(self) -> str:
"""Checks to see if the bot has available IEX Credits
Returns
-------
str
Human readable text on status of IEX Credits.
"""
usage = r.get(
f"https://cloud.iexapis.com/stable/account/metadata?token={self.IEX_TOKEN}"
).json()
try:
if (
usage["messagesUsed"] >= usage["messageLimit"] - 10000
and not usage["payAsYouGoEnabled"]
):
return "Bot may be out of IEX Credits."
else:
return "Bot has available IEX Credits."
except KeyError:
return "**IEX API could not be reached.**"
def search_symbols(self, search: str) -> List[Tuple[str, str]]:
"""Performs a fuzzy search to find stock symbols closest to a search term.
Parameters
----------
search : str
String used to search, could be a company name or something close to the companies stock ticker.
Returns
-------
List[tuple[str, str]]
A list tuples of every stock sorted in order of how well they match. Each tuple contains: (Symbol, Issue Name).
"""
schedule.run_pending()
search = search.lower()
try: # https://stackoverflow.com/a/3845776/8774114
return self.searched_symbols[search]
except KeyError:
pass
symbols = self.symbol_list
symbols["Match"] = symbols.apply(
lambda x: fuzz.ratio(search, f"{x['symbol']}".lower()),
axis=1,
)
symbols.sort_values(by="Match", ascending=False, inplace=True)
if symbols["Match"].head().sum() < 300:
symbols["Match"] = symbols.apply(
lambda x: fuzz.partial_ratio(search, x["name"].lower()),
axis=1,
)
symbols.sort_values(by="Match", ascending=False, inplace=True)
symbols = symbols.head(10)
symbol_list = list(zip(list(symbols["symbol"]), list(symbols["description"])))
self.searched_symbols[search] = symbol_list
return symbol_list
def find_symbols(self, text: str) -> List[str]:
"""Finds stock tickers starting with a dollar sign in a blob of text and returns them in a list.
Only returns each match once. Example: Whats the price of $tsla?
Parameters
----------
text : str
Blob of text.
Returns
-------
List[str]
List of stock symbols as strings without dollar sign.
"""
return list(set(re.findall(self.SYMBOL_REGEX, text)))
def price_reply(self, symbols: list) -> Dict[str, 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.
"""
dataMessages = {}
for symbol in symbols:
IEXurl = f"https://cloud.iexapis.com/stable/stock/{symbol}/quote?token={self.IEX_TOKEN}"
response = r.get(IEXurl)
if response.status_code == 200:
IEXData = response.json()
keys = (
"isUSMarketOpen",
"extendedChangePercent",
"extendedPrice",
"companyName",
"latestPrice",
"changePercent",
)
if set(keys).issubset(IEXData):
try: # Some symbols dont return if the market is open
IEXData["isUSMarketOpen"]
except KeyError:
IEXData["isUSMarketOpen"] = True
if (
IEXData["isUSMarketOpen"]
or (IEXData["extendedChangePercent"] is None)
or (IEXData["extendedPrice"] is None)
): # Check if market is open.
message = f"The current stock price of {IEXData['companyName']} is $**{IEXData['latestPrice']}**"
try:
change = round(IEXData["changePercent"] * 100, 2)
except (KeyError, TypeError):
change = 0
else:
message = (
f"{IEXData['companyName']} closed at $**{IEXData['latestPrice']}**,"
+ f" after hours _(15 minutes delayed)_ the stock price is $**{IEXData['extendedPrice']}**"
)
change = round(IEXData["extendedChangePercent"] * 100, 2)
# Determine wording of change text
if change > 0:
message += f", the stock is currently **up {change}%**"
elif change < 0:
message += f", the stock is currently **down {change}%**"
else:
message += ", the stock hasn't shown any movement today."
else:
message = f"The symbol: {symbol} encountered and error. This could be due to the symbol not being fully supported by IEX Cloud."
else:
message = f"The symbol: {symbol} was not found."
if symbol.upper() == "GME":
message += "\n\n🙌💎Power to the Players💎🙌"
if IEXData["latestPrice"] is None:
message = f"{symbol} has not reported price info to IEX Cloud."
dataMessages[symbol] = message
return dataMessages
def dividend_reply(self, symbol: str) -> Dict[str, str]:
"""Returns the most recent, or next dividend date for a stock symbol.
Parameters
----------
symbols : list
List of stock symbols.
Returns
-------
Dict[str, str]
Each symbol passed in is a key with its value being a human readable formatted string of the symbols div dates.
"""
IEXurl = f"https://cloud.iexapis.com/stable/stock/{symbol}/dividends/next?token={self.IEX_TOKEN}"
response = r.get(IEXurl)
if response.status_code == 200 and response.json():
IEXData = response.json()[0]
keys = (
"amount",
"currency",
"declaredDate",
"exDate",
"frequency",
"paymentDate",
"flag",
)
if set(keys).issubset(IEXData):
if IEXData["currency"] == "USD":
price = f"${IEXData['amount']}"
else:
price = f"{IEXData['amount']} {IEXData['currency']}"
# Pattern IEX uses for dividend date.
pattern = "%Y-%m-%d"
declared = datetime.strptime(IEXData["declaredDate"], pattern).strftime(
"%A, %B %w"
)
ex = datetime.strptime(IEXData["exDate"], pattern).strftime("%A, %B %w")
payment = datetime.strptime(IEXData["paymentDate"], pattern).strftime(
"%A, %B %w"
)
daysDelta = (
datetime.strptime(IEXData["paymentDate"], pattern) - datetime.now()
).days
return (
f"The next dividend for ${self.symbol_list[self.symbol_list['symbol']==symbol.upper()]['description'].item()}"
+ f" is on {payment} which is in {daysDelta} days."
+ f" The dividend is for {price} per share."
+ f"\nThe dividend was declared on {declared} and the ex-dividend date is {ex}"
)
return f"{symbol} either doesn't exist or pays no dividend."
def news_reply(self, symbols: list) -> Dict[str, str]:
"""Gets recent english news on stock symbols.
Parameters
----------
symbols : list
List of stock symbols.
Returns
-------
Dict[str, str]
Each symbol passed in is a key with its value being a human readable markdown formatted string of the symbols news.
"""
newsMessages = {}
for symbol in symbols:
IEXurl = f"https://cloud.iexapis.com/stable/stock/{symbol}/news/last/5?token={self.IEX_TOKEN}"
response = r.get(IEXurl)
if response.status_code == 200:
data = response.json()
if len(data):
newsMessages[symbol] = f"News for **{symbol.upper()}**:\n\n"
for news in data:
if news["lang"] == "en" and not news["hasPaywall"]:
message = f"*{news['source']}*: [{news['headline']}]({news['url']})\n"
newsMessages[symbol] = newsMessages[symbol] + message
else:
newsMessages[
symbol
] = f"No news found for: {symbol}\nEither today is boring or the symbol does not exist."
else:
newsMessages[
symbol
] = f"No news found for: {symbol}\nEither today is boring or the symbol does not exist."
return newsMessages
def info_reply(self, symbols: List[str]) -> Dict[str, 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.
"""
infoMessages = {}
for symbol in symbols:
IEXurl = f"https://cloud.iexapis.com/stable/stock/{symbol}/company?token={self.IEX_TOKEN}"
response = r.get(IEXurl)
if response.status_code == 200:
data = response.json()
infoMessages[symbol] = (
f"Company Name: [{data['companyName']}]({data['website']})\nIndustry:"
+ f" {data['industry']}\nSector: {data['sector']}\nCEO: {data['CEO']}\nDescription: {data['description']}\n"
)
else:
infoMessages[
symbol
] = f"No information found for: {symbol}\nEither today is boring or the symbol does not exist."
return infoMessages
def intra_reply(self, symbol: str) -> pd.DataFrame:
"""Returns price data for a symbol since the last market open.
Parameters
----------
symbol : str
Stock symbol.
Returns
-------
pd.DataFrame
Returns a timeseries dataframe with high, low, and volume data if its available. Otherwise returns empty pd.DataFrame.
"""
if symbol.upper() not in list(self.symbol_list["symbol"]):
return pd.DataFrame()
IEXurl = f"https://cloud.iexapis.com/stable/stock/{symbol}/intraday-prices?token={self.IEX_TOKEN}"
response = r.get(IEXurl)
if response.status_code == 200:
df = pd.DataFrame(response.json())
df.dropna(inplace=True, subset=["date", "minute", "high", "low", "volume"])
df["DT"] = pd.to_datetime(df["date"] + "T" + df["minute"])
df = df.set_index("DT")
return df
return pd.DataFrame()
def chart_reply(self, symbol: str) -> pd.DataFrame:
"""Returns price data for a symbol of the past month up until the previous trading days close.
Also caches multiple requests made in the same day.
Parameters
----------
symbol : str
Stock symbol.
Returns
-------
pd.DataFrame
Returns a timeseries dataframe with high, low, and volume data if its available. Otherwise returns empty pd.DataFrame.
"""
schedule.run_pending()
if symbol.upper() not in list(self.symbol_list["symbol"]):
return pd.DataFrame()
try: # https://stackoverflow.com/a/3845776/8774114
return self.charts[symbol.upper()]
except KeyError:
pass
response = r.get(
f"https://cloud.iexapis.com/stable/stock/{symbol}/chart/1mm?token={self.IEX_TOKEN}&chartInterval=3&includeToday=false"
)
if response.status_code == 200:
df = pd.DataFrame(response.json())
df.dropna(inplace=True, subset=["date", "minute", "high", "low", "volume"])
df["DT"] = pd.to_datetime(df["date"] + "T" + df["minute"])
df = df.set_index("DT")
self.charts[symbol.upper()] = df
return df
return pd.DataFrame()
def stat_reply(self, symbols: List[str]) -> Dict[str, 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.
"""
infoMessages = {}
for symbol in symbols:
IEXurl = f"https://cloud.iexapis.com/stable/stock/{symbol}/stats?token={self.IEX_TOKEN}"
response = r.get(IEXurl)
if response.status_code == 200:
data = response.json()
[data.pop(k) for k in list(data) if data[k] == ""]
m = ""
if "companyName" in data:
m += f"Company Name: {data['companyName']}\n"
if "marketcap" in data:
m += f"Market Cap: {data['marketcap']:,}\n"
if "week52high" in data:
m += f"52 Week (high-low): {data['week52high']:,} "
if "week52low" in data:
m += f"- {data['week52low']:,}\n"
if "employees" in data:
m += f"Number of Employees: {data['employees']:,}\n"
if "nextEarningsDate" in data:
m += f"Next Earnings Date: {data['nextEarningsDate']}\n"
if "peRatio" in data:
m += f"Price to Earnings: {data['peRatio']:.3f}\n"
if "beta" in data:
m += f"Beta: {data['beta']:.3f}\n"
infoMessages[symbol] = m
else:
infoMessages[
symbol
] = f"No information found for: {symbol}\nEither today is boring or the symbol does not exist."
return infoMessages
def crypto_reply(self, pair: str) -> str:
"""Returns the current price of a cryptocurrency
Parameters
----------
pair : str
symbol for the cryptocurrency, sometimes with a price pair like ETHUSD
Returns
-------
str
Returns a human readable markdown description of the price, or an empty string if no price was found.
"""
pair = pair.split(" ")[-1].replace("/", "").upper()
pair += "USD" if len(pair) == 3 else pair
IEXurl = f"https://cloud.iexapis.com/stable/crypto/{pair}/quote?token={self.IEX_TOKEN}"
response = r.get(IEXurl)
if response.status_code == 200:
data = response.json()
quote = f"Symbol: {data['symbol']}\n"
quote += f"Price: ${data['latestPrice']}\n"
new, old = data["latestPrice"], data["previousClose"]
if old is not None:
change = (float(new) - float(old)) / float(old)
quote += f"Change: {change}\n"
return quote
else:
return ""
+8
View File
@@ -0,0 +1,8 @@
[tool.black]
line-length = 130
[tool.flake8]
max-line-length = 130
[tool.pycodestyle]
max_line_length = 130
+5 -5
View File
@@ -1,7 +1,7 @@
python-telegram-bot==13.2
python-telegram-bot==13.5
requests==2.25.1
pandas==1.2.1
fuzzywuzzy==0.18.0
python-Levenshtein==0.12.1
pandas==2.0.0
schedule==1.0.0
mplfinance==0.12.7a5
mplfinance==0.12.7a5
markdownify==0.6.5
cachetools==4.2.2
+399
View File
@@ -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
+33
View File
@@ -0,0 +1,33 @@
import keyboard
import time
tests = """$$xno
/info $tsla
/info $$btc
/news $tsla
/news $$btc
/stat $tsla
/stat $$btc
/cap $tsla
/cap $$btc
/dividend $tsla
/dividend $msft
/dividend $$btc
/intra $tsla
/intra $$btc
/chart $tsla
/chart $$btc
/help
/trending""".split(
"\n"
)
print("press enter to start")
keyboard.wait("enter")
for test in tests:
print(test)
keyboard.write(test)
time.sleep(1)
keyboard.press_and_release("enter")