mirror of
https://gitlab.com/simple-stock-bots/simple-stock-bot.git
synced 2026-06-03 21:00:26 +00:00
Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 29240b99ac | |||
| 4abe4fedcc | |||
| 5b12ed1ce4 | |||
| c6a0320563 | |||
| bca9b3e111 | |||
| cedacc5749 | |||
| b72f0518c2 | |||
| bc1ad95c75 | |||
| 7966871869 |
@@ -13,7 +13,7 @@ COPY --from=builder /root/.local /root/.local
|
||||
|
||||
RUN pip install --no-cache-dir black
|
||||
ENV TELEGRAM=TOKEN
|
||||
ENV MARKETDATA=TOKEN
|
||||
ENV IEX=TOKEN
|
||||
|
||||
COPY . .
|
||||
|
||||
|
||||
+2
-2
@@ -16,7 +16,7 @@ build:master:
|
||||
--dockerfile "${CI_PROJECT_DIR}/Dockerfile"
|
||||
--destination "${CI_REGISTRY_IMAGE}:latest"
|
||||
rules:
|
||||
- if: '$CI_COMMIT_BRANCH == "master"'
|
||||
- if: '$CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "master"'
|
||||
|
||||
|
||||
build:branch:
|
||||
@@ -31,4 +31,4 @@ build:branch:
|
||||
--destination "${CI_REGISTRY_IMAGE}:${CI_COMMIT_SHORT_SHA}"
|
||||
--destination "${CI_REGISTRY_IMAGE}:${CI_COMMIT_BRANCH}"
|
||||
rules:
|
||||
- if: '$CI_COMMIT_BRANCH != "master"'
|
||||
- if: '$CI_MERGE_REQUEST_TARGET_BRANCH_NAME != "master"'
|
||||
+7
-44
@@ -1,6 +1,10 @@
|
||||
"""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
|
||||
@@ -9,8 +13,6 @@ import schedule
|
||||
|
||||
from Symbol import Stock
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class MarketData:
|
||||
"""
|
||||
@@ -36,7 +38,7 @@ class MarketData:
|
||||
self.MARKETDATA_TOKEN = ""
|
||||
except KeyError:
|
||||
self.MARKETDATA_TOKEN = ""
|
||||
log.warning("Starting without an MarketData.app Token will not allow you to get market data!")
|
||||
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)
|
||||
@@ -83,27 +85,7 @@ class MarketData:
|
||||
self.charts = {}
|
||||
|
||||
def status(self) -> str:
|
||||
# TODO: At the moment this API is poorly documented, this function likely needs to be revisited later.
|
||||
|
||||
try:
|
||||
status = r.get(
|
||||
"https://stats.uptimerobot.com/api/getMonitorList/6Kv3zIow0A",
|
||||
timeout=5,
|
||||
)
|
||||
status.raise_for_status()
|
||||
except r.HTTPError:
|
||||
return f"API returned an HTTP error code {status.status_code} in {status.elapsed.total_seconds()} Seconds."
|
||||
except r.Timeout:
|
||||
return "API timed out before it was able to give status. This is likely due to a surge in usage or a complete outage."
|
||||
|
||||
statusJSON = status.json()
|
||||
|
||||
if statusJSON["status"] == "ok":
|
||||
return (
|
||||
f"CoinGecko API responded that it was OK with a {status.status_code} in {status.elapsed.total_seconds()} Seconds."
|
||||
)
|
||||
else:
|
||||
return f"MarketData.app is currently reporting the following status: {statusJSON['status']}"
|
||||
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.
|
||||
@@ -119,30 +101,11 @@ class MarketData:
|
||||
"""
|
||||
|
||||
if quoteResp := self.get(f"stocks/quotes/{symbol}/"):
|
||||
price = round(quoteResp["last"][0], 2)
|
||||
changePercent = round(quoteResp["changepct"][0], 2)
|
||||
return f"The current price of {quoteResp['symbol']} is ${quoteResp['last']}"
|
||||
|
||||
message = f"The current price of {symbol.name} is ${price} and "
|
||||
|
||||
if changePercent > 0.0:
|
||||
message += f"is currently up {changePercent}% for the day."
|
||||
elif changePercent < 0.0:
|
||||
message += f"is currently down {changePercent}% for the day."
|
||||
else:
|
||||
message += "hasn't shown any movement for the day."
|
||||
|
||||
return message
|
||||
else:
|
||||
return f"Getting a quote for {symbol} encountered an error."
|
||||
|
||||
def spark_reply(self, symbol: Stock) -> str:
|
||||
if quoteResp := self.get(f"stocks/quotes/{symbol}/"):
|
||||
changePercent = round(quoteResp["changepct"][0], 2)
|
||||
return f"`{symbol.tag}`: {changePercent}%"
|
||||
else:
|
||||
logging.warning(f"{symbol} did not have 'changepct' field.")
|
||||
return f"`{symbol.tag}`"
|
||||
|
||||
def intra_reply(self, symbol: Stock) -> pd.DataFrame:
|
||||
"""Returns price data for a symbol of the past month up until the previous trading days close.
|
||||
Also caches multiple requests made in the same day.
|
||||
|
||||
@@ -15,7 +15,7 @@ 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 [Market Data](https://www.marketdata.app/).
|
||||
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.
|
||||
|
||||
@@ -29,4 +29,4 @@ If you have any questions get in [touch.](contact.md)
|
||||
- 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)
|
||||
- [Market Data](https://www.marketdata.app/)
|
||||
- [IEX Cloud](https://iexcloud.io/s/62c8503e)
|
||||
|
||||
@@ -32,8 +32,8 @@ class Stock(Symbol):
|
||||
def __init__(self, symbol: str) -> None:
|
||||
self.symbol = symbol
|
||||
self.id = symbol
|
||||
self.name = "$" + symbol.upper()
|
||||
self.tag = "$" + symbol.lower()
|
||||
self.name = "$" + symbol
|
||||
self.tag = "$" + symbol.upper()
|
||||
|
||||
|
||||
class Coin(Symbol):
|
||||
|
||||
@@ -26,15 +26,20 @@ Simply calling a symbol in any message that the bot can see will also return the
|
||||
|
||||
**Commands**
|
||||
- `/donate [amount in USD]` to donate. 🎗️
|
||||
- `/dividend $[symbol]` Dividend information for the symbol. 📅
|
||||
- `/intra $[symbol]` Plot of the stocks movement since the last market open. 📈
|
||||
- `/chart $[symbol]` Plot of the stocks movement for the past 1 month. 📊
|
||||
- `/news $[symbol]` News about the symbol. 📰
|
||||
- `/info $[symbol]` General information about the symbol. ℹ️
|
||||
- `/stat $[symbol]` Key statistics about the symbol. 🔢
|
||||
- `/cap $[symbol]` Market Capitalization of symbol. 💰
|
||||
- `/trending` Trending Stocks and Cryptos. 💬
|
||||
- `/help` Get some help using the bot. 🆘
|
||||
|
||||
**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 [Market Data](https://www.marketdata.app/)
|
||||
|
||||
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).
|
||||
"""
|
||||
@@ -42,7 +47,7 @@ Simply calling a symbol in any message that the bot can see will also return the
|
||||
donate_text = """
|
||||
Simple Stock Bot is run entirely on donations[.](https://www.buymeacoffee.com/Anson)
|
||||
All donations go directly towards paying for servers, and market data is provided by
|
||||
[Market Data](https://www.marketdata.app/).
|
||||
[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.
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import os
|
||||
import random
|
||||
import string
|
||||
import traceback
|
||||
import logging as log
|
||||
from uuid import uuid4
|
||||
|
||||
import mplfinance as mpf
|
||||
@@ -31,10 +32,6 @@ from telegram.ext import (
|
||||
from symbol_router import Router
|
||||
from T_info import T_info
|
||||
|
||||
# Enable logging
|
||||
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO)
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
TELEGRAM_TOKEN = os.environ["TELEGRAM"]
|
||||
|
||||
try:
|
||||
@@ -46,7 +43,10 @@ except KeyError:
|
||||
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.")
|
||||
|
||||
|
||||
@@ -304,6 +304,7 @@ def trending(update: Update, context: CallbackContext):
|
||||
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,
|
||||
@@ -379,22 +380,23 @@ def error(update: Update, context: CallbackContext):
|
||||
log.warning(f"Logging error: {err_code}")
|
||||
|
||||
if update:
|
||||
log.warning(
|
||||
message = (
|
||||
f"An exception was raised while handling an update\n"
|
||||
f"\tupdate = {html.escape(json.dumps(update.to_dict(), indent=2, ensure_ascii=False))}\n"
|
||||
f"\tcontext.chat_data = {str(context.chat_data)}\n"
|
||||
f"\tcontext.user_data = {str(context.user_data)}\n"
|
||||
f"\t{html.escape(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,
|
||||
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("No message to send to user.")
|
||||
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."""
|
||||
|
||||
+11
-3
@@ -1,4 +1,7 @@
|
||||
import logging
|
||||
"""Class with functions for running the bot with IEX Cloud.
|
||||
"""
|
||||
|
||||
import logging as log
|
||||
from typing import List
|
||||
|
||||
import pandas as pd
|
||||
@@ -8,8 +11,6 @@ from markdownify import markdownify
|
||||
|
||||
from Symbol import Coin
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class cg_Crypto:
|
||||
"""
|
||||
@@ -21,6 +22,13 @@ class cg_Crypto:
|
||||
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)
|
||||
|
||||
|
||||
+1
-2
@@ -3,5 +3,4 @@ black==23.3.0
|
||||
flake8==5.0.4
|
||||
Flake8-pyproject==1.2.3
|
||||
pylama==8.4.1
|
||||
mypy==1.2.0
|
||||
types-cachetools==5.3.0.5
|
||||
mypy==1.2.0
|
||||
+32
-28
@@ -5,6 +5,7 @@ import datetime
|
||||
import logging
|
||||
import random
|
||||
import re
|
||||
from logging import critical, debug, error, info, warning
|
||||
|
||||
import pandas as pd
|
||||
import schedule
|
||||
@@ -14,15 +15,11 @@ from cg_Crypto import cg_Crypto
|
||||
from MarketData import MarketData
|
||||
from Symbol import Coin, Stock, Symbol
|
||||
|
||||
from typing import Dict
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Router:
|
||||
STOCK_REGEX = "(?:^|[^\\$])\\$([a-zA-Z.]{1,6})"
|
||||
CRYPTO_REGEX = "[$]{2}([a-zA-Z]{1,20})"
|
||||
trending_count: Dict[str, float] = {}
|
||||
trending_count = {}
|
||||
|
||||
def __init__(self):
|
||||
self.stock = MarketData()
|
||||
@@ -46,9 +43,9 @@ class Router:
|
||||
t_copy.pop(dead)
|
||||
|
||||
self.trending_count = t_copy.copy()
|
||||
log.info("Decayed trending symbols.")
|
||||
info("Decayed trending symbols.")
|
||||
|
||||
def find_symbols(self, text: str, *, trending_weight: int = 1) -> list[Stock | Symbol]:
|
||||
def find_symbols(self, text: str, *, trending_weight: int = 1) -> list[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.
|
||||
|
||||
@@ -64,7 +61,7 @@ class Router:
|
||||
"""
|
||||
schedule.run_pending()
|
||||
|
||||
symbols: list[Symbol] = []
|
||||
symbols = []
|
||||
stocks = set(re.findall(self.STOCK_REGEX, text))
|
||||
for stock in stocks:
|
||||
# Market data lacks tools to check if a symbol is valid.
|
||||
@@ -73,16 +70,16 @@ class Router:
|
||||
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:
|
||||
if ~sym.empty:
|
||||
symbols.append(Coin(sym))
|
||||
else:
|
||||
info(f"{coin} is not in list of coins")
|
||||
if symbols:
|
||||
info(symbols)
|
||||
for symbol in symbols:
|
||||
self.trending_count[symbol.tag] = self.trending_count.get(symbol.tag, 0) + trending_weight
|
||||
log.warning(self.trending_count)
|
||||
|
||||
return symbols
|
||||
return symbols
|
||||
|
||||
def status(self, bot_resp) -> str:
|
||||
"""Checks for any issues with APIs.
|
||||
@@ -104,7 +101,7 @@ class Router:
|
||||
{self.crypto.status()}
|
||||
"""
|
||||
|
||||
log.warning(stats)
|
||||
warning(stats)
|
||||
|
||||
return stats
|
||||
|
||||
@@ -153,13 +150,13 @@ class Router:
|
||||
replies = []
|
||||
|
||||
for symbol in symbols:
|
||||
log.info(symbol)
|
||||
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")
|
||||
info(f"{symbol} is not a Stock or Coin")
|
||||
|
||||
return replies
|
||||
|
||||
@@ -185,7 +182,7 @@ class Router:
|
||||
elif isinstance(symbol, Coin):
|
||||
replies.append(self.crypto.info_reply(symbol))
|
||||
else:
|
||||
log.debug(f"{symbol} is not a Stock or Coin")
|
||||
debug(f"{symbol} is not a Stock or Coin")
|
||||
|
||||
return replies
|
||||
|
||||
@@ -209,7 +206,7 @@ class Router:
|
||||
elif isinstance(symbol, Coin):
|
||||
return self.crypto.intra_reply(symbol)
|
||||
else:
|
||||
log.debug(f"{symbol} is not a Stock or Coin")
|
||||
debug(f"{symbol} is not a Stock or Coin")
|
||||
return pd.DataFrame()
|
||||
|
||||
def chart_reply(self, symbol: Symbol) -> pd.DataFrame:
|
||||
@@ -232,7 +229,7 @@ class Router:
|
||||
elif isinstance(symbol, Coin):
|
||||
return self.crypto.chart_reply(symbol)
|
||||
else:
|
||||
log.debug(f"{symbol} is not a Stock or Coin")
|
||||
debug(f"{symbol} is not a Stock or Coin")
|
||||
return pd.DataFrame()
|
||||
|
||||
def stat_reply(self, symbols: list[Symbol]) -> list[str]:
|
||||
@@ -257,7 +254,7 @@ class Router:
|
||||
elif isinstance(symbol, Coin):
|
||||
replies.append(self.crypto.stat_reply(symbol))
|
||||
else:
|
||||
log.debug(f"{symbol} is not a Stock or Coin")
|
||||
debug(f"{symbol} is not a Stock or Coin")
|
||||
|
||||
return replies
|
||||
|
||||
@@ -283,7 +280,7 @@ class Router:
|
||||
elif isinstance(symbol, Coin):
|
||||
replies.append(self.crypto.cap_reply(symbol))
|
||||
else:
|
||||
log.debug(f"{symbol} is not a Stock or Coin")
|
||||
debug(f"{symbol} is not a Stock or Coin")
|
||||
|
||||
return replies
|
||||
|
||||
@@ -304,11 +301,12 @@ class Router:
|
||||
|
||||
for symbol in symbols:
|
||||
if isinstance(symbol, Stock):
|
||||
replies.append(self.stock.spark_reply(symbol))
|
||||
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")
|
||||
debug(f"{symbol} is not a Stock or Coin")
|
||||
|
||||
return replies
|
||||
|
||||
@@ -322,21 +320,26 @@ class Router:
|
||||
List of preformatted strings to be sent to user.
|
||||
"""
|
||||
|
||||
# stocks = self.stock.trending()
|
||||
stocks = self.stock.trending()
|
||||
coins = self.crypto.trending()
|
||||
|
||||
reply = ""
|
||||
|
||||
log.warning(self.trending_count)
|
||||
if self.trending_count:
|
||||
reply += "🔥Trending on the Stock Bot:\n`"
|
||||
reply += "━" * len("Trending on the Stock Bot:") + "`\n"
|
||||
|
||||
sorted_trending = [s[0] for s in sorted(self.trending_count.items(), key=lambda item: item[1])][::-1][0:5]
|
||||
log.warning(sorted_trending)
|
||||
|
||||
for t in sorted_trending:
|
||||
reply += self.spark_reply(self.find_symbols(t))[0] + "\n"
|
||||
|
||||
if stocks:
|
||||
reply += "\n\n💵Trending Stocks:\n`"
|
||||
reply += "━" * len("Trending Stocks:") + "`\n"
|
||||
for stock in stocks:
|
||||
reply += stock + "\n"
|
||||
|
||||
if coins:
|
||||
reply += "\n\n🦎Trending Crypto:\n`"
|
||||
reply += "━" * len("Trending Crypto:") + "`\n"
|
||||
@@ -349,7 +352,7 @@ class Router:
|
||||
if reply:
|
||||
return reply
|
||||
else:
|
||||
log.warning("Failed to collect trending data.")
|
||||
warning("Failed to collect trending data.")
|
||||
return "Trending data is not currently available."
|
||||
|
||||
def random_pick(self) -> str:
|
||||
@@ -382,9 +385,10 @@ class Router:
|
||||
elif isinstance(symbol, Coin):
|
||||
coins.append(symbol)
|
||||
else:
|
||||
log.debug(f"{symbol} is not a Stock or Coin")
|
||||
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:
|
||||
|
||||
Reference in New Issue
Block a user