pm6six commited on
Commit
3c87c5c
·
verified ·
1 Parent(s): 4355a46

Update app.py

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