Skip to content

Commit 456d97b

Browse files
authored
Merge pull request #171 from Intelligent-Advisor-Sem-4/main
Refactor risk score update process to improve API rate limit handling…
2 parents e46c8ca + d93a9a3 commit 456d97b

File tree

3 files changed

+22
-33
lines changed

3 files changed

+22
-33
lines changed

API/triggers.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from fastapi import APIRouter, Depends
1+
from fastapi import APIRouter, Depends, BackgroundTasks
22
from sqlalchemy.orm import Session
33
from db.dbConnect import get_db
44
from services.asset_management import update_all_stock_risk_scores
@@ -10,7 +10,7 @@
1010

1111

1212
@router.post("/update-risk-scores", status_code=200)
13-
def trigger_risk_score_updates(db: Session = Depends(get_db)):
13+
def trigger_risk_score_updates(background_tasks: BackgroundTasks, db: Session = Depends(get_db)):
1414
"""Trigger risk score updates for all stocks in the database."""
15-
update_all_stock_risk_scores(db)
16-
return {"message": "Risk score update initiated for all stocks"}
15+
background_tasks.add_task(update_all_stock_risk_scores, db)
16+
return {"message": "Risk score update initiated in the background"}

services/asset_management.py

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
from datetime import datetime
2+
import time
23

34
import yfinance as yf
45
from sqlalchemy.orm import Session
56

67
from classes.Asset import Asset, DB_Stock, AssetFastInfo, StockResponse
78
from models.models import Stock, AssetStatus
8-
from services.email_service.email_service import send_email_notification
99
from services.risk_analysis.analyser import RiskAnalysis
1010
from services.utils import calculate_shallow_risk_score
1111

@@ -39,20 +39,20 @@ def create_stock(db: Session, symbol: str) -> Stock:
3939
status=AssetStatus.PENDING,
4040
)
4141

42-
# # Send email notification
43-
# company_name = stock.asset_name
44-
# email_subject = f"New Stock Added: {symbol}"
45-
# email_message = f"""
46-
# A new stock has been added to the database:
42+
# # Send email notification
43+
# company_name = stock.asset_name
44+
# email_subject = f"New Stock Added: {symbol}"
45+
# email_message = f"""
46+
# A new stock has been added to the database:
4747

48-
# Ticker: {symbol}
49-
# Name: {company_name}
50-
# Exchange: {stock.exchange}
48+
# Ticker: {symbol}
49+
# Name: {company_name}
50+
# Exchange: {stock.exchange}
5151

52-
# Initiate the model training process for this stock.
53-
# Change the status to 'ACTIVE' when ready.
54-
# """
55-
# send_email_notification(email_subject, email_message)
52+
# Initiate the model training process for this stock.
53+
# Change the status to 'ACTIVE' when ready.
54+
# """
55+
# send_email_notification(email_subject, email_message)
5656

5757
db.add(stock)
5858
db.commit()
@@ -99,8 +99,11 @@ def update_all_stock_risk_scores(db: Session) -> None:
9999
for stock in stocks:
100100
try:
101101
# Get risk score using the analyzer and update it
102+
print(f"Updating risk score for {stock.ticker_symbol}...")
102103
analyser = RiskAnalysis(ticker=str(stock.ticker_symbol), db=db, db_stock=stock)
103-
analyser.get_risk_score_and_update()
104+
analyser.calculate_overall_risk()
105+
print(f"Risk score for {stock.ticker_symbol} updated to {stock.risk_score}")
106+
time.sleep(30) # Pause for 30 seconds to respect API rate limits
104107
except Exception as e:
105108
# Log error but continue processing other stocks
106109
print(f"Error updating risk score for {stock.ticker_symbol}: {str(e)}")

services/risk_analysis/analyser.py

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -295,18 +295,4 @@ def get_risk_score_and_update(self) -> RiskScoreUpdate:
295295
return RiskScoreUpdate(
296296
risk_score=fast_report["risk_score"],
297297
was_updated=fast_report["updated"]
298-
)
299-
300-
301-
# if __name__ == "__main__":
302-
# # Example usage
303-
# db_gen = get_db()
304-
# session = next(db_gen)
305-
# try:
306-
# analyzer = RiskAnalysis("TSLA", session)
307-
# report = analyzer.generate_risk_report(lookback_days=30)
308-
# print(report)
309-
# except Exception as e:
310-
# print(f"Error: {e}")
311-
# finally:
312-
# session.close()
298+
)

0 commit comments

Comments
 (0)