การจำลองโจทย์ผลกำไร
สมมติว่าคุณทำงานให้กับบริษัทผู้ผลิตอุปกรณ์อุตสาหกรรม โดยราคาขายของอุปกรณ์แต่ละชิ้นอยู่ที่ $100,000 นอกจากนี้ยังทราบว่า inflation_rate และ volume ของยอดขายมีความสัมพันธ์เชิงลบอย่างชัดเจน ความสัมพันธ์นี้ถูกเก็บไว้ในเมทริกซ์ความแปรปรวนร่วม cov_matrix ซึ่งมีให้ใช้งานใน console แล้ว
ฟังก์ชัน 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
ไลบรารีต่อไปนี้ถูก import ให้แล้ว: pandas เป็น pd, numpy เป็น np, scipy.stats เป็น st, matplotlib.pyplot เป็น plt และ seaborn เป็น sns
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Monte Carlo Simulations ใน Python
คำแนะนำการฝึกหัด
- รันการจำลอง Monte Carlo โดยเรียกใช้
profit_next_year_mc()500 ครั้ง โดยกำหนดmean_inflationเป็น2และmean_volumeเป็น500 - แสดงผลลัพธ์ของการจำลองด้วย
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()