Spaces:
Sleeping
Sleeping
Rename Gradio to app.py
Browse files- Gradio → app.py +28 -26
Gradio → app.py
RENAMED
@@ -5,47 +5,35 @@ import matplotlib.pyplot as plt
|
|
5 |
import gradio as gr
|
6 |
import io
|
7 |
|
8 |
-
|
9 |
-
return f"Hello, {name}!"
|
10 |
-
|
11 |
-
app = gr.Interface(fn=test_function, inputs="text", outputs="text")
|
12 |
-
app.launch()
|
13 |
-
|
14 |
-
|
15 |
-
print("Starting app...")
|
16 |
-
|
17 |
-
try:
|
18 |
-
import pandas as pd
|
19 |
-
print("Pandas imported.")
|
20 |
-
import yfinance as yf
|
21 |
-
print("yfinance imported.")
|
22 |
-
import numpy as np
|
23 |
-
print("NumPy imported.")
|
24 |
-
import matplotlib.pyplot as plt
|
25 |
-
print("Matplotlib imported.")
|
26 |
-
import gradio as gr
|
27 |
-
print("Gradio imported.")
|
28 |
-
except Exception as e:
|
29 |
-
print(f"Error importing libraries: {e}")
|
30 |
-
raise
|
31 |
-
|
32 |
|
|
|
33 |
def sma_crossover_strategy(initial_budget, start_date, end_date, ticker):
|
|
|
34 |
try:
|
|
|
35 |
df = yf.download(ticker, start=start_date, end=end_date, progress=False)
|
36 |
if df.empty:
|
|
|
37 |
return None, "No data available for the specified ticker and date range.", None
|
38 |
except Exception as e:
|
|
|
39 |
return None, f"Error fetching data: {str(e)}", None
|
40 |
|
|
|
|
|
41 |
df = df[['Close']]
|
42 |
df['SMA_50'] = df['Close'].rolling(window=50).mean()
|
43 |
df['SMA_150'] = df['Close'].rolling(window=150).mean()
|
|
|
|
|
44 |
df['Signal'] = 0
|
45 |
df['Signal'][df['SMA_50'] > df['SMA_150']] = 1
|
46 |
df['Signal'][df['SMA_50'] < df['SMA_150']] = -1
|
47 |
df['Position'] = df['Signal'].diff()
|
48 |
|
|
|
|
|
49 |
cash = initial_budget
|
50 |
shares = 0
|
51 |
portfolio_values = []
|
@@ -53,18 +41,23 @@ def sma_crossover_strategy(initial_budget, start_date, end_date, ticker):
|
|
53 |
for index, row in df.iterrows():
|
54 |
if pd.isna(row['Close']):
|
55 |
continue
|
56 |
-
if row['Position'] == 1 and cash > 0:
|
57 |
shares = cash / row['Close']
|
58 |
cash = 0
|
59 |
-
elif row['Position'] == -1 and shares > 0:
|
60 |
cash = shares * row['Close']
|
61 |
shares = 0
|
|
|
|
|
62 |
portfolio_value = cash + (shares * row['Close'])
|
63 |
portfolio_values.append(portfolio_value)
|
64 |
|
|
|
65 |
df = df.iloc[149:]
|
66 |
df['Portfolio Value'] = portfolio_values[149:]
|
67 |
|
|
|
|
|
68 |
plt.figure(figsize=(14, 8))
|
69 |
plt.plot(df['Portfolio Value'], label='Portfolio Value', color='purple')
|
70 |
plt.xlabel('Date')
|
@@ -74,11 +67,13 @@ def sma_crossover_strategy(initial_budget, start_date, end_date, ticker):
|
|
74 |
plt.grid()
|
75 |
plt.tight_layout()
|
76 |
|
|
|
77 |
plot_file = io.BytesIO()
|
78 |
plt.savefig(plot_file, format='png')
|
79 |
plot_file.seek(0)
|
80 |
plt.close()
|
81 |
|
|
|
82 |
final_value = portfolio_values[-1]
|
83 |
profit_loss = final_value - initial_budget
|
84 |
percentage_return = (profit_loss / initial_budget) * 100
|
@@ -94,10 +89,13 @@ def sma_crossover_strategy(initial_budget, start_date, end_date, ticker):
|
|
94 |
|
95 |
return plot_file, results, None
|
96 |
|
|
|
|
|
97 |
with gr.Blocks() as app:
|
98 |
gr.Markdown("# SMA Crossover Trading Strategy Simulator")
|
99 |
|
100 |
with gr.Tabs():
|
|
|
101 |
with gr.Tab("SMA Strategy Simulator"):
|
102 |
with gr.Row():
|
103 |
initial_budget = gr.Number(label="Initial Investment ($)", value=100, interactive=True)
|
@@ -113,6 +111,7 @@ with gr.Blocks() as app:
|
|
113 |
portfolio_graph = gr.Image(label="Portfolio Value Over Time")
|
114 |
summary_text = gr.Textbox(label="Simulation Summary", lines=8)
|
115 |
|
|
|
116 |
with gr.Tab("Instructions"):
|
117 |
gr.Markdown("""
|
118 |
## How to Use:
|
@@ -122,11 +121,14 @@ with gr.Blocks() as app:
|
|
122 |
4. Click "Run Simulation" to visualize the portfolio value over time and view a summary of results.
|
123 |
""")
|
124 |
|
|
|
125 |
run_button.click(
|
126 |
sma_crossover_strategy,
|
127 |
inputs=[initial_budget, start_date, end_date, ticker],
|
128 |
outputs=[portfolio_graph, summary_text],
|
129 |
)
|
130 |
|
|
|
131 |
app.launch()
|
132 |
|
|
|
|
5 |
import gradio as gr
|
6 |
import io
|
7 |
|
8 |
+
print("App is starting...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
+
# Define the SMA Crossover Trading Strategy Function
|
11 |
def sma_crossover_strategy(initial_budget, start_date, end_date, ticker):
|
12 |
+
print(f"Fetching data for {ticker} from {start_date} to {end_date}...")
|
13 |
try:
|
14 |
+
# Fetch stock data
|
15 |
df = yf.download(ticker, start=start_date, end=end_date, progress=False)
|
16 |
if df.empty:
|
17 |
+
print("No data fetched. Returning error message.")
|
18 |
return None, "No data available for the specified ticker and date range.", None
|
19 |
except Exception as e:
|
20 |
+
print(f"Error fetching data: {str(e)}")
|
21 |
return None, f"Error fetching data: {str(e)}", None
|
22 |
|
23 |
+
# Calculate SMAs
|
24 |
+
print("Calculating SMAs...")
|
25 |
df = df[['Close']]
|
26 |
df['SMA_50'] = df['Close'].rolling(window=50).mean()
|
27 |
df['SMA_150'] = df['Close'].rolling(window=150).mean()
|
28 |
+
|
29 |
+
# Define signals
|
30 |
df['Signal'] = 0
|
31 |
df['Signal'][df['SMA_50'] > df['SMA_150']] = 1
|
32 |
df['Signal'][df['SMA_50'] < df['SMA_150']] = -1
|
33 |
df['Position'] = df['Signal'].diff()
|
34 |
|
35 |
+
# Initialize portfolio simulation
|
36 |
+
print("Simulating portfolio...")
|
37 |
cash = initial_budget
|
38 |
shares = 0
|
39 |
portfolio_values = []
|
|
|
41 |
for index, row in df.iterrows():
|
42 |
if pd.isna(row['Close']):
|
43 |
continue
|
44 |
+
if row['Position'] == 1 and cash > 0: # Buy signal
|
45 |
shares = cash / row['Close']
|
46 |
cash = 0
|
47 |
+
elif row['Position'] == -1 and shares > 0: # Sell signal
|
48 |
cash = shares * row['Close']
|
49 |
shares = 0
|
50 |
+
|
51 |
+
# Calculate current portfolio value
|
52 |
portfolio_value = cash + (shares * row['Close'])
|
53 |
portfolio_values.append(portfolio_value)
|
54 |
|
55 |
+
# Handle missing data at the start
|
56 |
df = df.iloc[149:]
|
57 |
df['Portfolio Value'] = portfolio_values[149:]
|
58 |
|
59 |
+
# Generate plot
|
60 |
+
print("Generating plot...")
|
61 |
plt.figure(figsize=(14, 8))
|
62 |
plt.plot(df['Portfolio Value'], label='Portfolio Value', color='purple')
|
63 |
plt.xlabel('Date')
|
|
|
67 |
plt.grid()
|
68 |
plt.tight_layout()
|
69 |
|
70 |
+
# Save plot to in-memory buffer
|
71 |
plot_file = io.BytesIO()
|
72 |
plt.savefig(plot_file, format='png')
|
73 |
plot_file.seek(0)
|
74 |
plt.close()
|
75 |
|
76 |
+
# Final portfolio summary
|
77 |
final_value = portfolio_values[-1]
|
78 |
profit_loss = final_value - initial_budget
|
79 |
percentage_return = (profit_loss / initial_budget) * 100
|
|
|
89 |
|
90 |
return plot_file, results, None
|
91 |
|
92 |
+
# Create Gradio Interface
|
93 |
+
print("Setting up Gradio app...")
|
94 |
with gr.Blocks() as app:
|
95 |
gr.Markdown("# SMA Crossover Trading Strategy Simulator")
|
96 |
|
97 |
with gr.Tabs():
|
98 |
+
# SMA Strategy Simulator Tab
|
99 |
with gr.Tab("SMA Strategy Simulator"):
|
100 |
with gr.Row():
|
101 |
initial_budget = gr.Number(label="Initial Investment ($)", value=100, interactive=True)
|
|
|
111 |
portfolio_graph = gr.Image(label="Portfolio Value Over Time")
|
112 |
summary_text = gr.Textbox(label="Simulation Summary", lines=8)
|
113 |
|
114 |
+
# Instructions Tab
|
115 |
with gr.Tab("Instructions"):
|
116 |
gr.Markdown("""
|
117 |
## How to Use:
|
|
|
121 |
4. Click "Run Simulation" to visualize the portfolio value over time and view a summary of results.
|
122 |
""")
|
123 |
|
124 |
+
# Connect simulation function to Gradio app
|
125 |
run_button.click(
|
126 |
sma_crossover_strategy,
|
127 |
inputs=[initial_budget, start_date, end_date, ticker],
|
128 |
outputs=[portfolio_graph, summary_text],
|
129 |
)
|
130 |
|
131 |
+
print("Launching Gradio app...")
|
132 |
app.launch()
|
133 |
|
134 |
+
|