How to Perform Time Series Forecasting in Python

How to Perform Time Series Forecasting in Python

Introduction to Time Series Forecasting

Time series forecasting helps you predict future values using historical data. This technique is useful in many areas like finance, weather, and sales. For example, you might want to predict future stock prices or next month’s weather. In this article, we’ll show you how to perform time series forecasting in Python. We’ll start by creating some simple data for practice and then apply a forecasting model.

Creating Synthetic Data

To begin, let’s create synthetic data that we can use for forecasting. This data will include a trend, some seasonal patterns, and a bit of random noise to make it more realistic.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Set random seed for reproducibility
np.random.seed(0)

# Create a date range
date_range = pd.date_range(start='2021-01-01', end='2023-01-01', freq='M')

# Generate synthetic data with trend and seasonality
trend = np.linspace(0, 10, len(date_range))
seasonal_effect = 10 * np.sin(np.linspace(0, 2 * np.pi, len(date_range)))
noise = np.random.normal(loc=0, scale=1, size=len(date_range))
data = trend + seasonal_effect + noise

# Create a DataFrame
df = pd.DataFrame(data, index=date_range, columns=['Value'])

# Plot the synthetic data
plt.figure(figsize=(10, 6))
plt.plot(df.index, df['Value'], label='Synthetic Data')
plt.title('Synthetic Time Series Data')
plt.xlabel('Date')
plt.ylabel('Value')
plt.legend()
plt.show()

# Save the data to CSV for later use
df.to_csv('synthetic_time_series_data.csv')

Performing Time Series Forecasting

Now that we have our synthetic data, we can use it to make predictions. We’ll use a forecasting model called ARIMA, which is commonly used for this purpose. We’ll use Python’s statsmodels library to fit the model and predict future values.

import pandas as pd
from statsmodels.tsa.arima_model import ARIMA
import matplotlib.pyplot as plt

# Load the synthetic data
data = pd.read_csv('synthetic_time_series_data.csv', index_col='Date', parse_dates=True)
series = data['Value']

# Fit ARIMA model
model = ARIMA(series, order=(5, 1, 0)) # Adjust (p, d, q) as needed
model_fit = model.fit()

# Forecast future values
forecast = model_fit.forecast(steps=10)[0]

# Plot the results
plt.figure(figsize=(10, 6))
plt.plot(series, label='Observed Data')
plt.plot(pd.date_range(start=series.index[-1], periods=11, freq='M')[1:], forecast, label='Forecast', color='red')
plt.title('ARIMA Forecast')
plt.xlabel('Date')
plt.ylabel('Value')
plt.legend()
plt.show()

Conclusion

Time series forecasting lets you predict future values based on past data. In this guide, you learned how to create simple synthetic data and use an ARIMA model for forecasting in Python. By practicing with this data and model, you can get comfortable with forecasting techniques. As you become more familiar with these methods, you can experiment with different models and settings to improve your predictions. Mastering these skills will help you make better forecasts in various applications.

One Reply to “How to Perform Time Series Forecasting in Python”

  1. The code does not work. The Creating Synthetic Data appears to work but it creates a csv that doesn’t pull in the “Date” header. This causes an issue when getting to the Performing Time Series Forecasting code because the “Date” object isn’t available. Easy enough fix, open the file and add “Date” to the header. However, if you do this and then run the code, you get the laundry list of other errors such as “ValueError: x and y must have same first dimension, but have shapes (10,) and (1,)” or how ARIMA is deprecated.

Leave a Reply

Your email address will not be published. Required fields are marked *