開始使用免費開始

利潤問題的模擬

你任職於一家生產工業設備的公司。每件設備的售價為 $100,000。你也知道 inflation_rate 與銷售 volume 之間具有強烈的負相關。這個關係由協方差矩陣 cov_matrix 表示,已在主控台中提供給你。

函式 profit_next_year_mc() 會進行 Monte Carlo 模擬,並在給定平均通膨率與平均銷售量作為引數時,回傳預期利潤(單位為千美元)。你也需要傳入 n,也就是要執行模擬的次數。此函式已為你載入,定義如下所示。

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 作為 pdnumpy 作為 npscipy.stats 作為 stmatplotlib.pyplot 作為 plt,以及 seaborn 作為 sns

本練習屬於課程

Python 的 Monte Carlo 模擬

檢視課程

練習說明

  • 使用 mean_inflation2mean_volume500,呼叫 profit_next_year_mc() 執行 500 次,完成一次 Monte Carlo 模擬。
  • 使用 displot 視覺化模擬結果。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Run a Monte Carlo simulation 500 times using a mean_inflation of 2 and a mean_volume of 500
profits = profit_next_year_mc(____)

# Create a displot of the results
____
plt.show()
編輯並執行程式碼