保留正文与补采附件。源页面当前未重新核验;具体限制见交付清单。

Revisit consent button We value your privacy We use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking "Accept All", you consent to our use of cookies. Customise Reject All Accept All Customise Consent Preferences We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below. The cookies that are categorised as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more NecessaryAlways Active Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

Functional Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

Analytics Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

Performance Performance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Advertisement Advertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.

Uncategorised Other uncategorised cookies are those that are being analysed and have not been classified into a category as yet. No cookies to display. Reject All Save My Preferences Accept All Toggle SearchToggle Mobile Navigation Publish AI, ML & data-science insights to a global community of data professionals. Sign inSubmit an Article LatestEditor's PicksNewsletterShipAI


Write For TDS LinkedInXToggle Search Data Science

Time-Series Forecasting: Predicting Stock Prices Using An ARIMA Model

In this post I show you how to predict the TESLA stock price using a forecasting ARIMA model Serafeim Loukas, PhD July 23, 20206 min read ARIMA model performance on the test set ARIMA model performance on the test set

1. Introduction

1.1. Time-series & forecasting models

Time-series forecasting models are the models that are capable to predict future values based on previously observed values. Time-series forecasting is widely used for non-stationary data. Non-stationary data are called the data whose statistical properties e.g. the mean and standard deviation are not constant over time but instead, these metrics vary over time. These non-stationary input data (used as input to these models) are usually called time-series. Some examples of time-series include the temperature values over time, stock price over time, price of a house over time etc. So, the input is a signal (time-series) that is defined by observations taken sequentially in time.

A time series is a sequence of observations taken sequentially in time. An example of a time-series. Plot created by the author in Python. An example of a time-series. Plot created by the author in Python. Observation: Time-series data is recorded on a discrete time scale. Disclaimer : There have been attempts to predict stock prices using time series analysis algorithms, though they still cannot be used to place bets in the real market. This is just a tutorial article that does not intent in any way to "direct" people into buying stocks.


If you're passionate about diving deeper into machine learning with Python and sklearn, I highly recommend checking out this book; it's a game-changer in breaking down complex topics into digestible insights.

Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques...


2. The AutoRegressive Integrated Moving Average (ARIMA) model

A famous and widely used forecasting method for time-series prediction is the AutoRegressive Integrated Moving Average (ARIMA) model. ARIMA models are capable of capturing a suite of different standard temporal structures in time-series data.

Terminology

Let's break down these terms:

Model parameters

The standard ARIMA models expect as input parameters 3 arguments i.e. p,d,q.



3. Getting the stock price history data

Thanks to Yahoo finance we can get the data for free. Use the following link to get the stock price history of TESLA : https://finance.yahoo.com/quote/TSLA/history?period1=1436486400&period2=1594339200&interval=1d&filter=history&frequency=1d You should see the following: Click on the Download and save the .csv file locally on your computer. The data are from 2015 till now (2020) !


4. Python working example

Modules needed: Numpy, Pandas, Statsmodels , Scikit-Learn 4.1. Load & inspect the data Our imports : text

import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt
from pandas.plotting import lag_plot
from pandas import datetime
from statsmodels.tsa.arima_model import ARIMA
from sklearn.metrics import mean_squared_error

Now let's load the TESLA stock history data : text

df = pd.read_csv("TSLA.csv")
df.head(5)

Before building the ARIMA model, let's see if there is some cross-correlation in out data.

text

plt.figure()
lag_plot(df['Open'], lag=3)
plt.title('TESLA Stock - Autocorrelation plot with lag = 3')
plt.show()

TESLA Stock - Autocorrelation plot with lag = 3 TESLA Stock - Autocorrelation plot with lag = 3 We can now confirm that ARIMA is going to be a good model to be applied to this type of data (there is auto-correlation in the data). Finally, let's plot the stock price evolution over time. text

plt.plot(df["Date"], df["Close"])
plt.xticks(np.arange(0,1259, 200), df['Date'][0:1259:200])
plt.title("TESLA stock price over time")
plt.xlabel("time")
plt.ylabel("price")
plt.show()

4.2. Build the predictive ARIMA model Next, let's divide the data into a training (70 % ) and test (30%) set. For this tutorial we select the following ARIMA parameters: p=4, d=1 and q=0. text

train_data, test_data = df[0:int(len(df)*0.7)], df[int(len(df)*0.7):]

text

training_data = train_data['Close'].values
test_data = test_data['Close'].values

text

history = [x for x in training_data]
model_predictions = []
N_test_observations = len(test_data)

text

for time_point in range(N_test_observations):
    model = ARIMA(history, order=(4,1,0))
    model_fit = model.fit(disp=0)
    output = model_fit.forecast()
    yhat = output[0]
    model_predictions.append(yhat)
    true_test_value = test_data[time_point]
    history.append(true_test_value)

text

MSE_error = mean_squared_error(test_data, model_predictions)
print('Testing Mean Squared Error is {}'.format(MSE_error))

Summary of the code

Testing Mean Squared Error is 741.0594879572484

The MSE of the test set is quite large denoting that the precise prediction is a hard problem. However, this is the average squared value across all the test set predictions. Let's visualize the predictions to understand the performance of the model more. text

test_set_range = df[int(len(df)*0.7):].index

text

plt.plot(test_set_range, model_predictions, color='blue', marker='o', linestyle='dashed',label='Predicted Price')

text

plt.plot(test_set_range, test_data, color='red', label='Actual Price')

text

plt.title('TESLA Prices Prediction')
plt.xlabel('Date')
plt.ylabel('Prices')
plt.xticks(np.arange(881,1259,50), df.Date[881:1259:50])
plt.legend()
plt.show()

ARIMA model performance on the test set ARIMA model performance on the test set

Not so bad right?

Our ARIMA model results in appreciable results. This model offers a good prediction accuracy and to be relatively fast compared to other alternatives, in terms of training/fitting time and complexity. That's all folks ! Hope you liked this article!


If you're passionate about diving deeper into machine learning with Python and sklearn, I highly recommend checking out this book; it's a game-changer in breaking down complex topics into digestible insights.

Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques...


Stay tuned & support this effort

If you liked and found this article useful, follow me to be able to see all my new posts. Questions? Post them as a comment and I will reply as soon as possible. We offer our expertise through a platform, the "Data Science Hub" on Patreon (https://www.patreon.com/TheDataScienceHub). This hub is our way of providing you with bespoke consulting services and comprehensive responses to all your inquiries , ranging from Machine Learning to strategic data analytics planning.


My previous articles that you might also like:

LSTM Time-Series Forecasting: Predicting Stock Prices Using An LSTM Model

LSTM Time-Series Forecasting: Predicting Stock Prices Using An LSTM Model Time-Series Forecasting: Predicting Stock Prices Using Facebook's Prophet Model Time-Series Forecasting: Predicting Stock Prices Using Facebook's Prophet Model


References

[1] https://en.wikipedia.org/wiki/Autoregressive_integrated_moving_average


Other posts

The Best FREE Data Science Resources: FREE Books & Online Courses ROC Curve Explained using a COVID-19 hypothetical example: Binary & Multi-Class Classification... Support Vector Machines (SVM) clearly explained: A python tutorial for classification problems... PCA clearly explained - How, when, why to use it and feature importance: A guide in Python Everything you need to know about Min-Max normalization in Python How Scikit-Learn's StandardScaler works

Register Now to Continue Reading

Unlock Towards Data Science with a Free Account

All articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more. Register for freeSign in to your account


Written By

Serafeim Loukas, PhD

See all from Serafeim Loukas, PhD Data ScienceForecastingMachine LearningStock MarketTime Series Analysis Share This Article

Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program. Write for TDS

Related Articles

How to Build a Context Layer and a Company Brain

Machine Learning What it actually takes to turn a company's scattered knowledge into something an LLM can reliably use — and why the demo is 5% of the work. Tomer Mesika July 30, 202610 min read

The Westworld Blunder

Artificial Intelligence Why AI shouldn’t suffer, even if it acts like it does James O'Brien May 12, 202513 min read

Functions & DAGs: introducing Hamilton, a microframework for dataframe generation (& more)

Data Science Creating pandasdataframes is easy, but managing the codebase can be hard. Introduction Hamilton, a micro-framework for dataframe... Stefan Krawczyk March 9, 202220 min read

Ways To Handle Categorical Data Before Train ML Models With Implementation.

Machine Learning In my last blogs, I explained types of missing values and different ways to handle Continous and Categorical missing values with... Ganesh Dhasade September 9, 20207 min read

Automating Deep Learning: A Gentle Introduction to AutoKeras and Keras Tuner

Artificial Intelligence How to save time and boost your models with these two approachable AutoML libraries Himanshu Sharma July 15, 20254 min read

Visualizing Trends of Multivariate Data in R using ggplot2

Data Science How to simply visualize data with multiple dependent and independent variables. NASTARAN EMAMINEJAD August 26, 20208 min read

PyCaret Time Series Module Architecture Overview

Machine Learning Looking under the hood Nikhil Gupta November 15, 20215 min read

Partial Proportional Odd Model in R

Data Science Statistics in R Series Md Sohel Mahmood December 12, 20222 min read

Python args, kwargs, and All Other Ways to Pass Arguments to Your Function

Programming Expertly design your function parameters in 6 examples Mike Huls March 7, 20238 min read

Your home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals. Subscribe to Our NewsletterWrite For TDS•About•Advertise•Privacy Policy•Terms of Use © Insight Media Group, LLC 2026•The New Stack•roadmap.sh•Creator Network

Recommended Articles

Close