-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
234 lines (195 loc) · 9.72 KB
/
Copy pathmain.py
File metadata and controls
234 lines (195 loc) · 9.72 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# Script Created by: Pablo Calatayud
# Email: pablocalatayudpelayo@gmail.com
# LinkedIn: https://www.linkedin.com/in/pablo-calatayud-pelayo/
# Copyright (c) 2025, Pablo Calatayud. All rights reserved.
import requests
from loguru import logger
from utils.utils import *
import datetime
from weekdays.Dividends import DividendBot
from weekdays.Earnings import EarningsBot
from weekdays.Splits import SplitBot
from weekdays.Open_Market_Performance import Market_Daily_Performance
from weekends.performance_Automatization_US_ALL import US_StocksPerformance
from weekends.Performance_Mag_7 import StockSevenMagnificenPerformance
from weekends.Performance_Markets import MarketPerformanceTracker
from weekends.Performance_Sector import SectorPerformance
from utils.utils import post_twitter,bot_send_text
from config.api_keys import api_key
class Execution_twitter_information:
WEEKDAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
WEEKENDS = ['Saturday', 'Sunday']
def __init__(self):
# These days and hours are just used for the task scheduler to know what to run at different times.
self.morning_update = [8]
self.time_open = [15,30]
self.time_close = [22,00]
self.time_performance = [18,30]
self.performance_markets = ['Saturday',8]
self.performance_US_ALL = ['Saturday', 17]
self.performance_mag_7= ['Sunday', 8]
self.performance_Sector = ['Sunday', 17]
logger.add("logs/main.log", rotation="500 MB")
logger.info('Initialising Main')
self.time = None
self.exchange = "NASDAQ"
self.api_key = api_key
self.current_year = datetime.datetime.now().year
self.today = datetime.datetime.now().date()
# self.today = datetime.date(2025, 1, 20)
self.current_hour = datetime.datetime.now().hour
self.current_minute = datetime.datetime.now().minute
self.day_of_week = self.today.strftime('%A')
self.market_open = None
def is_market_open(self):
"""
Check if the market is open by checking against local holiday calendar.
Uses config/market_holidays.json to determine if today is a market holiday.
returns -> None (sets self.market_open to True/False)
"""
import json
import os
try:
# Load market holidays from local JSON file
holidays_file = os.path.join(os.path.dirname(__file__), 'utils', 'market_holidays.json')
with open(holidays_file, 'r') as f:
all_holidays = json.load(f)
# Get holidays for current year
year_str = str(self.current_year)
holidays_this_year = all_holidays.get(year_str, {})
today_str = self.today.strftime('%Y-%m-%d')
current_date = self.today.strftime("%A, %d of %B")
# Check if today is a holiday
if today_str in holidays_this_year:
reason = holidays_this_year[today_str]
if self.morning_update[0] == self.current_hour:
logger.info(f"Today {current_date} the market is closed due to: {reason}.")
post_twitter(f"Today {current_date} the market is closed due to: {reason}.")
self.market_open = False
else:
# Not a holiday - market is open
if self.morning_update[0] == self.current_hour:
logger.info(f"Today {current_date} the {self.exchange} is open.")
post_twitter(f"Today {current_date} the {self.exchange} is open (09:30 - 16:00 ET).")
self.market_open = True
except FileNotFoundError:
logger.error(f"Market holidays file not found. Assuming market is open.")
bot_send_text(f"⚠️ Market holidays file not found. Assuming market is open.")
self.market_open = True
except Exception as e:
logger.error(f"Error checking market holidays: {e}")
bot_send_text(f"⚠️ Error checking market holidays: {e}\nAssuming market is open on weekday.")
self.market_open = True
return None
def is_weekend(self):
"""
Check if today is a weekend and update the market status.
"""
if self.day_of_week in self.WEEKENDS:
logger.info(f"{self.day_of_week} is a weekend. The market is closed.")
self.market_open = False
else:
logger.info(f"{self.day_of_week} is a weekday. The market could be open.")
self.is_market_open()
return None
def run(self):
send_telegram_message('Running main.py')
self.is_weekend()
if self.day_of_week in self.WEEKDAYS and self.market_open==True:
logger.info("Today the market opens")
if self.current_hour == self.morning_update[0]:
logger.info("Running Earnings + Dividends + Splits")
try:
bot = EarningsBot()
bot.run()
except Exception as e:
logger.error(f"EarningsBot failed: {e}")
bot_send_text(f"❌ EarningsBot Error: {type(e).__name__}: {str(e)}")
time.sleep(300)
try:
bot = DividendBot()
bot.run()
except Exception as e:
logger.error(f"DividendBot failed: {e}")
bot_send_text(f"❌ DividendBot Error: {type(e).__name__}: {str(e)}")
time.sleep(300)
try:
bot = SplitBot()
bot.run()
except Exception as e:
logger.error(f"SplitBot failed: {e}")
bot_send_text(f"❌ SplitBot Error: {type(e).__name__}: {str(e)}")
elif self.current_hour == self.time_open[0] and self.current_minute >= self.time_open[1]:
logger.info('The market just opened -> ')
try:
market = Market_Daily_Performance()
market.market_just_open()
except Exception as e:
logger.error(f"Market open performance failed: {e}")
bot_send_text(f"❌ Market Open Error: {type(e).__name__}: {str(e)}")
elif self.current_hour == self.time_performance[0]:
logger.info('The market has been opened for 3 hours -> ')
try:
market = Market_Daily_Performance()
market.market_is_open()
except Exception as e:
logger.error(f"Market performance check failed: {e}")
bot_send_text(f"❌ Market Performance Error: {type(e).__name__}: {str(e)}")
elif self.current_hour == self.time_close[0]:
logger.info('The market just closed -> ')
try:
market = Market_Daily_Performance()
market.market_is_just_closed()
market.market_1_week()
except Exception as e:
logger.error(f"Market close performance failed: {e}")
bot_send_text(f"❌ Market Close Error: {type(e).__name__}: {str(e)}")
elif self.day_of_week in self.WEEKENDS:
logger.info('Today the market is closed -> Weekend.')
if self.day_of_week == self.performance_markets[0] and self.current_hour == self.performance_markets[1]:
try:
tracker = MarketPerformanceTracker()
tracker.run()
except Exception as e:
logger.error(f"MarketPerformanceTracker failed: {e}")
bot_send_text(f"❌ Market Performance Tracker Error: {type(e).__name__}: {str(e)}")
elif self.day_of_week == self.performance_US_ALL[0] and self.current_hour == self.performance_US_ALL[1]:
try:
US_stocks = US_StocksPerformance()
US_stocks.run()
except Exception as e:
logger.error(f"US_StocksPerformance failed: {e}")
bot_send_text(f"❌ US Stocks Performance Error: {type(e).__name__}: {str(e)}")
elif self.day_of_week == self.performance_mag_7[0] and self.current_hour == self.performance_mag_7[1]:
try:
stock_performance = StockSevenMagnificenPerformance()
stock_performance.run()
except Exception as e:
logger.error(f"Magnificent 7 Performance failed: {e}")
bot_send_text(f"❌ Mag 7 Performance Error: {type(e).__name__}: {str(e)}")
elif self.day_of_week == self.performance_Sector[0] and self.current_hour == self.performance_Sector[1]:
try:
stock_perf = SectorPerformance()
stock_perf.run()
except Exception as e:
logger.error(f"SectorPerformance failed: {e}")
bot_send_text(f"❌ Sector Performance Error: {type(e).__name__}: {str(e)}")
else:
logger.info('Nothing to post...')
bot_send_text('Nothing to post...')
else:
logger.info('Nothing to post...')
bot_send_text('Nothing to post...')
return None
if __name__ == "__main__":
try:
twitting = Execution_twitter_information()
processed_data = twitting.run()
except Exception as e:
error_msg = f"🚨 CRITICAL ERROR in main.py:\n{type(e).__name__}: {str(e)}"
logger.exception("Critical error in main execution")
try:
bot_send_text(error_msg)
except:
pass # Don't fail if telegram notification fails
raise # Re-raise to see full traceback