Kh commited on
Commit
d5dd2e2
·
verified ·
1 Parent(s): 934ea44

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -66
app.py CHANGED
@@ -1,9 +1,6 @@
1
  import pandas as pd
2
  import gradio as gr
3
- import lightgbm as lgb
4
- import plotly.graph_objects as go
5
  import numpy as np
6
- from sklearn.model_selection import train_test_split
7
 
8
  # Load dataset
9
  DATA_PATH = "/mnt/data/AAPL_stock_data_finalversion (1).csv"
@@ -13,7 +10,7 @@ data = pd.read_csv(DATA_PATH)
13
  data['Date'] = pd.to_datetime(data['Date'])
14
  data['DateNumeric'] = data['Date'].map(pd.Timestamp.toordinal)
15
 
16
- # Define prediction function
17
  def stock_analysis(start_date, end_date):
18
  try:
19
  # Filter data by date range
@@ -22,81 +19,39 @@ def stock_analysis(start_date, end_date):
22
  if filtered_data.empty:
23
  return "No data available for the given date range.", None, None
24
 
25
- # Prepare data for forecasting
26
- X = filtered_data[['DateNumeric']]
27
- y = filtered_data['Close']
28
 
29
- # Train-test split
30
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
31
 
32
- # Prepare LightGBM dataset
33
- train_data = lgb.Dataset(X_train, label=y_train)
34
-
35
- # LightGBM parameters
36
- params = {
37
- 'objective': 'regression',
38
- 'metric': 'rmse',
39
- 'boosting_type': 'gbdt',
40
- 'num_leaves': 31,
41
- 'learning_rate': 0.05,
42
- 'verbose': -1
43
- }
44
-
45
- # Train LightGBM model
46
- model = lgb.train(params, train_data, num_boost_round=100)
47
-
48
- # Predict future stock prices (next 30 days)
49
  last_date = filtered_data['Date'].iloc[-1]
50
  future_dates = pd.date_range(last_date, periods=30, freq='B')
51
- future_dates_numeric = future_dates.map(pd.Timestamp.toordinal).values.reshape(-1, 1)
52
- future_predictions = model.predict(future_dates_numeric)
53
 
54
- # Add trend or variation to predictions based on historical data
55
- historical_trend = np.gradient(filtered_data['Close'].values)
56
- trend_mean = np.mean(historical_trend) if len(historical_trend) > 0 else 0
57
- future_predictions = future_predictions + np.linspace(0, trend_mean * 30, len(future_predictions))
58
-
59
- # Create a DataFrame for predictions
60
  future_df = pd.DataFrame({
61
  'Date': future_dates,
62
- 'Predicted Close Price': future_predictions.flatten()
63
  })
64
 
65
- # Create a plot using Plotly
66
- fig = go.Figure()
67
-
68
- # Add historical data to the plot
69
- fig.add_trace(go.Scatter(
70
- x=filtered_data['Date'],
71
- y=filtered_data['Close'],
72
- mode='lines',
73
- name='Historical Close Prices'
74
- ))
75
-
76
- # Add predicted data to the plot
77
- fig.add_trace(go.Scatter(
78
- x=future_df['Date'],
79
- y=future_df['Predicted Close Price'],
80
- mode='lines',
81
- name='Predicted Close Prices'
82
- ))
83
-
84
- fig.update_layout(
85
- title="Stock Prices: Historical and Predicted",
86
- xaxis_title="Date",
87
- yaxis_title="Close Price (USD)",
88
- legend_title="Legend",
89
- template="plotly_white"
90
- )
91
-
92
- return "Analysis completed!", fig, future_df
93
 
94
  except Exception as e:
95
  return f"An error occurred: {str(e)}", None, None
96
 
97
  # Define Gradio app
98
  with gr.Blocks() as app:
99
- gr.Markdown("# Stock Price Prediction App (Using Uploaded Dataset)")
100
 
101
  with gr.Row():
102
  start_date_input = gr.Textbox(label="Start Date", placeholder="YYYY-MM-DD")
@@ -105,13 +60,13 @@ with gr.Blocks() as app:
105
  analyze_button = gr.Button("Analyze")
106
 
107
  output_message = gr.Textbox(label="Message", interactive=False)
108
- stock_plot = gr.Plot(label="Stock Price Plot")
109
  prediction_table = gr.Dataframe(label="Future Predictions")
110
 
111
  analyze_button.click(
112
  stock_analysis,
113
  inputs=[start_date_input, end_date_input],
114
- outputs=[output_message, stock_plot, prediction_table]
115
  )
116
 
117
  # Launch the app
 
1
  import pandas as pd
2
  import gradio as gr
 
 
3
  import numpy as np
 
4
 
5
  # Load dataset
6
  DATA_PATH = "/mnt/data/AAPL_stock_data_finalversion (1).csv"
 
10
  data['Date'] = pd.to_datetime(data['Date'])
11
  data['DateNumeric'] = data['Date'].map(pd.Timestamp.toordinal)
12
 
13
+ # Define a basic prediction function
14
  def stock_analysis(start_date, end_date):
15
  try:
16
  # Filter data by date range
 
19
  if filtered_data.empty:
20
  return "No data available for the given date range.", None, None
21
 
22
+ # Simple linear trend for predictions
23
+ dates_numeric = filtered_data['DateNumeric'].values
24
+ prices = filtered_data['Close'].values
25
 
26
+ # Calculate slope and intercept for linear trend
27
+ slope, intercept = np.polyfit(dates_numeric, prices, 1)
28
 
29
+ # Predict next 30 business days
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  last_date = filtered_data['Date'].iloc[-1]
31
  future_dates = pd.date_range(last_date, periods=30, freq='B')
32
+ future_dates_numeric = future_dates.map(pd.Timestamp.toordinal)
33
+ future_predictions = slope * future_dates_numeric + intercept
34
 
35
+ # Create DataFrame for predictions
 
 
 
 
 
36
  future_df = pd.DataFrame({
37
  'Date': future_dates,
38
+ 'Predicted Close Price': future_predictions
39
  })
40
 
41
+ # Combine historical and future data for graphing
42
+ graph_data = pd.concat([
43
+ filtered_data[['Date', 'Close']].rename(columns={'Close': 'Price'}),
44
+ future_df.rename(columns={'Predicted Close Price': 'Price'})
45
+ ])
46
+
47
+ return "Analysis completed!", graph_data.to_dict(orient='list'), future_df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
  except Exception as e:
50
  return f"An error occurred: {str(e)}", None, None
51
 
52
  # Define Gradio app
53
  with gr.Blocks() as app:
54
+ gr.Markdown("# Simple Stock Price Prediction App")
55
 
56
  with gr.Row():
57
  start_date_input = gr.Textbox(label="Start Date", placeholder="YYYY-MM-DD")
 
60
  analyze_button = gr.Button("Analyze")
61
 
62
  output_message = gr.Textbox(label="Message", interactive=False)
63
+ stock_table = gr.Dataframe(label="Historical and Predicted Prices")
64
  prediction_table = gr.Dataframe(label="Future Predictions")
65
 
66
  analyze_button.click(
67
  stock_analysis,
68
  inputs=[start_date_input, end_date_input],
69
+ outputs=[output_message, stock_table, prediction_table]
70
  )
71
 
72
  # Launch the app