mirror of
https://gitlab.com/simple-stock-bots/simple-stock-bot.git
synced 2025-06-16 15:17:28 +00:00
cleanup and readability changes
This commit is contained in:
parent
baf3757206
commit
3c506e124f
21
bot.py
21
bot.py
@ -1,4 +1,4 @@
|
|||||||
# Work with Python 3.7
|
# Works with Python 3.7
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
|
||||||
@ -7,7 +7,6 @@ from functions import *
|
|||||||
from telegram.ext import CommandHandler, Filters, MessageHandler, Updater
|
from telegram.ext import CommandHandler, Filters, MessageHandler, Updater
|
||||||
|
|
||||||
TELEGRAM_TOKEN = os.environ["TELEGRAM"]
|
TELEGRAM_TOKEN = os.environ["TELEGRAM"]
|
||||||
symbol_REGEX = "[$]([a-zA-Z]{1,4})"
|
|
||||||
|
|
||||||
# Enable logging
|
# Enable logging
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
@ -27,7 +26,7 @@ def start(bot, update):
|
|||||||
|
|
||||||
def help(bot, update):
|
def help(bot, update):
|
||||||
"""Send link to docs when the command /help is issued."""
|
"""Send link to docs when the command /help is issued."""
|
||||||
message = "[Please see the docs for Bot information](https://simple-stock-bots.gitlab.io/site/telegram/)"
|
message = "[Please see the documentaion for Bot information](https://simple-stock-bots.gitlab.io/site/telegram/)"
|
||||||
update.message.reply_text(text=message, parse_mode=telegram.ParseMode.MARKDOWN)
|
update.message.reply_text(text=message, parse_mode=telegram.ParseMode.MARKDOWN)
|
||||||
|
|
||||||
|
|
||||||
@ -43,10 +42,10 @@ def symbolDetect(bot, update):
|
|||||||
# Let user know bot is working
|
# Let user know bot is working
|
||||||
bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
|
bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
|
||||||
|
|
||||||
for symbol, reply in symbolDataReply(symbols).items():
|
for reply in symbolDataReply(symbols).items():
|
||||||
|
|
||||||
update.message.reply_text(
|
update.message.reply_text(
|
||||||
text=reply, parse_mode=telegram.ParseMode.MARKDOWN
|
text=reply[1], parse_mode=telegram.ParseMode.MARKDOWN
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@ -61,10 +60,10 @@ def dividend(bot, update):
|
|||||||
if symbols:
|
if symbols:
|
||||||
bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
|
bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
|
||||||
|
|
||||||
for symbol, reply in symbolDividend(symbols).items():
|
for reply in symbolDividend(symbols).items():
|
||||||
|
|
||||||
update.message.reply_text(
|
update.message.reply_text(
|
||||||
text=reply, parse_mode=telegram.ParseMode.MARKDOWN
|
text=reply[1], parse_mode=telegram.ParseMode.MARKDOWN
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@ -79,10 +78,10 @@ def news(bot, update):
|
|||||||
if symbols:
|
if symbols:
|
||||||
bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
|
bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
|
||||||
|
|
||||||
for symbol, reply in symbolNews(symbols).items():
|
for reply in symbolNews(symbols).items():
|
||||||
|
|
||||||
update.message.reply_text(
|
update.message.reply_text(
|
||||||
text=reply, parse_mode=telegram.ParseMode.MARKDOWN
|
text=reply[1], parse_mode=telegram.ParseMode.MARKDOWN
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@ -97,10 +96,10 @@ def info(bot, update):
|
|||||||
if symbols:
|
if symbols:
|
||||||
bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
|
bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
|
||||||
|
|
||||||
for symbol, reply in symbolInfo(symbols).items():
|
for reply in symbolInfo(symbols).items():
|
||||||
|
|
||||||
update.message.reply_text(
|
update.message.reply_text(
|
||||||
text=reply, parse_mode=telegram.ParseMode.MARKDOWN
|
text=reply[1], parse_mode=telegram.ParseMode.MARKDOWN
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
83
functions.py
83
functions.py
@ -1,16 +1,17 @@
|
|||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import urllib.request
|
|
||||||
import requests
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
IEX_TOKEN = "sk_130b8e8f75ba4e14a5683ff37a655584" # os.environ["IEX"]
|
import requests
|
||||||
|
|
||||||
|
IEX_TOKEN = os.environ["IEX"]
|
||||||
|
# "sk_130b8e8f75ba4e14a5683ff37a655584"
|
||||||
|
|
||||||
|
|
||||||
def getSymbols(text: str):
|
def getSymbols(text: str):
|
||||||
"""
|
"""
|
||||||
Takes a blob of text and returns any stock symbols found.
|
Takes a blob of text and returns a list of symbols without any repeats.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
SYMBOL_REGEX = "[$]([a-zA-Z]{1,4})"
|
SYMBOL_REGEX = "[$]([a-zA-Z]{1,4})"
|
||||||
@ -20,105 +21,107 @@ def getSymbols(text: str):
|
|||||||
|
|
||||||
def symbolDataReply(symbols: list):
|
def symbolDataReply(symbols: list):
|
||||||
"""
|
"""
|
||||||
Takes a list of symbols and returns a list of strings with information about the symbol.
|
Takes a list of symbols and returns a dictionary of strings with information about the symbol.
|
||||||
"""
|
"""
|
||||||
symbolReplies = {}
|
dataMessages = {}
|
||||||
for symbol in symbols:
|
for symbol in symbols:
|
||||||
IEXURL = (
|
IEXurl = (
|
||||||
f"https://cloud.iexapis.com/stable/stock/{symbol}/quote?token={IEX_TOKEN}"
|
f"https://cloud.iexapis.com/stable/stock/{symbol}/quote?token={IEX_TOKEN}"
|
||||||
)
|
)
|
||||||
try:
|
|
||||||
with urllib.request.urlopen(IEXURL) as url:
|
|
||||||
IEXData = json.loads(url.read().decode())
|
|
||||||
|
|
||||||
reply = f"The current stock price of {IEXData['companyName']} is $**{IEXData['latestPrice']}**"
|
response = requests.get(IEXurl)
|
||||||
|
if response.status_code is 200:
|
||||||
|
IEXData = response.json()
|
||||||
|
message = f"The current stock price of {IEXData['companyName']} is $**{IEXData['latestPrice']}**"
|
||||||
|
|
||||||
# Determine wording of change text
|
# Determine wording of change text
|
||||||
change = round(IEXData["changePercent"] * 100, 2)
|
change = round(IEXData["changePercent"] * 100, 2)
|
||||||
if change > 0:
|
if change > 0:
|
||||||
reply += f", the stock is currently **up {change}%**"
|
message += f", the stock is currently **up {change}%**"
|
||||||
elif change < 0:
|
elif change < 0:
|
||||||
reply += f", the stock is currently **down {change}%**"
|
message += f", the stock is currently **down {change}%**"
|
||||||
else:
|
else:
|
||||||
reply += ", the stock hasn't shown any movement today."
|
message += ", the stock hasn't shown any movement today."
|
||||||
except:
|
else:
|
||||||
reply = f"The symbol: {symbol} was not found."
|
message = f"The symbol: {symbol} was not found."
|
||||||
|
|
||||||
symbolReplies[symbol] = reply
|
dataMessages[symbol] = message
|
||||||
|
|
||||||
return symbolReplies
|
return dataMessages
|
||||||
|
|
||||||
|
|
||||||
def symbolDividend(symbols: list):
|
def symbolDividend(symbols: list):
|
||||||
messages = {}
|
divMessages = {}
|
||||||
|
|
||||||
for symbol in symbols:
|
for symbol in symbols:
|
||||||
IEXurl = f"https://cloud.iexapis.com/stable/data-points/{symbol}/NEXTDIVIDENDDATE?token={IEX_TOKEN}"
|
IEXurl = f"https://cloud.iexapis.com/stable/data-points/{symbol}/NEXTDIVIDENDDATE?token={IEX_TOKEN}"
|
||||||
response = requests.get(IEXurl)
|
response = requests.get(IEXurl)
|
||||||
if response.status_code is 200:
|
if response.status_code is 200:
|
||||||
|
|
||||||
|
# extract date from json
|
||||||
date = response.json()
|
date = response.json()
|
||||||
# Pattern IEX uses for dividend date.
|
# Pattern IEX uses for dividend date.
|
||||||
pattern = "%Y-%m-%d"
|
pattern = "%Y-%m-%d"
|
||||||
divDate = datetime.strptime(date, pattern)
|
divDate = datetime.strptime(date, pattern)
|
||||||
#
|
|
||||||
daysDelta = (divDate - datetime.now()).days
|
daysDelta = (divDate - datetime.now()).days
|
||||||
datePretty = divDate.strftime("%A, %B %w")
|
datePretty = divDate.strftime("%A, %B %w")
|
||||||
if daysDelta < 0:
|
if daysDelta < 0:
|
||||||
messages[
|
divMessages[
|
||||||
symbol
|
symbol
|
||||||
] = f"{symbol.upper()} dividend was on {datePretty} and a new date hasn't been announced yet."
|
] = f"{symbol.upper()} dividend was on {datePretty} and a new date hasn't been announced yet."
|
||||||
elif daysDelta > 0:
|
elif daysDelta > 0:
|
||||||
messages[
|
divMessages[
|
||||||
symbol
|
symbol
|
||||||
] = f"{symbol.upper()} dividend is on {datePretty} which is in {daysDelta} Days."
|
] = f"{symbol.upper()} dividend is on {datePretty} which is in {daysDelta} Days."
|
||||||
else:
|
else:
|
||||||
messages[symbol] = f"{symbol.upper()} is today."
|
divMessages[symbol] = f"{symbol.upper()} is today."
|
||||||
|
|
||||||
else:
|
else:
|
||||||
messages[symbol] = f"{symbol} either doesn't exist or pays no dividend."
|
divMessages[symbol] = f"{symbol} either doesn't exist or pays no dividend."
|
||||||
|
|
||||||
return messages
|
return divMessages
|
||||||
|
|
||||||
|
|
||||||
def symbolNews(symbols: list):
|
def symbolNews(symbols: list):
|
||||||
messages = {}
|
newsMessages = {}
|
||||||
|
|
||||||
for symbol in symbols:
|
for symbol in symbols:
|
||||||
IEXurl = f"https://cloud.iexapis.com/stable/stock/{symbol}/news/last/3?token={IEX_TOKEN}"
|
IEXurl = f"https://cloud.iexapis.com/stable/stock/{symbol}/news/last/3?token={IEX_TOKEN}"
|
||||||
with urllib.request.urlopen(IEXurl) as url:
|
response = requests.get(IEXurl)
|
||||||
data = json.loads(url.read().decode())
|
if response.status_code is 200:
|
||||||
if data:
|
data = response.json()
|
||||||
messages[symbol] = f"News for **{symbol.upper()}**:\n"
|
newsMessages[symbol] = f"News for **{symbol.upper()}**:\n"
|
||||||
for news in data:
|
for news in data:
|
||||||
message = f"\t[{news['headline']}]({news['url']})\n\n"
|
message = f"\t[{news['headline']}]({news['url']})\n\n"
|
||||||
messages[symbol] = messages[symbol] + message
|
newsMessages[symbol] = newsMessages[symbol] + message
|
||||||
else:
|
else:
|
||||||
messages[
|
newsMessages[
|
||||||
symbol
|
symbol
|
||||||
] = f"No news found for: {symbol}\nEither today is boring or the symbol does not exist."
|
] = f"No news found for: {symbol}\nEither today is boring or the symbol does not exist."
|
||||||
|
|
||||||
return messages
|
return newsMessages
|
||||||
|
|
||||||
|
|
||||||
def symbolInfo(symbols: list):
|
def symbolInfo(symbols: list):
|
||||||
messages = {}
|
infoMessages = {}
|
||||||
|
|
||||||
for symbol in symbols:
|
for symbol in symbols:
|
||||||
IEXurl = (
|
IEXurl = (
|
||||||
f"https://cloud.iexapis.com/stable/stock/{symbol}/company?token={IEX_TOKEN}"
|
f"https://cloud.iexapis.com/stable/stock/{symbol}/company?token={IEX_TOKEN}"
|
||||||
)
|
)
|
||||||
with urllib.request.urlopen(IEXurl) as url:
|
response = requests.get(IEXurl)
|
||||||
data = json.loads(url.read().decode())
|
|
||||||
if data:
|
if response.status_code is 200:
|
||||||
messages[
|
data = response.json()
|
||||||
|
infoMessages[
|
||||||
symbol
|
symbol
|
||||||
] = f"Company Name: [{data['companyName']}]({data['website']})\nIndustry: {data['industry']}\nSector: {data['sector']}\nCEO: {data['CEO']}\nDescription: {data['description']}\n"
|
] = f"Company Name: [{data['companyName']}]({data['website']})\nIndustry: {data['industry']}\nSector: {data['sector']}\nCEO: {data['CEO']}\nDescription: {data['description']}\n"
|
||||||
|
|
||||||
else:
|
else:
|
||||||
messages[
|
infoMessages[
|
||||||
symbol
|
symbol
|
||||||
] = f"No information found for: {symbol}\nEither today is boring or the symbol does not exist."
|
] = f"No information found for: {symbol}\nEither today is boring or the symbol does not exist."
|
||||||
|
|
||||||
return messages
|
return infoMessages
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user