Last active
August 29, 2015 14:27
-
-
Save primaryobjects/3274d7f954943fe30103 to your computer and use it in GitHub Desktop.
Forecasting stock charts in R.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(quantmod) | |
library(forecast) | |
# Set the ticker symbol. | |
ticker = 'SPY' | |
# Set the date range. | |
from <- as.Date('01/02/10', format='%m/%d/%y') | |
to <- Sys.Date() #as.Date('08/14/15', format='%m/%d/%y') | |
# Get the data. | |
data <- get(getSymbols('JNK', src='google', from=from, to=to)) | |
# Display a 20-day moving average of the data. | |
chartSeries(data, TA="addSMA(20)") | |
# Convert to monthly open prices. | |
monthly <- to.monthly(data) | |
openPrices <- Op(monthly) | |
# Create a time-series. | |
timeSeries <- ts(openPrices, frequency=12) | |
# Plot the time series. | |
plot(timeSeries, xlab='Years', ylab = 'Stock') | |
# Decompose a time series and plot the chart. | |
plot(decompose(timeSeries), xlab='Years') | |
# Create a training and test set. | |
training <- window(timeSeries, start=1, end=4) | |
testing <- window(timeSeries, start=4) | |
# Plot the moving average of the time-series. | |
plot(training) | |
lines(ma(training, order=3), col='red') | |
# Predict with exponential smoothing. | |
fit <- ets(training, model='MMM') | |
fcast <- forecast(fit) | |
# Plot the training and forecast of the testing data (red). | |
plot(fcast) | |
lines(testing, col='red') | |
# Check accuracy. | |
accuracy(fcast, testing) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment