QuantumLearner commited on
Commit
ff970a2
·
verified ·
1 Parent(s): c9cb969

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +256 -0
app.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import yfinance as yf
3
+ import pandas as pd
4
+ import numpy as np
5
+ import plotly.graph_objs as go
6
+ from itertools import product
7
+ from datetime import datetime, timedelta
8
+ from plotly.subplots import make_subplots
9
+
10
+ # Set Streamlit page configuration
11
+ st.set_page_config(page_title="3-Way Moving Average Crossover Strategy", layout="wide")
12
+
13
+ # Title and description
14
+ st.title("3-Way Moving Average Crossover Strategy")
15
+ st.write("""
16
+ This tool allows users to backtest a 3-way moving average crossover strategy across different time horizons (short-term, medium-term, and long-term).
17
+ The strategy uses three different moving averages to generate buy/sell signals when shorter-term averages cross above or below longer-term averages.
18
+ By adjusting parameters like the length of each moving average and the signal threshold, you can further customize how strict or lenient the crossover signals are.
19
+ """)
20
+
21
+ # Sidebar: How to use the app
22
+ with st.sidebar.expander("How to Use", expanded=False):
23
+ st.write("""
24
+ 1. **Select Ticker**: Choose the asset ticker symbol (e.g., AAPL, TSLA, BTC-USD) and date range for historical data.
25
+ 2. **Run Strategy**: Click "Run Strategy" to perform optimization and backtesting of the strategy using the default parameters for the selected horizon.
26
+ 3. **Adjust Parameters**: After running the strategy, use the sliders to adjust the moving average windows and threshold, and see the results update live.
27
+ 4. **Threshold Parameter**: Controls how strict the buy/sell signals are when moving averages cross. Lower thresholds generate more signals; higher thresholds generate fewer, stricter signals.
28
+ """)
29
+
30
+ # Sidebar: Navigation
31
+ st.sidebar.markdown("### Page Navigation")
32
+ page = st.sidebar.radio("Select Strategy Horizon", options=["Short-Term", "Medium-Term", "Long-Term"])
33
+
34
+ # Sidebar: Select Ticker and Date Range
35
+ with st.sidebar.expander("Select Ticker and Date Range", expanded=True):
36
+ ticker = st.text_input("Asset Symbol", value="AAPL", help="Ticker symbol (Indicate the stock ticker or Cryptocurrency Pair (e.g., AAPL, BTC-USD))")
37
+ start_date = st.date_input("Start Date", value=datetime(2015, 1, 1), help="Select the start date for historical data.")
38
+ end_date = st.date_input("End Date", value=datetime.today() + timedelta(days=1), help="Select the end date for historical data.")
39
+
40
+ # Function to download data
41
+ @st.cache_data
42
+ def download_data(ticker, start, end):
43
+ data = yf.download(ticker, start=start, end=end)
44
+ return data
45
+
46
+ # Function to calculate moving averages
47
+ def calculate_moving_averages(data, short_window, medium_window, long_window):
48
+ data['short_ma'] = data['Adj Close'].rolling(window=short_window).mean()
49
+ data['medium_ma'] = data['Adj Close'].rolling(window=medium_window).mean()
50
+ data['long_ma'] = data['Adj Close'].rolling(window=long_window).mean()
51
+ return data
52
+
53
+ # Function to generate trading signals with a percentage-based threshold
54
+ def generate_signals(data, threshold=0.01):
55
+ data['signal'] = 0
56
+ data['signal'][(data['short_ma'] > data['medium_ma'] * (1 + threshold)) &
57
+ (data['medium_ma'] > data['long_ma'] * (1 + threshold))] = 1
58
+ data['signal'][(data['short_ma'] < data['medium_ma'] * (1 - threshold)) &
59
+ (data['medium_ma'] < data['long_ma'] * (1 - threshold))] = -1
60
+ data['positions'] = data['signal'].diff()
61
+ return data
62
+
63
+ # Function to calculate equity curve
64
+ def calculate_equity_curve(data):
65
+ data['returns'] = data['Adj Close'].pct_change()
66
+ data['strategy_returns'] = data['returns'] * data['signal'].shift(1)
67
+ data['equity_curve'] = (1 + data['strategy_returns']).cumprod()
68
+ return data
69
+
70
+ # Function to optimize parameters for different trading terms
71
+ def optimize_parameters(data, short_window_range, medium_window_range, long_window_range):
72
+ best_params = None
73
+ best_equity = 0
74
+
75
+ for short, medium, long in product(short_window_range, medium_window_range, long_window_range):
76
+ if short < medium < long:
77
+ df = calculate_moving_averages(data.copy(), short, medium, long)
78
+ df = generate_signals(df)
79
+ df = calculate_equity_curve(df)
80
+ final_equity = df['equity_curve'].iloc[-1]
81
+ if final_equity > best_equity:
82
+ best_equity = final_equity
83
+ best_params = (short, medium, long)
84
+
85
+ return best_params, best_equity
86
+
87
+ # Function to execute and plot the strategy
88
+ def execute_strategy(data, short_window, medium_window, long_window, threshold, title_suffix):
89
+ data = calculate_moving_averages(data, short_window, medium_window, long_window)
90
+ data = generate_signals(data, threshold)
91
+ data = calculate_equity_curve(data)
92
+ return data
93
+
94
+ # Function to plot results
95
+ # Function to plot results with subplots for better alignment
96
+ def plot_results(data, params, title_suffix):
97
+ # Create subplots: 2 rows (Price + MA, and Equity Curve), shared x-axis for alignment
98
+ fig = make_subplots(
99
+ rows=2, cols=1, shared_xaxes=True,
100
+ vertical_spacing=0.1, # Increased vertical spacing between plots
101
+ subplot_titles=(f'{title_suffix} Price and Moving Averages', 'Equity Curve')
102
+ )
103
+
104
+ # Price and Moving Averages plot
105
+ fig.add_trace(go.Scatter(x=data.index, y=data['Adj Close'], mode='lines', name='Price', line=dict(color='black')), row=1, col=1)
106
+ fig.add_trace(go.Scatter(x=data.index, y=data['short_ma'], mode='lines', name=f'Short MA ({params[0]})', line=dict(color='blue')), row=1, col=1)
107
+ fig.add_trace(go.Scatter(x=data.index, y=data['medium_ma'], mode='lines', name=f'Medium MA ({params[1]})', line=dict(color='orange')), row=1, col=1)
108
+ fig.add_trace(go.Scatter(x=data.index, y=data['long_ma'], mode='lines', name=f'Long MA ({params[2]})', line=dict(color='green')), row=1, col=1)
109
+
110
+ # Buy/Sell Signals with markers
111
+ buy_signals = data[data['positions'] == 1]
112
+ sell_signals = data[data['positions'] == -1]
113
+ fig.add_trace(go.Scatter(x=buy_signals.index, y=buy_signals['short_ma'], mode='markers', name='Buy Signal',
114
+ marker=dict(color='green', symbol='triangle-up', size=10)), row=1, col=1)
115
+ fig.add_trace(go.Scatter(x=sell_signals.index, y=sell_signals['short_ma'], mode='markers', name='Sell Signal',
116
+ marker=dict(color='red', symbol='triangle-down', size=10)), row=1, col=1)
117
+
118
+ # Equity Curve plot
119
+ fig.add_trace(go.Scatter(x=data.index, y=data['equity_curve'], mode='lines', name='Equity Curve', line=dict(color='blue')), row=2, col=1)
120
+
121
+ # Update layout for better clarity and spacing
122
+ fig.update_layout(
123
+ height=800, # Increased height for better visualization
124
+ title_text=f'{title_suffix} 3-Way Moving Average Crossover',
125
+ xaxis_title='Date',
126
+ yaxis_title='Price',
127
+ legend=dict(orientation="h", yanchor="bottom", y=1.05, xanchor="center", x=0.5),
128
+ margin=dict(t=30, b=30), # Adjust top and bottom margins for spacing
129
+ font=dict(size=12),
130
+ showlegend=True
131
+ )
132
+
133
+ # Display the chart in Streamlit
134
+ st.plotly_chart(fig, use_container_width=True)
135
+
136
+ # Load and cache data
137
+ data = download_data(ticker, start_date, end_date)
138
+
139
+ # Short, Medium, Long-Term settings
140
+ horizons = {
141
+ "Short-Term": {"short_range": range(2, 10, 1), "medium_range": range(10, 20, 1), "long_range": range(20, 50, 2)},
142
+ "Medium-Term": {"short_range": range(10, 30, 2), "medium_range": range(30, 60, 3), "long_range": range(60, 100, 5)},
143
+ "Long-Term": {"short_range": range(30, 60, 5), "medium_range": range(60, 120, 10), "long_range": range(120, 200, 10)}
144
+ }
145
+
146
+ # Cache the results for each horizon so they persist when switching between pages
147
+ if "results_cache" not in st.session_state:
148
+ st.session_state["results_cache"] = {}
149
+
150
+ # Initialize or update the MA parameters and threshold based on the selected page
151
+ if page in st.session_state["results_cache"]:
152
+ params = st.session_state["results_cache"][page]["params"]
153
+ threshold_value = st.session_state["results_cache"][page]["threshold"]
154
+ else:
155
+ params = None
156
+ threshold_value = 0.01 # Default value for threshold
157
+
158
+ # Run Strategy Button
159
+ run_strategy = st.sidebar.button(f"Run Strategy for {page}")
160
+ run_with_adjusted_params = False
161
+
162
+ # If Run Strategy is clicked, run optimization and reset parameters
163
+ if run_strategy:
164
+ horizon_settings = horizons.get(page)
165
+
166
+ # Re-run optimization and reset to best parameters
167
+ best_params, best_equity = optimize_parameters(
168
+ data,
169
+ short_window_range=horizon_settings["short_range"],
170
+ medium_window_range=horizon_settings["medium_range"],
171
+ long_window_range=horizon_settings["long_range"]
172
+ )
173
+
174
+ # Cache the best parameters and reset adjusted parameters to best params
175
+ st.session_state["results_cache"][page] = {
176
+ "best_params": best_params,
177
+ "best_equity": best_equity,
178
+ "threshold": threshold_value, # Store the default threshold initially
179
+ "params": best_params, # Reset to best params after optimization
180
+ }
181
+
182
+ # Reset sliders to best parameters after optimization
183
+ params = best_params
184
+ run_with_adjusted_params = True
185
+
186
+ # If user-adjusted parameters (after the initial run)
187
+ if params:
188
+ horizon_settings = horizons.get(page)
189
+
190
+ short_window = st.sidebar.slider(
191
+ f"Short MA Window ({page})",
192
+ min_value=horizon_settings["short_range"].start,
193
+ max_value=horizon_settings["short_range"].stop - 1,
194
+ value=params[0],
195
+ help="Defines the window for the shortest moving average. Increasing this value smooths the moving average and reduces its sensitivity to price changes."
196
+ )
197
+
198
+ medium_window = st.sidebar.slider(
199
+ f"Medium MA Window ({page})",
200
+ min_value=horizon_settings["medium_range"].start,
201
+ max_value=horizon_settings["medium_range"].stop - 1,
202
+ value=params[1],
203
+ help="Defines the window for the medium moving average. A larger window increases smoothing and lags price changes more than the short MA."
204
+ )
205
+
206
+ long_window = st.sidebar.slider(
207
+ f"Long MA Window ({page})",
208
+ min_value=horizon_settings["long_range"].start,
209
+ max_value=horizon_settings["long_range"].stop - 1,
210
+ value=params[2],
211
+ help="Defines the window for the long moving average. A larger window results in a much slower-moving average that tracks long-term trends."
212
+ )
213
+
214
+ threshold = st.sidebar.slider(
215
+ f"Threshold ({page})",
216
+ 0.0, 0.05, threshold_value, 0.01,
217
+ help="Adjusts the strictness of the crossover signals. A higher threshold generates fewer, stricter signals."
218
+ )
219
+
220
+ # If any adjustments are made to the parameters, mark the run as "adjusted"
221
+ run_with_adjusted_params = True
222
+
223
+ # Execute the strategy using user-adjusted parameters
224
+ result_data = execute_strategy(data.copy(), short_window, medium_window, long_window, threshold, page)
225
+
226
+ # Cache updated parameters and threshold without overwriting the best params
227
+ st.session_state["results_cache"][page]["params"] = (short_window, medium_window, long_window)
228
+ st.session_state["results_cache"][page]["threshold"] = threshold
229
+ st.session_state["results_cache"][page]["data"] = result_data
230
+
231
+ # If results are cached, display them
232
+ if page in st.session_state["results_cache"]:
233
+ cached_result = st.session_state["results_cache"][page]
234
+
235
+ # Display best parameters in JSON (always show the optimized "best" params, not the adjusted ones)
236
+ st.json({
237
+ "Best Parameters": {
238
+ "Short MA": cached_result["best_params"][0],
239
+ "Medium MA": cached_result["best_params"][1],
240
+ "Long MA": cached_result["best_params"][2],
241
+ "Threshold": cached_result["threshold"],
242
+ "Final Equity": cached_result["best_equity"]
243
+ }
244
+ })
245
+
246
+ # Plot results with either optimized or adjusted parameters
247
+ if "data" in cached_result:
248
+ plot_results(cached_result["data"], cached_result["params"], page)
249
+
250
+ hide_streamlit_style = """
251
+ <style>
252
+ #MainMenu {visibility: hidden;}
253
+ footer {visibility: hidden;}
254
+ </style>
255
+ """
256
+ st.markdown(hide_streamlit_style, unsafe_allow_html=True)