-
Notifications
You must be signed in to change notification settings - Fork 0
/
swing_stock_price_fetch_fno.py
151 lines (121 loc) · 5.91 KB
/
swing_stock_price_fetch_fno.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
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
import yfinance as yf
import csv
from datetime import datetime, time
import time as t
import subprocess
import asyncio
from telegram.error import TelegramError
from telegram import Bot, error
# Function to fetch stock prices
def fetch_stock_prices(stock_names, live, file_name,upside_bo_msg_list, downside_bo_msg_list):
for stock_info in stock_names:
#print (stock_info)
updated_rows = []
stock_name, high_price, low_price, is_enable, comment = stock_info
try:
if live:
stock_data = yf.download(stock_name, start=datetime.now(), end=datetime.now())
else:
stock_data = yf.download(stock_name)
if not stock_data.empty:
print(f"Stock: {stock_name}, Price: {stock_data['Adj Close'].iloc[-1]}")
#current_price = stock.history(period="1d")['Close'].iloc[-1]
current_price = stock_data['Adj Close'].iloc[-1]
is_enable = 'TRUE'
if current_price >= float(high_price):
message = f""" <b> {stock_name} </b> - crossed <b> HIGH </b> price of {high_price} \n"""
send_notification(message)
#asyncio.run(tgmain(message))
upside_bo_msg_list.append(message)
is_enable = 'FALSE'
elif current_price <= float(low_price):
message = f""" <b> {stock_name} </b> - crossed <b> LOW </b> price of {low_price} \n"""
send_notification(message)
#asyncio.run(tgmain(message))
downside_bo_msg_list.append(message)
is_enable = 'FALSE'
updated_rows.append([stock_name, high_price, low_price, is_enable,comment])
else:
print(f"Stock: {stock_name}, Data not available")
updated_rows.append([stock_name, high_price, low_price, is_enable,comment])
except Exception as e:
print(f"Error fetching data for {stock_name}: {e}")
# Write the updated rows back to the CSV file, skipping the first line
with open(file_name, 'r') as file:
lines = file.readlines()
with open(file_name, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['SCRIP', 'High Price', 'Low Price', 'EnaBle','Comment']) # Rewrite the header
writer.writerows(updated_rows)
file.writelines(lines[len(updated_rows)+1:]) # Write the skipped lines back to the file
# Function to read stock names from CSV file
def read_stock_names(file_name):
stock_names = []
with open(file_name, 'r') as file:
reader = csv.reader(file)
next(reader) # Skip the first line
for row in reader:
#stock_names.extend(row)
#print (row[3])
if row[3] == 'TRUE':
stock_names.append(row)
return stock_names
# Function to send notification
def send_notification(message):
subprocess.Popen(['notify-send', 'Stock Alert', message])
# Replace 'YOUR_BOT_TOKEN' with your actual bot token from BotFather
bot_token = '7059155564:AAGT0jZsElWyAJ8ClP-8hqZTmjxC4bZR1A8'
# Replace 'YOUR_CHANNEL_ID' with your channel's username or ID (e.g., '@channelusername')
#channel_id = '@vrzonebof'
channel_id = '-1002033022952'
#channel_id = '1460012524'
async def tgmain(message):
# Create a bot instance
bot = Bot(token=bot_token)
try:
# Send a message to the channel
await bot.send_message(chat_id=channel_id, text=message, parse_mode='HTML')
print("Message sent successfully!")
except error.BadRequest as e:
print(f"Failed to send message: {e}")
except error.Unauthorized as e:
print(f"Bot is not authorized to send messages to the channel: {e}")
except error.TelegramError as e:
print(f"Failed to send message due to Telegram error: {e}")
# Main function
def main():
# File containing stock names
stock_file = 'swing_stock_fno_list.csv'
# Read stock names from CSV file
stock_names = read_stock_names(stock_file)
# Run until 3:30 PM IST
end_time = datetime.combine(datetime.now().date(), time(hour=15, minute=30))
start_time = datetime.combine(datetime.now().date(), time(hour=00, minute=15))
no_of_exec = 1
while datetime.now() < end_time:
upside_bo_msg_list = []
downside_bo_msg_list = []
#asyncio.run(tgmain(message))
fetch_stock_prices(stock_names, live=True, file_name=stock_file, upside_bo_msg_list=upside_bo_msg_list, downside_bo_msg_list=downside_bo_msg_list )
message_up = f""" No of Execution for the day - {no_of_exec} \n\n ======Upside Breakout====== \n\n """ + "\n".join(upside_bo_msg_list)
message_down = """ \n ======Downside Breakout====== \n\n""" + "\n".join(downside_bo_msg_list)
message = message_up + message_down
asyncio.run(tgmain(message))
print ("\n\n===========================================")
print ("==== Waiting for another 5 Minutes ======")
print ("===========================================\n\n")
t.sleep(300) # Wait for 5 minute before fetching again
no_of_exec+=1
print (" Market will open at 9:15 am ")
print ("==== We will find our zone using today/yesterday closed price =====")
upside_bo_msg_list = []
downside_bo_msg_list = []
fetch_stock_prices(stock_names, live=False, file_name=stock_file, upside_bo_msg_list=upside_bo_msg_list, downside_bo_msg_list=downside_bo_msg_list )
message = f""" No of Execution for the day - {no_of_exec} \n\n ======Upside Breakout====== \n\n """ \
+ "\n".join(upside_bo_msg_list) + \
"\n ======Downside Breakout====== \n\n"+ "\n".join(downside_bo_msg_list)
print (message)
asyncio.run(tgmain(message))
if __name__ == "__main__":
main()
""" ApolloTyre Balkrishna """