-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmartstock.py
245 lines (206 loc) · 8.12 KB
/
smartstock.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# -*- coding: utf-8 -*-
"""SmartStock.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1MhfsNfM1s8yX1_TYYa3wm5qFxPcBXiNl
"""
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from sklearn.linear_model import LinearRegression
from typing import Dict, List, Optional
import json
import warnings
warnings.filterwarnings('ignore')
class InventoryManagementSystem:
def __init__(self):
"""Initialize the Inventory Management System with empty data structures"""
# Core inventory data
self.inventory = pd.DataFrame(columns=[
'product_id', 'product_name', 'category', 'quantity',
'unit_price', 'reorder_point', 'supplier_id', 'min_order_qty'
])
# Sales history
self.sales_history = pd.DataFrame(columns=[
'transaction_id', 'product_id', 'quantity', 'sale_date', 'sale_price'
])
# Supplier information
self.suppliers = pd.DataFrame(columns=[
'supplier_id', 'name', 'lead_time_days', 'reliability_score'
])
# Purchase orders
self.purchase_orders = pd.DataFrame(columns=[
'po_id', 'product_id', 'supplier_id', 'quantity',
'order_date', 'expected_delivery', 'status'
])
def add_product(self, product_data: Dict) -> bool:
"""
Add a new product to inventory
Args:
product_data (dict): Product information including name, category, etc.
Returns:
bool: Success status
"""
try:
new_product = pd.DataFrame([product_data])
self.inventory = pd.concat([self.inventory, new_product], ignore_index=True)
return True
except Exception as e:
print(f"Error adding product: {e}")
return False
def record_sale(self, sale_data: Dict) -> bool:
"""
Record a new sale transaction
Args:
sale_data (dict): Sale transaction details
Returns:
bool: Success status
"""
try:
# Record the sale
new_sale = pd.DataFrame([sale_data])
self.sales_history = pd.concat([self.sales_history, new_sale], ignore_index=True)
# Update inventory
product_id = sale_data['product_id']
quantity = sale_data['quantity']
self.inventory.loc[self.inventory['product_id'] == product_id, 'quantity'] -= quantity
# Check if reorder is needed
self._check_reorder_point(product_id)
return True
except Exception as e:
print(f"Error recording sale: {e}")
return False
def predict_demand(self, product_id: int, days_ahead: int = 30) -> float:
"""
Predict demand for a product using simple linear regression
Args:
product_id (int): Product identifier
days_ahead (int): Number of days to forecast
Returns:
float: Predicted demand
"""
try:
# Get historical sales data
product_sales = self.sales_history[
self.sales_history['product_id'] == product_id
].copy()
if len(product_sales) < 5: # Need minimum data points
return None
# Prepare data for prediction
product_sales['sale_date'] = pd.to_datetime(product_sales['sale_date'])
daily_sales = product_sales.groupby('sale_date')['quantity'].sum().reset_index()
# Create features (days since first sale)
first_date = daily_sales['sale_date'].min()
daily_sales['days_since_start'] = (daily_sales['sale_date'] - first_date).dt.days
# Train model
model = LinearRegression()
X = daily_sales['days_since_start'].values.reshape(-1, 1)
y = daily_sales['quantity'].values
model.fit(X, y)
# Predict future demand
future_days = np.array(range(
daily_sales['days_since_start'].max() + 1,
daily_sales['days_since_start'].max() + days_ahead + 1
)).reshape(-1, 1)
predictions = model.predict(future_days)
return max(0, predictions.mean()) # Ensure non-negative prediction
except Exception as e:
print(f"Error predicting demand: {e}")
return None
def _check_reorder_point(self, product_id: int) -> None:
"""
Check if product needs reordering and create purchase order if necessary
Args:
product_id (int): Product identifier
"""
try:
product = self.inventory[self.inventory['product_id'] == product_id].iloc[0]
if product['quantity'] <= product['reorder_point']:
# Calculate optimal order quantity
predicted_demand = self.predict_demand(product_id)
if predicted_demand is None:
order_quantity = product['min_order_qty']
else:
order_quantity = max(
product['min_order_qty'],
int(predicted_demand * 1.2) # 20% buffer
)
# Create purchase order
po_data = {
'po_id': len(self.purchase_orders) + 1,
'product_id': product_id,
'supplier_id': product['supplier_id'],
'quantity': order_quantity,
'order_date': datetime.now().strftime('%Y-%m-%d'),
'expected_delivery': (datetime.now() + timedelta(days=7)).strftime('%Y-%m-%d'),
'status': 'pending'
}
new_po = pd.DataFrame([po_data])
self.purchase_orders = pd.concat([self.purchase_orders, new_po], ignore_index=True)
except Exception as e:
print(f"Error checking reorder point: {e}")
def generate_report(self) -> Dict:
"""
Generate a summary report of inventory status
Returns:
dict: Summary statistics and alerts
"""
try:
report = {
'total_products': len(self.inventory),
'low_stock_items': len(self.inventory[
self.inventory['quantity'] <= self.inventory['reorder_point']
]),
'pending_orders': len(self.purchase_orders[
self.purchase_orders['status'] == 'pending'
]),
'total_inventory_value': (
self.inventory['quantity'] * self.inventory['unit_price']
).sum(),
'alerts': []
}
# Generate alerts for low stock items
low_stock = self.inventory[
self.inventory['quantity'] <= self.inventory['reorder_point']
]
for _, product in low_stock.iterrows():
report['alerts'].append(
f"Low stock alert: {product['product_name']} "
f"(Quantity: {product['quantity']})"
)
return report
except Exception as e:
print(f"Error generating report: {e}")
return None
# Example usage and demonstration
def demo_system():
# Initialize system
ims = InventoryManagementSystem()
# Add sample product
product = {
'product_id': 1,
'product_name': 'Sample Product',
'category': 'Electronics',
'quantity': 100,
'unit_price': 29.99,
'reorder_point': 20,
'supplier_id': 1,
'min_order_qty': 50
}
ims.add_product(product)
# Record some sample sales
for i in range(5):
sale = {
'transaction_id': i + 1,
'product_id': 1,
'quantity': 10,
'sale_date': (datetime.now() - timedelta(days=i)).strftime('%Y-%m-%d'),
'sale_price': 29.99
}
ims.record_sale(sale)
# Generate and print report
report = ims.generate_report()
print(json.dumps(report, indent=2))
return ims
if __name__ == "__main__":
demo_system()