import requests
import os
from twilio.rest import Client
from dotenv import load_dotenv
# Load Environmental Variables from .env
load_dotenv()
# Stock Price Web API
ALPHA_VANTAGE_URL = "https://www.alphavantage.co/query"
ALPHA_VANTAGE_API_KEY = os.environ.get("ALPHA_VANTAGE_API_KEY")
# News Web API
NEWS_API_URL = "https://newsapi.org/v2/everything"
NEWS_API_KEY = os.environ.get("NEWS_API_KEY")
# SMS Web API
TWILIO_ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID")
TWILIO_AUTH_TOKEN = os.environ.get("TWILIO_AUTH_TOKEN")
# Company to monitor
COMPANY = "AXSM"
def get_stock_price_history_data_by_company(company):
# Prepare parameters for API
parameters = {
"function": "TIME_SERIES_DAILY_ADJUSTED",
"symbol": company,
"apikey": ALPHA_VANTAGE_API_KEY
}
# Sends a GET request.
response = requests.get(ALPHA_VANTAGE_URL, params=parameters)
# Raises HTTPError, if one occurred.
response.raise_for_status()
# Returns the json-encoded content of a response, if any.
res = response.json()
# Get Daily Time Series Dictionary
time_series_daily = res["Time Series (Daily)"]
# Get all keys
time_series_daily_key = list(time_series_daily.keys())
# Get close price of yesterday
yesterday_close_price = float(
time_series_daily[time_series_daily_key[0]]["4. close"])
# Get close price of the day before yesterday
the_day_before_yesterday_close_price = float(
time_series_daily[time_series_daily_key[1]]["4. close"])
# Calculate
return {
"yesterday": yesterday_close_price,
"the_day_before_yesterday": the_day_before_yesterday_close_price
}
def get_first_three_news_by_company(company):
# Prepare parameters for API
parameters = {
"q": company,
"apiKey": NEWS_API_KEY
}
# Sends a GET request.
response = requests.get(NEWS_API_URL, params=parameters)
# Raises HTTPError, if one occurred.
response.raise_for_status()
# Returns the json-encoded content of a response, if any.
res = response.json()
# Get the top three news
return res["articles"][:3]
def send_sms(text: str):
client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
message = client.messages.create(
body=text,
from_='twilio test number',
to='your_phone_number'
)
# If there is a sid, SMS was sent successfully
print(message.sid)
stock_price_historical_data = get_stock_price_history_data_by_company(COMPANY)
chagne_rate = round(
(stock_price_historical_data["yesterday"] -
stock_price_historical_data["the_day_before_yesterday"]
)/stock_price_historical_data["yesterday"] * 100, 2)
if abs(chagne_rate) >= 5:
first_three_news = get_first_three_news_by_company(COMPANY)
text = f"{COMPANY}: {'🔺' if chagne_rate > 0 else '🔻'} {chagne_rate}%\n\n"
# Loop through news
for news in first_three_news:
text += f"Headine: {news['title']}\nBrief: {news['description']}\n\n"
send_sms(text)