1
0
mirror of https://gitlab.com/simple-stock-bots/simple-stock-bot.git synced 2025-06-16 15:17:28 +00:00
This commit is contained in:
Anson 2019-03-22 17:55:44 -07:00
commit e5d198dfc8
3 changed files with 27 additions and 53 deletions

View File

@ -1,5 +1,5 @@
secrets = { secrets = {
"TELEGRAM_TOKEN": "TELEGRAM BOT TOKEN HERE", "TELEGRAM_TOKEN": "724630968:AAG3-J26jID34AK_SJg5nJCgr7atiVOZc6A",
"TWITTER_CONSUMER_API": "CONSUMER_API", "TWITTER_CONSUMER_API": "CONSUMER_API",
"TWITTER_CONSUMER_SECRET": "CONSUMER_SECRET", "TWITTER_CONSUMER_SECRET": "CONSUMER_SECRET",
"TWITTER_ACCESS_TOKEN": "ACCESS_TOKEN", "TWITTER_ACCESS_TOKEN": "ACCESS_TOKEN",

View File

@ -11,6 +11,7 @@ import credentials
import tickerInfo import tickerInfo
TOKEN = credentials.secrets["TELEGRAM_TOKEN"] TOKEN = credentials.secrets["TELEGRAM_TOKEN"]
TICKER_REGEX = "[$]([a-zA-Z]{1,4})"
# Enable logging # Enable logging
logging.basicConfig( logging.basicConfig(
@ -41,17 +42,15 @@ def news(bot, update):
try: try:
# regex to find tickers in messages, looks for up to 4 word characters following a dollar sign and captures the 4 word characters # regex to find tickers in messages, looks for up to 4 word characters following a dollar sign and captures the 4 word characters
tickers = re.findall("[$](\w{1,4})", message) tickers = re.findall(TICKER_REGEX, message)
bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING) bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
## Checks if a ticker was passed in ## Checks if a ticker was passed in
if tickers == []: if tickers == []:
message = "No Ticker, showing Market News:" message = "No Ticker, showing Market News:"
news = tickerInfo.stockNews("market") news = tickerInfo.stockNews("market")
for i in range(3): for i in range(len(news["title"])):
message = "{}\n\n[{}]({})".format( message = f"{message}\n\n[{news['title'][i]}]({news['link'][i]})"
message, news["title"][i], news["link"][i]
)
update.message.reply_text( update.message.reply_text(
text=message, parse_mode=telegram.ParseMode.MARKDOWN text=message, parse_mode=telegram.ParseMode.MARKDOWN
) )
@ -65,36 +64,22 @@ def news(bot, update):
price = tickerData[ticker + "Price"] price = tickerData[ticker + "Price"]
change = tickerData[ticker + "Change"] change = tickerData[ticker + "Change"]
message = ( message = f"The current stock price of {name} is $**{price}**"
"The current stock price of "
+ name
+ " is $**"
+ str(price)
+ "**"
)
if change > 0: if change > 0:
message = ( message = f"{message}, the stock is currently **up {change}%**"
message
+ ", the stock is currently **up "
+ str(change)
+ "%**"
)
elif change < 0: elif change < 0:
message = ( message = (
message f"{message}, the stock is currently **down {change}%**"
+ ", the stock is currently **down "
+ str(change)
+ "%**"
) )
else: else:
message = ( message = (
message + ", the stock hasn't shown any movement today." f"{message}, the stock hasn't shown any movement today."
) )
news = tickerInfo.stockNews(ticker) news = tickerInfo.stockNews(ticker)
for i in range(3): for i in range(len(news["title"])):
message = "{}\n\n[{}]({})".format( message = (
message, news["title"][i], news["link"][i] f"{message}\n\n[{news['title'][i]}]({news['link'][i]})"
) )
update.message.reply_text( update.message.reply_text(
@ -112,10 +97,11 @@ def stockInfo(bot, update):
try: try:
# regex to find tickers in messages, looks for up to 4 word characters following a dollar sign and captures the 4 word characters # regex to find tickers in messages, looks for up to 4 word characters following a dollar sign and captures the 4 word characters
tickers = re.findall("[$](\w{1,4})", message) tickers = re.findall(TICKER_REGEX, message)
tickerData = tickerInfo.tickerQuote(tickers) if len(tickers) > 0:
bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING) tickerData = tickerInfo.tickerQuote(tickers)
bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
for ticker in tickers: for ticker in tickers:
ticker = ticker.upper() ticker = ticker.upper()
@ -124,22 +110,13 @@ def stockInfo(bot, update):
name = tickerData[ticker + "Name"] name = tickerData[ticker + "Name"]
price = tickerData[ticker + "Price"] price = tickerData[ticker + "Price"]
change = tickerData[ticker + "Change"] change = tickerData[ticker + "Change"]
message = ( message = f"The current stock price of {name} is $**{price}**"
"The current stock price of " + name + " is $**" + str(price) + "**"
)
if change > 0: if change > 0:
message = ( message = f"{message}, the stock is currently **up {change}%**"
message + ", the stock is currently **up " + str(change) + "%**"
)
elif change < 0: elif change < 0:
message = ( message = f"{message}, the stock is currently **down {change}%**"
message
+ ", the stock is currently **down "
+ str(change)
+ "%**"
)
else: else:
message = message + ", the stock hasn't shown any movement today." message = f"{message}, the stock hasn't shown any movement today."
update.message.reply_text( update.message.reply_text(
text=message, parse_mode=telegram.ParseMode.MARKDOWN text=message, parse_mode=telegram.ParseMode.MARKDOWN
) )
@ -152,10 +129,9 @@ def stockInfo(bot, update):
def dividend(bot, update): def dividend(bot, update):
message = update.message.text message = update.message.text
chat_id = update.message.chat_id chat_id = update.message.chat_id
print("div")
try: try:
# regex to find tickers in messages, looks for up to 4 word characters following a dollar sign and captures the 4 word characters # regex to find tickers in messages, looks for up to 4 word characters following a dollar sign and captures the 4 word characters
tickers = re.findall("[$](\w{1,4})", message) tickers = re.findall(TICKER_REGEX, message)
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 ticker in tickers: for ticker in tickers:

View File

@ -38,13 +38,13 @@ def stockNews(ticker):
"""Makes a bunch of strings that are links to news websites for an input ticker""" """Makes a bunch of strings that are links to news websites for an input ticker"""
print("Gather News on " + ticker) print("Gather News on " + ticker)
newsLink = "https://api.iextrading.com/1.0/stock/{}/news/last/5".format(ticker) newsLink = f"https://api.iextrading.com/1.0/stock/{ticker}/news/last/5"
print(newsLink)
with urllib.request.urlopen(newsLink) as url: with urllib.request.urlopen(newsLink) as url:
data = json.loads(url.read().decode()) data = json.loads(url.read().decode())
news = {"link": [], "title": []} news = {"link": [], "title": []}
for i in range(3): for i in range(len(data)):
news["link"].append(data[i]["url"]) news["link"].append(data[i]["url"])
news["title"].append(data[i]["headline"]) news["title"].append(data[i]["headline"])
return news return news
@ -52,12 +52,12 @@ def stockNews(ticker):
def stockLogo(ticker): def stockLogo(ticker):
"""returns a png of an input ticker""" """returns a png of an input ticker"""
logoURL = "https://g.foolcdn.com/art/companylogos/mark/" + ticker + ".png" logoURL = f"https://g.foolcdn.com/art/companylogos/mark/{ticker}.png"
return logoURL return logoURL
def stockInfo(ticker): def stockInfo(ticker):
infoURL = "https://api.iextrading.com/1.0/stock/{}/stats".format(ticker) infoURL = f"https://api.iextrading.com/1.0/stock/{ticker}/stats"
with urllib.request.urlopen(infoURL) as url: with urllib.request.urlopen(infoURL) as url:
data = json.loads(url.read().decode()) data = json.loads(url.read().decode())
@ -99,9 +99,7 @@ def stockDividend(ticker):
h, m = divmod(h, 3600) h, m = divmod(h, 3600)
m, s = divmod(m, 60) m, s = divmod(m, 60)
countdownMessage = "\n\nThe dividend is in: {:.0f} Days {:.0f} Hours {:.0f} Minutes {:.0f} Seconds.".format( countdownMessage = f"\n\nThe dividend is in: {d:.0f} Days {h:.0f} Hours {m:.0f} Minutes {s:.0f} Seconds."
d, h, m, s
)
message = line1 + countdownMessage message = line1 + countdownMessage
return message return message