Day 4 โ€“ Building a Python Forecasting Script for Sales Prediction #SalesForecastAI #LaravelPython #ProphetForecast #SalesPrediction #TimeSeriesAI


Now that we have clean CSV data, weโ€™ll build a Python script to forecast future sales using Facebook Prophet, a powerful tool for time-series prediction.


๐Ÿ Step 1: Install Python dependencies

Create a new virtual environment (optional):

python -m venv venv
source venv/bin/activate  # or venv\Scripts\activate on Windows

Install dependencies:

pip install pandas prophet matplotlib

If prophet fails to install, try:
pip install prophet --upgrade --no-cache-dir
On M1 Macs: use pip install prophet --no-binary :all:


๐Ÿ“ Step 2: Place CSV in working directory

Export the file from Laravel at:

http://localhost:8000/sales/export

Save it as sales_data.csv inside your Python folder.


๐Ÿ“Š Step 3: Create the forecasting script

Create forecast_sales.py:

import pandas as pd
from prophet import Prophet
import matplotlib.pyplot as plt

# Load and prepare data
df = pd.read_csv('sales_data.csv')
df = df.rename(columns={'Date': 'ds', 'TotalSales': 'y'})

# Create and train model
model = Prophet()
model.fit(df)

# Forecast next 30 days
future = model.make_future_dataframe(periods=30)
forecast = model.predict(future)

# Plot forecast
model.plot(forecast)
plt.title("30-Day Sales Forecast")
plt.xlabel("Date")
plt.ylabel("Sales")
plt.tight_layout()
plt.savefig('forecast_plot.png')
plt.show()

๐Ÿงช Step 4: Run the script

python forecast_sales.py

Youโ€™ll see a plot with:

  • Actual data (black dots)
  • Predicted sales (blue line)
  • Confidence intervals (shaded area)

The chart is also saved as forecast_plot.png.


โœ… Output example

| ds         | yhat   | yhat_lower | yhat_upper |
|------------|--------|------------|------------|
| 2024-06-11 | 132.44 | 110.25     | 154.22     |
| 2024-06-12 | 138.02 | 115.78     | 162.65     |
...

โœ… Up next (Day 5): weโ€™ll connect Laravel and Python using Artisan + ShellExec, so forecasts run directly from the Laravel app.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.