Spaces:
Running
Running
Upload 4 files
Browse files
data.csv
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
ticker,trend,Entry_time,Entry_price
|
| 2 |
+
NSE:SHRIRAMFIN,Buy|30m,16:20:09,2296.55
|
| 3 |
+
NSE:PGEL,Sell|30m,16:20:09,2085.0
|
| 4 |
+
NSE:GRASIM,Buy|15m,16:20:09,2080.0
|
| 5 |
+
NSE:INDIAMART,Sell|15m,16:20:09,2448.0
|
| 6 |
+
NSE:LALPATHLAB,Buy|5m,16:20:09,2433.55
|
| 7 |
+
NSE:PHOENIXLTD,Sell|5m,16:20:09,2364.5
|
| 8 |
+
NSE:ACC,Buy|1m,16:20:09,2232.5
|
| 9 |
+
NSE:BSE,Sell|1m,16:20:09,2100.0
|
duck.png
ADDED
|
main.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from keep_alive import keep_alive
|
| 2 |
+
keep_alive()
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from tradingview_screener import Scanner, Query, Column
|
| 6 |
+
from time import sleep
|
| 7 |
+
import pdb
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import matplotlib.pyplot as plt
|
| 10 |
+
from PIL import Image
|
| 11 |
+
import urllib
|
| 12 |
+
import os
|
| 13 |
+
import requests
|
| 14 |
+
from datetime import datetime
|
| 15 |
+
from pytz import timezone
|
| 16 |
+
day1_local = datetime.now(timezone("Asia/Kolkata"))
|
| 17 |
+
day10 = day1_local.strftime('%H:%M:%S')
|
| 18 |
+
from datetime import datetime
|
| 19 |
+
from pytz import timezone
|
| 20 |
+
day2_local = datetime.now(timezone("Asia/Kolkata"))
|
| 21 |
+
day2 = day2_local.strftime('%d-%m-%Y')
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
csv_file_path = 'data.csv' # Replace with your desired CSV file path
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class YourClass:
|
| 31 |
+
def crosses_below(self, column, other):
|
| 32 |
+
return {'left': column.name, 'operation': 'crosses_below', 'right': column._extract_value(other)}
|
| 33 |
+
|
| 34 |
+
def crosses_above(self, column, other):
|
| 35 |
+
return {'left': column.name, 'operation': 'crosses_above', 'right': column._extract_value(other)}
|
| 36 |
+
|
| 37 |
+
time_intervals = ['1','5','15','30']
|
| 38 |
+
|
| 39 |
+
def setup_ui():
|
| 40 |
+
limit = 1
|
| 41 |
+
price_from = 2000
|
| 42 |
+
price_to = 2500
|
| 43 |
+
return price_from, price_to, limit
|
| 44 |
+
|
| 45 |
+
def main():
|
| 46 |
+
price_from, price_to,limit = setup_ui()
|
| 47 |
+
temp = pd.DataFrame()
|
| 48 |
+
|
| 49 |
+
if True:
|
| 50 |
+
final_df = pd.DataFrame()
|
| 51 |
+
for x in time_intervals:
|
| 52 |
+
your_instance = YourClass()
|
| 53 |
+
|
| 54 |
+
df_bullish = (Query()
|
| 55 |
+
.select('Exchange', f'close|{x}', f'volume|{x}', f'ADX-DI|{x}', f'ADX+DI|{x}')
|
| 56 |
+
.where(your_instance.crosses_below(Column(f'ADX-DI|{x}'), Column(f'ADX+DI|{x}')),
|
| 57 |
+
Column(f'close|{x}').between(price_from, price_to))
|
| 58 |
+
.order_by(f'volume|{x}', ascending=False)
|
| 59 |
+
.limit(limit))
|
| 60 |
+
|
| 61 |
+
df_bearish = (Query()
|
| 62 |
+
.select('Exchange', f'close|{x}', f'volume|{x}', f'ADX-DI|{x}', f'ADX+DI|{x}')
|
| 63 |
+
.where(your_instance.crosses_above(Column(f'ADX-DI|{x}'), Column(f'ADX+DI|{x}')),
|
| 64 |
+
Column(f'close|{x}').between(price_from, price_to))
|
| 65 |
+
.order_by(f'volume|{x}', ascending=False)
|
| 66 |
+
.limit(limit))
|
| 67 |
+
|
| 68 |
+
df_bullish = df_bullish.set_markets('india').get_scanner_data()[1]
|
| 69 |
+
df_bullish = df_bullish[df_bullish['exchange'] == 'NSE']
|
| 70 |
+
df_bullish['trend'] = f'Buy|{x}m'
|
| 71 |
+
df_bullish['Entry_time'] = day1_local.strftime('%H:%M:%S')
|
| 72 |
+
df_bullish['Entry_price'] = df_bullish[f'close|{x}']
|
| 73 |
+
df_bullish = df_bullish[['ticker', 'trend', 'Entry_time', 'Entry_price']]
|
| 74 |
+
|
| 75 |
+
df_bearish = df_bearish.set_markets('india').get_scanner_data()[1]
|
| 76 |
+
df_bearish = df_bearish[df_bearish['exchange'] == 'NSE']
|
| 77 |
+
df_bearish['trend'] = f'Sell|{x}m'
|
| 78 |
+
df_bearish['Entry_time'] = day1_local.strftime('%H:%M:%S')
|
| 79 |
+
df_bearish['Entry_price'] = df_bearish[f'close|{x}']
|
| 80 |
+
df_bearish = df_bearish[['ticker', 'trend', 'Entry_time', 'Entry_price']]
|
| 81 |
+
|
| 82 |
+
merge_cols = ['ticker', 'trend', 'Entry_time', 'Entry_price']
|
| 83 |
+
merged_df = pd.concat([df_bullish, df_bearish], ignore_index=True)
|
| 84 |
+
#merged_df = pd.merge(df_bullish, df_bearish, on=merge_cols, how='outer')
|
| 85 |
+
final_df = pd.concat([merged_df, final_df], ignore_index=True)
|
| 86 |
+
|
| 87 |
+
# Fetch data already stored in the CSV file
|
| 88 |
+
try:
|
| 89 |
+
stored_data = pd.read_csv(csv_file_path)
|
| 90 |
+
except FileNotFoundError:
|
| 91 |
+
stored_data = pd.DataFrame(columns=final_df.columns)
|
| 92 |
+
|
| 93 |
+
# Convert 'ticker' columns to string data type
|
| 94 |
+
final_df['ticker'] = final_df['ticker'].astype(str)
|
| 95 |
+
stored_data['ticker'] = stored_data['ticker'].astype(str)
|
| 96 |
+
|
| 97 |
+
# Remove rows from final_df that are already in the CSV file based on the 'ticker' column
|
| 98 |
+
final_df = final_df[~final_df['ticker'].isin(stored_data['ticker'])]
|
| 99 |
+
|
| 100 |
+
# Store new rows in the CSV file
|
| 101 |
+
final_df.to_csv(csv_file_path, mode='a', header=False, index=False)
|
| 102 |
+
print(final_df)
|
| 103 |
+
def Report():
|
| 104 |
+
data = pd.read_csv(csv_file_path)
|
| 105 |
+
data['Ltp'] = ''
|
| 106 |
+
ticker_list = data['ticker'].tolist()
|
| 107 |
+
q = Query().select('close')
|
| 108 |
+
try:
|
| 109 |
+
result = q.set_tickers(*ticker_list).get_scanner_data()[1]
|
| 110 |
+
result.set_index('ticker', inplace=True)
|
| 111 |
+
data.set_index('ticker', inplace=True)
|
| 112 |
+
data['Ltp'].update(result['close'])
|
| 113 |
+
data.reset_index(inplace=True)
|
| 114 |
+
|
| 115 |
+
# Calculate P/L and P/L percentage
|
| 116 |
+
data['Qty'] = int(10)
|
| 117 |
+
data['Inv_Amount'] = data['Qty'] * data['Entry_price']
|
| 118 |
+
|
| 119 |
+
data['P/L'] = (data['Ltp'] - data['Entry_price']) * data['Qty']
|
| 120 |
+
data['P/L'] = round(data['P/L'].astype('float'),2)
|
| 121 |
+
data['P/L %'] = ((data['Ltp'] - data['Entry_price']) / data['Entry_price']) * 100
|
| 122 |
+
data['P/L %'] = round(data['P/L %'].astype('float'),2)
|
| 123 |
+
# Add new columns for trade result and win/loss
|
| 124 |
+
data['Result'] = 'Neutral'
|
| 125 |
+
data['Win/Loss'] = 0 # 1 for win, 0 for loss
|
| 126 |
+
|
| 127 |
+
# Identify winning trades
|
| 128 |
+
win_condition = data['P/L'] > 0
|
| 129 |
+
data.loc[win_condition, 'Result'] = 'Win'
|
| 130 |
+
data.loc[win_condition, 'Win/Loss'] = 1
|
| 131 |
+
|
| 132 |
+
# Identify losing trades
|
| 133 |
+
loss_condition = data['P/L'] < 0
|
| 134 |
+
data.loc[loss_condition, 'Result'] = 'Loss'
|
| 135 |
+
|
| 136 |
+
# Calculate total number of winning and losing trades
|
| 137 |
+
total_wins = data['Win/Loss'].sum()
|
| 138 |
+
total_losses = len(data) - total_wins
|
| 139 |
+
total_pl = data['P/L'].sum()
|
| 140 |
+
|
| 141 |
+
# Print the updated dataframe
|
| 142 |
+
#print(data)
|
| 143 |
+
|
| 144 |
+
# Print total wins and losses
|
| 145 |
+
print(f'Time:{day2}_{day10}')
|
| 146 |
+
print(f'Total P/L: Rs.{int(total_pl)}')
|
| 147 |
+
print(f'Total Wins: {total_wins}')
|
| 148 |
+
print(f'Total Losses: {total_losses}')
|
| 149 |
+
|
| 150 |
+
def ax_logo(ax):
|
| 151 |
+
club_icon = Image.open('duck.png')
|
| 152 |
+
ax.imshow(club_icon)
|
| 153 |
+
ax.axis('off')
|
| 154 |
+
return ax
|
| 155 |
+
|
| 156 |
+
fig = plt.figure(figsize=(20,8), dpi=300)
|
| 157 |
+
ax = plt.subplot()
|
| 158 |
+
ncols = 11
|
| 159 |
+
df_example_2 = data
|
| 160 |
+
nrows = df_example_2.shape[0]
|
| 161 |
+
ax.set_xlim(0, ncols + 1)
|
| 162 |
+
ax.set_ylim(0, nrows + 1)
|
| 163 |
+
positions = [0.25, 2.5, 3.5, 4.5, 5.5,6.5,7.5,8.5,9.5,10.5,11.5]
|
| 164 |
+
columns = ['ticker','trend','Entry_time','Entry_price','Ltp','Qty','Inv_Amount','P/L','P/L %','Result','Win/Loss']
|
| 165 |
+
# Add table's main text
|
| 166 |
+
for i in range(nrows):
|
| 167 |
+
for j, column in enumerate(columns):
|
| 168 |
+
if j == 0:
|
| 169 |
+
ha = 'left'
|
| 170 |
+
cell_color = 'black'
|
| 171 |
+
elif j == 1 or j == 2 or j == 3 or j == 4 or j == 5 or j == 6 or j == 9:
|
| 172 |
+
ha = 'center'
|
| 173 |
+
cell_color ='black'
|
| 174 |
+
else:
|
| 175 |
+
ha = 'center'
|
| 176 |
+
value = df_example_2[column].iloc[i]
|
| 177 |
+
try:
|
| 178 |
+
cell_color = 'limegreen' if value > 0 else 'red'
|
| 179 |
+
text_label = f'{df_example_2[column].iloc[i]:,.00f}'
|
| 180 |
+
except :
|
| 181 |
+
try:
|
| 182 |
+
numeric_value = float(value.rstrip('%'))
|
| 183 |
+
cell_color = 'limegreen' if numeric_value > 0 else 'red'
|
| 184 |
+
except ValueError:
|
| 185 |
+
cell_color = 'white'
|
| 186 |
+
if column == 'Min':
|
| 187 |
+
text_label = f'{df_example_2[column].iloc[i]:,.00f}'
|
| 188 |
+
weight = 'bold'
|
| 189 |
+
else:
|
| 190 |
+
text_label = f'{df_example_2[column].iloc[i]}'
|
| 191 |
+
weight = 'normal'
|
| 192 |
+
ax.annotate(xy=(positions[j], i + .5),text=text_label,ha=ha,va='center',weight=weight,color=cell_color)
|
| 193 |
+
# Add column names
|
| 194 |
+
column_names = ['ticker','trend','Entry_time','Entry_price','Ltp','Qty','Inv_Amount',f'P/L\n₹ {round(total_pl,2)}','P/L %','Result','Win/Loss']
|
| 195 |
+
for index, c in enumerate(column_names):
|
| 196 |
+
if index == 0:
|
| 197 |
+
ha = 'left'
|
| 198 |
+
cell_color = 'black'
|
| 199 |
+
else:
|
| 200 |
+
ha = 'center'
|
| 201 |
+
value = index
|
| 202 |
+
try:
|
| 203 |
+
cell_color = 'limegreen' if value > 0 else 'red'
|
| 204 |
+
except :
|
| 205 |
+
try:
|
| 206 |
+
numeric_value = float(value.rstrip('%'))
|
| 207 |
+
cell_color = 'limegreen' if numeric_value > 0 else 'red'
|
| 208 |
+
except ValueError:
|
| 209 |
+
cell_color = 'white'
|
| 210 |
+
ax.annotate(xy=(positions[index], nrows + .25),text=column_names[index],ha=ha,va='bottom',weight='bold',color=cell_color)
|
| 211 |
+
# Add dividing lines
|
| 212 |
+
ax.plot([ax.get_xlim()[0], ax.get_xlim()[1]], [nrows, nrows], lw=1.5, color='black', marker='', zorder=11)
|
| 213 |
+
ax.plot([ax.get_xlim()[0], ax.get_xlim()[1]], [0, 0], lw=1.5, color='black', marker='', zorder=11)
|
| 214 |
+
for x in range(1, nrows):
|
| 215 |
+
ax.plot([ax.get_xlim()[0], ax.get_xlim()[1]], [x, x], lw=1.15, color='gray', ls=':', zorder=3 , marker='')
|
| 216 |
+
ax.fill_between(x=[0,2],y1=nrows, y2=0,color='lightgrey',alpha=0.5,ec='None')
|
| 217 |
+
ax.set_axis_off()
|
| 218 |
+
logo_ax = fig.add_axes([.825, .31, 0.1, 1.45])
|
| 219 |
+
ax_logo(logo_ax)
|
| 220 |
+
fig.text(x=0.15, y=.91, s=f'Intraday Screener Daily Summery Report on {day2}\nTotal Wins: {total_wins}\nTotal Losses: {total_losses}',color ='blue', ha='left',va='bottom', weight='bold', size=25)
|
| 221 |
+
|
| 222 |
+
plt.savefig('Report.jpg', dpi=300, transparent=True, bbox_inches='tight')
|
| 223 |
+
sleep(2)
|
| 224 |
+
except Exception as e:
|
| 225 |
+
print(f"Error: {e}")
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def send_report():
|
| 229 |
+
tele_auth_token = '5719015279:AAHTTTus2_dmsVvp9xTlO2QUFuHwtRmUfbY'
|
| 230 |
+
chat_id = {'chat_id' : "-1001954093602"}
|
| 231 |
+
send_photo_url = f"https://api.telegram.org/bot{tele_auth_token}/sendPhoto"
|
| 232 |
+
data = {"photo": open('./Report.jpg','rb')}
|
| 233 |
+
response = requests.post(send_photo_url,chat_id,files=data)
|
| 234 |
+
if response.status_code == 200:
|
| 235 |
+
print(f"Report sent successfully")
|
| 236 |
+
else:
|
| 237 |
+
print(f"Failed to send the Report")
|
| 238 |
+
print(response.text)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def clear_csv_data_without_header(file_path):
|
| 243 |
+
import csv
|
| 244 |
+
# Read the header from the existing file
|
| 245 |
+
with open(file_path, 'r', newline='') as csvfile:
|
| 246 |
+
csv_reader = csv.reader(csvfile)
|
| 247 |
+
header = next(csv_reader, None)
|
| 248 |
+
|
| 249 |
+
# Write the header back to the file
|
| 250 |
+
with open(file_path, 'w', newline='') as csvfile:
|
| 251 |
+
csv_writer = csv.writer(csvfile)
|
| 252 |
+
if header:
|
| 253 |
+
csv_writer.writerow(header)
|
| 254 |
+
|
| 255 |
+
if __name__ == "__main__":
|
| 256 |
+
while True:
|
| 257 |
+
report_minutes = [5,10,15,20,25,30,35,40,45,50,55,0]
|
| 258 |
+
from datetime import datetime
|
| 259 |
+
import time
|
| 260 |
+
from pytz import timezone
|
| 261 |
+
day = datetime.now(timezone("Asia/Kolkata"))
|
| 262 |
+
current_time = day.time()
|
| 263 |
+
if day.strptime("09:16:00", "%H:%M:%S").time() <= current_time <= day.strptime("18:16:00", "%H:%M:%S").time():
|
| 264 |
+
main()
|
| 265 |
+
sleep(18)
|
| 266 |
+
print('..........')
|
| 267 |
+
Report()
|
| 268 |
+
if current_time.minute in report_minutes:
|
| 269 |
+
send_report()
|
| 270 |
+
sleep(60)
|
| 271 |
+
else:
|
| 272 |
+
print('Wait for Trading Time...!!')
|
| 273 |
+
clear_csv_data_without_header(csv_file_path)
|
| 274 |
+
sleep(60)
|
| 275 |
+
sleep(60)
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pandas
|
| 2 |
+
tradingview-screener
|
| 3 |
+
flask
|
| 4 |
+
matplotlib
|