Create a script in R to implement a machine learning model for predicting stock prices
Create a script in R to implement a machine learning model for predicting stock prices
回复样本
Here's a basic script in R for implementing a machine learning model to predict stock prices:
```
# Load necessary libraries
library(tidyverse)
library(caret)
library(xts)
library(quantmod)
# Define the ticker symbol and the time period for prediction
ticker <- "AAPL"
start_date <- as.Date("2015-01-01")
end_date <- as.Date("2023-03-10")
# Import stock data
getSymbols(ticker, from = start_date, to = end_date)
stock_data <- as.data.frame(AAPL)
# Create new columns for technical indicators
stock_data$MA_50 <- SMA(Cl(AAPL), n = 50)
stock_data$RSI_14 <- RSI(Cl(AAPL), n = 14)
# Define training and testing data sets
train_size <- floor(0.75 * nrow(stock_data))
train_set <- stock_data[1:train_size, ]
test_set <- stock_data[(train_size + 1):nrow(stock_data), ]
# Create input and output variables for the model
input_vars <- c("MA_50", "RSI_14")
output_var <- "AAPL.Adjusted"
# Train the model using caret package
model <- train(train_set[, input_vars], train_set[, output_var],
method = "lm",
trControl = trainControl(method = "cv"))
# Use the trained model to make predictions on the test set
predictions <- predict(model, test_set[, input_vars])
# Calculate mean squared error (MSE) of predictions
mse <- mean((predictions - test_set[, output_var])^2)
# Print the MSE
cat("Mean Squared Error:", mse)
```
Note that this is just a basic example and there are many ways to improve the accuracy of the model, such as adding more technical indicators, using different machine learning algorithms, or incorporating external factors like news or economic data.
出版日期: 1 年前