Spaces:
Runtime error
Runtime error
File size: 1,916 Bytes
7022ed6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | import streamlit as st
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Streamlit Title
st.title("Turtle Strategy Implementation for NIFTY 500 Stocks")
# Stock Symbol Input
st.sidebar.header("Stock Selection & Parameters")
symbol = st.sidebar.text_input("Enter Stock Ticker (e.g., RELIANCE.NS):", value='RELIANCE.NS')
# Parameters for the Turtle Strategy
entry_days = st.sidebar.slider("Entry Lookback Period (days)", min_value=10, max_value=60, value=20, step=1)
exit_days = st.sidebar.slider("Exit Lookback Period (days)", min_value=5, max_value=30, value=10, step=1)
# Fetch Stock Data
data = yf.download(symbol, start='2022-01-01', end='2023-01-01')
st.write(f"### Historical Data for {symbol}")
st.dataframe(data.tail(10))
# Turtle Strategy Calculations
data['20D_High'] = data['High'].rolling(window=entry_days).max()
data['10D_Low'] = data['Low'].rolling(window=exit_days).min()
# Entry and Exit Signals
data['Long'] = np.where(data['Close'] > data['20D_High'].shift(1), 1, 0)
data['Exit'] = np.where(data['Close'] < data['10D_Low'].shift(1), -1, 0)
# Position Management
data['Position'] = 0
data.loc[data['Long'] == 1, 'Position'] = 1
data.loc[data['Exit'] == -1, 'Position'] = 0
data['Position'] = data['Position'].ffill().shift(1).fillna(0)
# Strategy Returns Calculation
data['Strategy Returns'] = data['Position'] * data['Close'].pct_change()
data['Cumulative Returns'] = (1 + data['Strategy Returns']).cumprod()
# Plotting Strategy Performance
st.subheader("Turtle Strategy vs Buy and Hold Returns")
plt.figure(figsize=(14, 7))
plt.plot(data['Cumulative Returns'], label='Turtle Strategy Returns')
plt.plot((1 + data['Close'].pct_change()).cumprod(), label='Buy and Hold Returns')
plt.title(f'Turtle Strategy vs Buy and Hold for {symbol}')
plt.legend()
st.pyplot(plt)
# Show Raw Data
st.subheader("Strategy Data Preview")
st.write(data.tail(20))
|