Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
# Import necessary libraries
|
| 2 |
import pandas as pd
|
| 3 |
import yfinance as yf
|
| 4 |
import numpy as np
|
|
@@ -6,46 +5,35 @@ 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']]
|
| 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 |
-
|
| 18 |
-
df['Signal']
|
| 19 |
-
df['Signal'][df['SMA_50']
|
| 20 |
-
df['
|
| 21 |
-
df['Position'] = df['Signal'].diff() # Capture points where the signal changes
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 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
|
| 34 |
-
|
| 35 |
-
# Sell signal
|
| 36 |
elif row['Position'] == -1 and shares > 0:
|
| 37 |
cash = shares * row['Close']
|
| 38 |
-
shares = 0
|
| 39 |
|
| 40 |
-
# Calculate current portfolio value
|
| 41 |
portfolio_value = cash + (shares * row['Close'])
|
| 42 |
portfolio_values.append(portfolio_value)
|
| 43 |
|
| 44 |
-
|
| 45 |
-
df =
|
| 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')
|
|
@@ -55,17 +43,14 @@ def sma_crossover_strategy(initial_budget, start_date, end_date, ticker):
|
|
| 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 |
-
# Create summary text
|
| 69 |
results = f"""
|
| 70 |
Ticker: {ticker}
|
| 71 |
Trading Period: {start_date} to {end_date}
|
|
@@ -75,19 +60,16 @@ def sma_crossover_strategy(initial_budget, start_date, end_date, ticker):
|
|
| 75 |
Percentage Return: {percentage_return:.2f}%
|
| 76 |
"""
|
| 77 |
|
| 78 |
-
# Save results to a text file
|
| 79 |
results_file = "simulation_results.txt"
|
| 80 |
with open(results_file, "w") as f:
|
| 81 |
f.write(results)
|
| 82 |
|
| 83 |
return plot_file, results, results_file
|
| 84 |
|
| 85 |
-
# Define Gradio interface components
|
| 86 |
with gr.Blocks() as app:
|
| 87 |
gr.Markdown("# SMA Crossover Trading Strategy Simulator")
|
| 88 |
|
| 89 |
with gr.Tabs():
|
| 90 |
-
# Tab for SMA Strategy Simulation
|
| 91 |
with gr.Tab("SMA Strategy Simulator"):
|
| 92 |
with gr.Row():
|
| 93 |
initial_budget = gr.Number(label="Initial Investment ($)", value=100, interactive=True)
|
|
@@ -104,7 +86,6 @@ with gr.Blocks() as app:
|
|
| 104 |
summary_text = gr.Textbox(label="Simulation Summary", lines=8)
|
| 105 |
download_button = gr.File(label="Download Results (.txt)")
|
| 106 |
|
| 107 |
-
# Tab for Instructions
|
| 108 |
with gr.Tab("Instructions"):
|
| 109 |
gr.Markdown("""
|
| 110 |
## How to Use:
|
|
@@ -113,19 +94,12 @@ with gr.Blocks() as app:
|
|
| 113 |
3. Select a stock ticker symbol (e.g., SPY, TSLA, GOOGL).
|
| 114 |
4. Click "Run Simulation" to visualize the portfolio value over time and view a summary of results.
|
| 115 |
5. Download the results as a `.txt` file using the download button.
|
| 116 |
-
|
| 117 |
-
### Notes:
|
| 118 |
-
- The 50-day and 150-day SMAs are used for buy and sell signals.
|
| 119 |
-
- Ensure the trading period is valid for the selected ticker symbol.
|
| 120 |
""")
|
| 121 |
|
| 122 |
-
# Link simulation function to UI
|
| 123 |
run_button.click(
|
| 124 |
sma_crossover_strategy,
|
| 125 |
inputs=[initial_budget, start_date, end_date, ticker],
|
| 126 |
outputs=[portfolio_graph, summary_text, download_button],
|
| 127 |
)
|
| 128 |
|
| 129 |
-
# Launch the app
|
| 130 |
app.launch()
|
| 131 |
-
|
|
|
|
|
|
|
| 1 |
import pandas as pd
|
| 2 |
import yfinance as yf
|
| 3 |
import numpy as np
|
|
|
|
| 5 |
import gradio as gr
|
| 6 |
|
| 7 |
def sma_crossover_strategy(initial_budget, start_date, end_date, ticker):
|
|
|
|
| 8 |
df = yf.download(ticker, start=start_date, end=end_date, progress=False)
|
| 9 |
+
df = df[['Close']]
|
| 10 |
|
|
|
|
| 11 |
df['SMA_50'] = df['Close'].rolling(window=50).mean()
|
| 12 |
df['SMA_150'] = df['Close'].rolling(window=150).mean()
|
| 13 |
|
| 14 |
+
df['Signal'] = 0
|
| 15 |
+
df['Signal'][df['SMA_50'] > df['SMA_150']] = 1
|
| 16 |
+
df['Signal'][df['SMA_50'] < df['SMA_150']] = -1
|
| 17 |
+
df['Position'] = df['Signal'].diff()
|
|
|
|
| 18 |
|
| 19 |
+
cash = initial_budget
|
| 20 |
+
shares = 0
|
| 21 |
+
portfolio_values = []
|
|
|
|
| 22 |
|
|
|
|
| 23 |
for index, row in df.iterrows():
|
|
|
|
| 24 |
if row['Position'] == 1 and cash > 0:
|
| 25 |
shares = cash / row['Close']
|
| 26 |
+
cash = 0
|
|
|
|
|
|
|
| 27 |
elif row['Position'] == -1 and shares > 0:
|
| 28 |
cash = shares * row['Close']
|
| 29 |
+
shares = 0
|
| 30 |
|
|
|
|
| 31 |
portfolio_value = cash + (shares * row['Close'])
|
| 32 |
portfolio_values.append(portfolio_value)
|
| 33 |
|
| 34 |
+
df = df.iloc[149:]
|
| 35 |
+
df['Portfolio Value'] = portfolio_values[149:]
|
|
|
|
| 36 |
|
|
|
|
| 37 |
plt.figure(figsize=(14, 8))
|
| 38 |
plt.plot(df['Portfolio Value'], label='Portfolio Value', color='purple')
|
| 39 |
plt.xlabel('Date')
|
|
|
|
| 43 |
plt.grid()
|
| 44 |
plt.tight_layout()
|
| 45 |
|
|
|
|
| 46 |
plot_file = "portfolio_value_plot.png"
|
| 47 |
plt.savefig(plot_file)
|
| 48 |
plt.close()
|
| 49 |
|
|
|
|
| 50 |
final_value = portfolio_values[-1]
|
| 51 |
profit_loss = final_value - initial_budget
|
| 52 |
percentage_return = (profit_loss / initial_budget) * 100
|
| 53 |
|
|
|
|
| 54 |
results = f"""
|
| 55 |
Ticker: {ticker}
|
| 56 |
Trading Period: {start_date} to {end_date}
|
|
|
|
| 60 |
Percentage Return: {percentage_return:.2f}%
|
| 61 |
"""
|
| 62 |
|
|
|
|
| 63 |
results_file = "simulation_results.txt"
|
| 64 |
with open(results_file, "w") as f:
|
| 65 |
f.write(results)
|
| 66 |
|
| 67 |
return plot_file, results, results_file
|
| 68 |
|
|
|
|
| 69 |
with gr.Blocks() as app:
|
| 70 |
gr.Markdown("# SMA Crossover Trading Strategy Simulator")
|
| 71 |
|
| 72 |
with gr.Tabs():
|
|
|
|
| 73 |
with gr.Tab("SMA Strategy Simulator"):
|
| 74 |
with gr.Row():
|
| 75 |
initial_budget = gr.Number(label="Initial Investment ($)", value=100, interactive=True)
|
|
|
|
| 86 |
summary_text = gr.Textbox(label="Simulation Summary", lines=8)
|
| 87 |
download_button = gr.File(label="Download Results (.txt)")
|
| 88 |
|
|
|
|
| 89 |
with gr.Tab("Instructions"):
|
| 90 |
gr.Markdown("""
|
| 91 |
## How to Use:
|
|
|
|
| 94 |
3. Select a stock ticker symbol (e.g., SPY, TSLA, GOOGL).
|
| 95 |
4. Click "Run Simulation" to visualize the portfolio value over time and view a summary of results.
|
| 96 |
5. Download the results as a `.txt` file using the download button.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
""")
|
| 98 |
|
|
|
|
| 99 |
run_button.click(
|
| 100 |
sma_crossover_strategy,
|
| 101 |
inputs=[initial_budget, start_date, end_date, ticker],
|
| 102 |
outputs=[portfolio_graph, summary_text, download_button],
|
| 103 |
)
|
| 104 |
|
|
|
|
| 105 |
app.launch()
|
|
|