Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -5,28 +5,27 @@ import matplotlib.pyplot as plt
|
|
5 |
import io
|
6 |
import gradio as gr
|
7 |
|
8 |
-
def sma_crossover_strategy():
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
|
|
|
|
|
|
14 |
df['SMA_50'] = df['Close'].rolling(window=50).mean()
|
15 |
df['SMA_150'] = df['Close'].rolling(window=150).mean()
|
16 |
|
17 |
-
|
18 |
-
df['
|
19 |
-
df.loc[df['SMA_50']
|
20 |
-
df
|
21 |
-
df['Position'] = df['Signal'].diff() # Capture the points where the signal changes
|
22 |
|
23 |
-
# Initialize investment simulation
|
24 |
-
initial_budget = 100
|
25 |
cash = initial_budget
|
26 |
shares = 0
|
27 |
portfolio_values = []
|
28 |
|
29 |
-
# Simulate the strategy
|
30 |
for index, row in df.iterrows():
|
31 |
if pd.isna(row['Close']):
|
32 |
continue
|
@@ -39,53 +38,60 @@ def sma_crossover_strategy():
|
|
39 |
portfolio_value = cash + (shares * row['Close'])
|
40 |
portfolio_values.append(portfolio_value)
|
41 |
|
42 |
-
#
|
43 |
-
df = df.iloc[149:] # Ignore the initial rows with NaN values due to SMA calculations
|
44 |
df['Portfolio Value'] = portfolio_values[149:]
|
45 |
|
46 |
-
# Create plot
|
47 |
plt.figure(figsize=(14, 8))
|
48 |
plt.plot(df['Portfolio Value'], label='Portfolio Value', color='purple')
|
49 |
plt.xlabel('Date')
|
50 |
plt.ylabel('Portfolio Value ($)')
|
51 |
-
plt.title('Portfolio Value Over Time with 50/150 SMA Crossover Strategy')
|
52 |
plt.legend()
|
53 |
plt.grid()
|
54 |
plt.tight_layout()
|
55 |
|
56 |
-
# Save plot to a buffer
|
57 |
plot_file = io.BytesIO()
|
58 |
plt.savefig(plot_file, format='png')
|
59 |
plot_file.seek(0)
|
60 |
plt.close()
|
61 |
|
62 |
-
# Final results
|
63 |
final_value = portfolio_values[-1]
|
64 |
-
|
|
|
|
|
|
|
|
|
|
|
65 |
Initial Investment: ${initial_budget}
|
66 |
Final Portfolio Value: ${final_value:.2f}
|
67 |
-
Total Profit/Loss: ${
|
68 |
-
Percentage Return: {
|
69 |
"""
|
70 |
|
71 |
-
return plot_file,
|
72 |
|
73 |
-
# Define Gradio
|
74 |
with gr.Blocks() as app:
|
75 |
-
gr.Markdown("# SMA Crossover Trading Strategy")
|
76 |
-
|
77 |
-
portfolio_plot = gr.Image()
|
78 |
-
summary_text = gr.Textbox(lines=5)
|
79 |
|
80 |
with gr.Row():
|
81 |
-
|
82 |
-
|
83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
84 |
sma_crossover_strategy,
|
85 |
-
inputs=[],
|
86 |
-
outputs=[
|
87 |
)
|
88 |
|
89 |
-
app.launch()
|
90 |
-
|
91 |
|
|
|
5 |
import io
|
6 |
import gradio as gr
|
7 |
|
8 |
+
def sma_crossover_strategy(initial_budget, start_date, end_date, ticker):
|
9 |
+
try:
|
10 |
+
df = yf.download(ticker, start=start_date, end=end_date, progress=False)
|
11 |
+
if df.empty:
|
12 |
+
return None, "No data available for the specified ticker and date range."
|
13 |
+
except Exception as e:
|
14 |
+
return None, f"Error fetching data: {str(e)}"
|
15 |
+
|
16 |
+
df = df[['Close']]
|
17 |
df['SMA_50'] = df['Close'].rolling(window=50).mean()
|
18 |
df['SMA_150'] = df['Close'].rolling(window=150).mean()
|
19 |
|
20 |
+
df['Signal'] = 0
|
21 |
+
df.loc[df['SMA_50'] > df['SMA_150'], 'Signal'] = 1
|
22 |
+
df.loc[df['SMA_50'] < df['SMA_150'], 'Signal'] = -1
|
23 |
+
df['Position'] = df['Signal'].diff()
|
|
|
24 |
|
|
|
|
|
25 |
cash = initial_budget
|
26 |
shares = 0
|
27 |
portfolio_values = []
|
28 |
|
|
|
29 |
for index, row in df.iterrows():
|
30 |
if pd.isna(row['Close']):
|
31 |
continue
|
|
|
38 |
portfolio_value = cash + (shares * row['Close'])
|
39 |
portfolio_values.append(portfolio_value)
|
40 |
|
41 |
+
df = df.iloc[149:] # Skip rows without SMA values
|
|
|
42 |
df['Portfolio Value'] = portfolio_values[149:]
|
43 |
|
|
|
44 |
plt.figure(figsize=(14, 8))
|
45 |
plt.plot(df['Portfolio Value'], label='Portfolio Value', color='purple')
|
46 |
plt.xlabel('Date')
|
47 |
plt.ylabel('Portfolio Value ($)')
|
48 |
+
plt.title(f'Portfolio Value Over Time with 50/150 SMA Crossover Strategy ({ticker})')
|
49 |
plt.legend()
|
50 |
plt.grid()
|
51 |
plt.tight_layout()
|
52 |
|
|
|
53 |
plot_file = io.BytesIO()
|
54 |
plt.savefig(plot_file, format='png')
|
55 |
plot_file.seek(0)
|
56 |
plt.close()
|
57 |
|
|
|
58 |
final_value = portfolio_values[-1]
|
59 |
+
profit_loss = final_value - initial_budget
|
60 |
+
percentage_return = (profit_loss / initial_budget) * 100
|
61 |
+
|
62 |
+
results = f"""
|
63 |
+
Ticker: {ticker}
|
64 |
+
Trading Period: {start_date} to {end_date}
|
65 |
Initial Investment: ${initial_budget}
|
66 |
Final Portfolio Value: ${final_value:.2f}
|
67 |
+
Total Profit/Loss: ${profit_loss:.2f}
|
68 |
+
Percentage Return: {percentage_return:.2f}%
|
69 |
"""
|
70 |
|
71 |
+
return plot_file, results
|
72 |
|
73 |
+
# Define Gradio App
|
74 |
with gr.Blocks() as app:
|
75 |
+
gr.Markdown("# SMA Crossover Trading Strategy Simulator")
|
|
|
|
|
|
|
76 |
|
77 |
with gr.Row():
|
78 |
+
initial_budget = gr.Number(label="Initial Investment ($)", value=100)
|
79 |
+
start_date = gr.Text(label="Start Date (YYYY-MM-DD)", value="1993-01-01")
|
80 |
+
end_date = gr.Text(label="End Date (YYYY-MM-DD)", value="2023-12-31")
|
81 |
+
ticker = gr.Dropdown(
|
82 |
+
label="Stock Ticker Symbol",
|
83 |
+
choices=["SPY", "TSLA", "GOOGL", "AAPL", "MSFT"],
|
84 |
+
value="SPY",
|
85 |
+
)
|
86 |
+
run_button = gr.Button("Run Simulation")
|
87 |
+
portfolio_graph = gr.Image(label="Portfolio Value Over Time")
|
88 |
+
summary_text = gr.Textbox(label="Simulation Summary", lines=8)
|
89 |
+
|
90 |
+
run_button.click(
|
91 |
sma_crossover_strategy,
|
92 |
+
inputs=[initial_budget, start_date, end_date, ticker],
|
93 |
+
outputs=[portfolio_graph, summary_text],
|
94 |
)
|
95 |
|
96 |
+
app.launch(server_port=7861) # No share=True
|
|
|
97 |
|