riteshcp commited on
Commit
df9795e
·
verified ·
1 Parent(s): 9290592

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -0
app.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import yfinance as yf
3
+ import pandas as pd
4
+ import numpy as np
5
+
6
+ # Streamlit Title
7
+ st.title("NIFTY 500 Turtle Strategy Scanner with Entry and Exit Signals")
8
+
9
+ # Load the NIFTY 500 stock list
10
+ stock_list = pd.read_csv('ind_nifty500list.csv')
11
+ stock_list['Symbol'] = stock_list['Symbol'] + ".NS"
12
+ nifty_500_stocks = stock_list['Symbol'].tolist()
13
+
14
+ # Sidebar for Parameters
15
+ st.sidebar.header("Turtle Strategy Parameters")
16
+ entry_days = st.sidebar.slider("Entry Lookback Period (days)", min_value=10, max_value=60, value=20, step=1)
17
+ exit_days = st.sidebar.slider("Exit Lookback Period (days)", min_value=5, max_value=30, value=10, step=1)
18
+
19
+ # Option to limit the number of stocks to scan
20
+ limit_stocks = st.sidebar.slider("Number of Stocks to Scan", min_value=5, max_value=len(nifty_500_stocks), value=50, step=5)
21
+
22
+ # Initialize an empty DataFrame to store the filtered stocks
23
+ filtered_data = pd.DataFrame(columns=["Stock", "Latest Price", "Entry Signal", "Exit Signal"])
24
+
25
+ # Loop through the selected stocks to scan
26
+ st.write(f"Scanning the top {limit_stocks} stocks in NIFTY 500 based on Turtle Strategy parameters...")
27
+ for symbol in nifty_500_stocks[:limit_stocks]:
28
+ try:
29
+ # Fetch historical data for the stock
30
+ data = yf.download(symbol, start='2022-01-01', end='2023-01-01', progress=False)
31
+
32
+ # Calculate Turtle Strategy parameters
33
+ data['20D_High'] = data['High'].rolling(window=entry_days).max()
34
+ data['10D_Low'] = data['Low'].rolling(window=exit_days).min()
35
+
36
+ # Entry and Exit Signals
37
+ data['Long'] = np.where(data['Close'] > data['20D_High'].shift(1), 1, 0)
38
+ data['Exit'] = np.where(data['Close'] < data['10D_Low'].shift(1), 1, 0) # Exit Signal as 1 if true
39
+
40
+ # Position Management
41
+ data['Position'] = 0
42
+ data.loc[data['Long'] == 1, 'Position'] = 1
43
+ data.loc[data['Exit'] == 1, 'Position'] = 0
44
+ data['Position'] = data['Position'].ffill().shift(1).fillna(0)
45
+
46
+ # Check for the latest entry or exit signal
47
+ latest_entry = data['Long'].iloc[-1] # Last Long signal (Entry)
48
+ latest_exit = data['Exit'].iloc[-1] # Last Exit signal
49
+
50
+ # Add to filtered data if an entry or exit signal is active
51
+ if latest_entry == 1 or latest_exit == 1:
52
+ latest_price = data['Close'].iloc[-1]
53
+ filtered_data = pd.concat([filtered_data, pd.DataFrame([[symbol, latest_price, latest_entry, latest_exit]], columns=filtered_data.columns)], ignore_index=True)
54
+
55
+ except Exception as e:
56
+ st.write(f"Error processing {symbol}: {e}")
57
+
58
+ # Display the filtered stocks that meet the criteria
59
+ if not filtered_data.empty:
60
+ st.subheader("Filtered Stocks with Entry or Exit Signals:")
61
+ # Display as a table
62
+ st.dataframe(filtered_data)
63
+ else:
64
+ st.write("No stocks meeting the criteria for entry or exit signals.")
65
+
66
+ # Optional: Show performance for a single stock
67
+ selected_stock = st.selectbox("Select a Stock to View Detailed Performance", nifty_500_stocks)
68
+ if selected_stock:
69
+ st.write(f"### Detailed Analysis for {selected_stock}")
70
+
71
+ # Fetch detailed data for the selected stock
72
+ detailed_data = yf.download(selected_stock, start='2022-01-01', end='2023-01-01')
73
+
74
+ # Turtle Strategy Calculations
75
+ detailed_data['20D_High'] = detailed_data['High'].rolling(window=entry_days).max()
76
+ detailed_data['10D_Low'] = detailed_data['Low'].rolling(window=exit_days).min()
77
+ detailed_data['Long'] = np.where(detailed_data['Close'] > detailed_data['20D_High'].shift(1), 1, 0)
78
+ detailed_data['Exit'] = np.where(detailed_data['Close'] < detailed_data['10D_Low'].shift(1), 1, 0)
79
+ detailed_data['Position'] = 0
80
+ detailed_data.loc[detailed_data['Long'] == 1, 'Position'] = 1
81
+ detailed_data.loc[detailed_data['Exit'] == 1, 'Position'] = 0
82
+ detailed_data['Position'] = detailed_data['Position'].ffill().shift(1).fillna(0)
83
+
84
+ # Strategy Returns Calculation
85
+ detailed_data['Strategy Returns'] = detailed_data['Position'] * detailed_data['Close'].pct_change()
86
+ detailed_data['Cumulative Returns'] = (1 + detailed_data['Strategy Returns']).cumprod()
87
+
88
+ # Show Raw Data
89
+ st.subheader("Strategy Data Preview")
90
+ st.write(detailed_data.tail(20))