Sure! You can use time series forecasting methods to predict future spending based on the data you have. Below, I'll show you an example Python code that uses the ARIMA (AutoRegressive Integrated Moving Average) model. ARIMA is one of the common methods used for time series forecasting.
Before running the code, make sure you install the required libraries:
pip install pandas numpy statsmodels matplotlib
Python Code to Forecast Spend
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from sklearn.metrics import mean_squared_error
# Sample Input Data: Replace this with your actual data
data = {
'month': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
'year': [2022]*12,
'spend': [200, 220, 250, 300, 320, 310, 350, 370, 400, 410, 430, 450]
}
# Convert the data into a DataFrame
df = pd.DataFrame(data)
# Create a datetime index based on year and month
df['date'] = pd.to_datetime(df[['year', 'month']].assign(day=1))
df.set_index('date', inplace=True)
# Keep only the spend column
df = df[['spend']]
# Plot the data
plt.figure(figsize=(10, 6))
plt.plot(df, label="Spend Over Time")
plt.title("Spend Time Series")
plt.xlabel("Date")
plt.ylabel("Spend")
plt.legend()
plt.grid()
plt.show()
# Step 1: Differencing (to make the series stationary, if required)
from statsmodels.tsa.stattools import adfuller
# Check if the time series is stationary
result = adfuller(df['spend'])
print(f'ADF Statistic: {result[0]}')
print(f'p-value: {result[1]}')
if result[1] > 0.05:
print("The series is not stationary. Differencing is required.")
df['spend_diff'] = df['spend'].diff().dropna()
else:
print("The series is stationary. Differencing is not required.")
# Step 2: Plot ACF and PACF to determine ARIMA order
plot_acf(df['spend'].dropna())
plt.title('ACF Plot')
plt.show()
plot_pacf(df['spend'].dropna())
plt.title('PACF Plot')
plt.show()
# Step 3: Fit ARIMA Model
# Parameters (p, d, q) can be determined based on ACF/PACF or trial and error
model = ARIMA(df['spend'], order=(1, 1, 1)) # Example order; adjust (p, d, q) as necessary
model_fit = model.fit()
# Model Summary
print(model_fit.summary())
# Step 4: Make Forecasts
forecast_steps = 12 # Number of months to predict into the future
forecast = model_fit.get_forecast(steps=forecast_steps)
forecast_index = pd.date_range(start=df.index[-1] + pd.offsets.MonthBegin(), periods=forecast_steps, freq='MS')
forecast_df = pd.DataFrame({'Forecast': forecast.predicted_mean}, index=forecast_index)
# Plot Actual vs Forecast
plt.figure(figsize=(12, 6))
plt.plot(df.index, df['spend'], label='Actual Spend', color='blue')
plt.plot(forecast_index, forecast_df['Forecast'], label='Forecast Spend', color='orange')
plt.xlabel('Date')
plt.ylabel('Spend')
plt.title('Actual vs Forecasted Spend')
plt.legend()
plt.grid()
plt.show()
# Step 5: Evaluate the Model
# Split dataset into train and test to calculate performance metrics (e.g., RMSE)
df_train = df['spend'][:-forecast_steps]
df_test = df['spend'][-forecast_steps:]
model = ARIMA(df_train, order=(1, 1, 1))
model_fit = model.fit()
predictions = model_fit.forecast(steps=len(df_test)).predicted_mean
rmse = np.sqrt(mean_squared_error(df_test, predictions))
print(f"RMSE: {rmse}")
Key Notes:
-
Adjust ARIMA Order: Use the ACF and PACF plots to guide the choice of ARIMA parameters (p, d, q).
p: Lag order (from PACF)
d: Differencing order (to make the series stationary)
q: Moving average order (from ACF)
-
Dataset: Replace the sample data in the script with your actual dataset. Ensure the data is continuous in terms of time (no missing months/years).
-
Evaluation Metrics: Evaluate the model's performance using metrics like Root Mean Square Error (RMSE) by splitting the dataset into train and test sets.
-
Visualizations: The script includes visualizations to better understand the data (ACF/PACF plots, actual vs. forecast).
Let me know if you want a more specific implementation or help with your particular dataset!