-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfetch_api_data.py
More file actions
55 lines (49 loc) · 2.25 KB
/
fetch_api_data.py
File metadata and controls
55 lines (49 loc) · 2.25 KB
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
53
54
55
# Fetching stock data from StockAPI and returning a list of stocks
import datetime
import json
import os
from fastapi import HTTPException
import requests
from database import get_table_length
from dotenv import load_dotenv
load_dotenv()
TOK_API_TOKEN = os.getenv("TOK_API_TOKEN")
def fetch_api_data() -> list:
print("\nFetching API data form stockapi.org . . . ")
print("Token for api : ", TOK_API_TOKEN)
try:
stock_tickers_list = ["AAPL,TSLA,MSFT","KO,NVDA,GOOG","AMZN,LLY,JPM"] #, "KO,NVDA,GOOG", "AMZN,LLY,JPM" <- lisää nämä kun tarvitaan enemmän tietoja
stock_data_list = []
table_length = get_table_length('stock')
print("\nLength of 'stock_data' table:", table_length)
for ticker in stock_tickers_list:
url = f"https://api.stockdata.org/v1/data/quote?symbols={ticker}&api_token={TOK_API_TOKEN}"
response = requests.get(url)
if response.status_code == 200:
quotes_data = json.loads(response.text)
print("Response status OK")
if 'data' in quotes_data:
stock_data = quotes_data['data']
# Print out the fetched data
print(f"Fetched stock quotes for {len(stock_data)} stocks:")
today = datetime.date.today()
if type(today) == str:
pass
else:
today = today.strftime('%Y-%m-%d')
for stock in stock_data:
stock_info = {
"id": table_length,
"ticker": stock['ticker'],
"name": stock['name'],
"price_today": stock['price'],
"volume": stock['volume'],
"last_days_price": stock['previous_close_price'],
"date": today
}
stock_data_list.append(stock_info)
table_length += 1
return stock_data_list
except Exception as e:
print("Fetching from stockdata API failed.")
raise HTTPException(status_code=500, detail=str(e))