開始使用免費開始

公司敏感度分析

你現在要在多組 mean_inflationmean_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 pdnumpy as npscipy.stats as stmatplotlib.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()
編輯並執行程式碼