python 布林带
时间: 2023-10-20 11:35:02 AIGC 浏览: 195
布林带(Bollinger Bands)是一种技术分析指标,用来衡量价格的波动性和市场的超买超卖情况。它由三条线组成:中轨线(中间移动平均线)和上下轨线(标准差线)。Python中有多种库可以计算布林带,最常用的是使用ta库。以下是使用ta库计算布林带的示例代码:
```python
import ta
# 假设我们有一个名为df的数据框,其中包含价格数据
# 首先,我们需要计算移动平均线
df['ma'] = ta.bollinger_mavg(df['close'], n=20) # n表示移动平均的窗口大小
# 接下来,我们计算上轨线和下轨线
df['upper'] = df['ma'] + 2 * ta.bollinger_std(df['close'], n=20) # 2表示标准差倍数
df['lower'] = df['ma'] - 2 * ta.bollinger_std(df['close'], n=20)
# 将布林带数据添加到数据框中后,您可以根据需要进行进一步的分析或绘图
```
请注意,这只是一个示例代码,您需要根据自己的数据和需求进行适当的调整。另外,您还可以尝试其他的技术指标库或自定义计算方法来计算布林带。
相关问题
python布林带
### 如何用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()
```
以上脚本展示了如何自动生成一组随机价格变动轨迹作为输入样本集合,并据此调用辅助函数完成相应统计量估算工作流程演示效果.
怎么用Python写布林带
### 布林带计算和绘制的实现方法
布林带是一种常用的技术指标,由三条线组成:中轨(通常是N日的简单移动平均线)、上轨(中轨加上K倍的标准差)和下轨(中轨减去K倍的标准差)。以下是使用Python实现布林带计算和绘制的具体方法。
#### 1. 安装必要的库
为了实现布林带计算和绘制,需要安装以下Python库:
- `numpy`:用于数学计算。
- `pandas`:用于数据处理和分析。
- `matplotlib`:用于数据可视化。
可以通过以下命令安装这些库[^2]:
```bash
pip install numpy pandas matplotlib
```
#### 2. 数据获取
在计算布林带之前,需要获取股票或其他金融资产的历史价格数据。可以使用`pandas_datareader`从Yahoo Finance等来源获取数据[^4]。例如:
```python
import pandas_datareader as pdr
import datetime
# 设置日期范围
start = datetime.datetime(2020, 1, 1)
end = datetime.datetime(2023, 1, 1)
# 获取SPY数据
data = pdr.get_data_yahoo('SPY', start=start, end=end)
```
#### 3. 布林带计算
布林带的计算基于移动平均线和标准差。以下是一个计算布林带的函数[^5]:
```python
import pandas as pd
import numpy as np
def calculate_bollinger_bands(data, window=20, k=2, price_column='Adj Close'):
"""
计算布林带
:param data: 包含价格数据的DataFrame
:param window: 移动平均窗口大小
:param k: 标准差的倍数
:param price_column: 价格列名
:return: 包含布林带数据的DataFrame
"""
rolling_mean = data[price_column].rolling(window=window).mean() # 中轨
rolling_std = data[price_column].rolling(window=window).std() # 标准差
upper_band = rolling_mean + (k * rolling_std) # 上轨
lower_band = rolling_mean - (k * rolling_std) # 下轨
data['Rolling Mean'] = rolling_mean
data['Upper Band'] = upper_band
data['Lower Band'] = lower_band
return data
```
#### 4. 绘制布林带
使用`matplotlib`可以将布林带绘制出来[^3]。以下是一个绘图函数:
```python
import matplotlib.pyplot as plt
def plot_bollinger_bands(data):
"""
绘制布林带
:param data: 包含布林带数据的DataFrame
"""
plt.figure(figsize=(14, 7))
plt.plot(data.index, data['Adj Close'], label='Adj Close', color='blue')
plt.plot(data.index, data['Rolling Mean'], label='Rolling Mean', color='orange')
plt.plot(data.index, data['Upper Band'], label='Upper Band', color='red', linestyle='--')
plt.plot(data.index, data['Lower Band'], label='Lower Band', color='green', linestyle='--')
plt.fill_between(data.index, data['Lower Band'], data['Upper Band'], color='gray', alpha=0.2)
plt.title('Bollinger Bands')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.show()
```
#### 5. 示例代码
将上述步骤整合成一个完整的示例代码:
```python
import pandas_datareader as pdr
import datetime
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 数据获取
start = datetime.datetime(2020, 1, 1)
end = datetime.datetime(2023, 1, 1)
data = pdr.get_data_yahoo('SPY', start=start, end=end)
# 布林带计算
def calculate_bollinger_bands(data, window=20, k=2, price_column='Adj Close'):
rolling_mean = data[price_column].rolling(window=window).mean()
rolling_std = data[price_column].rolling(window=window).std()
upper_band = rolling_mean + (k * rolling_std)
lower_band = rolling_mean - (k * rolling_std)
data['Rolling Mean'] = rolling_mean
data['Upper Band'] = upper_band
data['Lower Band'] = lower_band
return data
data = calculate_bollinger_bands(data)
# 布林带绘制
def plot_bollinger_bands(data):
plt.figure(figsize=(14, 7))
plt.plot(data.index, data['Adj Close'], label='Adj Close', color='blue')
plt.plot(data.index, data['Rolling Mean'], label='Rolling Mean', color='orange')
plt.plot(data.index, data['Upper Band'], label='Upper Band', color='red', linestyle='--')
plt.plot(data.index, data['Lower Band'], label='Lower Band', color='green', linestyle='--')
plt.fill_between(data.index, data['Lower Band'], data['Upper Band'], color='gray', alpha=0.2)
plt.title('Bollinger Bands')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.show()
plot_bollinger_bands(data)
```
### 注意事项
- 窗口大小(`window`)和标准差倍数(`k`)可以根据具体需求调整[^1]。
- 数据质量对布林带计算结果有重要影响,确保数据完整且无缺失值。
阅读全文
相关推荐















