Practical Risk Quantification for Medicine Stock¶
We know that medicine stockouts and expiration losses can still occur, even with careful forecasting and well-managed supply chains. While it’s not possible to foresee everything, data science can help you identify potential risks early.
Here’s how data science can help anticipate risks before they lead to treatment interruptions, losses from expired products, or unplanned budget waste.
Explore Data¶
Suppose that your Logistics Management Information System provides Months of Stock as the usable stock on hand divided by average monthly consumption.
Show Python code
import pandas as pd
import seaborn as sns
df = pd.read_excel(
"MoS2021-2023.xlsx",
sheet_name="Data",
parse_dates=["Month"]
).sort_values("Month")
## transform data for ensure float and remove zeros
epsilon = 1e-6 # 0.000001
df['Months of Stock']=df['Months of Stock'].astype(float).round(2).replace(0, epsilon)
The chart below shows Months of Stock for the antibiotic kanamycin in a provincial hospital for the 12 most recent observations and 24 preceding. It seems the stock could have been managed more effectively, considering the dips in March 2021 and November 2023 and the spike in October 2022. Still, no harm has been done so far.
Show Python code
## define width and height for charts
chart_height=5
chart_aspect=2
def makePretty(g): ## make the chart pretty look
## title
g.fig.suptitle("Months of stock by months", fontsize=24)
g.fig.subplots_adjust(top=0.9) # Make room for the title
## axis labels
g.ax.set_xlabel("Reported month", fontsize=20)
g.ax.set_ylabel("Months of stock", fontsize=20)
# define thresholds
low_threshold_color='red'
upper_threshold_color='orange'
##if low_threshold>0:
## g.ax.axhspan(plot_df1['value'].min(),low_threshold, color=low_threshold_color, alpha=0.15, label="MOS is below minimum");
##if upper_threshold>0:
## g.ax.axhspan(upper_threshold,plot_df1['value'].max(), color=upper_threshold_color, alpha=0.15,label="MOS is above maximum");
##legend
g.legend.remove()
g.ax.legend(title="");
g.ax.legend(title="");
g.ax.legend(fontsize=14);
## plotting
plot_df1=pd.melt(df, id_vars=['Month'],value_vars=['Months of Stock'],var_name='category') ## de-pivot for sns
evaluation_period=df[-12:].copy()
evaluation_period['unique_id']='Most recent period'
reference_period=df[-36:-12].copy()
reference_period['unique_id']='Preceding period'
both_periods=pd.concat([reference_period, evaluation_period], ignore_index=True)
g=sns.relplot(
data=both_periods, kind="line", marker="o",
x="Month", y="Months of Stock",
hue=both_periods["unique_id"],
height=chart_height,
aspect=chart_aspect
)
makePretty(g)
g.fig.suptitle("Kanamycin", fontsize=24);
sns.move_legend(g.ax, "center left", bbox_to_anchor=(1.02, 0.5), title="",)
The Months of Stock looks different in the most recent 12 observations than it does in the preceding 24. That’s expected, but how can we measure the difference?
Model Preceding Observations¶
We use a statistical model based on preceding observations to simulate the most recent ones. Statistically, these simulations are expected to behave much like the preceding observations.
Then, we’ll compare the most recent observations with simulations. If the most recent observations are similar to the simulations, the difference is not significant. If they don’t, we may have spotted something new that might be risky.
For modeling, we use statistical software available in Python. Expand the code section if you are interested in which modules are included.
Show Python code
from typing import Tuple
import numpy as np
import pandas as pd
import seaborn as sns
from scipy.special import expit
from statsforecast import StatsForecast
from statsforecast.models import AutoARIMA
from statsmodels.tsa.arima.model import ARIMA as StatsmodelsARIMA
You don’t need to hire additional data scientists. We get to build and fit the model automatically. Expand the code section if you are interested in the techniques.
Show Python code
## Auto fit a model considering 18 months subject area restriction
global_max = 18.0 ## MOS specific no more 18 months restriction
sorted_history = reference_period.sort_values("Month").copy()
y = sorted_history["Months of Stock"].to_numpy(dtype=float)
# validate it!
if not np.isfinite(y).all():
raise ValueError("MOS contains missing or non-finite values.")
if ((y <= 0) | (y >= global_max)).any():
raise ValueError(f"Logit transformation requires 0 < MOS < {global_max}.")
# logit observed values to make a result inside 0 to global_max. Indeed, it is a cheating
z = np.log(y / (global_max - y))
transformed_history = sorted_history.copy()
transformed_history["Months of Stock"] = z
## most parameters below are excess
sf = StatsForecast(
models=[
AutoARIMA(
season_length=12,
seasonal=True,
d=None,
max_d=1,
max_p=1,
max_q=1,
max_order=1,
allowmean=True,
allowdrift=False,
ic="aicc",
stepwise=False,
approximation=False
)
],
freq="MS",
n_jobs=-1
)
sf.fit(
df=transformed_history,
time_col="Month",
target_col="Months of Stock"
)
model = sf.fitted_[0, 0].model_
p, q, P, Q, m, d, D = map(int, model["arma"])
coefficients = model["coef"]
if "drift" in coefficients:
trend = "t"
elif "intercept" in coefficients:
trend = "c"
else:
trend = "n"
seasonal_order = (P, D, Q, m) if m > 1 else (0, 0, 0, 0)
sorted_history = reference_period.sort_values("Month")
stock_values = sorted_history["Months of Stock"]
# Fit the automatically selected specification, but consider the 0-18 boundaries
y = stock_values.to_numpy(dtype=float)
z = np.log(y / (global_max - y))
reference_period_model = StatsmodelsARIMA(
z,
order=(p, d, q),
seasonal_order=seasonal_order,
trend=trend
).fit()
## print("Selected order:", (p, d, q))
## print("Seasonal order:", seasonal_order)
## print("Trend:", trend)
## print("Transformed range:", z.min(), z.max())
## print(reference_period_model.summary())
Run Simulations¶
To ensure significant results, we perform one thousand simulations. Expand code to inspect the techniques used.
Show Python code
def simulate_projections(model : StatsmodelsARIMA, nsimulations: int,
repetitions: int,
anchor,
max_value: float)-> Tuple[pd.DataFrame, pd.DataFrame]:
"""
Simulate projections using a model given
Args:
model: ARIMA model
nsimulation: quantity of simulated observations
repetitions: quantity of simulation repetitions
anchor:'start': Begins the simulation at the very first period of the sample. 'end': simulating future steps.
max_value: subject area constraint for observations
Returns:
simulations and quantiles DataFrames
"""
raw_simulations = model.simulate(
nsimulations=nsimulations,
repetitions=repetitions,
anchor=anchor,
random_state=42,
initial_state=None,
measurement_shocks=None,
state_shocks=None,
)
## restore simulated values from logit to its original measurement
filtered_simulations=(global_max * expit(raw_simulations))[:,0,:] ## make 2D array and apply subject area restiction
## apply
## keep = ((raw_simulations >= 0) & (raw_simulations <= 18)).all(axis=(0, 1))
##filtered_simulations=raw_simulations[:,0,keep]
## rows are months in the evaluation period, columns are simulations
simulated = pd.DataFrame(
filtered_simulations,
index=pd.RangeIndex(1, nsimulations+1, name="Months")
)
# Expected behavior: three sigma
behavior = simulated.quantile(
[0.0013, 0.0228, 0.1587, 0.5, 0.8413, 0.9772, 0.9987],
axis=1
).rename_axis("quantile")
return simulated, behavior
# Simulate projections, each covering the next 12 months
expected, expected_behavior=simulate_projections(reference_period_model,12,1000,'end',global_max)
projection_center=expected_behavior.loc[0.5]
# Calculate percentiles across simulations for each month
months = pd.to_datetime(evaluation_period["Month"]).sort_values().to_numpy()
The chart below shows that the most recent observations generally fall within or near the shaded band. The band illustrates what would happen if things had gone as before. It helps make the differences easier to see, though it doesn’t measure them.
Show Python code
g=sns.relplot(
data=both_periods, kind="line", marker="o",
x="Month", y="Months of Stock",
hue=both_periods["unique_id"],
height=chart_height,
aspect=chart_aspect
)
#g.ax.fill_between(
# months, expected_behavior.loc[0.0013], expected_behavior.loc[0.9987],
# color="steelblue", alpha=0.1,
# label="Within 3 standard deviation"
#)
#g.ax.fill_between(
# months, expected_behavior.loc[0.0228], expected_behavior.loc[0.9772],
# color="steelblue", alpha=0.3,
# label="Within 2 standard deviations"
#)
g.ax.fill_between(
months, expected_behavior.loc[0.1587], expected_behavior.loc[0.8413],
color="steelblue", alpha=0.5,
label="Expected from preceding"
)
makePretty(g)
g.fig.suptitle("Kanamycin", fontsize=24);
sns.move_legend(g.ax, "center left", bbox_to_anchor=(1.02, 0.5), title="",)
It looks like there may be some differences. Let's find a good way to measure them.
Measure Differences¶
We can find a statistical center for the simulations and use it as a helpful reference point for measuring differences. We measure the difference by looking at the percentage of simulations that are closer to the center than the most recent observations.
The math can be a little complicated, but Python offers some tools to help. Expand the code if you are interested in the implementation.
Show Python code
from scipy.spatial import distance
from typing import Tuple
def statistics_vector(time_series) -> Tuple[float, float, float]:
mean=time_series.mean() ## mean of time series values
std = time_series.std(ddof=0) ## population standard deviation
lag1 = time_series.autocorr(lag=1) ## correlation from one month to the next
return mean,std,lag1
## Distance from the origin to evaluation period data
origin_statistics=statistics_vector(projection_center)
eval_period_statistics=statistics_vector(evaluation_period['Months of Stock'])
expected_statistics = expected.apply(
lambda column: pd.Series(
statistics_vector(column),
index=["Mean", "Std", "Lag1"]
),
axis=0
).T
expected_spread=expected_statistics.var(axis=0, ddof=1)
## distance from the review period data to the center
evaluated_distance=distance.seuclidean(eval_period_statistics,origin_statistics, V=expected_spread)
## distances from the projections to the center
expected_distances=expected_statistics.apply(
lambda column:
pd.Series(
distance.seuclidean(column.values,origin_statistics, V=expected_spread),
index=["distance"]
),
axis=1
)
## apply the scale
numeric_scale=(expected_distances["distance"] < evaluated_distance).mean() * 100
print(f"It’s helpful to note that {numeric_scale:.2f}% of the simulations are closer to the statistical center",
f"than the most recent\nobservations.")
It’s helpful to note that 90.90% of the simulations are closer to the statistical center than the most recent observations.
We’re measuring the difference now, and we’ll also need a scale to help us understand just how risky it is.
Quantify Risks¶
Generally, if all simulations are closer to the center, that may suggest a major difference. If half or fewer are closer, it may suggest a minor difference. The more difference, the more risks.
Yet you may need a detailed risk quantification scale. It may be helpful to go over the example below with your procurement team to see how it fits with your standard procedures.
Show Python code
from IPython.display import Markdown, display
idf = pd.read_excel(
"MoS2021-2023.xlsx",
sheet_name="Risks",
)
message = f"Actual difference is {numeric_scale:.2f}%"
display(Markdown(f"**{message}**"))
with pd.option_context("display.max_colwidth", None):
display(
idf.style
.set_table_styles([
{
"selector": "th.col_heading",
"props": [("text-align", "center")],
}
])
.set_properties(
subset=list(idf.columns[-3:]),
**{"text-align": "left"},
)
)
Actual difference is 90.90%
| Difference | Risk | Next Step (SOP Monthly Stock Status Review.) | |
|---|---|---|---|
| 0 | Below 50% | Minor | Continue routine monitoring. |
| 1 | 50% to 90% | Low | Check at the next scheduled review whether the same behavior persists. |
| 2 | 90% to 95% | Moderate | During the current review, identify what drove the score and check for a reporting issue or a known stock movement. |
| 3 | 95% to 99% | High | Assign a reviewer to verify the stock records, assess the operational impact, and document the recommended follow-up. |
| 4 | Above 99% | Major | Notify the designated supply chain lead for prompt detailed review. Confirm the finding, assess the operational impact, and assign an owner and due date for any action agreed. |
Conclusion¶
Even well-defined supply chains can still face medicine stockouts, expiration losses, and budget waste. The good news is that applying data science techniques to existing data can help make logistics less risky.
Applying data science isn’t a one-size-fits-all software solution. We offer a comprehensive service that includes exploratory data analysis, statistical modeling, quantifying risks, and tailoring all of the above to your standard procedures.
We use familiar, standard Python software that data science professionals around the world already know, so there’s no need to hire additional staff or seek domestic or international support.
A practical next step is to evaluate this approach using routine LMIS data. Feel free to download Jupyter notebook. For questions or feedback, contact me on LinkedIn.