import numpy as np
import matplotlib.pyplot as plt
[docs]
def plot_scenarios_with_confidence(matrix, time_range, xlabel="Hour of Day", ylabel="Value"):
"""
Plot multiple time series (scenarios) over a time range, with the average and confidence interval.
Args:
- matrix (numpy.ndarray): 2D array of shape (n_scenarios, time_range).
- time_range (array-like): Time range (e.g., array of hours of the day).
- xlabel (str): Label for the x-axis.
- ylabel (str): Label for the y-axis.
Returns:
- fig: Handle to the generated figure.
"""
n_scenarios, n_timepoints = matrix.shape
# Calculate the average and confidence interval (95%)
avg_series = np.mean(matrix, axis=0)
std_series = np.std(matrix, axis=0)
confidence_interval = 1.96 * std_series / np.sqrt(n_scenarios)
# Plot all individual scenarios in grey
fig, ax = plt.subplots()
for i in range(n_scenarios):
ax.plot(time_range, matrix[i, :], color="grey", alpha=0.3)
# Plot the average in black
ax.plot(time_range, avg_series, color="black", label="Average")
# Fill the confidence interval area
ax.fill_between(time_range, avg_series - confidence_interval, avg_series + confidence_interval,
color="blue", alpha=0.7, label="95% Confidence Interval")
# Labels and title
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
ax.set_xticks(np.arange(0, len(time_range), len(time_range) // 24))
ax.set_xticklabels(np.arange(24)) # Assuming the time range covers 24 hours
ax.legend()
return fig
[docs]
def compute_financial_metrics(cashflows: np.array, discount_rate: float):
"""
Computes common financial metrics including NPV, IRR, and Payback Period.
Parameters:
- cashflows: np.array of cashflows where the first value is the initial investment (negative)
and subsequent values are returns.
- discount_rate: The discount rate as a decimal (e.g., 0.1 for 10%).
Returns:
- A dictionary containing NPV, IRR, and Payback Period.
"""
# 1. Net Present Value (NPV)
npv = np.sum([cf / (1 + discount_rate) ** t for t, cf in enumerate(cashflows)])
# 2. Internal Rate of Return (IRR)
irr = np.irr(cashflows)
# 3. Payback Period
cumulative_cashflows = np.cumsum(cashflows)
payback_period = np.argmax(cumulative_cashflows >= 0) if np.any(cumulative_cashflows >= 0) else np.inf
# 4. Profitability Index (PI)
initial_investment = cashflows[0]
pi = np.sum(cashflows[1:] / (1 + discount_rate) ** np.arange(1, len(cashflows))) / -initial_investment
return {
'NPV': npv,
'IRR': irr,
'Payback Period (years)': payback_period,
'Profitability Index': pi
}