Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,73 +1,96 @@
|
|
| 1 |
import streamlit as st
|
|
|
|
| 2 |
import pandas as pd
|
| 3 |
import numpy as np
|
| 4 |
import matplotlib.pyplot as plt
|
| 5 |
-
import yfinance as yf
|
| 6 |
-
|
| 7 |
-
# Streamlit App Title
|
| 8 |
-
st.title("Enhanced Turtle Strategy with Streamlit")
|
| 9 |
-
|
| 10 |
-
# File Uploader for CSV
|
| 11 |
-
uploaded_file = st.file_uploader("Upload a CSV file", type=["csv"])
|
| 12 |
-
|
| 13 |
-
if uploaded_file:
|
| 14 |
-
# Read the uploaded CSV file
|
| 15 |
-
data = pd.read_csv(uploaded_file)
|
| 16 |
-
|
| 17 |
-
# Display the raw data for reference
|
| 18 |
-
st.write("### Raw Data Preview:")
|
| 19 |
-
st.dataframe(data.head(10))
|
| 20 |
-
|
| 21 |
-
# Convert Date column to datetime format for analysis
|
| 22 |
-
data['Date'] = pd.to_datetime(data['Date'])
|
| 23 |
-
|
| 24 |
-
# Turtle Strategy Parameters
|
| 25 |
-
entry_days = st.sidebar.slider("Entry Lookback Period (days)", min_value=10, max_value=60, value=20, step=1)
|
| 26 |
-
exit_days = st.sidebar.slider("Exit Lookback Period (days)", min_value=5, max_value=30, value=10, step=1)
|
| 27 |
-
|
| 28 |
-
# Calculate the 20-day high and 10-day low based on user inputs
|
| 29 |
-
data['20D_High'] = data['High'].rolling(window=entry_days).max()
|
| 30 |
-
data['10D_Low'] = data['Low'].rolling(window=exit_days).min()
|
| 31 |
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
# Strategy Returns Calculation
|
| 47 |
-
|
| 48 |
-
|
| 49 |
|
| 50 |
-
#
|
| 51 |
-
data['Buy and Hold Returns'] = (1 + data['Close'].pct_change()).cumprod()
|
| 52 |
-
|
| 53 |
-
# Show calculated signals and strategy
|
| 54 |
-
st.write("### Strategy Calculation Preview:")
|
| 55 |
-
st.dataframe(data[['Date', 'Close', '20D_High', '10D_Low', 'Long', 'Exit', 'Position', 'Strategy Returns', 'Cumulative Returns']].tail(20))
|
| 56 |
-
|
| 57 |
-
# Plotting the Turtle Strategy vs Buy and Hold
|
| 58 |
st.subheader("Turtle Strategy vs Buy and Hold Returns")
|
| 59 |
plt.figure(figsize=(14, 7))
|
| 60 |
-
plt.plot(
|
| 61 |
-
plt.plot(
|
| 62 |
-
plt.title('Turtle Strategy
|
| 63 |
-
plt.xlabel('Date')
|
| 64 |
-
plt.ylabel('Cumulative Returns')
|
| 65 |
plt.legend()
|
| 66 |
st.pyplot(plt)
|
| 67 |
|
| 68 |
-
# Show
|
| 69 |
-
st.
|
| 70 |
-
st.write(
|
| 71 |
-
|
| 72 |
-
else:
|
| 73 |
-
st.write("Please upload a CSV file to analyze the Turtle Strategy.")
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
import yfinance as yf
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
| 5 |
import matplotlib.pyplot as plt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
+
# Streamlit Title
|
| 8 |
+
st.title("NIFTY 500 Turtle Strategy Scanner")
|
| 9 |
+
|
| 10 |
+
# Load the NIFTY 500 stock list
|
| 11 |
+
stock_list = pd.read_csv('ind_nifty500list.csv')
|
| 12 |
+
stock_list['Symbol'] = stock_list['Symbol'] + ".NS"
|
| 13 |
+
nifty_500_stocks = stock_list['Symbol'].tolist()
|
| 14 |
+
|
| 15 |
+
# Sidebar for Parameters
|
| 16 |
+
st.sidebar.header("Turtle Strategy Parameters")
|
| 17 |
+
entry_days = st.sidebar.slider("Entry Lookback Period (days)", min_value=10, max_value=60, value=20, step=1)
|
| 18 |
+
exit_days = st.sidebar.slider("Exit Lookback Period (days)", min_value=5, max_value=30, value=10, step=1)
|
| 19 |
+
|
| 20 |
+
# Option to limit the number of stocks to scan
|
| 21 |
+
limit_stocks = st.sidebar.slider("Number of Stocks to Scan", min_value=5, max_value=len(nifty_500_stocks), value=50, step=5)
|
| 22 |
+
|
| 23 |
+
# Initialize an empty list to store the stocks meeting the criteria
|
| 24 |
+
filtered_stocks = []
|
| 25 |
+
|
| 26 |
+
# Loop through the selected stocks to scan
|
| 27 |
+
st.write(f"Scanning the top {limit_stocks} stocks in NIFTY 500 based on Turtle Strategy parameters...")
|
| 28 |
+
for symbol in nifty_500_stocks[:limit_stocks]:
|
| 29 |
+
try:
|
| 30 |
+
# Fetch historical data for the stock
|
| 31 |
+
data = yf.download(symbol, start='2022-01-01', end='2023-01-01', progress=False)
|
| 32 |
+
|
| 33 |
+
# Calculate Turtle Strategy parameters
|
| 34 |
+
data['20D_High'] = data['High'].rolling(window=entry_days).max()
|
| 35 |
+
data['10D_Low'] = data['Low'].rolling(window=exit_days).min()
|
| 36 |
+
|
| 37 |
+
# Entry and Exit Signals
|
| 38 |
+
data['Long'] = np.where(data['Close'] > data['20D_High'].shift(1), 1, 0)
|
| 39 |
+
data['Exit'] = np.where(data['Close'] < data['10D_Low'].shift(1), -1, 0)
|
| 40 |
+
|
| 41 |
+
# Position Management
|
| 42 |
+
data['Position'] = 0
|
| 43 |
+
data.loc[data['Long'] == 1, 'Position'] = 1
|
| 44 |
+
data.loc[data['Exit'] == -1, 'Position'] = 0
|
| 45 |
+
data['Position'] = data['Position'].ffill().shift(1).fillna(0)
|
| 46 |
+
|
| 47 |
+
# If a stock has an active long position, add it to the filtered list
|
| 48 |
+
if data['Position'].iloc[-1] == 1:
|
| 49 |
+
filtered_stocks.append(symbol)
|
| 50 |
+
st.write(f"Stock: {symbol} - Current Position: Long")
|
| 51 |
+
|
| 52 |
+
except Exception as e:
|
| 53 |
+
st.write(f"Error processing {symbol}: {e}")
|
| 54 |
+
|
| 55 |
+
# Display the filtered stocks that meet the criteria
|
| 56 |
+
if filtered_stocks:
|
| 57 |
+
st.subheader("Stocks with Active Long Positions:")
|
| 58 |
+
for stock in filtered_stocks:
|
| 59 |
+
st.write(f"- {stock}")
|
| 60 |
+
else:
|
| 61 |
+
st.write("No stocks meeting the criteria for active long positions.")
|
| 62 |
+
|
| 63 |
+
# Optional: Show performance for a single stock
|
| 64 |
+
selected_stock = st.selectbox("Select a Stock to View Detailed Performance", nifty_500_stocks)
|
| 65 |
+
if selected_stock:
|
| 66 |
+
st.write(f"### Detailed Analysis for {selected_stock}")
|
| 67 |
+
|
| 68 |
+
# Fetch detailed data for the selected stock
|
| 69 |
+
detailed_data = yf.download(selected_stock, start='2022-01-01', end='2023-01-01')
|
| 70 |
+
|
| 71 |
+
# Turtle Strategy Calculations
|
| 72 |
+
detailed_data['20D_High'] = detailed_data['High'].rolling(window=entry_days).max()
|
| 73 |
+
detailed_data['10D_Low'] = detailed_data['Low'].rolling(window=exit_days).min()
|
| 74 |
+
detailed_data['Long'] = np.where(detailed_data['Close'] > detailed_data['20D_High'].shift(1), 1, 0)
|
| 75 |
+
detailed_data['Exit'] = np.where(detailed_data['Close'] < detailed_data['10D_Low'].shift(1), -1, 0)
|
| 76 |
+
detailed_data['Position'] = 0
|
| 77 |
+
detailed_data.loc[detailed_data['Long'] == 1, 'Position'] = 1
|
| 78 |
+
detailed_data.loc[detailed_data['Exit'] == -1, 'Position'] = 0
|
| 79 |
+
detailed_data['Position'] = detailed_data['Position'].ffill().shift(1).fillna(0)
|
| 80 |
|
| 81 |
# Strategy Returns Calculation
|
| 82 |
+
detailed_data['Strategy Returns'] = detailed_data['Position'] * detailed_data['Close'].pct_change()
|
| 83 |
+
detailed_data['Cumulative Returns'] = (1 + detailed_data['Strategy Returns']).cumprod()
|
| 84 |
|
| 85 |
+
# Plotting Strategy Performance
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
st.subheader("Turtle Strategy vs Buy and Hold Returns")
|
| 87 |
plt.figure(figsize=(14, 7))
|
| 88 |
+
plt.plot(detailed_data['Cumulative Returns'], label='Turtle Strategy Returns')
|
| 89 |
+
plt.plot((1 + detailed_data['Close'].pct_change()).cumprod(), label='Buy and Hold Returns')
|
| 90 |
+
plt.title(f'Turtle Strategy vs Buy and Hold for {selected_stock}')
|
|
|
|
|
|
|
| 91 |
plt.legend()
|
| 92 |
st.pyplot(plt)
|
| 93 |
|
| 94 |
+
# Show Raw Data
|
| 95 |
+
st.subheader("Strategy Data Preview")
|
| 96 |
+
st.write(detailed_data.tail(20))
|
|
|
|
|
|
|
|
|