Write a python code that will analyse the datapoints i attach in a csv file, using various statistical approach to check what might be the relationship and also predict/forecast the potential trend of the primary series. Forecasting might be done using Models like ARIMA and LSTM
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Sure! Below is a Python script that performs the following tasks:
Data Loading and Preprocessing: Reads data from a CSV file and preprocesses it.
Exploratory Data Analysis (EDA): Analyzes the data to understand its structure and relationships.
Statistical Analysis: Checks for relationships using correlation and regression analysis.
Forecasting with ARIMA Model: Builds an ARIMA model to forecast the time series.
Forecasting with LSTM Model: Builds an LSTM neural network to forecast the time series.
Visualization: Plots the results for comparison.
Note: You'll need to adjust column names and parameters based on your actual data. Also, ensure all necessary libraries are installed.
python
# Import necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# Statistical libraries
from statsmodels.tsa.stattools import adfuller
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
import statsmodels.api as sm
from pmdarima.arima import auto_arima
# Machine Learning libraries
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM
# Ignore warnings
import warnings
warnings.filterwarnings('ignore')
# Load the data
data = pd.read_csv('your_data.csv', parse_dates=['Date'], index_col='Date')
print(data.head())
# If your date column is not named 'Date', adjust accordingly.
# Ensure 'Date' column is in datetime format and set as index.
# data['Date'] = pd.to_datetime(data['Date'])
# data.set_index('Date', inplace=True)
# Exploratory Data Analysis
print("\nData Summary:")
print(data.describe())
print("\nMissing Values:")
print(data.isnull().sum())
# Plotting the time series data
plt.figure(figsize=(14, 7))
plt.plot(data, label='Time Series Data')
plt.title('Time Series Data')
plt.xlabel('Date')
plt.ylabel('Value')
plt.legend()
plt.show()
# Correlation Matrix
if len(data.columns) > 1:
plt.figure(figsize=(10, 8))
sns.heatmap(data.corr(), annot=True, cmap='coolwarm')
plt.title('Correlation Matrix')
plt.show()
# Statistical Analysis - Check for stationarity
result = adfuller(data.iloc[:, 0]) # Assuming the primary series is the first column
print('ADF Statistic: %f' % result[0])
print('p-value: %f' % result[1])
# If data is not stationary, differencing
d = 0
if result[1] > 0.05:
d = 1
data_diff = data.diff().dropna()
result = adfuller(data_diff.iloc[:, 0])
print('\nAfter differencing:')
print('ADF Statistic: %f' % result[0])
print('p-value: %f' % result[1])
else:
data_diff = data.copy()
# Auto ARIMA to find optimal parameters
stepwise_model = auto_arima(data.iloc[:, 0], start_p=1, start_q=1,
max_p=3, max_q=3, m=12,
start_P=0, seasonal=False,
d=d, D=1, trace=True,
error_action='ignore',
suppress_warnings=True,
stepwise=True)
print(stepwise_model.summary())
# Split data into train and test sets
train_size = int(len(data) * 0.8)
train, test = data.iloc[:train_size], data.iloc[train_size:]
# ARIMA Model
model = sm.tsa.ARIMA(train.iloc[:, 0], order=stepwise_model.order)
model_fit = model.fit()
print(model_fit.summary())
# Forecast
forecast_arima = model_fit.forecast(steps=len(test))
forecast_arima = pd.Series(forecast_arima, index=test.index)
# Calculate RMSE
rmse_arima = np.sqrt(mean_squared_error(test.iloc[:, 0], forecast_arima))
print('ARIMA Model RMSE:', rmse_arima)
# Plotting ARIMA results
plt.figure(figsize=(14, 7))
plt.plot(train.index, train.iloc[:, 0], label='Train')
plt.plot(test.index, test.iloc[:, 0], label='Test')
plt.plot(forecast_arima.index, forecast_arima, label='ARIMA Forecast')
plt.title('ARIMA Forecast vs Actuals')
plt.xlabel('Date')
plt.ylabel('Value')
plt.legend()
plt.show()
# Prepare data for LSTM
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data)
# Create sequences
def create_sequences(data, seq_length):
x = []
y = []
for i in range(len(data) - seq_length):
x.append(data[i:(i+seq_length)])
y.append(data[i+seq_length])
return np.array(x), np.array(y)
seq_length = 10 # You can adjust this
x, y = create_sequences(scaled_data, seq_length)
# Split into train and test sets
train_size = int(len(x) * 0.8)
x_train, x_test = x[:train_size], x[train_size:]
y_train, y_test = y[:train_size], y[train_size:]
# Build LSTM Model
model_lstm = Sequential()
model_lstm.add(LSTM(50, activation='relu', input_shape=(seq_length, x.shape[2])))
model_lstm.add(Dense(1))
model_lstm.compile(optimizer='adam', loss='mse')
# Train the model
history = model_lstm.fit(x_train, y_train, epochs=20, batch_size=32, validation_data=(x_test, y_test))
# Forecast using LSTM
predictions = model_lstm.predict(x_test)
predictions = scaler.inverse_transform(predictions)
y_test_inv = scaler.inverse_transform(y_test)
# Calculate RMSE
rmse_lstm = np.sqrt(mean_squared_error(y_test_inv, predictions))
print('LSTM Model RMSE:', rmse_lstm)
# Plotting LSTM results
plt.figure(figsize=(14, 7))
plt.plot(data.index[-len(y_test_inv):], y_test_inv, label='Actual')
plt.plot(data.index[-len(predictions):], predictions, label='LSTM Forecast')
plt.title('LSTM Forecast vs Actuals')
plt.xlabel('Date')
plt.ylabel('Value')
plt.legend()
plt.show()
# Compare RMSE
print('ARIMA RMSE:', rmse_arima)
print('LSTM RMSE:', rmse_lstm)
Instructions:
Replace 'your_data.csv' with the path to your CSV file.
Ensure that the date column is correctly parsed and set as the index.
Adjust the column indexing data.iloc[:, 0] if your primary series is not the first column.
You might need to adjust the ARIMA parameters based on the data characteristics.
Modify the sequence length seq_length for LSTM as needed.
Adjust the number of epochs and batch size for LSTM training.
Install any missing libraries using pip install library_name.
Explanation:
Data Loading: Reads the CSV file and sets the date column as the index.
EDA: Provides summary statistics, checks for missing values, and plots the time series data.
Statistical Analysis: Calculates the correlation matrix and checks for stationarity using the Augmented Dickey-Fuller test.
ARIMA Model:
Uses auto_arima to find the optimal order of the ARIMA model.
Splits the data into training and testing sets.
Builds and fits the ARIMA model.
Forecasts future values and calculates RMSE.
LSTM Model:
Scales the data using MinMaxScaler.
Creates sequences for LSTM input.
Splits the data into training and testing sets.
Builds and trains the LSTM model.
Forecasts future values and calculates RMSE.
Visualization: Plots the forecasts from both ARIMA and LSTM models against the actual data.
Note: Time series forecasting can be complex, and the performance of models like ARIMA and LSTM greatly depends on the nature of the data and the tuning of model parameters. It's recommended to experiment with different parameters and models to achieve the best results.
Let me know if you need further assistance or explanations on any part of the code!