Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,55 +3,33 @@ import yfinance as yf
|
|
| 3 |
import pandas as pd
|
| 4 |
import plotly.graph_objects as go
|
| 5 |
|
| 6 |
-
# Function to fetch data from Yahoo Finance
|
| 7 |
def fetch_data(ticker, start_date, end_date):
|
| 8 |
data = yf.download(ticker, start=start_date, end=end_date)
|
| 9 |
return data
|
| 10 |
|
| 11 |
-
# Calculate indicators based on user-defined window sizes
|
| 12 |
def calculate_indicators(data, window_short, window_long):
|
| 13 |
data['High Short'] = data['High'].rolling(window=window_short).max()
|
| 14 |
data['Low Short'] = data['Low'].rolling(window=window_short).min()
|
| 15 |
-
data['High Long'] = data['High'].rolling(window=window_long).max()
|
| 16 |
-
data['Low Long'] = data['Low'].rolling(window=window_long).min()
|
| 17 |
return data
|
| 18 |
|
| 19 |
-
# Identify buy and sell signals based on breakout strategy
|
| 20 |
def identify_signals(data):
|
| 21 |
data['Buy Signal'] = (data['Close'] > data['High Short'].shift(1))
|
| 22 |
data['Sell Signal'] = (data['Close'] < data['Low Short'].shift(1))
|
| 23 |
return data
|
| 24 |
|
| 25 |
-
# Collect and display signals
|
| 26 |
def collect_signals(data):
|
| 27 |
signals = pd.DataFrame()
|
| 28 |
-
signals['Date'] = data
|
| 29 |
-
signals['Price'] = data[
|
| 30 |
-
signals['Signal'] =
|
|
|
|
| 31 |
signals.loc[data['Sell Signal'], 'Signal'] = 'Sell'
|
|
|
|
| 32 |
return signals
|
| 33 |
|
| 34 |
-
# Calculate returns and metrics for backtesting
|
| 35 |
-
def backtest_signals(data):
|
| 36 |
-
data['Position'] = 0
|
| 37 |
-
data['Position'] = data['Buy Signal'].replace(True, 1).cumsum()
|
| 38 |
-
data['Position'] = data['Position'] - data['Sell Signal'].replace(True, 1).cumsum()
|
| 39 |
-
data['Position'] = data['Position'].clip(lower=0, upper=1)
|
| 40 |
-
|
| 41 |
-
data['Market Returns'] = data['Close'].pct_change()
|
| 42 |
-
data['Strategy Returns'] = data['Market Returns'] * data['Position'].shift(1)
|
| 43 |
-
|
| 44 |
-
data['Cumulative Market Returns'] = (1 + data['Market Returns']).cumprod() - 1
|
| 45 |
-
data['Cumulative Strategy Returns'] = (1 + data['Strategy Returns']).cumprod() - 1
|
| 46 |
-
|
| 47 |
-
return data, data['Cumulative Market Returns'].iloc[-1], data['Cumulative Strategy Returns'].iloc[-1]
|
| 48 |
-
|
| 49 |
-
# Plotting function using Plotly for interactive charts
|
| 50 |
def plot_data(data):
|
| 51 |
fig = go.Figure()
|
| 52 |
fig.add_trace(go.Scatter(x=data.index, y=data['Close'], name='Close Price', line=dict(color='blue')))
|
| 53 |
-
fig.add_trace(go.Scatter(x=data.index, y=data['High Short'], name='High Short', line=dict(dash='dot')))
|
| 54 |
-
fig.add_trace(go.Scatter(x=data.index, y=data['Low Short'], name='Low Short', line=dict(dash='dot')))
|
| 55 |
buys = data[data['Buy Signal']]
|
| 56 |
sells = data[data['Sell Signal']]
|
| 57 |
fig.add_trace(go.Scatter(x=buys.index, y=buys['Close'], mode='markers', name='Buy Signal', marker_symbol='triangle-up', marker_color='green', marker_size=10))
|
|
@@ -59,32 +37,24 @@ def plot_data(data):
|
|
| 59 |
fig.update_layout(title='Stock Price and Trading Signals', xaxis_title='Date', yaxis_title='Price', template='plotly_dark')
|
| 60 |
return fig
|
| 61 |
|
| 62 |
-
# Main application function
|
| 63 |
def main():
|
| 64 |
st.title("Enhanced Turtle Trading Strategy with Backtesting and Signal Table")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
-
|
| 67 |
-
with st.sidebar:
|
| 68 |
-
ticker = st.text_input("Enter the ticker symbol, e.g., 'AAPL'")
|
| 69 |
-
start_date = st.date_input("Select the start date")
|
| 70 |
-
end_date = st.date_input("Select the end date")
|
| 71 |
-
window_short = st.number_input("Short term window", min_value=5, max_value=60, value=20)
|
| 72 |
-
window_long = st.number_input("Long term window", min_value=5, max_value=120, value=55)
|
| 73 |
-
|
| 74 |
-
if st.button("Analyze"):
|
| 75 |
data = fetch_data(ticker, start_date, end_date)
|
| 76 |
if not data.empty:
|
| 77 |
data = calculate_indicators(data, window_short, window_long)
|
| 78 |
data = identify_signals(data)
|
| 79 |
signals = collect_signals(data)
|
| 80 |
-
data, market_return, strategy_return = backtest_signals(data)
|
| 81 |
fig = plot_data(data)
|
| 82 |
st.plotly_chart(fig, use_container_width=True)
|
| 83 |
-
st.
|
| 84 |
-
st.dataframe(signals)
|
| 85 |
-
st.subheader("Backtesting Results")
|
| 86 |
-
st.write(f"Market Return: {market_return * 100:.2f}%")
|
| 87 |
-
st.write(f"Strategy Return: {strategy_return * 100:.2f}%")
|
| 88 |
else:
|
| 89 |
st.error("No data found for the selected ticker and date range.")
|
| 90 |
|
|
|
|
| 3 |
import pandas as pd
|
| 4 |
import plotly.graph_objects as go
|
| 5 |
|
|
|
|
| 6 |
def fetch_data(ticker, start_date, end_date):
|
| 7 |
data = yf.download(ticker, start=start_date, end=end_date)
|
| 8 |
return data
|
| 9 |
|
|
|
|
| 10 |
def calculate_indicators(data, window_short, window_long):
|
| 11 |
data['High Short'] = data['High'].rolling(window=window_short).max()
|
| 12 |
data['Low Short'] = data['Low'].rolling(window=window_short).min()
|
|
|
|
|
|
|
| 13 |
return data
|
| 14 |
|
|
|
|
| 15 |
def identify_signals(data):
|
| 16 |
data['Buy Signal'] = (data['Close'] > data['High Short'].shift(1))
|
| 17 |
data['Sell Signal'] = (data['Close'] < data['Low Short'].shift(1))
|
| 18 |
return data
|
| 19 |
|
|
|
|
| 20 |
def collect_signals(data):
|
| 21 |
signals = pd.DataFrame()
|
| 22 |
+
signals['Date'] = data.index
|
| 23 |
+
signals['Price'] = data['Close']
|
| 24 |
+
signals['Signal'] = None # Initialize the column with None
|
| 25 |
+
signals.loc[data['Buy Signal'], 'Signal'] = 'Buy'
|
| 26 |
signals.loc[data['Sell Signal'], 'Signal'] = 'Sell'
|
| 27 |
+
signals = signals.dropna(subset=['Signal'])
|
| 28 |
return signals
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
def plot_data(data):
|
| 31 |
fig = go.Figure()
|
| 32 |
fig.add_trace(go.Scatter(x=data.index, y=data['Close'], name='Close Price', line=dict(color='blue')))
|
|
|
|
|
|
|
| 33 |
buys = data[data['Buy Signal']]
|
| 34 |
sells = data[data['Sell Signal']]
|
| 35 |
fig.add_trace(go.Scatter(x=buys.index, y=buys['Close'], mode='markers', name='Buy Signal', marker_symbol='triangle-up', marker_color='green', marker_size=10))
|
|
|
|
| 37 |
fig.update_layout(title='Stock Price and Trading Signals', xaxis_title='Date', yaxis_title='Price', template='plotly_dark')
|
| 38 |
return fig
|
| 39 |
|
|
|
|
| 40 |
def main():
|
| 41 |
st.title("Enhanced Turtle Trading Strategy with Backtesting and Signal Table")
|
| 42 |
+
ticker = st.sidebar.text_input("Enter the ticker symbol, e.g., 'AAPL'")
|
| 43 |
+
start_date = st.sidebar.date_input("Select the start date")
|
| 44 |
+
end_date = st.sidebar.date_input("Select the end date")
|
| 45 |
+
window_short = st.sidebar.number_input("Short term window", min_value=5, max_value=60, value=20)
|
| 46 |
+
window_long = st.sidebar.number_input("Long term window", min_value=5, max_value=120, value=55)
|
| 47 |
|
| 48 |
+
if st.sidebar.button("Analyze"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
data = fetch_data(ticker, start_date, end_date)
|
| 50 |
if not data.empty:
|
| 51 |
data = calculate_indicators(data, window_short, window_long)
|
| 52 |
data = identify_signals(data)
|
| 53 |
signals = collect_signals(data)
|
|
|
|
| 54 |
fig = plot_data(data)
|
| 55 |
st.plotly_chart(fig, use_container_width=True)
|
| 56 |
+
st.write("Trading Signals:")
|
| 57 |
+
st.dataframe(signals.style.hide_index())
|
|
|
|
|
|
|
|
|
|
| 58 |
else:
|
| 59 |
st.error("No data found for the selected ticker and date range.")
|
| 60 |
|