公司敏感度分析
你現在要在多組 mean_inflation 和 mean_volume 值下,檢視上一個練習中的公司其利潤會發生什麼變化。這能幫助公司為不同程度的通膨與銷售量做規劃,因為沒有任何公司能確定未來的通膨或銷售量會是多少。
你想探索的平均通膨百分比為 0, 1, 2, 5, 10, 15, 20, 50,而作為平均銷售量使用的值為 100, 200, 500, 800, 1000。提醒一下,以下是已為你載入的 profit_next_year_mc() 函式定義。
def profit_next_year_mc(mean_inflation, mean_volume, n):
profits = []
for i in range(n):
# Generate inputs by sampling from the multivariate normal distribution
rate_sales_volume = st.multivariate_normal.rvs(mean=[mean_inflation,mean_volume], cov=cov_matrix,size=1000)
# Deterministic calculation of company profit
price = 100 * (100 + rate_sales_volume[:,0])/100
volume = rate_sales_volume[:,1]
loan_and_cost = 50 * volume + 45 * (100 + 3 * rate_sales_volume[:,0]) * (volume/100)
profit = (np.mean(price * volume - loan_and_cost))
profits.append(profit)
return profits
以下套件已經匯入:pandas as pd、numpy as np、scipy.stats as st、matplotlib.pyplot as plt,以及 seaborn as sns。
本練習屬於課程
Python 的 Monte Carlo 模擬
練習說明
- 透過執行
profit_next_year_mc()完成 Monte Carlo 模擬,計算利潤 100 次;每一次都要迴圈跑過infl值清單與vol值清單。 - 使用
displot視覺化結果 DataFrame 中Profit欄位所儲存的模擬結果。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
x1 = []
x2 = []
y = []
for infl in [0, 1, 2, 5, 10, 15, 20, 50]:
for vol in [100, 200, 500, 800, 1000]:
# Run profit_next_year_mc so that it samples 100 times for each infl and vol combination
avg_prof = np.mean(____)
x1.append(infl)
x2.append(vol)
y.append(avg_prof)
df_sa = pd.concat([pd.Series(x1), pd.Series(x2), pd.Series(y)], axis=1)
df_sa.columns = ["Inflation", "Volume", "Profit"]
# Create a displot of the simulation results for "Profit"
____
plt.show()