diff --git a/README.md b/README.md index 9e6c192..28ca8a0 100644 --- a/README.md +++ b/README.md @@ -1,40 +1,4 @@ -# 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 +# API-Stock-Signalling App -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. - -#### 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. - -## 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! +## Overview of Existing Code +This code returns real-time prices for the stocks provided (AAPL, GOOGL, TSLA, MSFT and NKE). With an extended deadline, this application will alert the user(s) to price drops of at least £0.25 GBP, and whether the latest price is lower than the 7-day average for that particular stock. diff --git a/Rough b/Rough new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/Rough @@ -0,0 +1 @@ + diff --git a/Stock_Signaller_App.py b/Stock_Signaller_App.py new file mode 100644 index 0000000..7c7a104 --- /dev/null +++ b/Stock_Signaller_App.py @@ -0,0 +1,112 @@ +# Import packages +# import os +import requests +import time +# from dotenv import load_dotenv + +# Load environment variables from .env file +# load_dotenv() + +# API_KEY = os.environ['API_KEY'] +# PRICE_DROP_KEY = os.environ['PRICE_DROP_KEY'] +# average_drop_key = os.environ['AVERAGE_DROP_KEY'] + +# Replace with your IFTTT Webhooks keys and event names +price_drop_key = 'hk1XqN9c6Lf3fny61cgEOLQb3L_J71xc5h2WpNu9MmP' +price_drop_event = 'sp_25p_alert' +# average_drop_key="hk1XqN9c6Lf3fny61cgEOMkLhEGT8CNupRK-3l5KgWy" +average_drop_event = 'sp_7da_alert' + +# Define a list of stock symbols you want to monitor +stock_symbols = ["TSLA", "AAPL", "GOOGL", "MSFT", "NKE"] + +# Dictionaries to store data +last_prices = {} +seven_day_averages = {} + +# Define the max number of API calls before stopping +max_api_calls = 1 # Change this to your desired limit + +# Counter to keep track of API calls +api_call_count = 0 + +def send_webhook_alert(event_key, event_name, message): + # Send a webhook alert + url = f'https://maker.ifttt.com/trigger/{event_name}/with/key/hk1XqN9c6Lf3fny61cgEOMkLhEGT8CNupRK-3l5KgWy' + playload = {'value1': message} + response = requests.post(url, data=playload) + if response.status_code == 200: + print(f"Alert sent successfully to {event_name}.") + else: + print(f"Failed to send alert to {event_name}. Status code: {response.status_code}") + +def fetch_stock_data(symbol): + try: + # Fetch intraday data - fix .env -> + intraday_url = 'https://financialmodelingprep.com/api/v3/quote-short/AAPL,GOOGL,TSLA,MSFT,NKE?apikey=151bf0b888c3544b249779155b5233a9' + intraday_data = requests.get(intraday_url).json() + for element in intraday_data: + print('Here is the real time stock price for: ' f"{element['symbol']}: {element['price']}") + + + # Fetch daily data - fix .env -> + daily_url = 'https://financialmodelingprep.com/api/v3/historical-price-full/AAPL,GOOGL,TSLA,MSFT,NKE?serietype=line&apikey=151bf0b888c3544b249779155b5233a9' + daily_data = requests.get(daily_url).json() + daily_prices = daily_data['historicalStockList'] + + # Calculate the 7-day average + # daily_prices_list = [float(daily_prices[date]['4. close']) for date in list(daily_prices.keys())[:7]] + daily_prices_list = [float(entry["close"]) for entry in daily_data["historicalStockList"][0]["historical"]] + seven_day_average = sum(daily_prices_list) / len(daily_prices_list) + for element in seven_day_average: + print('Here is the seven-day average stock price for: ' f"{element['symbol']}: {element['seven_day_average']}") + + return latest_price, seven_day_average + + except KeyError: + # Handle missing data in the API response + print(f"Data not available for {symbol}.") + return None, None + + except Exception as e: + # Handle other exceptions + print(f"An error occurred while fetching data for {symbol}: {str(e)}") + return None, None + + + +while True: + try: + for symbol in stock_symbols: + latest_price, seven_day_average = fetch_stock_data(symbol) + + if latest_price is not None: + # Check for price drop and 7-day average as before + if symbol in last_prices: + price_drop = last_prices[symbol] - latest_price + if price_drop >= 0.25: + message = f"{symbol} Alert: Price Drop of £0.25 or More\nCurrent Price: £{latest_price:.2f}" + send_webhook_alert(price_drop_key, price_drop_event, message) + + if latest_price < seven_day_averages.get(symbol, latest_price): + message = f"{symbol} Alert: Price Fell Below 7-Day Average\nCurrent Price: £{latest_price:.2f}, 7-Day Avg: £{seven_day_average:.2f}" + send_webhook_alert(average_drop_key, average_drop_event, message) + + # Update last_prices and seven_day_averages as before + last_prices[symbol] = latest_price + seven_day_averages[symbol] = seven_day_average + + # Print stock data + print(f"{symbol}: £{latest_price:.2f} (7-Day Avg: £{seven_day_average:.2f})") + + # API call count (useful for accounts with call limit) + api_call_count += 1 + + # Sleep for a few seconds before fetching data again + time.sleep(6000) # Adjust the interval as needed + + except KeyboardInterrupt: + print("Monitoring stopped by user.") + break + except Exception as e: + print(f"An error occurred: {str(e)}") \ No newline at end of file