Phân tích độ nhạy của công ty
Giờ bạn sẽ xem điều gì sẽ xảy ra với lợi nhuận của công ty từ bài trước khi thay đổi các giá trị mean_inflation và mean_volume. Việc này giúp công ty lập kế hoạch cho nhiều mức lạm phát và sản lượng bán khác nhau, vì không công ty nào có thể chắc chắn trước về lạm phát hay sản lượng bán trong tương lai.
Các mức lạm phát trung bình bạn muốn khảo sát là 0, 1, 2, 5, 10, 15, 20, 50, còn các giá trị doanh số dùng làm giá trị trung bình cho sản lượng là 100, 200, 500, 800, 1000. Nhắc lại, dưới đây là định nghĩa hàm profit_next_year_mc() đã được nạp sẵn cho bạ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
Các gói sau đã được import: pandas là pd, numpy là np, scipy.stats là st, matplotlib.pyplot là plt, và seaborn là sns.
Bài tập này là một phần của khóa học
Mô phỏng Monte Carlo với Python
Hướng dẫn bài tập
- Hoàn thành mô phỏng Monte Carlo bằng cách chạy
profit_next_year_mc()để tính lợi nhuận 100 lần, mỗi lần lặp qua danh sách giá trịinflvà danh sách giá trịvol. - Dùng
displotđể trực quan hóa kết quả mô phỏng được lưu trong cộtProfitcủa DataFrame thu được.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
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()