Building a Python stock alert is easy with this step-by-step guide. ๐ Donโt Miss the Profit Train!
There are quite a number of reasons why you should set up a Stock price alert. Reasons may include:
โฐ๐ Timely Decision-Making.
๐๐ฐ Seize Profitable Opportunities.
๐ซ๐ก Reduce Emotional Bias.
๐ฒ๐ Stay Informed and Engaged.
Python setup (skip if it's already set up).
It is assumed that you have Python installed and your favorite code editor is set up if you are reading this article.
Please come back after reviewing this guide to follow along if you are not sure where to start.
Python setup tutorial click here.
Setting up Python for Pycharm
What to do next.
Use Alpha vantage to retrieve the stock prices.
Use News API to retrieve the news about the stock.
Use Twilio to send the SMS notification.
Use Alpha Vantage to retrieve the stock prices.
Import relevant packages
import requests import json import math import random from twilio.rest import Client import html
Get the API key from Alpha Vantage using this link
Retrieving yesterday's closing stock and the day before yesterday's closing stock price from Alpha Vantage.
STOCK_ENDPOINT = "https://www.alphavantage.co/query" stock_api_key = "YOUR API KEY" #Your API KEY from Alpha Vantage. STOCK = "TSLA" #In this case, I have used Tesla or TSLA but you can use your own stocks. stock_parameters = { "function": "TIME_SERIES_INTRADAY", "symbol": STOCK, "apikey": stock_api_key, "interval": "60min", "datatype": "json", "to_symbol": "USD" } stock_response = requests.get(STOCK_ENDPOINT, stock_parameters) stock_data = stock_response.json() time_stamps = list((stock_data["Time Series (60min)"]).keys()) before_yesterday_closure_time = time_stamps[0] yesterday_closure_time = time_stamps[16] stock_before_yesterday_closing_value = float((stock_data["Time Series (60min)"][before_yesterday_closure_time]["4. close"])) stock_yesterday_closing_value = float((stock_data["Time Series (60min)"][yesterday_closure_time]["4. close"]))
Work out the percentage difference in price between the closing price yesterday and the closing price the day before yesterday.
stock_percentage_difference = math.ceil(((stock_before_yesterday_closing_value - stock_yesterday_closing_value) / stock_yesterday_closing_value) * 100)
Setting the arrow direction to mark the difference in positive and negative.
direction = "๐ป" if (stock_before_yesterday_closing_value - stock_yesterday_closing_value) > 0: direction = "๐บ"
Retrieving the Stock price using News API
COMPANY_NAME = "Tesla Inc" NEWS_ENDPOINT = "https://newsapi.org/v2/everything" news_api_key = "Your API KEY" #Your API KEY from https://newsapi.org/ news_parameters = { "q": COMPANY_NAME, "apiKey": news_api_key } news_response = requests.get(NEWS_ENDPOINT, params=news_parameters) articles = news_response.json()["articles"][:3] random_key = random.randint(0, len(articles) - 1) news_titles = [articles[article]["title"] for article in range(len(articles))] news_contents = [articles[article]["content"] for article in range(len(articles))]
Using Twilio to send the SMS notification. Click here to sign up on Twilio for free
account_sid = "Account SID from your Twilio account" auth_token = "AUTH Token from your Twilio account" client = Client(account_sid, auth_token)
Formatting the news to be sent.
content = (news_contents[random_key]).split("<ul>") content = ".".join(content) content = (content.split(".")) brief = html.unescape(content[0] + ".") message_to_send = f"{STOCK}: {direction}{stock_percentage_difference}%\nHeadline: {news_titles[random_key]}\nBrief:{brief}" #This is the message to be sent.
Sending the SMS.
message = client.messages \ .create( body=message_to_send, from_='Your Twilio number', to='Your verified contact on Twilio' )
Youโre DONE!
If everything went as planned you should receive SMS like this:
Please find the full code below:
import requests
import json
import math
import random
from twilio.rest import Client
import html
COMPANY_NAME = "Tesla Inc"
NEWS_ENDPOINT = "https://newsapi.org/v2/everything"
news_api_key = "Your API KEY" #Your API KEY from https://newsapi.org/
news_parameters = {
"q": COMPANY_NAME,
"apiKey": news_api_key
}
news_response = requests.get(NEWS_ENDPOINT, params=news_parameters)
articles = news_response.json()["articles"][:3]
random_key = random.randint(0, len(articles) - 1)
news_titles = [articles[article]["title"] for article in range(len(articles))]
news_contents = [articles[article]["content"] for article in range(len(articles))]
stock_api_key = "YOUR API KEY" #Your API KEY from Alpha Vantage.
STOCK = "TSLA"
STOCK_ENDPOINT = "https://www.alphavantage.co/query"
stock_parameters = {
"function": "TIME_SERIES_INTRADAY",
"symbol": STOCK,
"apikey": stock_api_key,
"interval": "60min",
"datatype": "json",
"to_symbol": "USD"
}
stock_response = requests.get(STOCK_ENDPOINT, stock_parameters)
stock_data = stock_response.json()
time_stamps = list((stock_data["Time Series (60min)"]).keys())
before_yesterday_closure_time = time_stamps[0]
yesterday_closure_time = time_stamps[16]
stock_before_yesterday_closing_value = float((stock_data["Time Series (60min)"][before_yesterday_closure_time]["4. close"]))
stock_yesterday_closing_value = float((stock_data["Time Series (60min)"][yesterday_closure_time]["4. close"]))
stock_percentage_difference = math.ceil(
((stock_before_yesterday_closing_value - stock_yesterday_closing_value) / stock_yesterday_closing_value) * 100)
direction = "๐ป"
if (stock_before_yesterday_closing_value - stock_yesterday_closing_value) > 0:
direction = "๐บ"
account_sid = "Account SID from your Twilio account"
auth_token = "AUTH Token from your Twilio account"
client = Client(account_sid, auth_token)
content = (news_contents[random_key]).split("<ul>")
content = ".".join(content)
content = (content.split("."))
brief = html.unescape(content[0] + ".")
message_to_send = f"{STOCK}: {direction}{stock_percentage_difference}%\nHeadline: {news_titles[random_key]}\nBrief:{brief}" #This is the message to be sent.
message = client.messages \
.create(
body=message_to_send,
from_='Your Twilio number',
to='Your verified contact on Twilio'
)
Notes:
If you copy and paste the full code above DO NOT forget to enter your own Phone number and Twilio mobile number.
Make sure to use your own API key obtained from Alpha Vantage and News API
Make sure to use your own auth_token and account_sid obtained from Twilio.
By no means is this trading or stock investment advice.
In conclusion, I hope this step-by-step walkthrough has provided you with a simple introduction to the world of coding. Whether or not you have prior coding experience, my aim was to make the process easy to follow and understand.
Happy coding, and may your coding journey be filled with excitement, creativity, and endless possibilities!๐