Spaces:
Runtime error
Runtime error
Create linear_regression.py
Browse files- algo/linear_regression.py +34 -0
algo/linear_regression.py
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pandas as pd
|
2 |
+
import numpy as np
|
3 |
+
from sklearn.linear_model import LinearRegression
|
4 |
+
|
5 |
+
def linear_regression_forecast(data, forecast_horizon):
|
6 |
+
"""
|
7 |
+
Forecast future values using Linear Regression, with a dynamic forecast horizon.
|
8 |
+
|
9 |
+
Parameters:
|
10 |
+
- data: Pandas Series of historical closing prices.
|
11 |
+
- forecast_horizon: Integer specifying the number of days to forecast.
|
12 |
+
|
13 |
+
Returns:
|
14 |
+
- Pandas Series containing the forecasted values with a datetime index.
|
15 |
+
"""
|
16 |
+
# Prepare the features (time) and target (data values)
|
17 |
+
X = np.arange(len(data)).reshape(-1, 1) # Time as the feature
|
18 |
+
y = data.values # Stock prices as the target
|
19 |
+
|
20 |
+
# Fit the Linear Regression model
|
21 |
+
model = LinearRegression()
|
22 |
+
model.fit(X, y)
|
23 |
+
|
24 |
+
# Prepare future time points for prediction based on the forecast horizon
|
25 |
+
future_X = np.arange(len(data), len(data) + forecast_horizon).reshape(-1, 1)
|
26 |
+
|
27 |
+
# Forecast future stock prices
|
28 |
+
forecast = model.predict(future_X)
|
29 |
+
|
30 |
+
# Create a pandas Series for the forecasted values with a date index
|
31 |
+
future_dates = pd.date_range(start=data.index[-1] + pd.Timedelta(days=1), periods=forecast_horizon)
|
32 |
+
forecast_series = pd.Series(forecast, index=future_dates)
|
33 |
+
|
34 |
+
return forecast_series
|