Spaces:
Running
Running
import streamlit as st | |
st.set_page_config(layout="wide") | |
import pandas as pd | |
from tradingview_screener import Scanner, Query, Column | |
import pandas as pd | |
import os | |
import requests | |
from datetime import datetime | |
from time import sleep | |
from pytz import timezone | |
day1_local = datetime.now(timezone("Asia/Kolkata")) | |
day10 = day1_local.strftime('%H:%M:%S') | |
from datetime import datetime | |
from pytz import timezone | |
day2_local = datetime.now(timezone("Asia/Kolkata")) | |
day2 = day2_local.strftime('%d-%m-%Y') | |
placeholder = st.empty() | |
placeholder1 = st.empty() | |
csv_file_path = 'data.csv' | |
overall_data = 'overall_data.csv' | |
class YourClass: | |
def crosses_below(self, column, other): | |
return {'left': column.name, 'operation': 'crosses_below', 'right': column._extract_value(other)} | |
def crosses_above(self, column, other): | |
return {'left': column.name, 'operation': 'crosses_above', 'right': column._extract_value(other)} | |
time_intervals = ['1','5','15','30'] | |
def setup_ui(): | |
limit = 1 | |
price_from = 2000 | |
price_to = 2500 | |
return price_from, price_to, limit | |
def main(): | |
price_from, price_to,limit = setup_ui() | |
temp = pd.DataFrame() | |
if True: | |
final_df = pd.DataFrame() | |
for x in time_intervals: | |
your_instance = YourClass() | |
df_bullish = (Query() | |
.select('Exchange', f'close|{x}', f'volume|{x}', f'ADX-DI|{x}', f'ADX+DI|{x}') | |
.where(your_instance.crosses_below(Column(f'ADX-DI|{x}'), Column(f'ADX+DI|{x}')), | |
Column(f'close|{x}').between(price_from, price_to)) | |
.order_by(f'volume|{x}', ascending=False) | |
.limit(limit)) | |
df_bearish = (Query() | |
.select('Exchange', f'close|{x}', f'volume|{x}', f'ADX-DI|{x}', f'ADX+DI|{x}') | |
.where(your_instance.crosses_above(Column(f'ADX-DI|{x}'), Column(f'ADX+DI|{x}')), | |
Column(f'close|{x}').between(price_from, price_to)) | |
.order_by(f'volume|{x}', ascending=False) | |
.limit(limit)) | |
df_bullish = df_bullish.set_markets('india').get_scanner_data()[1] | |
df_bullish = df_bullish[df_bullish['exchange'] == 'NSE'] | |
df_bullish['trend'] = f'Buy|{x}m' | |
df_bullish['Entry_time'] = day1_local.strftime('%H:%M:%S') | |
df_bullish['Entry_price'] = df_bullish[f'close|{x}'] | |
df_bullish = df_bullish[['ticker', 'trend', 'Entry_time', 'Entry_price']] | |
df_bearish = df_bearish.set_markets('india').get_scanner_data()[1] | |
df_bearish = df_bearish[df_bearish['exchange'] == 'NSE'] | |
df_bearish['trend'] = f'Sell|{x}m' | |
df_bearish['Entry_time'] = day1_local.strftime('%H:%M:%S') | |
df_bearish['Entry_price'] = df_bearish[f'close|{x}'] | |
df_bearish = df_bearish[['ticker', 'trend', 'Entry_time', 'Entry_price']] | |
merge_cols = ['ticker', 'trend', 'Entry_time', 'Entry_price'] | |
merged_df = pd.concat([df_bullish, df_bearish], ignore_index=True) | |
#merged_df = pd.merge(df_bullish, df_bearish, on=merge_cols, how='outer') | |
final_df = pd.concat([merged_df, final_df], ignore_index=True) | |
# Fetch data already stored in the CSV file | |
try: | |
stored_data = pd.read_csv(csv_file_path) | |
except FileNotFoundError: | |
stored_data = pd.DataFrame(columns=final_df.columns) | |
# Convert 'ticker' columns to string data type | |
final_df['ticker'] = final_df['ticker'].astype(str) | |
stored_data['ticker'] = stored_data['ticker'].astype(str) | |
# Remove rows from final_df that are already in the CSV file based on the 'ticker' column | |
final_df = final_df[~final_df['ticker'].isin(stored_data['ticker'])] | |
# Store new rows in the CSV file | |
final_df.to_csv(csv_file_path, mode='a', header=False, index=False) | |
print(final_df) | |
def Report(): | |
data = pd.read_csv(csv_file_path) | |
data['Ltp'] = '' | |
ticker_list = data['ticker'].tolist() | |
q = Query().select('close') | |
try: | |
result = q.set_tickers(*ticker_list).get_scanner_data()[1] | |
result.set_index('ticker', inplace=True) | |
data.set_index('ticker', inplace=True) | |
data['Ltp'] = result['close'] | |
data.reset_index(inplace=True) | |
# Calculate P/L and P/L percentage | |
data['Qty'] = int(10) | |
data['Inv_Amount'] = data['Qty'] * data['Entry_price'] | |
data['P/L'] = (data['Ltp'] - data['Entry_price']) * data['Qty'] | |
data['P/L'] = round(data['P/L'].astype('float'),2) | |
data['P/L %'] = ((data['Ltp'] - data['Entry_price']) / data['Entry_price']) * 100 | |
data['P/L %'] = round(data['P/L %'].astype('float'),2) | |
# Add new columns for trade result and win/loss | |
data['Result'] = 'Neutral' | |
data['Win/Loss'] = 0 # 1 for win, 0 for loss | |
# Identify winning trades | |
win_condition = data['P/L'] > 0 | |
data.loc[win_condition, 'Result'] = 'Win' | |
data.loc[win_condition, 'Win/Loss'] = 1 | |
# Identify losing trades | |
loss_condition = data['P/L'] < 0 | |
data.loc[loss_condition, 'Result'] = 'Loss' | |
# Calculate total number of winning and losing trades | |
total_wins = data['Win/Loss'].sum() | |
total_losses = len(data) - total_wins | |
total_pl = data['P/L'].sum() | |
# Print the updated dataframe | |
col10 , col20 = st.columns(2,gap="small") | |
with col10: | |
with placeholder.container(): | |
from datetime import datetime | |
from pytz import timezone | |
local = datetime.now(timezone("Asia/Kolkata")) | |
date = local.strftime('⏰%I:%M:%S %p') | |
col1 ,col2,col3 = st.columns(3,gap="small") | |
with col1: | |
st.info(f'Total P/L: Rs.{int(total_pl)}') | |
with col2: | |
dat = f'Total Wins: {total_wins}' | |
st.success(dat) | |
with col3: | |
dat1 = f'Total Losses: {total_losses}' | |
st.error(dat1) | |
df = pd.read_csv('overall_data.csv') | |
report = {'time' : date , 'Profit&Loss' : int(total_pl), 'Win': total_wins , 'Loss': total_losses} | |
df = pd.concat([df, pd.DataFrame([report])], ignore_index=True) | |
df.to_csv(overall_data,index = False) | |
st.line_chart(df, x="time", y="Profit&Loss") | |
st.write(data) | |
with col20: | |
with placeholder1.container(): | |
data10 = pd.read_csv(overall_data) | |
st.write(data10) | |
except Exception as e: | |
print(f"Error: {e}") | |
def clear_csv_data_without_header(file_path): | |
import csv | |
# Read the header from the existing file | |
with open(file_path, 'r', newline='') as csvfile: | |
csv_reader = csv.reader(csvfile) | |
header = next(csv_reader, None) | |
# Write the header back to the file | |
with open(file_path, 'w', newline='') as csvfile: | |
csv_writer = csv.writer(csvfile) | |
if header: | |
csv_writer.writerow(header) | |
if __name__ == "__main__": | |
while True: | |
from datetime import datetime | |
import time | |
from pytz import timezone | |
day = datetime.now(timezone("Asia/Kolkata")) | |
current_time = day.time() | |
if day.strptime("09:16:00", "%H:%M:%S").time() <= current_time <= day.strptime("18:16:00", "%H:%M:%S").time(): | |
main() | |
sleep(5) | |
Report() | |
elif day.strptime("09:10:00", "%H:%M:%S").time() <= current_time <= day.strptime("09:12:00", "%H:%M:%S").time(): | |
clear_csv_data_without_header(csv_file_path) | |
clear_csv_data_without_header(overall_data) | |
sleep(120) | |
else: | |
st.write('Wait for Trading Time...!!') | |
sleep(60) | |