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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -21
app.py CHANGED
@@ -1,54 +1,83 @@
1
  import pandas as pd
2
  import gradio as gr
3
- from prophet import Prophet
4
  import plotly.graph_objects as go
 
 
5
 
6
  # Load dataset
7
- DATA_PATH = "/content/AAPL_stock_data_finalversion (1).csv"
8
  data = pd.read_csv(DATA_PATH)
9
 
10
  # Ensure the dataset has the required columns
11
  data['Date'] = pd.to_datetime(data['Date'])
12
-
13
- # Rename columns for Prophet compatibility
14
- data = data.rename(columns={'Date': 'ds', 'Close': 'y'})
15
 
16
  # Define prediction function
17
  def stock_analysis(start_date, end_date):
18
  try:
19
  # Filter data by date range
20
- filtered_data = data[(data['ds'] >= pd.to_datetime(start_date)) & (data['ds'] <= pd.to_datetime(end_date))]
21
 
22
  if filtered_data.empty:
23
  return "No data available for the given date range.", None, None
24
 
25
- # Fit the Prophet model
26
- model = Prophet()
27
- model.fit(filtered_data)
28
 
29
- # Predict future stock prices (next 30 days)
30
- future_dates = model.make_future_dataframe(periods=30)
31
- forecast = model.predict(future_dates)
 
 
32
 
33
- # Filter only the forecasted dates
34
- forecast = forecast[['ds', 'yhat']].tail(30).rename(columns={'ds': 'Date', 'yhat': 'Predicted Close Price'})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
  # Create a plot using Plotly
37
  fig = go.Figure()
38
 
39
  # Add historical data to the plot
40
  fig.add_trace(go.Scatter(
41
- x=filtered_data['ds'],
42
- y=filtered_data['y'],
43
- mode='lines',
44
  name='Historical Close Prices'
45
  ))
46
 
47
  # Add predicted data to the plot
48
  fig.add_trace(go.Scatter(
49
- x=forecast['Date'],
50
- y=forecast['Predicted Close Price'],
51
- mode='lines',
52
  name='Predicted Close Prices'
53
  ))
54
 
@@ -60,7 +89,7 @@ def stock_analysis(start_date, end_date):
60
  template="plotly_white"
61
  )
62
 
63
- return "Analysis completed!", fig, forecast
64
 
65
  except Exception as e:
66
  return f"An error occurred: {str(e)}", None, None
 
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"
10
  data = pd.read_csv(DATA_PATH)
11
 
12
  # Ensure the dataset has the required columns
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
20
+ filtered_data = data[(data['Date'] >= pd.to_datetime(start_date)) & (data['Date'] <= pd.to_datetime(end_date))]
21
 
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
 
 
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