Spaces:
Sleeping
Sleeping
Create app
Browse files
app
ADDED
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Import necessary libraries
|
2 |
+
import pandas as pd
|
3 |
+
import yfinance as yf
|
4 |
+
import numpy as np
|
5 |
+
import matplotlib.pyplot as plt
|
6 |
+
import gradio as gr
|
7 |
+
|
8 |
+
def sma_crossover_strategy(initial_budget, start_date, end_date, ticker):
|
9 |
+
# Fetch the selected stock data using yfinance
|
10 |
+
df = yf.download(ticker, start=start_date, end=end_date, progress=False)
|
11 |
+
df = df[['Close']] # Use only the 'Close' price for SMA calculations
|
12 |
+
|
13 |
+
# Calculate SMAs
|
14 |
+
df['SMA_50'] = df['Close'].rolling(window=50).mean()
|
15 |
+
df['SMA_150'] = df['Close'].rolling(window=150).mean()
|
16 |
+
|
17 |
+
# Determine buy and sell signals
|
18 |
+
df['Signal'] = 0 # Initialize a column for signals
|
19 |
+
df['Signal'][df['SMA_50'] > df['SMA_150']] = 1 # Buy signal
|
20 |
+
df['Signal'][df['SMA_50'] < df['SMA_150']] = -1 # Sell signal
|
21 |
+
df['Position'] = df['Signal'].diff() # Capture points where the signal changes
|
22 |
+
|
23 |
+
# Initialize investment simulation
|
24 |
+
cash = initial_budget # Start with user-specified cash
|
25 |
+
shares = 0 # No shares initially
|
26 |
+
portfolio_values = [] # Store portfolio values
|
27 |
+
|
28 |
+
# Iterate over the dataframe to simulate trading
|
29 |
+
for index, row in df.iterrows():
|
30 |
+
# Buy signal
|
31 |
+
if row['Position'] == 1 and cash > 0:
|
32 |
+
shares = cash / row['Close']
|
33 |
+
cash = 0 # All money is invested in shares
|
34 |
+
|
35 |
+
# Sell signal
|
36 |
+
elif row['Position'] == -1 and shares > 0:
|
37 |
+
cash = shares * row['Close']
|
38 |
+
shares = 0 # All shares are sold
|
39 |
+
|
40 |
+
# Calculate current portfolio value
|
41 |
+
portfolio_value = cash + (shares * row['Close'])
|
42 |
+
portfolio_values.append(portfolio_value)
|
43 |
+
|
44 |
+
# Add portfolio values to the dataframe for visualization
|
45 |
+
df = df.iloc[149:] # Ignore rows with NaN values due to SMA calculations
|
46 |
+
df['Portfolio Value'] = portfolio_values[149:] # Align portfolio values
|
47 |
+
|
48 |
+
# Plot Portfolio Value over time
|
49 |
+
plt.figure(figsize=(14, 8))
|
50 |
+
plt.plot(df['Portfolio Value'], label='Portfolio Value', color='purple')
|
51 |
+
plt.xlabel('Date')
|
52 |
+
plt.ylabel('Portfolio Value ($)')
|
53 |
+
plt.title(f'Portfolio Value Over Time with 50/150 SMA Crossover Strategy ({ticker})')
|
54 |
+
plt.legend()
|
55 |
+
plt.grid()
|
56 |
+
plt.tight_layout()
|
57 |
+
|
58 |
+
# Save plot to a file for display
|
59 |
+
plot_file = "portfolio_value_plot.png"
|
60 |
+
plt.savefig(plot_file)
|
61 |
+
plt.close()
|
62 |
+
|
63 |
+
# Final results
|
64 |
+
final_value = portfolio_values[-1]
|
65 |
+
profit_loss = final_value - initial_budget
|
66 |
+
percentage_return = (profit_loss / initial_budget) * 100
|
67 |
+
|
68 |
+
results = f"""
|
69 |
+
Ticker: {ticker}
|
70 |
+
Trading Period: {start_date} to {end_date}
|
71 |
+
Initial Investment: ${initial_budget}
|
72 |
+
Final Portfolio Value: ${final_value:.2f}
|
73 |
+
Total Profit/Loss: ${profit_loss:.2f}
|
74 |
+
Percentage Return: {percentage_return:.2f}%
|
75 |
+
"""
|
76 |
+
|
77 |
+
return plot_file, results
|
78 |
+
|
79 |
+
# Define Gradio interface components
|
80 |
+
with gr.Blocks() as app:
|
81 |
+
gr.Markdown("# SMA Crossover Trading Strategy Simulator")
|
82 |
+
|
83 |
+
with gr.Tabs():
|
84 |
+
# Tab for SMA Strategy Simulation
|
85 |
+
with gr.Tab("SMA Strategy Simulator"):
|
86 |
+
with gr.Row():
|
87 |
+
initial_budget = gr.Number(label="Initial Investment ($)", value=100, interactive=True)
|
88 |
+
start_date = gr.Text(label="Start Date (YYYY-MM-DD)", value="1993-01-01", interactive=True)
|
89 |
+
end_date = gr.Text(label="End Date (YYYY-MM-DD)", value="2023-12-31", interactive=True)
|
90 |
+
ticker = gr.Dropdown(
|
91 |
+
label="Stock Ticker Symbol",
|
92 |
+
choices=["SPY", "TSLA", "GOOGL", "AAPL", "MSFT"],
|
93 |
+
value="SPY",
|
94 |
+
)
|
95 |
+
run_button = gr.Button("Run Simulation")
|
96 |
+
with gr.Row():
|
97 |
+
portfolio_graph = gr.Image(label="Portfolio Value Over Time")
|
98 |
+
summary_text = gr.Textbox(label="Simulation Summary", lines=8)
|
99 |
+
|
100 |
+
# Tab for Instructions
|
101 |
+
with gr.Tab("Instructions"):
|
102 |
+
gr.Markdown("""
|
103 |
+
## How to Use:
|
104 |
+
1. Enter your initial investment amount.
|
105 |
+
2. Specify the trading period (start and end dates).
|
106 |
+
3. Select a stock ticker symbol (e.g., SPY, TSLA, GOOGL).
|
107 |
+
4. Click "Run Simulation" to visualize the portfolio value over time and view a summary of results.
|
108 |
+
|
109 |
+
### Notes:
|
110 |
+
- The 50-day and 150-day SMAs are used for buy and sell signals.
|
111 |
+
- Ensure the trading period is valid for the selected ticker symbol.
|
112 |
+
""")
|
113 |
+
|
114 |
+
# Link simulation function to UI
|
115 |
+
run_button.click(
|
116 |
+
sma_crossover_strategy,
|
117 |
+
inputs=[initial_budget, start_date, end_date, ticker],
|
118 |
+
outputs=[portfolio_graph, summary_text],
|
119 |
+
)
|
120 |
+
|
121 |
+
# Launch the app
|
122 |
+
app.launch()
|