-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
52 lines (44 loc) · 1.61 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import os
import requests
import datetime
today = datetime.date.today()
day = today.weekday()
# API endpoint and fetch key from env variable
stock_url = "https://www.alphavantage.co/query"
stock_key = os.environ.get("API_KEY")
# Create list of tickers and list for prices
tickers = ["AAPl", "MSFT", "GOOGL", "AMZN"]
values = []
# Check if it is a weekday, if so then API is called, else message is printed
if day < 5:
# Calls API for each ticker
for ticker in tickers:
params = {
"function": "TIME_SERIES_DAILY",
"symbol": ticker,
"apikey": stock_key,
}
response = requests.get(stock_url, params)
response.raise_for_status()
try:
data = response.json()["Time Series (Daily)"]
except KeyError as e:
print(f"API Error: {e}")
print(response.json())
data = None
# This API provides alot of data, so only the most recent date and close value is used
if data:
most_recent_date = max(data.keys())
close_value = data[most_recent_date]["4. close"]
values.append(f"{ticker}: {float(close_value)}")
print(f"{ticker}: {float(close_value)}")
# Converts date to mm/dd/yyyy format
date = datetime.datetime.now().strftime("%m/%d/%Y")
# Writes date and values to file for each ticker
with open("/home/Chris943/stocks.txt", "a") as file:
file.write(f"\n{date}\n")
for value in values:
file.write(f"{value}\n")
# If it is not a weekday, message is printed
else:
print("It is not a weekday, market is closed.")