import pd and load data
import pandas as pd
# Load data from CSV files
products = pd.read_csv('[Link]')
suppliers = pd.read_csv('[Link]')
warehouses = pd.read_csv('[Link]')
inventory = pd.read_csv('[Link]')
orders = pd.read_csv('[Link]')
sales = pd.read_csv('[Link]')
demand_forecasting = pd.read_csv('[Link]')
# Display the first few rows of the sales data to check
print(demand_forecasting.head())
ForecastID ProductID WarehouseID ForecastDate PredictedDemand \
0 1 71 6 2024-07-16 146
1 2 75 9 2023-04-01 280
2 3 85 4 2022-12-30 138
3 4 37 3 2020-04-09 274
4 5 37 4 2024-03-31 230
ForecastAccuracy CreatedAt
0 80.15 2024-05-17 08:35:43
1 70.89 2021-09-06 06:57:38
2 79.88 2024-04-27 22:41:30
3 80.61 2024-10-09 13:08:28
4 82.58 2024-07-20 15:11:02
identify sales trend using EDA
import [Link] as plt
# Convert ’SaleDate’ column to datetime format
sales['SaleDate'] = pd.to_datetime(sales['SaleDate'])
# Group sales data by date to aggregate the quantities sold
daily_sales = [Link]('SaleDate')['QuantitySold'].sum().reset_index()
# Plot daily sales trends
[Link](figsize=(12, 6))
[Link](daily_sales['SaleDate'], daily_sales['QuantitySold'], label='Daily Sales', color='
[Link]('Daily Sales Trends Over Time')
1
[Link]('Date')
[Link]('Quantity Sold')
[Link]()
[Link]()
Analyze Inventory Levels
# Assuming the correct column name is ’Stock_Quantity’
inventory_summary = [Link]('ProductID')['QuantityInStock'].sum().reset_index()
# Merge with product names
inventory_summary = inventory_summary.merge(products[['ProductID', 'ProductName']], on='Pro
# Plot inventory levels
[Link](figsize=(12, 6))
[Link](inventory_summary['ProductName'], inventory_summary['QuantityInStock'], color='gree
[Link]('Inventory Levels by Product')
[Link]('Product')
[Link]('Stock Level')
[Link](rotation=90)
[Link]()
2
demand forcasting with arima
from [Link] import ARIMA
from [Link] import mean_absolute_error
# Split the data into training (80%) and testing (20%)
train_size = int(len(daily_sales) * 0.8)
train, test = daily_sales['QuantitySold'][:train_size], daily_sales['QuantitySold'][train_s
# Display the sizes of the training and testing datasets
print(f'Training Data Size: {len(train)}, Testing Data Size: {len(test)}')
Training Data Size: 78, Testing Data Size: 20
# Set up the ARIMA model with order (p, d, q)
model = ARIMA(train, order=(5, 1, 0)) # Adjust the parameters (p, d, q) as needed
model_fit = [Link]()
# Make predictions on the test set
predictions = model_fit.forecast(steps=len(test))
# Plot the actual vs predicted values
[Link](figsize=(12, 6))
[Link](daily_sales['SaleDate'][train_size:], test, label='Actual Sales', color='blue')
3
[Link](daily_sales['SaleDate'][train_size:], predictions, label='Predicted Sales', color=
[Link]('Actual vs Predicted Sales')
[Link]('Date')
[Link]('Quantity Sold')
[Link]()
[Link]()
# Calculate mean absolute error for evaluation
mae = mean_absolute_error(test, predictions)
print(f'Mean Absolute Error: {mae}')
Mean Absolute Error: 13.589566155284857
optimization
from [Link] import differential_evolution
# Define the objective function for inventory cost minimization
def inventory_cost(params):
reorder_point, safety_stock = params
holding_cost = 0.1 * daily_sales['QuantitySold'].mean() # Average holding cost
ordering_cost = 50 # Fixed ordering cost
stockout_cost = 20 # Cost per stockout
total_cost = (holding_cost * safety_stock) + (ordering_cost / (reorder_point + 1)) +
return total_cost
# Define bounds for reorder point and safety stock
bounds = [(10, 100), (20, 200)]
4
# Use Genetic Algorithm (Differential Evolution) to find the optimal parameters
result = differential_evolution(inventory_cost, bounds)
optimized_reorder_point, optimized_safety_stock = result.x
print(f'Optimized Reorder Point: {optimized_reorder_point}')
print(f'Optimized Safety Stock: {optimized_safety_stock}')
Optimized Reorder Point: 100.0
Optimized Safety Stock: 20.0
visualization
# Plot the optimized vs current reorder points and safety stocks
[Link](figsize=(12, 6))
[Link](['Current Reorder Point', 'Optimized Reorder Point'], [50, optimized_reorder_point]
[Link]('Comparison of Reorder Points')
[Link]('Quantity')
[Link]()
[Link](figsize=(12, 6))
[Link](['Current Safety Stock', 'Optimized Safety Stock'], [100, optimized_safety_stock],
[Link]('Comparison of Safety Stocks')
[Link]('Quantity')
[Link]()
5
comparison of different optimization algorithm
# cost function
def inventory_cost(params, sales_data):
reorder_point, safety_stock = params
holding_cost_per_unit = 0.1 # Average holding cost
ordering_cost_per_order = 50 # Fixed ordering cost
stockout_cost_per_unit = 20 # Cost per stockout
# Calculate the mean of the quantity sold
average_demand = [Link](sales_data['QuantitySold'])
# Calculate the total stockouts based on average demand
total_stockouts = [Link](0, average_demand - reorder_point - safety_stock)
# Calculate the total cost
total_cost = (
holding_cost_per_unit * safety_stock +
ordering_cost_per_order / (reorder_point + 1) +
stockout_cost_per_unit * total_stockouts
)
return total_cost
# Assuming that optimized values are already calculated for Flybird, ACO, and PSO
# For demonstration, dummy values are used here
optimized_reorder_point_flybird, optimized_safety_stock_flybird = 300, 100
optimized_reorder_point_aco, optimized_safety_stock_aco = 280, 90
optimized_reorder_point_pso, optimized_safety_stock_pso = 290, 95
6
# Dummy sales data
sales_data = [Link]({
'QuantitySold': [Link](50, 500, size=100)
})
# Calculate total costs for each optimized solution
flybird_cost = inventory_cost([optimized_reorder_point_flybird, optimized_safety_stock_flyb
aco_cost = inventory_cost([optimized_reorder_point_aco, optimized_safety_stock_aco], sales_
pso_cost = inventory_cost([optimized_reorder_point_pso, optimized_safety_stock_pso], sales_
# Collecting results for comparison
results = {
'Technique': ['Flybird', 'ACO', 'PSO'],
'Reorder Point': [optimized_reorder_point_flybird, optimized_reorder_point_aco, optimiz
'Safety Stock': [optimized_safety_stock_flybird, optimized_safety_stock_aco, optimized_
'Total Cost': [flybird_cost, aco_cost, pso_cost]
}
# Create a DataFrame to display the comparison
comparison_df = [Link](results)
# Plotting the comparison
fig, ax = [Link](3, 1, figsize=(10, 15))
# Bar plot for Total Cost
ax[0].bar(comparison_df['Technique'], comparison_df['Total Cost'], color=['blue', 'orange',
ax[0].set_title('Total Cost Comparison')
ax[0].set_ylabel('Total Cost ($)')
ax[0].set_xticks(comparison_df['Technique'])
# Bar plot for Reorder Points
ax[1].bar(comparison_df['Technique'], comparison_df['Reorder Point'], color=['blue', 'orang
ax[1].set_title('Reorder Point Comparison')
ax[1].set_ylabel('Reorder Point (Units)')
ax[1].set_xticks(comparison_df['Technique'])
# Bar plot for Safety Stock
ax[2].bar(comparison_df['Technique'], comparison_df['Safety Stock'], color=['blue', 'orange
ax[2].set_title('Safety Stock Comparison')
ax[2].set_ylabel('Safety Stock (Units)')
ax[2].set_xticks(comparison_df['Technique'])
# Display the plot
plt.tight_layout()
[Link]()
7
# Identify the optimal solution
optimal_technique = comparison_df.loc[comparison_df['Total Cost'].idxmin()]
# Print optimal solution
print("\nOptimal Solution:")
print(f"Technique: {optimal_technique['Technique']}")
print(f"Reorder Point: {optimal_technique['Reorder Point']}")
print(f"Safety Stock: {optimal_technique['Safety Stock']}")
print(f"Total Cost: {optimal_technique['Total Cost']}")
8
Optimal Solution:
Technique: ACO
9
Reorder Point: 280
Safety Stock: 90
Total Cost: 9.177935943060499
import [Link] as plt
import numpy as np
# Sample data
techniques = ['Flybird', 'Ant Colony', 'Particle Swarm']
total_costs = [flybird_cost, aco_cost, pso_cost]
reorder_points = [optimized_reorder_point_flybird, optimized_reorder_point_aco, optimized_r
safety_stocks = [optimized_safety_stock_flybird, optimized_safety_stock_aco, optimized_safe
# Bar Width
bar_width = 0.25
index = [Link](len(techniques))
# Create bars
[Link](index, total_costs, bar_width, label='Total Cost', color='b')
[Link](index + bar_width, reorder_points, bar_width, label='Reorder Point', color='g')
[Link](index + 2 * bar_width, safety_stocks, bar_width, label='Safety Stock', color='r')
# Add labels and title
[Link]('Optimization Techniques')
[Link]('Values')
[Link]('Comparison of Inventory Optimization Techniques')
[Link](index + bar_width, techniques)
[Link]()
# Show plot
plt.tight_layout()
[Link]()
10
import [Link] as plt
import numpy as np
# Define the metrics and their values
labels = [Link](['Total Cost', 'Reorder Point', 'Safety Stock'])
values_flybird = [Link]([flybird_cost, optimized_reorder_point_flybird, optimized_safety_
values_aco = [Link]([aco_cost, optimized_reorder_point_aco, optimized_safety_stock_aco])
values_pso = [Link]([pso_cost, optimized_reorder_point_pso, optimized_safety_stock_pso])
# Number of variables
num_vars = len(labels)
# Compute angle for each axis
angles = [Link](0, 2 * [Link], num_vars, endpoint=False).tolist()
# The plot is a circle, so we need to "complete the loop"
values_flybird = [Link]((values_flybird,[values_flybird[0]]))
values_aco = [Link]((values_aco,[values_aco[0]]))
values_pso = [Link]((values_pso,[values_pso[0]]))
angles += angles[:1]
# Create the radar chart
[Link](figsize=(8, 8), dpi=120)
11
ax = [Link](111, polar=True)
[Link](angles, values_flybird, color='blue', alpha=0.25)
[Link](angles, values_aco, color='green', alpha=0.25)
[Link](angles, values_pso, color='red', alpha=0.25)
ax.set_yticklabels([])
# Add labels
[Link](angles[:-1], labels)
[Link]('Comparison of Optimization Techniques')
[Link](['Flybird', 'Ant Colony', 'Particle Swarm'], loc='upper right')
# Show plot
[Link]()
12