Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -3,9 +3,17 @@ import yfinance as yf
|
|
3 |
import numpy as np
|
4 |
import matplotlib.pyplot as plt
|
5 |
import gradio as gr
|
|
|
6 |
|
7 |
def sma_crossover_strategy(initial_budget, start_date, end_date, ticker):
|
8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
df = df[['Close']]
|
10 |
|
11 |
df['SMA_50'] = df['Close'].rolling(window=50).mean()
|
@@ -20,7 +28,10 @@ def sma_crossover_strategy(initial_budget, start_date, end_date, ticker):
|
|
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
|
@@ -43,8 +54,9 @@ def sma_crossover_strategy(initial_budget, start_date, end_date, ticker):
|
|
43 |
plt.grid()
|
44 |
plt.tight_layout()
|
45 |
|
46 |
-
plot_file =
|
47 |
-
plt.savefig(plot_file)
|
|
|
48 |
plt.close()
|
49 |
|
50 |
final_value = portfolio_values[-1]
|
@@ -60,11 +72,7 @@ def sma_crossover_strategy(initial_budget, start_date, end_date, ticker):
|
|
60 |
Percentage Return: {percentage_return:.2f}%
|
61 |
"""
|
62 |
|
63 |
-
|
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")
|
@@ -84,7 +92,6 @@ with gr.Blocks() as app:
|
|
84 |
with gr.Row():
|
85 |
portfolio_graph = gr.Image(label="Portfolio Value Over Time")
|
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("""
|
@@ -93,13 +100,13 @@ with gr.Blocks() as app:
|
|
93 |
2. Specify the trading period (start and end dates).
|
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
|
103 |
)
|
104 |
|
105 |
app.launch()
|
|
|
|
3 |
import numpy as np
|
4 |
import matplotlib.pyplot as plt
|
5 |
import gradio as gr
|
6 |
+
import io
|
7 |
|
8 |
def sma_crossover_strategy(initial_budget, start_date, end_date, ticker):
|
9 |
+
print("Fetching data...")
|
10 |
+
try:
|
11 |
+
df = yf.download(ticker, start=start_date, end=end_date, progress=False)
|
12 |
+
if df.empty:
|
13 |
+
return None, "No data available for the specified ticker and date range.", None
|
14 |
+
except Exception as e:
|
15 |
+
return None, f"Error fetching data: {str(e)}", None
|
16 |
+
|
17 |
df = df[['Close']]
|
18 |
|
19 |
df['SMA_50'] = df['Close'].rolling(window=50).mean()
|
|
|
28 |
shares = 0
|
29 |
portfolio_values = []
|
30 |
|
31 |
+
print("Starting simulation...")
|
32 |
for index, row in df.iterrows():
|
33 |
+
if pd.isna(row['Close']):
|
34 |
+
continue
|
35 |
if row['Position'] == 1 and cash > 0:
|
36 |
shares = cash / row['Close']
|
37 |
cash = 0
|
|
|
54 |
plt.grid()
|
55 |
plt.tight_layout()
|
56 |
|
57 |
+
plot_file = io.BytesIO()
|
58 |
+
plt.savefig(plot_file, format='png')
|
59 |
+
plot_file.seek(0)
|
60 |
plt.close()
|
61 |
|
62 |
final_value = portfolio_values[-1]
|
|
|
72 |
Percentage Return: {percentage_return:.2f}%
|
73 |
"""
|
74 |
|
75 |
+
return plot_file, results, None
|
|
|
|
|
|
|
|
|
76 |
|
77 |
with gr.Blocks() as app:
|
78 |
gr.Markdown("# SMA Crossover Trading Strategy Simulator")
|
|
|
92 |
with gr.Row():
|
93 |
portfolio_graph = gr.Image(label="Portfolio Value Over Time")
|
94 |
summary_text = gr.Textbox(label="Simulation Summary", lines=8)
|
|
|
95 |
|
96 |
with gr.Tab("Instructions"):
|
97 |
gr.Markdown("""
|
|
|
100 |
2. Specify the trading period (start and end dates).
|
101 |
3. Select a stock ticker symbol (e.g., SPY, TSLA, GOOGL).
|
102 |
4. Click "Run Simulation" to visualize the portfolio value over time and view a summary of results.
|
|
|
103 |
""")
|
104 |
|
105 |
run_button.click(
|
106 |
sma_crossover_strategy,
|
107 |
inputs=[initial_budget, start_date, end_date, ticker],
|
108 |
+
outputs=[portfolio_graph, summary_text],
|
109 |
)
|
110 |
|
111 |
app.launch()
|
112 |
+
|