Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 6 additions & 37 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,40 +1,9 @@
# API-Stock-Signalling
###### NOTE: this is a project to practice your Python industry skills. Please upload your solutions by opening a new branch to the main. All files that are instantly merged to the main will be deleted.
## Overview
A small consultancy who is currently delivering client work for a major bank wants to monitor the prices for the following stocks: Tesla, Apple, Microsoft, Google, and Nike. Once the stock falls below a certain price, they want to be immediately notified so that they can purchase more stocks.
## Goal
Write a real time Python application that monitors the prices then notifies the user when the price of any of these stocks falls by at least £0.25 GBP. The user should also be notified if today's price is less than the 7-day average of that stock price.
## Brief
To do this, the client has recommended using a popular automation website called IFTTT: https://ifttt.com/. They are willing to use a different provider or solution (use those consultancy skills!) if you believe there is a better option.
#### IFTTT Applet
# Stock Price Alert System 📈

IFTTT stands for “If This Then That” and it’s an automation platform that allows you to connect different apps and services together. An applet is a connection between two or more apps or devices that enables you to do something that those services couldn’t do on their own. Applets consists of two parts triggers and actions. Triggers tell an applet to start, and actions are the end result of an applet run. To use an applet, you’ll need to create a free IFTTT account and connect your apps and devices to IFTTT so that they can talk to each other.
This project is designed to monitor stock prices of given symbols and alert via IFTTT if the stock price for a given day is significantly different from the average of the previous days.

#### Proposed Workflow
- Write a script that returns the stock prices. This will involve making an API request.
- Set up a IFTTT account and applet. This will be accessible via the mobile app which allows you to trigger the webhook service provided by IFTTT.
- You will need to configure the 'webhooks' service to receive web requests. You can find more details here: https://ifttt.com/maker_webhooks.
- From here you can write an application that utilises the requests package to make POST and GET requests.
- Think of what aspects or components of your proposed solution needs to be tested and what would these tests look like and attempt to implement such tests.
## 📁 Files:

## Main Considerations
- Choose an automation approach. Are you planning on using IFTTT or another workflow?
- What API are you going to use? You can use this as a starting point: https://github.com/public-apis/public-apis
- Remember, this is a proposed workflow. If you believe you have a more efficient approach please reach out to the Academy Team.
#### Requirements Gathering
The start to any project is to make sure you have clear and well-defined requirements for your project. Most projects start with a vague idea of what the stakeholder wants, and as a consultant, we will never have as much knowledge about their problem/business context as they do. Therefore, we need to get as much information out of them as possible, as they will subconsciously assume that we know everything. For this project, Alex Naylor will be the stakeholder.

If you don't know the answer to any question then you should always ask - NEVER ASSUME. This will only risk the accuracy of your work and end up having to do everything all over again if you wrongly assume.

Questions to ask yourself constantly throughout the project are:

- What is the purpose of this project, why does the stakeholder want this and what is the desired outcome of the project?
- Is there any extra info that the stakeholder could tell you to help tailor the project to what they want?

## Assessment
For the assessment, you will have a 15 minute technical interview. This will consist of a strict 5 minute presentation on your technical solution. There is no need to create slides for this but you may want to demo your code. For the second half of the session, you will be asked technical questions related to the project. You will be assessed on:
- Project Complexity
- Brief Completness i.e. have you managed to meet the client brief?
- Coding Standards

Good Luck!
- **`main.py`**: This is the primary script which periodically fetches the stock prices for the symbols, calculates the average, and checks if an alert needs to be triggered.
- **`price_alert_utils.py`**: Contains utility functions to fetch stock prices and to send notifications to IFTTT.
- **`price_alert_utils_tests.py`**: Contains unit tests for the utility functions provided in `price_alert_utils.py`.
Binary file added __pycache__/price_alert_utils.cpython-311.pyc
Binary file not shown.
24 changes: 24 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import os
from time import sleep
from dotenv import load_dotenv
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good practice to use environment variables!

from price_alert_utils import fetch_price_and_avg, notify_ifttt

load_dotenv()

IEX_API_KEY = os.getenv('IEX_API_KEY')
IFTTT_WEBHOOK_KEY = os.getenv('IFTTT_WEBHOOK_KEY')
SYMBOLS = ['TSLA', 'AAPL', 'MSFT', 'GOOGL', 'NKE']
BASE_IEX_URL = "https://cloud.iexapis.com/stable"

def main():
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

main function is concise, clean and has less code. That makes us easier to understand.

while True:
for symbol in SYMBOLS:
today_price, avg_7_day = fetch_price_and_avg(symbol, BASE_IEX_URL, IEX_API_KEY)
if today_price is None or avg_7_day is None:
continue
if today_price < avg_7_day or (avg_7_day - today_price) >= 0.25:
notify_ifttt(IFTTT_WEBHOOK_KEY, "price_alert", symbol, str(today_price), str(avg_7_day))
sleep(900)

if __name__ == "__main__":
main()
27 changes: 27 additions & 0 deletions price_alert_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import requests

def fetch_price_and_avg(symbol, base_iex_url, iex_api_key):
endpoint = f"{base_iex_url}/stock/{symbol}/chart/5d?token={iex_api_key}"
try:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good use of error handling to detect errors!

response = requests.get(endpoint)
response.raise_for_status()
data = response.json()
prices = [entry['close'] for entry in data]
today_price = prices[-1]
avg_7_day = sum(prices[:-1]) / len(prices[:-1])
return today_price, avg_7_day
except requests.RequestException as e:
print(f"Error fetching data for {symbol}: {e}")
except ValueError:
print(f"Error decoding JSON for {symbol}")
return None, None

def notify_ifttt(ifttt_webhook_key, event, value1="", value2="", value3=""):
url = f"https://maker.ifttt.com/trigger/{event}/with/key/{ifttt_webhook_key}"
data = {"value1": value1, "value2": value2, "value3": value3}
try:
response = requests.post(url, data=data)
response.raise_for_status()
except requests.RequestException as e:
print(f"Error notifying IFTTT: {e}")
return response.status_code
35 changes: 35 additions & 0 deletions price_alert_utils_tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import unittest
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well done! well structured unit testing

from unittest.mock import patch, Mock
import price_alert_utils

class TestPriceAlertUtils(unittest.TestCase):

@patch("price_alert_utils.requests.get")
def test_fetch_price_and_avg_success(self, mock_get):
mock_response = Mock()
mock_response.json.return_value = [
{"close": 100},
{"close": 105},
{"close": 110},
{"close": 115},
{"close": 120},
]
mock_response.raise_for_status.return_value = None
mock_get.return_value = mock_response

today_price, avg_7_day = price_alert_utils.fetch_price_and_avg("AAPL", "https://fakeurl.com", "fake_key")
self.assertEqual(today_price, 120)
self.assertEqual(avg_7_day, 107.5)

@patch("price_alert_utils.requests.post")
def test_notify_ifttt_success(self, mock_post):
mock_response = Mock()
mock_response.raise_for_status.return_value = None
mock_post.return_value = mock_response

result = price_alert_utils.notify_ifttt("fake_webhook_key", "test_event")
self.assertIsNone(result)

if __name__ == "__main__":
unittest.main()