"AI/ML Model Architecture With Python" & "A Journey into AI"
Offers an exploration
of Artificial Intelligence
"Do-it-Yourself"
Books for your library & Python Programs👇
In the end Python Programs
"AI/ML Model Architecture With Python" & "A Journey into AI"
Offers an exploration
of Artificial Intelligence
"Do-it-Yourself"
Books for your library & Python Programs👇
In the end Python Programs
"Do-it-Yourself"
Chapter 18
About the Chapter (Prototype: Sales Forecast)
#Python Program
import pandas as pd
# Historical sales data
historical_sales = {
'Branch': ['Delhi', 'Delhi', 'Bombay', 'Bombay', 'Delhi', 'Delhi', 'Bombay', 'Bombay'],
'Year': [2022, 2022, 2022, 2022, 2023, 2023, 2023, 2023],
'Product': ['A', 'B', 'A', 'B', 'A', 'B', 'A', 'B'],
'Sale': [6579.00, 12024.00, 5089.00, 28013.00, 8291.00, 20064.00, 15023.00, 17713.00]
}
# Create DataFrame from historical sales data
df = pd.DataFrame(historical_sales)
# Forecasting
forecast_years = [2024, 2025, 2026, 2027, 2028]
# Initialize an empty list to store forecasted sales data
forecasted_sales = []
# Iterate over forecast years
for year in forecast_years:
# Apply 25% growth to the previous year's sales rounded to two decimal places
growth_factor = 1.25 ** (year - 2023)
df['Forecasted Sale'] = (df['Sale'] * growth_factor).round(2)
df['Year'] = year # Update the year to the current forecast year
# Append forecasted sales for the current year
forecasted_sales.append(df.copy())
# Concatenate forecasted sales DataFrames
forecast_df = pd.concat(forecasted_sales)
# Display forecasted sales
print("Forecast Sales:")
print(forecast_df[['Branch', 'Year', 'Product', 'Forecasted Sale']])
#Result
Forecast Sales:
Branch Year Product Forecasted Sale
0 Delhi 2024 A 8223.75
1 Delhi 2024 B 15030.00
2 Bombay 2024 A 6361.25
3 Bombay 2024 B 35016.25
4 Delhi 2024 A 10363.75
5 Delhi 2024 B 25080.00
6 Bombay 2024 A 18778.75
7 Bombay 2024 B 22141.25
0 Delhi 2025 A 10279.69
1 Delhi 2025 B 18787.50
2 Bombay 2025 A 7951.56
3 Bombay 2025 B 43770.31
4 Delhi 2025 A 12954.69
5 Delhi 2025 B 31350.00
6 Bombay 2025 A 23473.44
7 Bombay 2025 B 27676.56
0 Delhi 2026 A 12849.61
1 Delhi 2026 B 23484.38
2 Bombay 2026 A 9939.45
3 Bombay 2026 B 54712.89
4 Delhi 2026 A 16193.36
5 Delhi 2026 B 39187.50
6 Bombay 2026 A 29341.80
7 Bombay 2026 B 34595.70
0 Delhi 2027 A 16062.01
1 Delhi 2027 B 29355.47
2 Bombay 2027 A 12424.32
3 Bombay 2027 B 68391.11
4 Delhi 2027 A 20241.70
5 Delhi 2027 B 48984.38
6 Bombay 2027 A 36677.25
7 Bombay 2027 B 43244.63
0 Delhi 2028 A 20077.51
1 Delhi 2028 B 36694.34
2 Bombay 2028 A 15530.40
3 Bombay 2028 B 85488.89
4 Delhi 2028 A 25302.12
5 Delhi 2028 B 61230.47
6 Bombay 2028 A 45846.56
7 Bombay 2028 B 54055.79
==================================================================================
#Python Program for Graph
#Python Program
import pandas as pd
import matplotlib.pyplot as plt
# Data provided
data = {
'Vendor': ['Vendor A', 'Vendor A', 'Vendor A', 'Vendor A', 'Vendor B', 'Vendor B', 'Vendor B', 'Vendor B',
'Vendor A', 'Vendor A', 'Vendor A', 'Vendor A', 'Vendor B', 'Vendor B', 'Vendor B', 'Vendor B',
'Vendor A', 'Vendor A', 'Vendor A', 'Vendor A', 'Vendor B', 'Vendor B', 'Vendor B', 'Vendor B'],
'Item': ['Item A', 'Item A', 'Item A', 'Item A', 'Item A', 'Item A', 'Item A', 'Item A',
'Item A', 'Item A', 'Item A', 'Item A', 'Item A', 'Item A', 'Item A', 'Item A',
'Item A', 'Item A', 'Item A', 'Item A', 'Item A', 'Item A', 'Item A', 'Item A'],
'Lead Time (Weeks)': [10, 12, 10, 15, 11, 10, 12, 16, 10, 12, 10, 15, 12, 10, 12, 16,
12, 11, 9, 14, 15, 11, 14, 15],
'Quarter': ['Q1', 'Q2', 'Q3', 'Q4', 'Q1', 'Q2', 'Q3', 'Q4',
'Q1', 'Q2', 'Q3', 'Q4', 'Q1', 'Q2', 'Q3', 'Q4',
'Q1', 'Q2', 'Q3', 'Q4', 'Q1', 'Q2', 'Q3', 'Q4'],
'Year': [2021]*8 + [2022]*8 + [2023]*8
}
# Creating DataFrame
df = pd.DataFrame(data)
# Grouping by Year, Vendor, and Item, calculating mean Lead Time
yearly_vendor_item_lead_time = df.groupby(['Year', 'Vendor', 'Item'])['Lead Time (Weeks)'].mean().unstack()
# Plotting
yearly_vendor_item_lead_time.plot(kind='bar', figsize=(12, 6), width=0.8)
plt.title('Lead Time by Vendor and Item Over Years')
plt.xlabel('Year')
plt.ylabel('Lead Time (Weeks)')
plt.xticks(rotation=45)
plt.legend(title='Item', bbox_to_anchor=(1.05, 1), loc='upper left')
plt.tight_layout()
plt.show()
==============================================================================================
# Data representing rates and lead times for Vendor A and Vendor B
vendor_data = {
'Vendor A': {
'rates': {
'2021': [1200.50, 1400.00, 1250.00, 1400.00],
'2022': [1400.50, 1500.00, 1400.00, 1450.00],
'2023': [1450.00, 1500.00, 1400.00, 1500.00]
},
'lead_times': [10, 12, 10, 15] # Lead times in weeks
},
'Vendor B': {
'rates': {
'2021': [1502.00, 1450.00, 1350.00, 1700.00],
'2022': [1510.00, 1470.00, 1900.00, 1800.00],
'2023': [1600.00, 1500.00, 1400.00, 1800.00]
},
'lead_times': [11, 10, 12, 16] # Lead times in weeks
}
}
# Calculate average rates for each vendor for Item A
average_rates = {}
for vendor, data in vendor_data.items():
all_rates = [rate for rates in data['rates'].values() for rate in rates]
average_rates[vendor] = sum(all_rates) / len(all_rates)
# Calculate average lead times for each vendor for Item A
average_lead_times = {}
for vendor, data in vendor_data.items():
average_lead_times[vendor] = sum(data['lead_times']) / len(data['lead_times'])
# Print the average rates and lead times for each vendor
print("Average Rates:")
for vendor, rate in average_rates.items():
print(f"{vendor}: ₹{rate:.2f}")
print("\nAverage Lead Times:")
for vendor, lead_time in average_lead_times.items():
print(f"{vendor}: {lead_time} weeks")
# Suggest the vendor based on rate and lead time
preferred_vendor = min(average_rates, key=average_rates.get)
print(f"\nBased on rate, Vendor A seems to be the preferable choice.")
# Check if there is a tie between vendors based on rates
# If there is a tie, suggest the vendor with the shorter lead time
for vendor, rate in average_rates.items():
if rate == average_rates[preferred_vendor] and average_lead_times[vendor] < average_lead_times[preferred_vendor]:
preferred_vendor = vendor
print(f"But Vendor B has a shorter lead time, so it might be worth considering it instead.")
print(f"\nTherefore, without any obligation, selecting {preferred_vendor} for Item A would be a reasonable choice.")
#Result
Average Rates:
Vendor A: ₹1404.25
Vendor B: ₹1581.83
Average Lead Times:
Vendor A: 11.75 weeks
Vendor B: 12.25 weeks
Based on rate, Vendor A seems to be the preferable choice.
Therefore, without any obligation, selecting Vendor A for Item A would be a reasonable choice.
"Do-it-Yourself"
Chapter 19
AI Model for Purchase Process (Organization and Vendor)
#Python Program
def find_minimum_machine_time(machine_data):
# Initialize a dictionary to store minimum machine times for each item
minimum_machine_time = {}
# Iterate over each item and its corresponding machine data
for item, machines in machine_data.items():
min_time = float('inf') # Set initial minimum time to infinity
selected_machine = None # Initialize selected machine to None
# Iterate over machines for the current item
for machine in machines:
# Check if the machine is free
if machine['Machine Free'] == 'Yes' and machine['Machine Time'] < min_time:
min_time = machine['Machine Time']
selected_machine = machine['M/C']
# If a free machine is found, store the minimum time and the selected machine
if selected_machine:
minimum_machine_time[item] = {'M/C': selected_machine, 'Machine Time': min_time}
return minimum_machine_time
def main():
# Define the machine data
machine_data = {
'a1': [
{'M/C': 'M/C-1', 'Machine Time': 1.50, 'Machine Free': 'Yes'},
{'M/C': 'M/C-2', 'Machine Time': 1.00, 'Machine Free': 'Yes'},
{'M/C': 'M/C-3', 'Machine Time': 2.00, 'Machine Free': 'Yes'},
{'M/C': 'M/C-4', 'Machine Time': 0.75, 'Machine Free': 'No'}
],
'a2': [
{'M/C': 'M/C-9', 'Machine Time': 2.00, 'Machine Free': 'Yes'},
{'M/C': 'NC M/C 5', 'Machine Time': 0.50, 'Machine Free': 'Yes'},
{'M/C': 'NC M/C 6', 'Machine Time': 0.50, 'Machine Free': 'Yes'},
{'M/C': 'NC M/C 7', 'Machine Time': 0.50, 'Machine Free': 'Yes'},
{'M/C': 'NC M/C 8', 'Machine Time': 0.50, 'Machine Free': 'Yes'},
{'M/C': 'NC M/C 9', 'Machine Time': 0.50, 'Machine Free': 'Yes'},
{'M/C': 'NC M/C 10', 'Machine Time': 0.40, 'Machine Free': 'Yes'}
]
}
# Find the minimum machine time for each item
minimum_machine_time = find_minimum_machine_time(machine_data)
# Print the result
for item, data in minimum_machine_time.items():
print(f"Item: {item}, M/C: {data['M/C']}, Machine Time: {data['Machine Time']}")
if __name__ == "__main__":
main()
#Result:
Item: a1, M/C: M/C-2, Machine Time: 1.0
Item: a2, M/C: NC M/C 10, Machine Time: 0.4
Do-it-Yourself”
Chapter – 20
Based on the Client's Invoice from AI Engine with Audit
#Python Program
import datetime
# Sample data
data = [
["A", "Dl/234/99", "Friday, 1 March, 2024", 34567.98, 30],
["A", "Dl/234/198", "Tuesday, 5 March, 2024", 765678.00, 30],
["A", "Dl/234/199", "Sunday, 5 March, 2024", 565557.00, 45],
["B", "Dl/234/200", "Friday, 1 March, 2024", 44567.00, 90],
["B", "Dl/234/205", "Tuesday, 5 March, 2024", 865678.00, 30],
["B", "Dl/234/301", "Sunday, 5 March, 2024", 765557.00, 45],
]
# Define a function to calculate the payment available date
def calculate_payment_date(invoice_date, credit_days):
invoice_date_obj = datetime.datetime.strptime(invoice_date, "%A, %d %B, %Y")
payment_date = invoice_date_obj + datetime.timedelta(days=credit_days)
return payment_date.strftime("%A, %d %B, %Y")
# Process data and calculate payment dates
processed_data = []
for row in data:
client, invoice_no, invoice_date_str, invoice_amount, credit_days = row
payment_date = calculate_payment_date(invoice_date_str, credit_days)
processed_data.append([client, invoice_no, invoice_date_str, invoice_amount, credit_days, payment_date, invoice_amount])
# Print table header
print("Client, Invoice No, Invoice Date, Invoice Amount (INR), Credit Days, Payment Available Date, Invoice Amount (Calculated)")
# Print data in table format
for row in processed_data:
print(", ".join(map(str, row)))
#Result:
Client, Invoice No, Invoice Date, Invoice Amount (INR), Credit Days, Payment Available Date, Invoice Amount (Calculated)
A, Dl/234/99, Friday, 1 March, 2024, 34567.98, 30, Sunday, 31 March, 2024, 34567.98
A, Dl/234/198, Tuesday, 5 March, 2024, 765678.0, 30, Thursday, 04 April, 2024, 765678.0
A, Dl/234/199, Sunday, 5 March, 2024, 565557.0, 45, Friday, 19 April, 2024, 565557.0
B, Dl/234/200, Friday, 1 March, 2024, 44567.0, 90, Thursday, 30 May, 2024, 44567.0
B, Dl/234/205, Tuesday, 5 March, 2024, 865678.0, 30, Thursday, 04 April, 2024, 865678.0
B, Dl/234/301, Sunday, 5 March, 2024, 765557.0, 45, Friday, 19 April, 2024, 765557.0
#Python Program (Data in Table)
import pandas as pd
# Create a list of data
data = [
["A", "Dl/234/99", "Friday, 1 March, 2024", 34567.98, 30, "Sunday, 31 March, 2024", 34567.98],
["A", "Dl/234/198", "Tuesday, 5 March, 2024", 765678.0, 30, "Thursday, 04 April, 2024", 765678.0],
["A", "Dl/234/199", "Sunday, 5 March, 2024", 565557.0, 45, "Friday, 19 April, 2024", 565557.0],
["B", "Dl/234/200", "Friday, 1 March, 2024", 44567.0, 90, "Thursday, 30 May, 2024", 44567.0],
["B", "Dl/234/205", "Tuesday, 5 March, 2024", 865678.0, 30, "Thursday, 04 April, 2024", 865678.0],
["B", "Dl/234/301", "Sunday, 5 March, 2024", 765557.0, 45, "Friday, 19 April, 2024", 765557.0],
]
# Define the column names
cols = ["Client", "Invoice No", "Invoice Date", "Invoice Amount (INR)", "Credit Days", "Payment Available Date", "Invoice Amount (Calculated)"]
# Create the pandas dataframe
df = pd.DataFrame(data, columns=cols)
# Print the dataframe
print(df.to_string())
====================================================
#Python Program
import datetime
# Sample data
data = [
["A", "Dl/234/99", "Friday, 1 March, 2024", 34567.98, 30],
["A", "Dl/234/198", "Tuesday, 5 March, 2024", 765678.00, 30],
["A", "Dl/234/199", "Sunday, 5 March, 2024", 565557.00, 45],
["B", "Dl/234/200", "Friday, 1 March, 2024", 44567.00, 90],
["B", "Dl/234/205", "Tuesday, 5 March, 2024", 865678.00, 30],
["B", "Dl/234/301", "Sunday, 5 March, 2024", 765557.00, 45],
]
# Define a function to calculate the payment available date
def calculate_payment_date(invoice_date, credit_days):
invoice_date_obj = datetime.datetime.strptime(invoice_date, "%A, %d %B, %Y")
payment_date = invoice_date_obj + datetime.timedelta(days=credit_days)
return payment_date.strftime("%A, %d %B, %Y")
# Process data and calculate payment dates
processed_data = []
for row in data:
client, invoice_no, invoice_date_str, invoice_amount, credit_days = row
payment_date = calculate_payment_date(invoice_date_str, credit_days)
processed_data.append([client, invoice_no, invoice_date_str, invoice_amount, credit_days, payment_date, invoice_amount])
# Calculate Invoice Amount with Interest (assuming interest rate is 0% for simplicity)
for row in processed_data:
row.append(row[3]) # Append invoice amount as invoice amount with interest (0% interest)
# Group and calculate totals by payment date
payment_date_totals = {}
for row in processed_data:
payment_date = row[5]
invoice_amount = row[3]
if payment_date in payment_date_totals:
payment_date_totals[payment_date]["total_invoice_amount"] += invoice_amount
else:
payment_date_totals[payment_date] = {"total_invoice_amount": invoice_amount, "count": 1}
# Print table header
print("Payment Available Date, Total Payment Available Date (INR), Invoice Count")
# Print payment date wise totals
for payment_date, totals in payment_date_totals.items():
total_invoice_amount = totals["total_invoice_amount"]
count = totals["count"]
print(f"{payment_date}, {total_invoice_amount:.2f}, {count}")
#Result
Payment Available Date, Total Payment Available Date (INR), Invoice Count
Sunday, 31 March, 2024, 34567.98, 1
Thursday, 04 April, 2024, 1631356.00, 1
Friday, 19 April, 2024, 1331114.00, 1
Thursday, 30 May, 2024, 44567.00, 1
===================================================
#Python Program
import matplotlib.pyplot as plt
import matplotlib.colors as colors
# Provided data
data = [
["Sunday, 31 March, 2024", 34567.98, 1],
["Thursday, 04 April, 2024", 1631356.00, 2],
["Friday, 19 April, 2024", 1331114.00, 2],
["Thursday, 30 May, 2024", 44567.00, 1],
]
# Extract data for plotting
dates = [row[0] for row in data]
total_amounts = [row[1] for row in data]
invoice_counts = [row[2] for row in data]
# Create a colormap for a light color scheme
cmap = colors.LinearSegmentedColormap.from_list("", ["lightblue", "lightgreen"])
# Create a bar chart
plt.figure(figsize=(10, 6))
plt.bar(dates, total_amounts, color=cmap(0.5), ec='k', lw=1) # Use colormap for light blue
plt.xlabel('Payment Available Date')
plt.ylabel('Total Invoice Amount (INR)')
plt.title('Payment Available Date vs Total Invoice Amount (Light Colors)')
plt.xticks(rotation=45, ha='right') # Rotate x-axis labels for better readability
# Create a secondary y-axis for invoice count
plt.twinx()
plt.plot(dates, invoice_counts, marker='o', linestyle='-', color='coral', label='Invoice Count')
plt.ylabel('Invoice Count', color='coral')
# Show legend
plt.legend()
# Show the chart with a light grid
plt.grid(True, which='both', linestyle='--', linewidth=0.5, color='lightgray')
plt.tight_layout()
plt.show()
=================================================================
"Do-it-Yourself"
Chapter 21
AI - Engine for BOM and PPC (Production Planning and Control)
#Python Program
class AssemblyItem:
def __init__(self, assembly, level_1_item, unit_1, quantity_1, level_2_item, quantity_2, unit_2):
self.assembly = assembly
self.level_1_item = level_1_item
self.unit_1 = unit_1
self.quantity_1 = quantity_1
self.level_2_item = level_2_item
self.quantity_2 = quantity_2
self.unit_2 = unit_2
def __str__(self):
return f"{self.assembly}\t{self.level_1_item}\t{self.unit_1}\t{self.quantity_1:.2f}\t{self.level_2_item}\t{self.quantity_2:.2f}\t{self.unit_2}"
def generate_assembly_structure(assembly, quantity):
assembly_items = [
AssemblyItem('A', 'a1', 'Number', 18.00, 'aa1', 5.00, 'Kg'),
AssemblyItem('A', 'a1', 'Number', 0.00, 'bb1', 6.00, 'Number'),
AssemblyItem('A', 'a1', 'Number', 0.00, 'cc1', 8.00, 'Kg'),
AssemblyItem('A', 'a2', 'Number', 19.00, 'aa2', 18.00, 'Number'),
AssemblyItem('A', 'a2', 'Number', 0.00, 'bb2', 5.00, 'Kg')
]
print("Assembly\tLevel 1 Item\tUnit of Measurement 1\tQuantity Required for one Assembly\tLevel 2 Item\tQuantity Required for one Sub Assembly\tUnit of Measurement 2")
for item in assembly_items:
if item.assembly == assembly:
item.quantity_1 *= quantity
item.quantity_2 *= quantity
print(item)
generate_assembly_structure('A', 50)
Result:
Assembly Itemlevel 1 UOM 1 Quantity level 1 Quantity level2 UOM level 2
A a1 Number 900.00 aa1 250.00 Kg
A a1 Number 0.00 bb1 300.00 Number
A a1 Number 0.00 cc1 400.00 Kg
A a2 Number 950.00 aa2 900.00 Number
A a2 Number 0.00 bb2 250.00 Kg
======================================================================
#Python Program
data = [
["A", "a1", 900, "S1", 2900, 11],
["A", "a1", 900, "S2", 3100, 14],
["A", "a1", 900, "S3", 2700, 10],
["A", "a1", 900, "S4", 3100, 11],
["A", "a1", 900, "S5", 2800, 12],
["A", "a2", 950, "S1", 1800, 10],
["A", "a2", 950, "S3", 1900, 11],
["A", "a2", 950, "S4", 1700, 12],
["A", "a2", 950, "S5", 1400, 15],
["A", "a2", 950, "S6", 1200, 18]
]
# Dictionary to store total costs for each item level 1 and vendor
total_costs = {}
# Calculate total cost for each combination of item level 1 and vendor
for entry in data:
item = entry[1]
vendor = entry[3]
rate_per_unit = entry[4]
quantity = entry[2]
total_cost = rate_per_unit * quantity
if (item, vendor) in total_costs:
total_costs[(item, vendor)] += total_cost
else:
total_costs[(item, vendor)] = total_cost
# Find the minimum total cost for each item level 1
min_total_costs = {}
for key, value in total_costs.items():
item = key[0]
cost = value
if item in min_total_costs:
if cost < min_total_costs[item][0]:
min_total_costs[item] = (cost, key[1])
else:
min_total_costs[item] = (cost, key[1])
# Print the selected vendor for each item level 1
for item, (cost, vendor) in min_total_costs.items():
print(f"For Item Level 1 '{item}', select Vendor '{vendor}' with total cost {cost}.")
#Result
For Item Level 1 'a1', select Vendor 'S3' with total cost 2430000.
For Item Level 1 'a2', select Vendor 'S6' with total cost 1140000.
=========================================
#Python Program
from datetime import datetime, timedelta
# Define the data
bom_data = [
("A", "a1", 900, "S1", 2900, 11),
("A", "a1", 900, "S2", 3100, 14),
("A", "a1", 900, "S3", 2700, 10),
("A", "a1", 900, "S4", 3100, 11),
("A", "a1", 900, "S5", 2800, 12),
("A", "a2", 950, "S1", 1800, 10),
("A", "a2", 950, "S3", 1900, 11),
("A", "a2", 950, "S4", 1700, 12),
("A", "a2", 950, "S5", 1400, 15),
("A", "a2", 950, "S6", 1200, 18)
]
# Function to calculate delivery date
def calculate_delivery_date(lead_time):
today = datetime.now()
delivery_date = today + timedelta(weeks=lead_time)
return delivery_date.strftime("%Y-%m-%d")
# Selecting vendor for each item
def select_vendor_item_wise(item):
selected_vendor = None
min_lead_time = float('inf')
for assembly, item_code, quantity, vendor, rate, lead_time in bom_data:
if item_code == item and lead_time < min_lead_time:
min_lead_time = lead_time
selected_vendor = (assembly, item_code, quantity, vendor, rate, lead_time)
return selected_vendor
# Main function
def main():
items = set(item[1] for item in bom_data)
for item in items:
vendor = select_vendor_item_wise(item)
if vendor:
print(f"Item: {vendor[1]}")
print("Selected Vendor: ", vendor[3])
print("Delivery Date: ", calculate_delivery_date(vendor[5]))
print("Lead Time: ", vendor[5], " weeks")
print()
if __name__ == "__main__":
main()
#Result
Item: a2
Selected Vendor: S1
Delivery Date: 2024-06-14
Lead Time: 10 weeks
Item: a1
Selected Vendor: S3
Delivery Date: 2024-06-14
Lead Time: 10 weeks
======================================================================
#Python Program
def generate_bom_email(bom_data, target_delivery_date, confirmation_date):
"""
Generates an email body with BOM information
Args:
bom_data (list): List of tuples containing BOM data (assembly, item_code, quantity, vendor, rate, lead_time)
target_delivery_date (str): Target delivery date for materials (YYYY-MM-DD)
confirmation_date (str): Date by which delivery date confirmation is needed (YYYY-MM-DD)
Returns:
str: Email body containing BOM information
"""
email_body = """Dear [Raw Material and Component Store Manager name],
This letter serves as an official request for materials and components needed for early production. To ensure a timely launch, we require the following items as soon as possible:
**Bill of Materials (BOM) Information:**
"""
# Build BOM table within email body
email_body += "**Item | Quantity | Vendor | Lead Time (weeks)**\n"
email_body += "-" * 50 + "\n"
for assembly, item_code, quantity, vendor, rate, lead_time in bom_data:
email_body += f"{item_code} | {quantity} | {vendor} | {lead_time}\n"
email_body += """
**Focus on Shortest Lead Times:**
We have prioritized vendors with the shortest lead times to expedite production.
**Delivery Timeline:**
To meet our production schedule, we require all materials and components to be delivered by {target_delivery_date}.
**Production Planning:**
Knowing the confirmed delivery dates for these items will be crucial for our production planning team. This will allow them to schedule production activities efficiently and avoid any delays.
**Sales and Inventory Planning:**
Confirmation of delivery dates will also be used to update our sales and inventory planning systems. This ensures we can accurately communicate availability to customers and avoid overselling products.
**Action Required:**
* Please review the BOM information above and prioritize processing orders for the listed items with the shortest lead times.
* Kindly provide a confirmation email with estimated delivery dates for each item by {confirmation_date}.
**Next Steps:**
Upon receiving confirmation of delivery dates, we will finalize the production schedule and provide further updates.
We appreciate prompt attention to this urgent matter. Please don't hesitate to contact me at [ Phone Number] or [ Email Address] if you have any questions or require further clarification.
Thank you for cooperation in ensuring a successful early production launch.
Sincerely,
[ Name]
"""
return email_body
# Example usage (replace with actual BOM data)
bom_data = [
("A", "a1", 900, "S1", 2900, 11),
("A", "a2", 950, "S3", 1900, 10),
]
target_delivery_date = "2024-05-31"
confirmation_date = "2024-04-10"
email_content = generate_bom_email(bom_data, target_delivery_date, confirmation_date)
# Use the generated email_content in email sending process (not included here)
print(email_content)
#Result
Dear [Raw Material and Component Store Manager name],
This letter serves as an official request for materials and components needed for early production. To ensure a timely launch, we require the following items as soon as possible:
**Bill of Materials (BOM) Information:**
**Item | Quantity | Vendor | Lead Time (weeks)**
--------------------------------------------------
a1 | 900 | S1 | 11
a2 | 950 | S3 | 10
**Focus on Shortest Lead Times:**
We have prioritized vendors with the shortest lead times to expedite production.
**Delivery Timeline:**
To meet our production schedule, we require all materials and components to be delivered by {target_delivery_date}.
**Production Planning:**
Knowing the confirmed delivery dates for these items will be crucial for our production planning team. This will allow them to schedule production activities efficiently and avoid any delays.
**Sales and Inventory Planning:**
Confirmation of delivery dates will also be used to update our sales and inventory planning systems. This ensures we can accurately communicate availability to customers and avoid overselling products.
**Action Required:**
* Please review the BOM information above and prioritize processing orders for the listed items with the shortest lead times.
* Kindly provide a confirmation email with estimated delivery dates for each item by {confirmation_date}.
**Next Steps:**
Upon receiving confirmation of delivery dates, we will finalize the production schedule and provide further updates.
We appreciate prompt attention to this urgent matter. Please don't hesitate to contact me at [ Phone Number] or [ Email Address] if you have any questions or require further clarification.
Thank you for cooperation in ensuring a successful early production launch.
Sincerely,
[ Name]
=========================================================================
#Result from the Above Python Program
def generate_bom_email(bom_data, target_delivery_date, confirmation_date):
"""
Generates an email body with BOM information
Args:
bom_data (list): List of tuples containing BOM data (assembly, item_code, quantity, vendor, rate, lead_time)
target_delivery_date (str): Target delivery date for materials (YYYY-MM-DD)
confirmation_date (str): Date by which delivery date confirmation is needed (YYYY-MM-DD)
Returns:
str: Email body containing BOM information
"""
email_body = """Dear [Raw Material and Component Store Manager name],
This letter serves as an official request for materials and components needed for early production. To ensure a timely launch, we require the following items as soon as possible:
**Bill of Materials (BOM) Information:**
"""
# Build BOM table within email body
email_body += "**Item | Quantity | Vendor | Lead Time (weeks)**\n"
email_body += "-" * 50 + "\n"
for assembly, item_code, quantity, vendor, rate, lead_time in bom_data:
email_body += f"{item_code} | {quantity} | {vendor} | {lead_time}\n"
email_body += """
**Focus on Shortest Lead Times:**
We have prioritized vendors with the shortest lead times to expedite production.
**Delivery Timeline:**
To meet our production schedule, we require all materials and components to be delivered by {target_delivery_date}.
**Production Planning:**
Knowing the confirmed delivery dates for these items will be crucial for our production planning team. This will allow them to schedule production activities efficiently and avoid any delays.
**Sales and Inventory Planning:**
Confirmation of delivery dates will also be used to update our sales and inventory planning systems. This ensures we can accurately communicate availability to customers and avoid overselling products.
**Action Required:**
* Please review the BOM information above and prioritize processing orders for the listed items with the shortest lead times.
* Kindly provide a confirmation email with estimated delivery dates for each item by {confirmation_date}.
**Next Steps:**
Upon receiving confirmation of delivery dates, we will finalize the production schedule and provide further updates.
We appreciate prompt attention to this urgent matter. Please don't hesitate to contact me at [ Phone Number] or [ Email Address] if you have any questions or require further clarification.
Thank you for cooperation in ensuring a successful early production launch.
Sincerely,
[ Name]
"""
return email_body
# Example usage (replace with actual BOM data)
bom_data = [
("A", "a1", 900, "S1", 2900, 11),
("A", "a2", 950, "S3", 1900, 10),
]
target_delivery_date = "2024-05-31"
confirmation_date = "2024-04-10"
email_content = generate_bom_email(bom_data, target_delivery_date, confirmation_date)
# Use the generated email_content in email sending process (not included here)
print(email_content)
===============================================================
#Python Progran
from datetime import datetime, timedelta
# Define the data
payment_data = [
("A", "a1", 900, "S3", 2700.00, 10, 2430000.00, "06-06-2024", 30),
("A", "a2", 950, "S1", 1800.00, 10, 1710000.00, "06-06-2024", 40)
]
# Function to calculate payment date
def calculate_payment_date(supply_date, credit_period):
supply_date = datetime.strptime(supply_date, "%d-%m-%Y")
payment_date = supply_date + timedelta(days=credit_period)
return payment_date.strftime("%d-%m-%Y")
# Main function
def main():
print("Vendor Payment Details:")
for assembly, item, quantity, vendor, rate, lead_time, order_amount, supply_date, credit_period in payment_data:
payment_date = calculate_payment_date(supply_date, credit_period)
print(f"Assembly: {assembly}, Item: {item}")
print(f"Quantity: {quantity}, Vendor/Supplier: {vendor}")
print(f"Rate Per Unit: {rate}, Lead time weeks: {lead_time}")
print(f"Order Amount: {order_amount}")
print("Supply Date:", supply_date)
print("Credit Period (Days):", credit_period)
print("Payment Date:", payment_date)
print()
if __name__ == "__main__":
main()
#Result
Vendor Payment Details:
Assembly: A, Item: a1
Quantity: 900, Vendor/Supplier: S3
Rate Per Unit: 2700.0, Lead time weeks: 10
Order Amount: 2430000.0
Supply Date: 06-06-2024
Credit Period (Days): 30
Payment Date: 06-07-2024
Assembly: A, Item: a2
Quantity: 950, Vendor/Supplier: S1
Rate Per Unit: 1800.0, Lead time weeks: 10
Order Amount: 1710000.0
Supply Date: 06-06-2024
Credit Period (Days): 40
Payment Date: 16-07-2024
============================================================================================
#Python Program
from datetime import datetime, timedelta
# Define the data
payment_data = [
("A", "a1", 900, "S3", 2700.00, 10, 2430000.00, "06-06-2024", 30),
("A", "a2", 950, "S1", 1800.00, 10, 1710000.00, "06-06-2024", 40)
]
# Function to calculate payment date
def calculate_payment_date(supply_date, credit_period):
supply_date = datetime.strptime(supply_date, "%d-%m-%Y")
payment_date = supply_date + timedelta(days=credit_period)
return payment_date.strftime("%d-%m-%Y")
# Main function to calculate cash flow for payment dates
def calculate_cash_flow(payment_data):
cash_flow = {}
for assembly, item, quantity, vendor, rate, lead_time, order_amount, supply_date, credit_period in payment_data:
payment_date = calculate_payment_date(supply_date, credit_period)
if payment_date not in cash_flow:
cash_flow[payment_date] = []
cash_flow[payment_date].append((vendor, order_amount))
return cash_flow
# Main function to print cash flow for payment dates
def main():
cash_flow = calculate_cash_flow(payment_data)
print("Cash Flow for Payment Dates:")
for payment_date, transactions in cash_flow.items():
print(f"Payment Date: {payment_date}")
for vendor, amount in transactions:
print(f"Vendor: {vendor}, Amount: {amount}")
print()
if __name__ == "__main__":
main()
#Result
Cash Flow for Payment Dates:
Payment Date: 06-07-2024
Vendor: S3, Amount: 2430000.0
Payment Date: 16-07-2024
Vendor: S1, Amount: 1710000.0
===================================================================
#Python Program for Graph
import matplotlib.pyplot as plt
# Cash flow data with formatted amounts
cash_flow_data = [
{"Payment Date": "06-07-2024", "Amount": 2430000.0},
{"Payment Date": "16-07-2024", "Amount": 1710000.0},
]
# Extract payment dates and amounts
payment_dates = [item["Payment Date"] for item in cash_flow_data]
amounts = [item["Amount"] for item in cash_flow_data]
# Create a bar graph
plt.figure(figsize=(10, 6)) # Set figure size
plt.bar(payment_dates, amounts, color='red') # Set bar color to red
# Customize the plot
plt.xlabel("Payment Date")
plt.ylabel("Amount (₹)")
plt.title("Cash Flow for Payment Dates")
plt.xticks(rotation=45, ha='right') # Rotate x-axis labels for better readability
plt.grid(axis='y', linestyle='--', alpha=0.6) # Add grid lines
# Display the plot
plt.tight_layout()
plt.show()
======================================================================
#Python Program
def find_minimum_machine_time(machine_data):
# Initialize a dictionary to store minimum machine times for each item
minimum_machine_time = {}
# Iterate over each item and its corresponding machine data
for item, machines in machine_data.items():
min_time = float('inf') # Set initial minimum time to infinity
selected_machine = None # Initialize selected machine to None
# Iterate over machines for the current item
for machine in machines:
# Check if the machine is free
if machine['Machine Free'] == 'Yes' and machine['Machine Time'] < min_time:
min_time = machine['Machine Time']
selected_machine = machine['M/C']
# If a free machine is found, store the minimum time and the selected machine
if selected_machine:
minimum_machine_time[item] = {'M/C': selected_machine, 'Machine Time': min_time}
return minimum_machine_time
def main():
# Define the machine data
machine_data = {
'a1': [
{'M/C': 'M/C-1', 'Machine Time': 1.50, 'Machine Free': 'Yes'},
{'M/C': 'M/C-2', 'Machine Time': 1.00, 'Machine Free': 'Yes'},
{'M/C': 'M/C-3', 'Machine Time': 2.00, 'Machine Free': 'Yes'},
{'M/C': 'M/C-4', 'Machine Time': 0.75, 'Machine Free': 'No'}
],
'a2': [
{'M/C': 'M/C-9', 'Machine Time': 2.00, 'Machine Free': 'Yes'},
{'M/C': 'NC M/C 5', 'Machine Time': 0.50, 'Machine Free': 'Yes'},
{'M/C': 'NC M/C 6', 'Machine Time': 0.50, 'Machine Free': 'Yes'},
{'M/C': 'NC M/C 7', 'Machine Time': 0.50, 'Machine Free': 'Yes'},
{'M/C': 'NC M/C 8', 'Machine Time': 0.50, 'Machine Free': 'Yes'},
{'M/C': 'NC M/C 9', 'Machine Time': 0.50, 'Machine Free': 'Yes'},
{'M/C': 'NC M/C 10', 'Machine Time': 0.40, 'Machine Free': 'No'}
]
}
# Find the minimum machine time for each item
minimum_machine_time = find_minimum_machine_time(machine_data)
# Print the result
for item, data in minimum_machine_time.items():
print(f"Item: {item}, M/C: {data['M/C']}, Machine Time: {data['Machine Time']}")
if __name__ == "__main__":
main()
Result
Item: a1, M/C: M/C-2, Machine Time: 1.0
Item: a2, M/C: NC M/C 5, Machine Time: 0.5
============================================================================
#Python Program
def find_minimum_machine_time(machine_data):
# Initialize a dictionary to store minimum machine times for each item
minimum_machine_time = {}
# Iterate over each item and its corresponding machine data
for item, machines in machine_data.items():
min_time = float('inf') # Set initial minimum time to infinity
selected_machine = None # Initialize selected machine to None
# Iterate over machines for the current item
for machine in machines:
# Check if the machine is free
if machine['Machine Free'] == 'Yes' and machine['Machine Time'] < min_time:
min_time = machine['Machine Time']
selected_machine = machine['M/C']
# If a free machine is found, store the minimum time and the selected machine
if selected_machine:
minimum_machine_time[item] = {'M/C': selected_machine, 'Machine Time': min_time}
return minimum_machine_time
def main():
# Define the machine data
machine_data = {
'a1': [
{'M/C': 'M/C-1', 'Machine Time': 1.50, 'Machine Free': 'Yes'},
{'M/C': 'M/C-2', 'Machine Time': 1.00, 'Machine Free': 'Yes'},
{'M/C': 'M/C-3', 'Machine Time': 2.00, 'Machine Free': 'Yes'},
{'M/C': 'M/C-4', 'Machine Time': 0.75, 'Machine Free': 'No'}
],
'a2': [
{'M/C': 'M/C-9', 'Machine Time': 2.00, 'Machine Free': 'Yes'},
{'M/C': 'NC M/C 5', 'Machine Time': 0.50, 'Machine Free': 'Yes'},
{'M/C': 'NC M/C 6', 'Machine Time': 0.50, 'Machine Free': 'Yes'},
{'M/C': 'NC M/C 7', 'Machine Time': 0.50, 'Machine Free': 'Yes'},
{'M/C': 'NC M/C 8', 'Machine Time': 0.50, 'Machine Free': 'Yes'},
{'M/C': 'NC M/C 9', 'Machine Time': 0.50, 'Machine Free': 'Yes'},
{'M/C': 'NC M/C 10', 'Machine Time': 0.40, 'Machine Free': 'Yes'}
]
}
# Find the minimum machine time for each item
minimum_machine_time = find_minimum_machine_time(machine_data)
# Print the result
for item, data in minimum_machine_time.items():
print(f"Item: {item}, M/C: {data['M/C']}, Machine Time: {data['Machine Time']}")
if __name__ == "__main__":
main()
#Result:
Item: a1, M/C: M/C-2, Machine Time: 1.0
Item: a2, M/C: NC M/C 10, Machine Time: 0.4
========================================================================
"Do-it-Yourself"
Chapter 22
Difference between interest calculation monthly and quarterly
#Python Program ("Difference between interest calculated monthly and quarterly: Rs."
# Function to calculate compound interest
def calculate_interest(principal, rate, time, frequency):
n = frequency # Number of times interest applied per time period
r = rate / 100 / n # Interest rate per period
t = time * n # Total number of time periods
# Calculate compound interest
amount = principal * (1 + r) ** t
interest = amount - principal
return interest
# Principal amount
principal = 550000 # Rs. 5,50,000
# Annual interest rate
annual_rate = 7.50 # 7.50% per annum
# Time period in years
time = 1
# Calculate interest calculated monthly
monthly_interest = calculate_interest(principal, annual_rate, time, 12)
# Calculate interest calculated quarterly
quarterly_interest = calculate_interest(principal, annual_rate, time, 4)
# Calculate the difference
difference = monthly_interest - quarterly_interest
# Output the results
print("Interest calculated monthly: Rs.", round(monthly_interest, 2))
print("Interest calculated quarterly: Rs.", round(quarterly_interest, 2))
print("Difference between interest calculated monthly and quarterly: Rs.", round(difference, 2))
Result:
Interest calculated monthly: Rs. 42697.93
Interest calculated quarterly: Rs. 42424.73
Difference between interest calculated monthly and quarterly: Rs. 273.2
===================================================================================
#Graph Python Program
import matplotlib.pyplot as plt
# Data from the question
compounding_frequencies = ["Monthly", "Quarterly", "Difference"]
interest_earned = [42697.93, 42424.73, 273.20]
# Create a bar graph
plt.figure(figsize=(8, 6))
plt.bar(compounding_frequencies, interest_earned, color=['skyblue', 'lightgreen', 'gold'])
plt.xlabel("Compounding Frequency")
plt.ylabel("Interest Earned (Rs.)")
plt.title("Interest Earned for Different Compounding Frequencies")
plt.xticks(rotation=0) # Rotate x-axis labels for better readability
# Display the graph
plt.tight_layout()
plt.show()
============================================
"Do-it-Yourself"
Chapter 24
Sales Forecast Branch wise for each sales head in the chart of Accounts using AI
#Python Program
# Define a list to store balance data
balances = []
# Input data
data = [
(310101, "Product A", "A00012", "ABC Co.", "Delhi", 2022, 450098.00, 356789.00),
(310101, "Product A", "A00014", "XYZ Co.", "Delhi", 2022, 750098.00, 556789.00),
(310101, "Product A", "A00015", "PQR Co.", "Delhi", 2022, 750098.00, 656789.00),
(310101, "Product A", "A00012", "ABC Co.", "Calcutta", 2022, 350098.00, 296789.00),
(310101, "Product A", "A00014", "XYZ Co.", "Calcutta", 2022, 750098.00, 656789.00),
(310101, "Product A", "A00015", "PQR Co.", "Calcutta", 2022, 750098.00, 750098.00),
(310101, "Product A", "A00012", "ABC Co.", "Delhi", 2023, 750098.00, 556789.00),
(310101, "Product A", "A00014", "XYZ Co.", "Delhi", 2023, 650098.00, 456789.00),
(310101, "Product A", "A00015", "PQR Co.", "Delhi", 2023, 650098.00, 556789.00),
(310101, "Product A", "A00012", "ABC Co.", "Calcutta", 2023, 450098.00, 426789.00),
(310101, "Product A", "A00014", "XYZ Co.", "Calcutta", 2023, 850098.00, 756789.00),
(310101, "Product A", "A00015", "PQR Co.", "Calcutta", 2023, 550098.00, 350100.00),
(310101, "Product B", "A00012", "ABC Co.", "Delhi", 2022, 350098.00, 456789.00),
(310101, "Product B", "A00014", "XYZ Co.", "Delhi", 2022, 550098.00, 656789.00),
(310101, "Product B", "A00015", "PQR Co.", "Delhi", 2022, 850098.00, 756789.00),
(310101, "Product B", "A00012", "ABC Co.", "Calcutta", 2022, 340098.00, 396789.00),
(310101, "Product B", "A00014", "XYZ Co.", "Calcutta", 2022, 750098.00, 850098.00),
(310101, "Product B", "A00015", "PQR Co.", "Calcutta", 2022, 650098.00, 850098.00),
(310101, "Product B", "A00012", "ABC Co.", "Delhi", 2023, 850098.00, 456789.00),
(310101, "Product B", "A00014", "XYZ Co.", "Delhi", 2023, 750098.00, 756789.00),
(310101, "Product B", "A00015", "PQR Co.", "Delhi", 2023, 650768.00, 656789.00),
(310101, "Product B", "A00012", "ABC Co.", "Calcutta", 2023, 350098.00, 326789.00),
(310101, "Product B", "A00014", "XYZ Co.", "Calcutta", 2023, 950098.00, 456789.00),
(310101, "Product B", "A00015", "PQR Co.", "Calcutta", 2023, 450098.00, 650199.00)
]
# Calculate balances and store data
for entry in data:
account_head, _, _, customer_name, location, year, invoice_amount, amount_received = entry
balance = invoice_amount - amount_received
balances.append((balance, invoice_amount, amount_received, account_head, customer_name, location, year))
# Print results
print("Balance Amount\tInvoice Amount\tAmount Received\tAccount Head\tCustomer Name\tLocation\tYear")
for balance_data in balances:
print("\t".join(map(str, balance_data)))
#Result
Balance Amount Invoice Amount Amount Received Account Head Customer Name Location Year
93309.0 450098.0 356789.0 310101 ABC Co. Delhi 2022
193309.0 750098.0 556789.0 310101 XYZ Co. Delhi 2022
93309.0 750098.0 656789.0 310101 PQR Co. Delhi 2022
53309.0 350098.0 296789.0 310101 ABC Co. Calcutta 2022
93309.0 750098.0 656789.0 310101 XYZ Co. Calcutta 2022
0.0 750098.0 750098.0 310101 PQR Co. Calcutta 2022
193309.0 750098.0 556789.0 310101 ABC Co. Delhi 2023
193309.0 650098.0 456789.0 310101 XYZ Co. Delhi 2023
93309.0 650098.0 556789.0 310101 PQR Co. Delhi 2023
23309.0 450098.0 426789.0 310101 ABC Co. Calcutta 2023
93309.0 850098.0 756789.0 310101 XYZ Co. Calcutta 2023
199998.0 550098.0 350100.0 310101 PQR Co. Calcutta 2023
-106691.0 350098.0 456789.0 310101 ABC Co. Delhi 2022
-106691.0 550098.0 656789.0 310101 XYZ Co. Delhi 2022
93309.0 850098.0 756789.0 310101 PQR Co. Delhi 2022
-56691.0 340098.0 396789.0 310101 ABC Co. Calcutta 2022
-100000.0 750098.0 850098.0 310101 XYZ Co. Calcutta 2022
-200000.0 650098.0 850098.0 310101 PQR Co. Calcutta 2022
393309.0 850098.0 456789.0 310101 ABC Co. Delhi 2023
-6691.0 750098.0 756789.0 310101 XYZ Co. Delhi 2023
-6021.0 650768.0 656789.0 310101 PQR Co. Delhi 2023
23309.0 350098.0 326789.0 310101 ABC Co. Calcutta 2023
493309.0 950098.0 456789.0 310101 XYZ Co. Calcutta 2023
-200101.0 450098.0 650199.0 310101 PQR Co. Calcutta 2023
==============================================================================================
#Python Program
# Define data
data = [
["Product A", "ABC Co.", "Delhi", 2022, 450098.00, 356789.00, 93309.00],
["Product A", "XYZ Co.", "Delhi", 2022, 750098.00, 556789.00, 193309.00],
["Product A", "PQR Co.", "Delhi", 2022, 750098.00, 656789.00, 93309.00],
["Product A", "ABC Co.", "Calcutta", 2022, 350098.00, 296789.00, 53309.00],
["Product A", "XYZ Co.", "Calcutta", 2022, 750098.00, 656789.00, 93309.00],
["Product A", "PQR Co.", "Calcutta", 2022, 750098.00, 750098.00, 0.00],
["Product A", "ABC Co.", "Delhi", 2023, 750098.00, 556789.00, 193309.00],
["Product A", "XYZ Co.", "Delhi", 2023, 650098.00, 456789.00, 193309.00],
["Product A", "PQR Co.", "Delhi", 2023, 650098.00, 556789.00, 93309.00],
["Product A", "ABC Co.", "Calcutta", 2023, 450098.00, 426789.00, 23309.00],
["Product A", "XYZ Co.", "Calcutta", 2023, 850098.00, 756789.00, 93309.00],
["Product A", "PQR Co.", "Calcutta", 2023, 550098.00, 350100.00, 199998.00],
["Product B", "ABC Co.", "Delhi", 2022, 350098.00, 456789.00, -106691.00],
["Product B", "XYZ Co.", "Delhi", 2022, 550098.00, 656789.00, -106691.00],
["Product B", "PQR Co.", "Delhi", 2022, 850098.00, 756789.00, 93309.00],
["Product B", "ABC Co.", "Calcutta", 2022, 340098.00, 396789.00, -56691.00],
["Product B", "XYZ Co.", "Calcutta", 2022, 750098.00, 850098.00, -100000.00],
["Product B", "PQR Co.", "Calcutta", 2022, 650098.00, 850098.00, -200000.00],
["Product B", "ABC Co.", "Delhi", 2023, 850098.00, 456789.00, 393309.00],
["Product B", "XYZ Co.", "Delhi", 2023, 750098.00, 756789.00, -6691.00],
["Product B", "PQR Co.", "Delhi", 2023, 650768.00, 656789.00, -6021.00],
["Product B", "ABC Co.", "Calcutta", 2023, 350098.00, 326789.00, 23309.00],
["Product B", "XYZ Co.", "Calcutta", 2023, 950098.00, 456789.00, 493309.00],
["Product B", "PQR Co.", "Calcutta", 2023, 450098.00, 650199.00, -200101.00]
]
# Initialize dictionaries to store totals
invoice_totals = {}
received_totals = {}
balance_totals = {}
# Process data
for item in data:
product, customer, location, year, invoice_amount, amount_received, balance = item
if customer not in invoice_totals:
invoice_totals[customer] = 0
received_totals[customer] = 0
balance_totals[customer] = 0
invoice_totals[customer] += invoice_amount
received_totals[customer] += amount_received
balance_totals[customer] += balance
# Print results
print("Customer Name: Total Invoice Amount, Total Amount Received, and Total Balance")
for customer in invoice_totals:
print(f"{customer}: {invoice_totals[customer]}, {received_totals[customer]}, {balance_totals[customer]}")
#Result
Customer Name: Total Invoice Amount, Total Amount Received, and Total Balance
ABC Co.: 3890784.0, 3274312.0, 616472.0
XYZ Co.: 6000784.0, 5147621.0, 853163.0
PQR Co.: 5301454.0, 5227651.0, 73803.0
===========================================================================
# Define initial data
customer_data = {
"ABC Co.": {
"Total Invoice Amount": 3890784.00,
"Total Amount Received": 3274312.00,
"Total Balance": 616472.00
},
"XYZ Co.": {
"Total Invoice Amount": 6000784.00,
"Total Amount Received": 5147621.00,
"Total Balance": 853163.00
},
"PQR Co.": {
"Total Invoice Amount": 5301454.00,
"Total Amount Received": 5227651.00,
"Total Balance": 73803.00
}
}
# Forecast for each customer
for customer, data in customer_data.items():
print(f"Forecast for {customer}:")
invoice_amount = data["Total Invoice Amount"]
for year in range(2024, 2031):
invoice_amount *= 1.15 # 15% growth every year
print(f"Year {year}: {invoice_amount:.2f}")
Result
Forecast for ABC Co.:
Year 2024: 4474401.60
Year 2025: 5145561.84
Year 2026: 5917396.12
Year 2027: 6805005.53
Year 2028: 7825756.36
Year 2029: 8999619.82
Year 2030: 10349562.79
Forecast for XYZ Co.:
Year 2024: 6900901.60
Year 2025: 7936036.84
Year 2026: 9126442.37
Year 2027: 10495408.72
Year 2028: 12069720.03
Year 2029: 13880178.03
Year 2030: 15962204.74
Forecast for PQR Co.:
Year 2024: 6096672.10
Year 2025: 7011172.91
Year 2026: 8062848.85
Year 2027: 9272276.18
Year 2028: 10663117.61
Year 2029: 12262585.25
Year 2030: 14101973.04
===========================================================================
#Python Program for the Forecast
def create_forecast_table(data):
"""
Creates a forecast table with grand totals, formatted to two decimal places.
Args:
data: A dictionary containing forecasts for different companies.
Returns:
A list of lists representing the forecast table.
"""
# Get company names and forecast years
company_names = list(data.keys())
forecast_years = list(data[company_names[0]].keys())
# Create table header
table = [["Company Name"] + forecast_years + ["Grand Total"]]
# Add company data and calculate grand total per year
grand_total_per_year = [0] * len(forecast_years)
for company_name, company_data in data.items():
company_row = [company_name]
for year, forecast in company_data.items():
company_row.append("{:.2f}".format(forecast))
grand_total_per_year[forecast_years.index(year)] += forecast
table.append(company_row)
# Add grand total row
grand_total_row = ["Grand Total"]
for total in grand_total_per_year:
grand_total_row.append("{:.2f}".format(total))
table.append(grand_total_row)
return table
# Sample forecast data
forecast_data = {
"ABC Co.": {
"Year 2024": 4474401.60,
"Year 2025": 5145561.84,
"Year 2026": 5917396.12,
"Year 2027": 6805005.53,
"Year 2028": 7825756.36,
"Year 2029": 8999619.82,
"Year 2030": 10349562.79
},
"XYZ Co.": {
"Year 2024": 6900901.60,
"Year 2025": 7936036.84,
"Year 2026": 9126442.37,
"Year 2027": 10495408.72,
"Year 2028": 12069720.03,
"Year 2029": 13880178.03,
"Year 2030": 15962204.74
},
"PQR Co.": {
"Year 2024": 6096672.10,
"Year 2025": 7011172.91,
"Year 2026": 8062848.85,
"Year 2027": 9272276.18,
"Year 2028": 10663117.61,
"Year 2029": 12262585.25,
"Year 2030": 14101973.04
}
}
# Generate and print the forecast table
forecast_table = create_forecast_table(forecast_data)
for row in forecast_table:
print(", ".join(row))
#Result
Company Name, Year 2024, Year 2025, Year 2026, Year 2027, Year 2028, Year 2029, Year 2030, Grand Total
ABC Co., 4474401.60, 5145561.84, 5917396.12, 6805005.53, 7825756.36, 8999619.82, 10349562.79
XYZ Co., 6900901.60, 7936036.84, 9126442.37, 10495408.72, 12069720.03, 13880178.03, 15962204.74
PQR Co., 6096672.10, 7011172.91, 8062848.85, 9272276.18, 10663117.61, 12262585.25, 14101973.04
Grand Total, 17471975.30, 20092771.59, 23106687.34, 26572690.43, 30558594.00, 35142383.10, 40413740.57
======================================================================
#Python Program for Graph
import matplotlib.pyplot as plt
# Company names
companies = ["ABC Co.", "XYZ Co.", "PQR Co."]
# Years
years = ["2024", "2025", "2026", "2027", "2028", "2029", "2030"]
# Profit data (in millions)
profits = [
[44.74, 51.45, 59.17, 68.05, 78.25, 89.99, 103.49],
[69.00, 79.36, 91.26, 104.95, 120.69, 138.80, 159.62],
[60.96, 70.11, 80.62, 92.72, 106.63, 122.62, 141.02],
]
# Create a line chart
plt.figure(figsize=(10, 6))
for i, company in enumerate(companies):
plt.plot(years, profits[i], label=company)
# Set labels and title
plt.xlabel("Year")
plt.ylabel("Profit (in Millions)")
plt.title("Company Profits from 2024 to 2030")
# Add legend
plt.legend()
# Rotate x-axis labels for better readability
plt.xticks(rotation=45)
# Add grid lines
plt.grid(True)
# Show the plot
plt.tight_layout()
plt.show()
======================================================
#Python Program
# Function to calculate the invoice amount for the year 2024 with 15% sales growth
def calculate_invoice_amount(previous_year_amount):
growth_rate = 0.15
growth_amount = previous_year_amount * growth_rate
invoice_amount_2024 = previous_year_amount + growth_amount
return invoice_amount_2024
# Example data
previous_year_invoice_amount = 650098.00
# Calculate the invoice amount for the year 2024
invoice_amount_2024 = calculate_invoice_amount(previous_year_invoice_amount)
# Print the result rounded to two decimal places
print("Invoice amount for the year 2024:", round(invoice_amount_2024, 2), "INR")
Result:
The invoice amount for the year 2024: is 747612.7 INR
The AI Engine Result Testing: #Result Audit
=======================================================================================
Do-it-Yourself (AI Engine Testing for Unseen Data)
Chapter 25
“The graph has been automatically generated by using a Training (Dataset) from an AI engine.
”Exercise: Test the engine for unseen data.
#Python Program
#Python Program
import pandas as pd
import matplotlib.pyplot as plt
# Create a DataFrame from the provided data
data = {
'Branch Location': ['Delhi', 'Gurgaon', 'Lucknow', 'Bombay', 'Kanpur', 'Calcutta'],
'Account Code': ['420301'] * 6,
'Account Head': ['Rent Office'] * 6,
'Rent 2022': [108009.00, 278900.00, 150009.00, 156456.00, 214567.00, 125000.00],
'Rent 2023': [120970.08, 312368.00, 168010.08, 175230.72, 240315.04, 140000.00],
'Forecast Rent 2024': [135486.49, 349852.16, 188171.29, 196258.41, 269152.84, 156800.00],
'Forecast Rent 2025': [151744.87, 391834.42, 210751.84, 219809.42, 301451.19, 175616.00],
'Forecast Rent 2026': [169954.25, 438854.55, 236042.07, 246186.54, 337625.33, 196689.92],
'Forecast Rent 2027': [190348.76, 491517.10, 264367.11, 275728.93, 378140.37, 220292.71],
'Fo, Forecast Rent 2024 recast Rent 2028': [213190.61, 550499.15, 296091.17, 308816.40, 423517.21, 246727.84],
'Forecast Rent 2029': [238773.49, 616559.04, 331622.11, 345874.37, 474339.28, 276335.18],
'Forecast Rent 2030': [267426.31, 690546.13, 371416.76, 387379.30, 531259.99, 309495.40]
}
df = pd.DataFrame(data)
# Create a line chart for each Branch Location
for location in df['Branch Location'].unique():
df_location = df[df['Branch Location'] == location]
plt.plot(df_location.columns[3:], df_location.iloc[0, 3:])
plt.title(f"Rent Forecast for {location}")
plt.xlabel("Year")
plt.ylabel("Rent")
plt.grid(True)
plt.show()
===================================================================================
"Do-it-Yourself"
Chapter 26
AI Modelling for vehicle repair and maintenance: Historical Data and Forecast
#Python
#Python
import pandas as pd
import matplotlib.pyplot as plt
# Create a DataFrame from the provided data
data = {
"Expense Head": ["vehicle repair and maintenance", "vehicle repair and maintenance", "vehicle repair and maintenance"],
"Vehicle No": [3211, 3343, 4989],
"2021": [45000.00, 36000.00, 27000.00],
"2022": [33987.00, 43456.00, 65342.00],
"2023": [29878.00, 65789.00, 76443.00],
"2024 (Forecast)": [32865.80, 72367.90, 84087.30],
"2025 (Forecast)": [33463.36, 73683.68, 85616.16],
}
df = pd.DataFrame(data)
# Define colors for each year
colors = ['blue', 'green', 'red', 'purple', 'orange']
# Create a bar chart
plt.figure(figsize=(10, 6))
for i, row in df.iterrows():
plt.bar(df.columns[2:], row[2:], label=row['Expense Head'] + ' (' + str(row['Vehicle No']) + ')', color=colors[i])
# Set labels and title
plt.xlabel('Year')
plt.ylabel('Expense')
plt.title('Vehicle Repair and Maintenance Expenses by Year')
# Rotate x-axis labels for better readability
plt.xticks(rotation=45)
# Add legend
plt.legend()
# Show the plot
plt.tight_layout()
plt.show()
============================================================================================
#From CoPilot
#Python Program
import pandas as pd
import matplotlib.pyplot as plt
# Create a DataFrame from the provided data
data = {
"Expense Head": ["vehicle repair and maintenance", "vehicle repair and maintenance", "vehicle repair and maintenance"],
"Vehicle No": [3211, 3343, 4989],
"2021": [45000.00, 36000.00, 27000.00],
"2022": [33987.00, 43456.00, 65342.00],
"2023": [29878.00, 65789.00, 76443.00],
"2024 (Forecast)": [32865.80, 72367.90, 84087.30],
"2025 (Forecast)": [33463.36, 73683.68, 85616.16],
}
df = pd.DataFrame(data)
# Define colors for each year
colors = ['blue', 'green', 'red', 'purple', 'orange']
# Create a bar chart
plt.figure(figsize=(10, 6))
for i, row in df.iterrows():
plt.bar(df.columns[2:], row[2:], label=row['Expense Head'] + ' (' + str(row['Vehicle No']) + ')', color=colors[i])
# Set labels and title
plt.xlabel('Year')
plt.ylabel('Expense')
plt.title('Vehicle Repair and Maintenance Expenses by Year')
# Rotate x-axis labels for better readability
plt.xticks(rotation=45)
# Add legend
plt.legend()
# Show the plot
plt.tight_layout()
plt.show()
=============================================================
"Do-it-Yourself"
Chapter 28
Sales Forecast in INR (AI Sales Forecast in INR for the Organization “Template” (AI Engine in Testing Phase)
Brief from the Sales Dashboard of the Branches (Delhi, Calcutta, Lucknow, Kanpur, Bombay, and Madras, from 2021, 2022, and 2023, and 2024, 2025, 2026, and 2027 Forecast Sales based on 2021, 2022, and 2023
#Sample: Python Program
#Draw Graph:
import matplotlib.pyplot as plt
# Define historical sales data (replace with your actual data)
sales_data = {
#Sale in Credit from chart of Acount
"Branch Calcutta": {
2021: -20.00,
2022: -19.32,
2023: -18.75,
2024: -18.08,
2025: -17.69,
2026: -17.35,
2027: -17.01,
}
}
# Extract years and sales data
years = list(sales_data["Branch Calcutta"].keys())
sales = list(sales_data["Branch Calcutta"].values())
# Create the line chart
plt.figure(figsize=(8, 5))
plt.plot(years, sales, marker='o', color='red', linestyle='-')
plt.xlabel("Year")
plt.ylabel("Sales (%)")
plt.title("Year-wise Sales for Branch Calcutta (2021-2027)")
plt.xticks(years) # Set x-axis labels
plt.grid(axis='y') # Add grid lines on the y-axis
# Show the chart
plt.show()
==============================================================================
#Python Program
#Python Program
# Define the data for each year
data = {
'2024': {'sales': 5475.00, 'expenses': 987.00, 'profit': 4488.00},
'2025': {'sales': 6266.25, 'expenses': 844.00, 'profit': 5422.25},
'2026': {'sales': 7176.14, 'expenses': 2678.00, 'profit': 4498.14},
'2027': {'sales': 8218.76, 'expenses': 4366.00, 'profit': 3852.76}
}
# Calculate percentages for each year
for year, values in data.items():
total_sales = values['sales']
total_expenses = values['expenses']
total_profit = values['profit']
total = total_sales + total_expenses + total_profit
# Calculate percentages
sales_percentage = (total_sales / total) * 100
expenses_percentage = (total_expenses / total) * 100
profit_percentage = (total_profit / total) * 100
# Print results
print(f'Year: {year}')
print(f'Percentage of Total Sales: {sales_percentage:.2f}%')
print(f'Percentage of Total Expenses: {expenses_percentage:.2f}%')
print(f'Percentage of Profit: {profit_percentage:.2f}%')
print()
#Result
Year: 2024
Percentage of Total Sales: 50.00%
Percentage of Total Expenses: 9.01%
Percentage of Profit: 40.99%
Year: 2025
Percentage of Total Sales: 50.00%
Percentage of Total Expenses: 6.73%
Percentage of Profit: 43.27%
Year: 2026
Percentage of Total Sales: 50.00%
Percentage of Total Expenses: 18.66%
Percentage of Profit: 31.34%
Year: 2027
Percentage of Total Sales: 50.00%
Percentage of Total Expenses: 26.56%
Percentage of Profit: 23.44%
=================================================================================
#Graph
import matplotlib.pyplot as plt
# Data for the bar graph
years = [2024, 2025, 2026, 2027]
profit_percentages = [40.99, 43.27, 31.34, 23.44]
# Create a bar chart
plt.figure(figsize=(8, 6)) # Set the figure size
plt.bar(years, profit_percentages, color=['green', 'blue', 'orange', 'red']) # Set bar colors
# Add labels and title
plt.xlabel("Year")
plt.ylabel("Profit Percentage (%)")
plt.title("Profit Percentage by Year (2024-2027)")
# Display the chart
plt.xticks(rotation=0) # Rotate x-axis labels for better readability
plt.tight_layout()
plt.show()
Click the Picture to Know about the books by | Pradeep K. Suri | Author and Researcher
Click the Picture "AI-Modelling and Process" Book for your library