python布林带
时间: 2025-05-23 08:15:52 AIGC 浏览: 32
### 如何用Python实现布林带指标计算或绘制
要实现在 Python 中计算并绘制布林带(Bollinger Bands),可以按照以下方法操作。这涉及几个关键步骤,包括数据准备、计算移动平均线和标准差、生成上下边界以及最终绘图。
#### 所需库安装
为了完成此任务,需要安装一些常用的数据科学库:
- `numpy`:提供高效的数值运算能力。
- `pandas`:用于数据分析和时间序列处理。
- `matplotlib` 或其他可视化工具如 `plotly`:用来展示图形化结果。
可以通过 pip 命令轻松安装这些依赖项[^2]:
```bash
pip install numpy pandas matplotlib
```
#### 数据获取与预处理
通常情况下,可以从金融 API 获取历史股价数据,比如 Yahoo Finance, Alpha Vantage 等服务接口。假设已经拥有了某只股票一段时间内的收盘价列表,则可以直接进入下一步骤;如果没有现成的数据源可用的话,也可以手动创建测试集来验证算法逻辑正确与否[^3]。
#### 计算 Bollinger Bands 的核心公式
布林带主要基于简单移动平均(SMA)及其波动范围(即两个标准偏差单位),具体定义如下:
1. **Middle Band (MB)** – N-period SMA of price.
2. **Upper Band (UB)** – MB + K * StdDeviation over same period as MA where typically k=2 .
3. **Lower Band (LB)**– MB -k*StdDeviation similarly defined above.
其中参数 n 表示窗口大小,默认取值为 20 天周期长度最为常见;而常数因子 k 则决定了宽度比例关系,默认设置等于两倍标准误差即可满足绝大多数应用场景需求[^1].
以下是完整的代码实现过程:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def get_bollinger_bands(prices, window_size=20, num_of_std=2):
"""
Calculate upper and lower bollinger bands given prices series
Args:
prices (pd.Series): Series containing closing prices
window_size(int): Size of rolling window used to calculate sma & std dev
num_of_std(float): Number of standard deviations away from mean
Returns:
tuple: Three elements representing middle band,support line,resistance level respectively
"""
# Compute Simple Moving Average
rolling_mean = prices.rolling(window=window_size).mean()
# Compute Standard Deviation within specified lookback period
rolling_std = prices.rolling(window=window_size).std()
# Define Upper/Lower Bounds based off calculated metrics plus/minus X stddevs
upper_band = rolling_mean + (rolling_std * num_of_std)
lower_band = rolling_mean - (rolling_std * num_of_std)
return rolling_mean, upper_band, lower_band
if __name__ == "__main__":
# Example usage with fabricated data points simulating daily closes values across several trading sessions...
dates = pd.date_range('20230101', periods=100)
df = pd.DataFrame(np.random.randn(len(dates)), index=dates, columns=['Close'])
close_prices = df['Close']
mb, ub, lb = get_bollinger_bands(close_prices)
fig, ax = plt.subplots()
ax.plot(df.index,close_prices,label='Price')
ax.fill_between(df.index.values,lb ,ub,color="lightblue",alpha=.5)
ax.plot(mb,'r--',label='SMA')
legend=ax.legend(loc='best')
plt.show()
```
以上脚本展示了如何自动生成一组随机价格变动轨迹作为输入样本集合,并据此调用辅助函数完成相应统计量估算工作流程演示效果.
阅读全文
相关推荐


















