1
0
mirror of https://gitlab.com/simple-stock-bots/simple-stock-bot.git synced 2026-06-04 05:10:25 +00:00

Compare commits

...

123 Commits

Author SHA1 Message Date
Anson 30f4f190df another sloppy bug 🙄 2021-03-11 14:27:06 -07:00
Anson d8884bce13 Merge branch 'master' of https://gitlab.com/simple-stock-bots/simple-telegram-stock-bot into master 2021-03-11 14:24:41 -07:00
Anson c2cb853db0 Previous update broke price_reply 2021-03-08 18:48:05 +00:00
Anson cb8a7ccad8 previous update introducted errors. 2021-03-08 11:45:51 -07:00
Anson 2f1eb6dcd6 Close #51 #52 2021-03-05 10:02:36 -07:00
Anson 728f433fe1 $GME 💎🙌 2021-02-24 23:18:35 -07:00
Anson 2422489bba bug where symbol had no dividend 2021-02-24 23:18:07 -07:00
Anson bbb73c8405 bug where dividend was only returning msft 2021-02-11 21:29:44 -07:00
Anson 9b100f4926 Happy with current coverage close # 46 2021-02-11 16:00:49 -07:00
Anson a44008234a Close #47 2021-02-11 15:57:06 -07:00
Anson 15be601a38 #37 2021-02-09 15:49:16 -07:00
Anson cbb2c6b422 close #37 2021-02-09 14:35:50 -07:00
Anson 0368834159 bug crunching 2021-02-09 14:01:45 -07:00
Anson 78218834e4 Close #45 2021-02-09 13:49:43 -07:00
Anson bff2e40411 grammar 2021-02-07 11:04:48 -07:00
Anson d99e7bc84a bug crunching 2021-02-07 11:03:03 -07:00
Anson 0b887b7042 Merge branch 'master' of gitlab.com:simple-stock-bots/simple-telegram-stock-bot 2021-02-07 10:59:13 -07:00
Anson e6438ab89d bug fix 2021-02-07 10:30:40 -07:00
Anson 554928db7e code cleanup 2021-02-06 14:13:24 -07:00
Anson a5505ab30c Close #39 2021-02-05 20:21:07 -07:00
Anson 19c84c1cd6 Close #42 2021-02-05 19:36:48 -07:00
Anson 3c9e1200d4 Close #43 That was surprisingly painless... 2021-02-05 18:45:09 -07:00
Anson 1e60528a08 fixed bug where data wasn't available afterhours. 2021-02-05 15:55:23 -07:00
Anson 0b01ddea15 document usage of status 2021-02-04 23:21:30 -07:00
Anson fa67a62b5f added status and error handling. #18 #28 2021-02-04 23:16:50 -07:00
Anson fb9ff6b651 formatting 2021-02-04 23:12:12 -07:00
Anson 1e3ebbb71b updated dependencies 2021-02-04 22:05:27 -07:00
Anson b5f1976d9e get ref-data daily 2021-02-04 21:42:41 -07:00
Anson 7d018b78b5 I cant grammar 2021-02-04 21:33:34 -07:00
Anson ecbbfcd9d6 Close #41 2021-02-04 21:29:19 -07:00
Anson 6dd033b7c2 Made IEX and Stripe Tokens optional 2021-02-02 09:00:36 -07:00
Anson 72e912319f cleanup and formatting 2021-02-02 08:51:06 -07:00
Anson 19655f02de add bot link to top of readme 2021-01-31 17:59:47 -07:00
Anson ba1f43b593 code cleanup 2021-01-31 17:14:15 -07:00
Anson f02ab0d14b finished donation functinoality. 2021-01-31 16:52:05 -07:00
Anson 71db661d72 add donations to bot 2021-01-31 16:00:58 -07:00
Anson 11d64ab413 make it easier to debug bot without using messages 2021-01-31 15:13:28 -07:00
Anson 6c1c9ac420 formatting license 2021-01-30 01:11:35 -07:00
Anson 4ab1750634 Merge branch 'master' of gitlab.com:simple-stock-bots/simple-telegram-stock-bot 2021-01-30 01:07:11 -07:00
Anson 38853582d1 Close #40 2021-01-30 01:07:08 -07:00
Anson d68b65d9e1 Close #40 2021-01-30 01:03:55 -07:00
Anson 4578ad43f1 Close #33 2021-01-30 00:09:51 -07:00
Anson 2016fba6b9 Closes #35 2021-01-29 23:28:40 -07:00
Anson dc2d1648ac updated help text 2021-01-27 22:20:15 +00:00
Anson 0098432514 added chart to help text 2021-01-27 13:05:59 -07:00
Anson 81c42000d8 Close #32 2021-01-27 12:50:12 -07:00
Anson 4de494d1d2 Close #32 2021-01-27 12:17:07 -07:00
Anson bce583fcf6 package vulnerability. 2021-01-24 14:26:44 -07:00
Anson f184fbe51d #31 2021-01-24 12:28:40 -07:00
Anson c4d984a751 add vscode files to ignore 2021-01-24 11:43:35 -07:00
Anson ee58fb186e Closes #30 2021-01-24 11:35:22 -07:00
Anson 0f20486fae /intra was dropping missing data from unnecessary columns 2020-12-10 21:46:49 -07:00
Anson 85d5cc9a30 Added a crypto command. 2020-11-01 15:26:35 -07:00
Anson 28f2ba2320 updated help text 2020-10-10 21:35:26 -07:00
Anson 78b412ebff Finishing touches to /stat 2020-10-10 21:35:11 -07:00
Anson b3e628023b Merge branch 'master' of https://gitlab.com/simple-stock-bots/simple-telegram-stock-bot into master 2020-10-02 18:35:01 -07:00
Anson 6cfbbeb992 added stat command 2020-10-02 18:34:55 -07:00
Anson 7090da8fea Updated news command #27 2020-09-09 12:19:46 -07:00
Anson e603c5345a Change symbols update to weekly 2020-08-20 11:48:52 -07:00
Anson 4cc4a2cda6 added random command 2020-08-06 03:06:05 -07:00
Anson df68df5e20 added a helper command for intra 2020-07-09 00:08:18 -07:00
Anson c76784647c reformat plot title 2020-07-09 00:07:38 -07:00
Anson 7ec1c02a8b changed historical to instraday plotting 2020-07-09 00:00:31 -07:00
Anson 68d66b833f need to make sure all packages are updated 2020-07-01 22:20:28 -07:00
Anson 463b2f1c3b added plotting of historical pricing 2020-07-01 20:08:24 -07:00
Anson fdf338a9c3 help link was incorrect 2020-06-12 02:49:38 -07:00
Anson f90aa14f24 added search command 2020-06-12 02:01:10 -07:00
Anson fb4990c96c readme header formatting 2020-05-21 01:38:55 -07:00
Anson d495932cf8 fix donation link on readme 2020-05-21 01:37:58 -07:00
Anson 9c0abb0946 upgraded /start and /help + donation info 2020-05-21 01:36:25 -07:00
Anson 7e7fbbceb2 Merge branch 'Upgrading-Dependencies' into 'master'
Upgrading dependencies

See merge request simple-stock-bots/simple-telegram-stock-bot!17
2020-04-15 14:44:54 +00:00
Anson c994afddf6 added schedule 2020-04-15 07:43:17 -07:00
Anson 5fea3efee5 prevent duplicate keys due to caps 2020-04-15 07:38:49 -07:00
Anson 9552ef169f formatting 2020-04-15 07:32:42 -07:00
Anson 28a90b2472 using iex api for symbol list 2020-04-15 07:32:36 -07:00
Anson 1a7cfb71b6 caching symbol search results 2020-04-15 06:47:05 -07:00
Anson 3b96fdf4ed markdown_v2 support removed 2020-04-14 19:32:18 -07:00
Anson 3c22fe4d5c added documentation for more confusing functions 2020-04-10 03:13:30 -07:00
Anson f213f1e7e7 updated all packages to newest versions 2020-04-10 02:38:34 -07:00
Anson e1ff4a3d56 never actually compared match to anything 2020-04-06 14:06:39 -07:00
Anson e7c94d51c8 speed and accuracy improvments to fuzzy search 2020-04-06 00:05:49 -07:00
Anson c48c53746d ignoring pycache 2020-04-06 00:05:34 -07:00
Anson e647cbc8ac update container tag to support python-Levenshtein 2020-04-05 04:32:07 -07:00
Anson 3a454083a5 added inline functionality 2020-04-05 04:31:38 -07:00
Anson aab4a4354e major refactor of functions 2020-04-05 02:41:35 -07:00
Anson 53d655fa48 making linter happy 2020-04-05 02:14:25 -07:00
Anson c7634967f6 Merge branch 'code-cleanup' into 'master'
Code cleanup

See merge request simple-stock-bots/simple-telegram-bot!16
2019-07-10 20:38:02 +00:00
Anson 63e5344e86 accidentally left a key in the code again 2019-07-10 13:21:30 -07:00
Anson 3c506e124f cleanup and readability changes 2019-07-10 12:33:11 -07:00
Anson baf3757206 turns out telegram was never needed 2019-07-10 12:32:55 -07:00
Anson a180e9f360 removed debugging code 2019-07-10 12:04:14 -07:00
Anson 33c80bd75b renamed ticker to symbol everywhere 2019-07-10 12:03:59 -07:00
Anson 38fcf6d054 added requests to requirements 2019-07-10 02:14:20 -07:00
Anson b716ef3bfb cleaned up dividend code 2019-07-10 02:04:50 -07:00
Anson 11f2146b7b Merge branch 'Features' into 'master'
Features

See merge request simple-stock-bots/simple-telegram-bot!15
2019-06-11 12:40:53 +00:00
Anson 685e4b94e6 fixed formatting 2019-06-11 05:28:22 -07:00
Anson de2b3e5398 added documentation for new commands 2019-06-11 05:28:08 -07:00
Anson 211fd0e2a9 added /info command 2019-06-11 05:20:50 -07:00
Anson fd1baad811 added /news functionality #22 2019-06-11 05:08:49 -07:00
Anson 99f0bf68d1 updated help link #21 2019-06-11 04:16:10 -07:00
Anson d341c7b1bb Merge branch 'readme-update' into 'master'
Readme update

See merge request simple-stock-bots/simple-telegram-bot!14
2019-06-09 21:52:04 +00:00
Anson 6fcceab32e added link to use hosted version of bot 2019-06-09 14:34:20 -07:00
Anson 381ecf3bf1 Removed API keys from project 2019-06-09 14:27:53 -07:00
Anson 6183ce33d3 Merge branch 'readme-update' into 'master'
Gave project proper readme

See merge request simple-stock-bots/simple-telegram-bot!13
2019-06-09 21:17:35 +00:00
Anson 7775bdc70a Gave project proper readme 2019-06-09 14:16:20 -07:00
Anson 4f5f56f874 Merge branch 'IEX-2.0' into 'master'
Iex 2.0

See merge request simple-stock-bots/simple-telegram-bot!12
2019-05-28 12:44:49 +00:00
Anson da5d071f34 fixed environ vars since now theres more than 1 2019-05-28 05:33:16 -07:00
Anson 4da5d9933f accidentaly deleted error handle in earlier commit 2019-05-28 05:28:28 -07:00
Anson 230f6fdeac added error handling for if ticker doesnt exist 2019-05-28 05:27:50 -07:00
Anson a195c87b6e updated bot to work with new functions 2019-05-28 05:06:59 -07:00
Anson c49a2c321e removed news command handler 2019-05-28 05:02:25 -07:00
Anson bc09be8ea4 fixed dividend function for if symbol doesnt exist 2019-05-28 04:59:16 -07:00
Anson 14ced9682a updated dividend function for new API 2019-05-28 01:00:40 -07:00
Anson 6b679963dd removed news since no longer supported by IEX 2019-05-27 09:19:42 -07:00
Anson 3113c17efb updated standard reply for tickers in text 2019-05-27 09:18:24 -07:00
Anson bfca21f176 Organized Imports 2019-05-22 06:00:49 -07:00
Anson d5533909a0 Merge branch 'issues' into 'master'
Issues

Closes #16

See merge request simple-stock-bots/simple-telegram-bot!11
2019-05-12 02:54:45 +00:00
Anson 9f87a86bde bot now types in chat while its working. 2019-05-11 19:45:28 -07:00
Anson 74e63bb697 fix #16 2019-05-11 19:44:25 -07:00
Anson 8589082439 added enviroment variables for telegram token 2019-05-10 00:30:34 -07:00
Anson 369f6d9efa update dockerfile for new filenames 2019-05-10 00:24:09 -07:00
Anson 1f474dca46 rewrote entire bot code. Functionally identical. 2019-05-10 00:21:56 -07:00
Anson d7d0962eea Gave website its own repo 2019-04-02 22:49:18 -07:00
19 changed files with 1271 additions and 648 deletions
+2
View File
@@ -0,0 +1,2 @@
__pycache__/
.vscode
-21
View File
@@ -1,21 +0,0 @@
stages:
- docs
pages:
stage: docs
image: python:alpine
before_script:
- pip install mkdocs
- pip install mkdocs-material
script:
- cd ./web
- mkdocs build
- mv site ../public
- cd ../
artifacts:
paths:
- public
only:
- documentation
+10
View File
@@ -0,0 +1,10 @@
FROM python:3.8-buster
COPY requirements.txt ./
RUN pip install --no-cache-dir -U -r requirements.txt
COPY . .
CMD [ "python", "./bot.py" ]
+171 -3
View File
@@ -1,5 +1,173 @@
# simple-telegram-bot <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>
## A Telegram Bot for stock market Data. <h3 align="center">Simple Telegram Stock Bot</h3>
## Full documentation [here.](https://misterbiggs.gitlab.io/simple-telegram-bot) <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)]()
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](/LICENSE)
</div>
---
<p align="center"> Telegram Bot 🤖 that provides Stock Market information.
<br>
</p>
Message the bot on Telegram [@SimpleStockBot](https://t.me/SimpleStockBot)
## 📝 Table of Contents
- [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)
## 🧐 About <a name = "about"></a>
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.
## 💭 How it works <a name = "working"></a>
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).
## 🎈 Usage <a name = "usage"></a>
### 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 ♥
+520
View File
@@ -0,0 +1,520 @@
# Works with Python 3.8
import datetime
import io
import logging
import os
import random
import html
import json
import traceback
import mplfinance as mpf
import telegram
from telegram import (
InlineQueryResultArticle,
InputTextMessageContent,
LabeledPrice,
Update,
)
from telegram.ext import (
CommandHandler,
Filters,
InlineQueryHandler,
MessageHandler,
PreCheckoutQueryHandler,
Updater,
CallbackContext,
)
from functions import Symbol
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!")
s = Symbol(IEX_TOKEN)
# Enable logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)
print("Bot Online")
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)
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)
def license(update: Update, context: CallbackContext):
"""Return bots license agreement"""
update.message.reply_text(text=s.license, parse_mode=telegram.ParseMode.MARKDOWN)
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"
# IEX Status
message += s.iex_status() + "\n"
# 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)
def donate(update: Update, context: CallbackContext):
chat_id = update.message.chat_id
if update.message.text.strip() == "/donate":
update.message.reply_text(
text=s.donate_text, parse_mode=telegram.ParseMode.MARKDOWN
)
return
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"
try:
price = int(float(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)]
context.bot.send_invoice(
chat_id,
title,
description,
payload,
provider_token,
start_parameter,
currency,
prices,
)
def precheckout_callback(update: Update, context: CallbackContext):
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...")
def successful_payment_callback(update: Update, context: CallbackContext):
update.message.reply_text("Thank you for your donation!")
def symbol_detect(update: Update, context: CallbackContext):
"""
Runs on any message that doesn't have a command and searches for symbols,
then returns the prices of any symbols found.
"""
message = update.message.text
chat_id = update.message.chat_id
symbols = s.find_symbols(message)
if symbols:
# Let user know bot is working
context.bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
for reply in s.price_reply(symbols).items():
update.message.reply_text(
text=reply[1], parse_mode=telegram.ParseMode.MARKDOWN
)
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
message = update.message.text
chat_id = update.message.chat_id
if message.strip() == "/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]
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,
)
return
context.bot.send_chat_action(
chat_id=chat_id, action=telegram.ChatAction.UPLOAD_PHOTO
)
buf = io.BytesIO()
mpf.plot(
df,
type="renko",
title=f"\n${symbol.upper()}",
volume=True,
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]}",
parse_mode=telegram.ParseMode.MARKDOWN,
)
def chart(update: Update, context: CallbackContext):
# TODO: Document usage of this command. https://iexcloud.io/docs/api/#historical-prices
message = update.message.text
chat_id = update.message.chat_id
if message.strip() == "/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]
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,
)
return
context.bot.send_chat_action(
chat_id=chat_id, action=telegram.ChatAction.UPLOAD_PHOTO
)
buf = io.BytesIO()
mpf.plot(
df,
type="candle",
title=f"\n${symbol.upper()}",
volume=True,
style="yahoo",
savefig=dict(fname=buf, dpi=400, bbox_inches="tight"),
)
buf.seek(0)
update.message.reply_photo(
photo=buf,
caption=f"\n1 Month chart for ${symbol.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]}",
parse_mode=telegram.ParseMode.MARKDOWN,
)
def stat(update: Update, context: CallbackContext):
"""
https://iexcloud.io/docs/api/#key-stats
"""
message = update.message.text
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
symbols = s.find_symbols(message)
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
)
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.
"""
matches = s.search_symbols(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
),
)
)
except TypeError:
logging.warning(str(match))
pass
if len(results) == 5:
update.inline_query.answer(results)
return
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")
update.message.reply_text(
text=f"{choice}\nBuy and hold until: {hold}",
parse_mode=telegram.ParseMode.MARKDOWN,
)
def error(update: Update, context: CallbackContext):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
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>"
)
# 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.")
def main():
"""Start the context.bot."""
# Create the EventHandler and pass it your bot's token.
updater = Updater(TELEGRAM_TOKEN)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("license", license))
dp.add_handler(CommandHandler("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("random", rand_pick))
dp.add_handler(CommandHandler("donate", donate))
dp.add_handler(CommandHandler("status", status))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text, symbol_detect))
# Inline Bot commands
dp.add_handler(InlineQueryHandler(inline_query))
# Pre-checkout handler to final check
dp.add_handler(PreCheckoutQueryHandler(precheckout_callback))
# Payment success
dp.add_handler(
MessageHandler(Filters.successful_payment, successful_payment_callback)
)
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == "__main__":
main()
-8
View File
@@ -1,8 +0,0 @@
FROM python:3.7-slim
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD [ "python", "./stockBot.py" ]
-7
View File
@@ -1,7 +0,0 @@
secrets = {
"TELEGRAM_TOKEN": "TELEGRAM_API_TOKEN",
"TWITTER_CONSUMER_API": "CONSUMER_API",
"TWITTER_CONSUMER_SECRET": "CONSUMER_SECRET",
"TWITTER_ACCESS_TOKEN": "ACCESS_TOKEN",
"TWITTER_ACCESS_SECRET": "ACCESS_SECRET",
}
-2
View File
@@ -1,2 +0,0 @@
telegram==0.0.1
python-telegram-bot==11.1.0
-182
View File
@@ -1,182 +0,0 @@
# Work with Python 3.7
import json
import logging
import re
import urllib.request
import telegram
from telegram.ext import CommandHandler, Filters, MessageHandler, Updater
import credentials
import tickerInfo
TOKEN = credentials.secrets["TELEGRAM_TOKEN"]
TICKER_REGEX = "[$]([a-zA-Z]{1,4})"
# Enable logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)
print("Bot Online")
# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update):
"""Send a message when the command /start is issued."""
update.message.reply_text("I am started and ready to go!")
def help(bot, update):
"""Send link to docs when the command /help is issued."""
message = "[Please see the docs for Bot information](https://misterbiggs.gitlab.io/simple-telegram-bot)"
update.message.reply_text(text=message, parse_mode=telegram.ParseMode.MARKDOWN)
def news(bot, update):
"""Send a message when the /news command is issued."""
message = update.message.text
chat_id = update.message.chat_id
try:
# regex to find tickers in messages, looks for up to 4 word characters following a dollar sign and captures the 4 word characters
tickers = re.findall(TICKER_REGEX, message)
bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
## Checks if a ticker was passed in
if tickers == []:
message = "No Ticker, showing Market News:"
news = tickerInfo.stockNews("market")
for i in range(len(news["title"])):
message = f"{message}\n\n[{news['title'][i]}]({news['link'][i]})"
update.message.reply_text(
text=message, parse_mode=telegram.ParseMode.MARKDOWN
)
else:
tickerData = tickerInfo.tickerQuote(tickers)
for ticker in tickers:
ticker = ticker.upper()
# Makes sure ticker exists
if tickerData[ticker] == 1:
name = tickerData[ticker + "Name"]
price = tickerData[ticker + "Price"]
change = tickerData[ticker + "Change"]
message = f"The current stock price of {name} is $**{price}**"
if change > 0:
message = f"{message}, the stock is currently **up {change}%**"
elif change < 0:
message = (
f"{message}, the stock is currently **down {change}%**"
)
else:
message = (
f"{message}, the stock hasn't shown any movement today."
)
news = tickerInfo.stockNews(ticker)
for i in range(len(news["title"])):
message = (
f"{message}\n\n[{news['title'][i]}]({news['link'][i]})"
)
update.message.reply_text(
text=message, parse_mode=telegram.ParseMode.MARKDOWN
)
else:
update.message.reply_text(ticker + " Does not exist.")
except:
pass
def stockInfo(bot, update):
message = update.message.text
chat_id = update.message.chat_id
try:
# regex to find tickers in messages, looks for up to 4 word characters following a dollar sign and captures the 4 word characters
tickers = re.findall(TICKER_REGEX, message)
if len(tickers) > 0:
tickerData = tickerInfo.tickerQuote(tickers)
bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
for ticker in tickers:
ticker = ticker.upper()
# Makes sure ticker exists
if tickerData[ticker] == 1:
name = tickerData[ticker + "Name"]
price = tickerData[ticker + "Price"]
change = tickerData[ticker + "Change"]
message = f"The current stock price of {name} is $**{price}**"
if change > 0:
message = f"{message}, the stock is currently **up {change}%**"
elif change < 0:
message = f"{message}, the stock is currently **down {change}%**"
else:
message = f"{message}, the stock hasn't shown any movement today."
update.message.reply_text(
text=message, parse_mode=telegram.ParseMode.MARKDOWN
)
else:
update.message.reply_text(ticker + " Does not exist.")
except:
pass
def dividend(bot, update):
message = update.message.text
chat_id = update.message.chat_id
try:
# regex to find tickers in messages, looks for up to 4 word characters following a dollar sign and captures the 4 word characters
tickers = re.findall(TICKER_REGEX, message)
bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
for ticker in tickers:
message = tickerInfo.stockDividend(ticker)
update.message.reply_text(
text=message, parse_mode=telegram.ParseMode.MARKDOWN
)
except:
pass
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
def main():
"""Start the bot."""
# Create the EventHandler and pass it your bot's token.
updater = Updater(TOKEN)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("news", news))
dp.add_handler(CommandHandler("dividend", dividend))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text, stockInfo))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == "__main__":
main()
-105
View File
@@ -1,105 +0,0 @@
import urllib.request
import json
from datetime import datetime
import time
def tickerQuote(tickers):
"""Gathers information from IEX api on stock"""
stockData = {}
IEXURL = (
"https://api.iextrading.com/1.0/stock/market/batch?symbols="
+ ",".join(tickers)
+ "&types=quote"
)
print("Gathering Quote from " + IEXURL)
with urllib.request.urlopen(IEXURL) as url:
IEXData = json.loads(url.read().decode())
for ticker in tickers:
ticker = ticker.upper()
# Makes sure ticker exists before populating a dictionary
if ticker in IEXData:
stockData[ticker] = 1
stockData[ticker + "Name"] = IEXData[ticker]["quote"]["companyName"]
stockData[ticker + "Price"] = IEXData[ticker]["quote"]["latestPrice"]
stockData[ticker + "Change"] = round(
(IEXData[ticker]["quote"]["changePercent"] * 100), 2
)
stockData[ticker + "Image"] = stockLogo(ticker)
print(ticker + " Quote Gathered")
else:
stockData[ticker] = 0
return stockData
def stockNews(ticker):
"""Makes a bunch of strings that are links to news websites for an input ticker"""
print("Gather News on " + ticker)
newsLink = f"https://api.iextrading.com/1.0/stock/{ticker}/news/last/5"
print(newsLink)
with urllib.request.urlopen(newsLink) as url:
data = json.loads(url.read().decode())
news = {"link": [], "title": []}
for i in range(len(data)):
news["link"].append(data[i]["url"])
news["title"].append(data[i]["headline"])
return news
def stockLogo(ticker):
"""returns a png of an input ticker"""
logoURL = f"https://g.foolcdn.com/art/companylogos/mark/{ticker}.png"
return logoURL
def stockInfo(ticker):
infoURL = f"https://api.iextrading.com/1.0/stock/{ticker}/stats"
with urllib.request.urlopen(infoURL) as url:
data = json.loads(url.read().decode())
info = {}
info["companyName"] = data["companyName"]
info["marketCap"] = data["marketcap"]
info["yearHigh"] = data["week52high"]
info["yearLow"] = data["week52low"]
info["divRate"] = data["dividendRate"]
info["divYield"] = data["dividendYield"]
info["divDate"] = data["exDividendDate"]
return info
def stockDividend(ticker):
data = stockInfo(ticker)
print(data["divDate"])
if data["divDate"] == 0:
return "{} has no dividend.".format(data["companyName"])
line1 = "{} current dividend yield is: {:.3f}%, or ${:.3f} per share.".format(
data["companyName"], data["divRate"], data["divYield"]
)
divDate = data["divDate"]
# Pattern IEX uses for dividend date.
pattern = "%Y-%m-%d %H:%M:%S.%f"
# Convert divDate to seconds, and subtract it from current time.
divSeconds = datetime.strptime(divDate, pattern).timestamp()
difference = divSeconds - int(time.time())
# Calculate (d)ays, (h)ours, (m)inutes, and (s)econds
d, h = divmod(difference, 86400)
h, m = divmod(h, 3600)
m, s = divmod(m, 60)
countdownMessage = f"\n\nThe dividend is in: {d:.0f} Days {h:.0f} Hours {m:.0f} Minutes {s:.0f} Seconds."
message = line1 + countdownMessage
return message
+8
View File
@@ -0,0 +1,8 @@
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. 📊
+553
View File
@@ -0,0 +1,553 @@
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 ""
+7
View File
@@ -0,0 +1,7 @@
python-telegram-bot==13.2
requests==2.25.1
pandas==1.2.1
fuzzywuzzy==0.18.0
python-Levenshtein==0.12.1
schedule==1.0.0
mplfinance==0.12.7a5
-179
View File
@@ -1,179 +0,0 @@
# License
## Stock Market Data
Provided for free by [IEX](https://iextrading.com/developer). View IEXs [Terms of Use](https://iextrading.com/api-exhibit-a/).
**This Website and the Associated Bot are Provided under the Following License**
## Attribution-ShareAlike 4.0 International
Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
### Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
* __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors).
* __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensors permission is not necessary for any reasonfor example, because of any applicable exception or limitation to copyrightthen that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
## Creative Commons Attribution-ShareAlike 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
### Section 1 Definitions.
a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
c. __BY-SA Compatible License__ means a license listed at [creativecommons.org/compatiblelicenses](http://creativecommons.org/compatiblelicenses), approved by Creative Commons as essentially the equivalent of this Public License.
d. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
e. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
f. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
g. __License Elements__ means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike.
h. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
i. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
j. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
k. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
l. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
m. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
### Section 2 Scope.
a. ___License grant.___
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
A. reproduce and Share the Licensed Material, in whole or in part; and
B. produce, reproduce, and Share Adapted Material.
2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
3. __Term.__ The term of this Public License is specified in Section 6(a).
4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
5. __Downstream recipients.__
A. __Offer from the Licensor Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
B. __Additional offer from the Licensor Adapted Material.__ Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapters License You apply.
C. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
b. ___Other rights.___
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties.
### Section 3 License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
a. ___Attribution.___
1. If You Share the Licensed Material (including in modified form), You must:
A. retain the following if it is supplied by the Licensor with the Licensed Material:
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
b. ___ShareAlike.___
In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
1. The Adapters License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
### Section 4 Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
### Section 5 Disclaimer of Warranties and Limitation of Liability.
a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__
b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
### Section 6 Term and Termination.
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
### Section 7 Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
### Section 8 Interpretation.
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
> Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” The text of the Creative Commons public licenses is dedicated to the public domain under the [CC0 Public Domain Dedication](https://creativecommons.org/publicdomain/zero/1.0/legalcode). Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
>
> Creative Commons may be contacted at creativecommons.org.
-1
View File
@@ -1 +0,0 @@
# Under Construction 🚧
-44
View File
@@ -1,44 +0,0 @@
# Telegram Bot Commands
## Getting a Stock Quote
Anytime the Bot is in your chat it will search all chats for `$` followed by a ticker. For example `$tsla` will return the following message for Tesla Motors:
```
The current stock price of Tesla Inc. is $321.35, the stock is currently up 2.7%
```
This works no matter where the ticker is in the message and you can have as many tickers as you want in the same message. For example:
```
I wonder how $aapl, $nflx, and $sono are performing today.
```
Will return:
![Conversation With Simple Telegram Bot](img\telegramBotTickerReply.png)
## Commands
* [`/help`](#/help) - Create a new project.
* [`/news`](#/news) - Start the live-reloading docs server.
### /help
This command just displays a short description of what the bot does and a link to this page.
### /news
This command is intelligent enough to get any tickers in the ticker format: `$amzn`, and can handle as many tickers as you would like to enter. The bot will then return the price of the ticker, and links various websites that provide news about the ticker. Currently for Apple stock the Bot would return:
`The current stock price of Apple Inc. is **$174.18**, the stock is currently up **1.71%**`
[`Bravos`](https://bravos.co/AAPL)
[`Seeking Alpha`](https://seekingalpha.com/symbol/AAPL)
[`MSN Money`](https://www.msn.com/en-us/money/stockdetails?symbol=AAPL)
[`Yahoo Finance`](https://finance.yahoo.com/quote/AAPL)
[`Wall Street Journal`](https://quotes.wsj.com/AAPL)
[`The Street`](https://www.thestreet.com/quote/AAPL.html)
[`Zacks`](https://www.zacks.com/stock/quote/AAPL)
*This command needs updating, feel free to [open an issue](https://gitlab.com/MisterBiggs/simple-telegram-bot/issues) with suggestions.*
Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

-82
View File
@@ -1,82 +0,0 @@
# Telegram Bot Commands
## About
If you aren't already, you can talk to this bot here: **[http://t.me/SimpleStockBot](http://t.me/SimpleStockBot)**
Simple Stock Bot is a bot for [Telegram](https://telegram.org/) that provides information about the stock market. You can view the source code [here.](https://gitlab.com/MisterBiggs/simple-telegram-bot). You can also build your own docker container to run [here.](#Build)
_Coded with ❤ by [@MisterBiggs](https://gitlab.com/MisterBiggs)_
## Getting a Stock Quote
Anytime the Bot is in your chat it will search all chats for `$` followed by a ticker. For example `$tsla` will return the following message for Tesla Motors:
```
The current stock price of Tesla Inc. is $321.35, the stock is currently up 2.7%
```
This works no matter where the ticker is in the message and you can have as many tickers as you want in the same message. For example:
```
I wonder how $aapl, $nflx, and $sono are performing today.
```
Will return:
![Conversation With Simple Telegram Bot](img\telegramBotTickerReply.png)
As long as the bot is in your chat it will reply to any stock tickers in your messages.
## Commands
- [`/help`](#/help)
- [`/news`](#/news)
- [`/dividend`](#/dividend)
### /help
This command just displays a short description of what the bot does and a link to this page.
### /news
This command is intelligent enough to get any tickers in the ticker format: `$amzn`, and can handle as many tickers as you would like to enter. The bot will then return the price of the ticker, and links various websites that provide news about the ticker. Currently the command `/news $aapl` returns:
---
`The current stock price of Apple Inc. is $**170.89**, the stock is currently **up 0.86%**`
[`Apple: The 4 Biggest Risks`](https://api.iextrading.com/1.0/stock/aapl/article/7171544094325661)
[`Apple is getting so serious about health, it's started hosting heart-health events at Apple Stores`](https://api.iextrading.com/1.0/stock/aapl/article/6966979968162641)
[`You can now ask Siri to get you directions with Waze so you don't even have to open the app`](https://api.iextrading.com/1.0/stock/aapl/article/7672481171984085)
---
### /dividend
The dividend command will give you the `dividend yield`, `dividend rate`, and will tell you how long until the payout date for any tickers input. Currently the command `/dividend $psec` returns:
---
`Prospect Capital Corporation current dividend yield is: 0.720%, or $11.285 per share.`
`The dividend is in: 14 Days 1 Hours 54 Minutes 46 Seconds.`
---
## Run your own bot using latest build
```powershell
docker run --detach registry.gitlab.com/misterbiggs/simple-telegram-bot:latest
```
## Built and Run your own Bot
You can also run your own bot super easily in a [Docker](https://hub.docker.com/) Container.
1. Download the repository.
2. Change information in [Credentials.py]() with your own Telegram Bot key, which can be found [here.]()
3. Run stockBot.py
4. profit???
-14
View File
@@ -1,14 +0,0 @@
site_name: Simple Stock Bot
site_url: https://misterbiggs.gitlab.io/simple-telegram-bot
edit_uri: blob/master/web/docs/
nav:
- Home: index.md
# - Commands: commands.md
# - About: about.md
# - Author's Website: https://blog.ansonbiggs.com/
- LICENSE: LICENSE.md
theme: "material"
repo_url: https://gitlab.com/MisterBiggs/simple-telegram-bot
repo_name: Simple Telegram Bot
site_description: A Telegram Bot for stock market Data.