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: usepip 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.