本文主要是介绍Python在股票交易分析中的应用:布林带与K线图的实战回测,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
引言
在股票交易的世界中,技术分析是投资者们用来预测市场动向的重要工具。布林带(Bollinger Bands)作为一种动态波动范围指标,因其直观性和实用性而广受欢迎。本文将通过Python代码,展示如何使用布林带结合K线图来分析股票价格走势,并寻找可能的交易信号。
布林带指标简介
布林带由三部分组成:中轨(移动平均线),上轨(中轨加上两倍标准差),以及下轨(中轨减去两倍标准差)。它们可以帮助交易者识别股票的超买或超卖状态,从而发现潜在的买卖机会。
Python代码实现
以下是使用Python进行布林带计算和K线图绘制的完整示例代码:
1. 导入必要的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
2. 定义布林带计算函数
def bollinger_bands(close_prices, window=20, num_std=2):rolling_mean = close_prices.rolling(window=window).mean()rolling_std = close_prices.rolling(window=window).std()upper_band = rolling_mean + (rolling_std * num_std)lower_band = rolling_mean - (rolling_std * num_std)return upper_band, lower_band
3. 生成模拟数据示例数据
np.random.seed(0)
dates = pd.date_range(start='2022-01-01', end='2024-01-01', freq='D')
prices = np.random.normal(loc=100, scale=2, size=len(dates)) + np.sin(np.arange(len(dates)) * 0.05) * 10
opens = prices * np.random.uniform(0.98, 1.02, len(prices))
closes = prices * np.random.uniform(0.98, 1.02, len(prices))
df = pd.DataFrame({'Open': opens, 'Close': closes}).set_index(dates)
4. 计算涨跌幅和布林带
df['Color'] = np.where(df['Close'] > df['Open'], 'red', 'cyan')
upper_band, lower_band = bollinger_bands(df['Close'])
5. 标记买卖信号
buy_signals = df[df['Close'] < lower_band]
sell_signals = df[df['Close'] > upper_band]
6. 计算累计盈利
profit = 0
profits = []
for i in range(1, len(df)):if df['Close'][i] > df['Close'][i-1]:profit += df['Close'][i] - df['Close'][i-1]else:profit -= df['Close'][i] - df['Close'][i-1]profits.append(profit)
df['Cumulative_Profit'] = profits
7. 绘制K线图、布林带和累计盈利图
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 10), sharex=True)
8.绘制K线图
for i in range(len(df)):color = df['Color'][i]ax1.plot(df.index[i:i+1], df['Open'][i:i+1], color=color, linewidth=1)ax1.plot(df.index[i:i+1], df['Close'][i:i+1], color=color, linewidth=1)
9.绘制布林带
ax1.plot(upper_band, color='red', linestyle='--', label='Upper Band')
ax1.plot(lower_band, color='green', linestyle='--', label='Lower Band')
9. 标记买卖信号
ax1.scatter(buy_signals.index, buy_signals['Close'], marker='^', color='blue', label='Buy Signal')
ax1.scatter(sell_signals.index, sell_signals['Close'], marker='v', color='red', label='Sell Signal')
9. 绘制累计盈利图
ax2.plot(df.index[1:], df['Cumulative_Profit'], color='blue', label='Cumulative Profit')
9.设置图表标题和标签
ax1.set_title('Stock Price with Bollinger Bands and Signals')
ax1.set_ylabel('Price')
ax2.set_title('Cumulative Profit Over Time')
ax2.set_ylabel('Profit')
9. 显示图例
ax1.legend()
ax2.legend()
9.显示图表
plt.tight_layout()
plt.show()
完整代码
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt# 计算布林带指标
def bollinger_bands(close_prices, window=20, num_std=2):rolling_mean = close_prices.rolling(window=window).mean()rolling_std = close_prices.rolling(window=window).std()upper_band = rolling_mean + (rolling_std * num_std)lower_band = rolling_mean - (rolling_std * num_std)return upper_band, lower_band# 生成示例数据
np.random.seed(0)
dates = pd.date_range(start='2022-01-01', end='2024-01-01', freq='D')
prices = np.random.normal(loc=100, scale=2, size=len(dates)) + np.sin(np.arange(len(dates)) * 0.05) * 10
opens = prices * np.random.uniform(0.98, 1.02, len(prices))
closes = prices * np.random.uniform(0.98, 1.02, len(prices))
df = pd.DataFrame({'Date': dates, 'Open': opens, 'Close': closes}).set_index('Date')# 计算涨跌幅
df['Color'] = np.where(df['Close'] > df['Open'], 'red', 'cyan')# 计算布林带
upper_band, lower_band = bollinger_bands(df['Close'])# 标记买卖信号
buy_signals = df[df['Close'] < lower_band]
sell_signals = df[df['Close'] > upper_band]# 计算累计盈利
profit = 0
profits = []
for i in range(1, len(df)):if df['Close'][i] > df['Close'][i-1]:profit += df['Close'][i] - df['Close'][i-1]else:profit -= df['Close'][i] - df['Close'][i-1]profits.append(profit)# 绘制K线图和信号图以及累计盈利图
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 10), sharex=True)# 绘制K线图
for i in range(len(df)):if df['Close'][i] > df['Open'][i]:ax1.plot([df.index[i], df.index[i]], [df['Open'][i], df['Close'][i]], color='red', linewidth=1)else:ax1.plot([df.index[i], df.index[i]], [df['Open'][i], df['Close'][i]], color='cyan', linewidth=1)ax1.set_title('Candlestick Chart and Signals')
ax1.set_ylabel('Price')
ax1.grid(True)# 绘制布林带
ax1.plot(upper_band.index, upper_band, label='Upper Bollinger Band', color='red', linestyle='--')
ax1.plot(lower_band.index, lower_band, label='Lower Bollinger Band', color='green', linestyle='--')# 标记买卖信号
ax1.scatter(buy_signals.index, buy_signals['Close'], marker='^', color='blue', label='Buy Signal')
ax1.scatter(sell_signals.index, sell_signals['Close'], marker='v', color='red', label='Sell Signal')# 绘制累计盈利图
ax2.plot(df.index[1:], profits, label='Cumulative Profit', color='blue')
ax2.set_title('Cumulative Profit')
ax2.set_xlabel('Date')
ax2.set_ylabel('Profit')
ax2.legend()
ax2.grid(True)plt.tight_layout()
plt.show()
效果展示
这篇关于Python在股票交易分析中的应用:布林带与K线图的实战回测的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!