From 2ba1dfbbcb24455d5ed3128bc4392dba2fe2e8e0 Mon Sep 17 00:00:00 2001 From: MuslemRahimi Date: Mon, 25 Nov 2024 12:42:20 +0100 Subject: [PATCH] bugfixing --- app/cron_analyst_insight.py | 26 ++++++++++---------------- 1 file changed, 10 insertions(+), 16 deletions(-) diff --git a/app/cron_analyst_insight.py b/app/cron_analyst_insight.py index 7b6c83f..e622271 100644 --- a/app/cron_analyst_insight.py +++ b/app/cron_analyst_insight.py @@ -8,6 +8,8 @@ from tqdm import tqdm from datetime import datetime from openai import OpenAI import aiofiles +import time + # Load environment variables load_dotenv() @@ -30,31 +32,19 @@ async def save_json(symbol, data): await file.write(ujson.dumps(data)) async def get_analyst_insight(session, ticker): - #there is a bug in benzinga api where the latest data can be at the second element instead the first - #solution check which date is the latest by comparing these two res_dict = {} try: querystring = {"token": benzinga_api_key, "symbols": ticker} async with session.get(url, params=querystring) as response: - output = await response.json() - if 'analyst-insights' in output and len(output['analyst-insights']) >= 2: - insight_1, insight_2 = output['analyst-insights'][:2] - - # Parse dates for comparison - date_1 = datetime.strptime(insight_1['date'], "%Y-%m-%d") - date_2 = datetime.strptime(insight_2['date'], "%Y-%m-%d") - - # Choose the insight with the latest date - latest_insight = insight_1 if date_1 >= date_2 else insight_2 - elif 'analyst-insights' in output and output['analyst-insights']: - latest_insight = output['analyst-insights'][0] # Only one insight available - else: - return res_dict # No insights available + output = (await response.json())['analyst-insights'] + output = sorted(output, key=lambda x: datetime.strptime(x['date'], '%Y-%m-%d'), reverse=True) + latest_insight = output[0] # Populate res_dict with the latest insight data res_dict = { 'insight': latest_insight['analyst_insights'], 'id': latest_insight['id'], + 'pt': round(float(latest_insight.get('pt'))) if latest_insight.get('pt', None) is not None else None, 'date': datetime.strptime(latest_insight['date'], "%Y-%m-%d").strftime("%b %d, %Y") } except Exception as e: @@ -113,6 +103,10 @@ async def main(): cursor = con.cursor() cursor.execute("SELECT DISTINCT symbol FROM stocks WHERE symbol NOT LIKE '%.%'") stock_symbols = [row[0] for row in cursor.fetchall()] + + #TestMode + #stock_symbols = ['WMT'] + con.close() async with aiohttp.ClientSession(headers=headers) as session: