notes_works/量化交易相关/收益预估直方图.md
zhangkun9038@dingtalk.com 4380e95e00 2025-04-07 13:07:53: ...
2025-04-07 13:08:02 +08:00

74 lines
2.4 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
date:
"{ date:YYYY-MM-DD }":
tags:
title:
---
```python
import random
import math
import numpy as np
import matplotlib.pyplot as plt
# 初始本金
initial_principal = 10000
# 游戏次数
num_games = 146
# 获胜概率
win_prob = 0.75
# 年化赢利率
annual_win_rate = 0.5
# 年化输利率
annual_loss_rate = -0.8
# 模拟次数
simulation_times = 10000
final_amounts = []
for _ in range(simulation_times):
principal = initial_principal
# 模拟游戏过程
for _ in range(num_games):
# 模拟游戏结果
result = random.random()
if result < win_prob:
# 赢了
daily_rate = (5 / 365) * annual_win_rate
principal *= (1 + daily_rate)
else:
# 输了
daily_rate = (5 / 365) * annual_loss_rate
principal *= (1 + daily_rate)
final_amounts.append(principal)
# 绘制直方图
plt.hist(final_amounts, bins=50, edgecolor='black')
plt.title('Histogram of Final Amounts after 10000 Simulations')
plt.xlabel('Final Amount')
plt.ylabel('Frequency')
plt.show()
```
### 代码解释
1. **模拟部分**
- 定义了初始本金、游戏次数、获胜概率、年化赢利率、年化输利率和模拟次数等参数。
- 通过两层循环模拟一万次两年的游戏过程,每次游戏根据随机结果更新本金,并将每次模拟的最终资金存储在 `final_amounts` 列表中。
2. **绘制直方图部分**
- 使用 `plt.hist()` 函数绘制 `final_amounts` 的直方图,`bins=50` 表示将数据分成 50 个区间,`edgecolor='black'` 为每个柱子添加黑色边框,使图形更清晰。
- 使用 `plt.title()``plt.xlabel()` 和 `plt.ylabel()` 分别设置图形的标题、x 轴标签和 y 轴标签。
3. **`plt.show()` 的作用**
- `plt.show()` 是 `matplotlib` 库中的一个函数,它的作用是显示当前绘制的图形。当你运行这段代码时,它会弹出一个窗口,在这个窗口中会显示绘制好的直方图图片。这个窗口允许你进行一些基本的操作,比如放大、缩小、保存图片等。
运行上述代码后你会看到一个直方图该直方图展示了一万次模拟后最终资金的分布情况x 轴表示最终资金的数值区间y 轴表示落在每个区间内的模拟次数(频率)。
![[../attachments/Pasted image 20250222115616.png]]