Now, let's say that you have stock data in a CSV file with Date, Open, High, Low, Close, and Volume columns. In this example, I will use the Python library pandas to read the CSV file, and the library scikit-learn to create a simple linear regression model.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
# Load the data
data = pd.read_csv('stock_data.csv')
data['Date'] = pd.to_datetime(data['Date'], format='%Y-%m-%d')
# Prepare the features
data['Day'] = data['Date'].dt.dayofyear
X = data[['Day']].values
y = data['Close'].values
# Split the data into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Fit the model
regression_model = LinearRegression()
regression_model.fit(X_train, y_train)
# Create predictions
y_pred_train = regression_model.predict(X_train)
y_pred_test = regression_model.predict(X_test)
# Evaluate the model
mse_train = mean_squared_error(y_train, y_pred_train)
mse_test = mean_squared_error(y_test, y_pred_test)
print("MSE on training set:", mse_train)
print("MSE on test set:", mse_test)
# Plot the results
plt.figure(figsize=(12, 6))
plt.scatter(data['Date'], data['Close'], color='blue', label='Actual close price')
plt.scatter(X_train, y_pred_train, color='red', label='Predicted close price (train)')
plt.scatter(X_test, y_pred_test, color='green', label='Predicted close price (test)')
plt.xlabel('Date')
plt.ylabel('Close price')
plt.title('Stock market prediction')
plt.legend()
plt.show()
Please note that this is a simple example that might not provide accurate predictions. For better results, you might want to look into more advanced techniques like time-series forecasting models (e.g., ARIMA, GARCH, LSTM).