sohangchopra

IITM sem 1, Python Assignment 2, Problem 7

Nov 14th, 2025
350
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.45 KB | Source Code | 0 0
  1. # solution of Pruthwira Lenka for Python Assignment 2 > Problem 7
  2. # in 1st trimester of IIT Madras Web MTech (Industrial AI) 2025
  3. def simulate_sales(df: pd.DataFrame, n: int) -> list:
  4.     """
  5.    Simulate n future sales based on average price change.
  6.    """
  7.     np.random.seed(0)
  8.     try:
  9.         if 'OrderDate' in df.columns:
  10.             last_price = df.sort_values(by='OrderDate')['Price'].iloc[-1]
  11.             price_changes = df['Price'].diff()
  12.         else:
  13.             last_price = df['Price'].iloc[-1]
  14.     except (IndexError, KeyError):
  15.         last_price = 0.0
  16.  
  17.     if len(df) > 1:
  18.         if 'OrderDate' in df.columns:
  19.             price_changes = df.sort_values(by='OrderDate')['Price'].diff()
  20.         else:
  21.             price_changes = df['Price'].diff()
  22.  
  23.         mean_change = price_changes.mean()
  24.         std_change = price_changes.std()
  25.  
  26.         if pd.isna(mean_change) or pd.isna(std_change) or std_change == 0:
  27.             sim_mean = 0.0
  28.             sim_std = 0.0
  29.         else:
  30.             sim_mean = mean_change
  31.             sim_std = std_change
  32.     else:
  33.         sim_mean = 0.0
  34.         sim_std = 5.0
  35.  
  36.     simulated_data = []
  37.     current_price = last_price
  38.  
  39.     for _ in range(n):
  40.         price_drift = np.random.normal(loc=sim_mean, scale=sim_std)
  41.         current_price += price_drift
  42.  
  43.         quantity = np.random.randint(low=1, high=6)
  44.  
  45.         simulated_data.append((current_price, quantity))
  46.  
  47.     return simulated_data
  48.  
Advertisement
Add Comment
Please, Sign In to add comment