Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,9 +2,11 @@ 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
|
| 8 |
|
| 9 |
# Load the NIFTY 500 stock list
|
| 10 |
stock_list = pd.read_csv('ind_nifty500list.csv')
|
|
@@ -12,22 +14,32 @@ 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
|
| 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=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
# Calculate Turtle Strategy parameters
|
| 33 |
data['20D_High'] = data['High'].rolling(window=entry_days).max()
|
|
@@ -37,31 +49,36 @@ for symbol in nifty_500_stocks[:limit_stocks]:
|
|
| 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]
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
#
|
| 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
|
| 65 |
|
| 66 |
# Optional: Show performance for a single stock
|
| 67 |
selected_stock = st.selectbox("Select a Stock to View Detailed Performance", nifty_500_stocks)
|
|
@@ -69,7 +86,7 @@ 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=
|
| 73 |
|
| 74 |
# Turtle Strategy Calculations
|
| 75 |
detailed_data['20D_High'] = detailed_data['High'].rolling(window=entry_days).max()
|
|
@@ -81,9 +98,8 @@ if selected_stock:
|
|
| 81 |
detailed_data.loc[detailed_data['Exit'] == 1, 'Position'] = 0
|
| 82 |
detailed_data['Position'] = detailed_data['Position'].ffill().shift(1).fillna(0)
|
| 83 |
|
| 84 |
-
#
|
| 85 |
-
detailed_data['
|
| 86 |
-
detailed_data['Cumulative Returns'] = (1 + detailed_data['Strategy Returns']).cumprod()
|
| 87 |
|
| 88 |
# Show Raw Data
|
| 89 |
st.subheader("Strategy Data Preview")
|
|
|
|
| 2 |
import yfinance as yf
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
| 5 |
+
import talib
|
| 6 |
+
from datetime import datetime
|
| 7 |
|
| 8 |
# Streamlit Title
|
| 9 |
+
st.title("NIFTY 500 Turtle Strategy Scanner with Entry, Exit, RSI, and Volume")
|
| 10 |
|
| 11 |
# Load the NIFTY 500 stock list
|
| 12 |
stock_list = pd.read_csv('ind_nifty500list.csv')
|
|
|
|
| 14 |
nifty_500_stocks = stock_list['Symbol'].tolist()
|
| 15 |
|
| 16 |
# Sidebar for Parameters
|
| 17 |
+
st.sidebar.header("Turtle Strategy and RSI Parameters")
|
| 18 |
entry_days = st.sidebar.slider("Entry Lookback Period (days)", min_value=10, max_value=60, value=20, step=1)
|
| 19 |
exit_days = st.sidebar.slider("Exit Lookback Period (days)", min_value=5, max_value=30, value=10, step=1)
|
| 20 |
+
rsi_threshold = st.sidebar.slider("RSI Threshold", min_value=10, max_value=90, value=30, step=5)
|
| 21 |
+
volume_threshold = st.sidebar.number_input("Volume Threshold", min_value=100000, value=500000)
|
| 22 |
|
| 23 |
# Option to limit the number of stocks to scan
|
| 24 |
limit_stocks = st.sidebar.slider("Number of Stocks to Scan", min_value=5, max_value=len(nifty_500_stocks), value=50, step=5)
|
| 25 |
|
| 26 |
# Initialize an empty DataFrame to store the filtered stocks
|
| 27 |
+
filtered_data = pd.DataFrame(columns=["Stock", "Latest Price", "RSI", "Volume", "Entry Signal", "Exit Signal"])
|
| 28 |
+
|
| 29 |
+
# Get today's date for the end date
|
| 30 |
+
end_date = datetime.today().strftime('%Y-%m-%d')
|
| 31 |
|
| 32 |
# Loop through the selected stocks to scan
|
| 33 |
+
st.write(f"Scanning the top {limit_stocks} stocks in NIFTY 500 based on Turtle Strategy, RSI, and Volume...")
|
| 34 |
for symbol in nifty_500_stocks[:limit_stocks]:
|
| 35 |
try:
|
| 36 |
+
# Fetch historical data for the stock up to today's date
|
| 37 |
+
data = yf.download(symbol, start='2022-01-01', end=end_date, progress=False)
|
| 38 |
+
|
| 39 |
+
# Check if the data is sufficient for analysis
|
| 40 |
+
if len(data) < entry_days:
|
| 41 |
+
st.write(f"Skipping {symbol}: Not enough data available.")
|
| 42 |
+
continue
|
| 43 |
|
| 44 |
# Calculate Turtle Strategy parameters
|
| 45 |
data['20D_High'] = data['High'].rolling(window=entry_days).max()
|
|
|
|
| 49 |
data['Long'] = np.where(data['Close'] > data['20D_High'].shift(1), 1, 0)
|
| 50 |
data['Exit'] = np.where(data['Close'] < data['10D_Low'].shift(1), 1, 0) # Exit Signal as 1 if true
|
| 51 |
|
| 52 |
+
# Calculate RSI using TA-Lib
|
| 53 |
+
data['RSI'] = talib.RSI(data['Close'], timeperiod=14)
|
| 54 |
+
|
| 55 |
# Position Management
|
| 56 |
data['Position'] = 0
|
| 57 |
data.loc[data['Long'] == 1, 'Position'] = 1
|
| 58 |
data.loc[data['Exit'] == 1, 'Position'] = 0
|
| 59 |
data['Position'] = data['Position'].ffill().shift(1).fillna(0)
|
| 60 |
|
| 61 |
+
# Check for the latest entry or exit signal, RSI, and Volume
|
| 62 |
latest_entry = data['Long'].iloc[-1] # Last Long signal (Entry)
|
| 63 |
+
latest_exit = data['Exit'].iloc[-1] # Last Exit signal
|
| 64 |
+
latest_rsi = data['RSI'].iloc[-1] # Last RSI value
|
| 65 |
+
latest_volume = data['Volume'].iloc[-1] # Last Volume
|
| 66 |
|
| 67 |
+
# Filter based on RSI and Volume thresholds
|
| 68 |
+
if (latest_entry == 1 or latest_exit == 1) and (latest_rsi <= rsi_threshold or latest_rsi >= 70) and latest_volume > volume_threshold:
|
| 69 |
latest_price = data['Close'].iloc[-1]
|
| 70 |
+
filtered_data = pd.concat([filtered_data, pd.DataFrame([[symbol, latest_price, latest_rsi, latest_volume, latest_entry, latest_exit]], columns=filtered_data.columns)], ignore_index=True)
|
| 71 |
|
| 72 |
except Exception as e:
|
| 73 |
st.write(f"Error processing {symbol}: {e}")
|
| 74 |
|
| 75 |
# Display the filtered stocks that meet the criteria
|
| 76 |
if not filtered_data.empty:
|
| 77 |
+
st.subheader("Filtered Stocks with Entry or Exit Signals, RSI, and Volume:")
|
| 78 |
# Display as a table
|
| 79 |
st.dataframe(filtered_data)
|
| 80 |
else:
|
| 81 |
+
st.write("No stocks meeting the criteria for entry/exit signals, RSI, or volume thresholds.")
|
| 82 |
|
| 83 |
# Optional: Show performance for a single stock
|
| 84 |
selected_stock = st.selectbox("Select a Stock to View Detailed Performance", nifty_500_stocks)
|
|
|
|
| 86 |
st.write(f"### Detailed Analysis for {selected_stock}")
|
| 87 |
|
| 88 |
# Fetch detailed data for the selected stock
|
| 89 |
+
detailed_data = yf.download(selected_stock, start='2022-01-01', end=end_date)
|
| 90 |
|
| 91 |
# Turtle Strategy Calculations
|
| 92 |
detailed_data['20D_High'] = detailed_data['High'].rolling(window=entry_days).max()
|
|
|
|
| 98 |
detailed_data.loc[detailed_data['Exit'] == 1, 'Position'] = 0
|
| 99 |
detailed_data['Position'] = detailed_data['Position'].ffill().shift(1).fillna(0)
|
| 100 |
|
| 101 |
+
# Calculate RSI
|
| 102 |
+
detailed_data['RSI'] = talib.RSI(detailed_data['Close'], timeperiod=14)
|
|
|
|
| 103 |
|
| 104 |
# Show Raw Data
|
| 105 |
st.subheader("Strategy Data Preview")
|