使用 Python 实现股票布林线策略与信号可视化
一、数据准备
在量化分析的最开始,需要获取历史行情数据。本文将以沪深 300 指数成分股或模拟数据为标的进行分析(包含日期、开盘价、最高价、最低价、收盘价、成交量字段)。
为了演示方便,我们将使用 pandas 和 numpy 生成模拟的随机游走数据,实际应用中可替换为 tushare、akshare 或 yfinance 等接口。
import pandas as pd
import numpy as np
# 设置随机种子以保证结果可复现
np.random.seed(42)
# 生成模拟日期
start_date = '2018-01-01'
dates = pd.date_range(start=start_date, periods=500, freq='D')
# 生成模拟价格数据 (基于随机游走模型)
close_prices = [100]
for _ in range(499):
change = np.random.normal(0.001, 0.02) # 均值 0.1%,波动率 2%
close_prices.append(close_prices[-1] * (1 + change))
# 构建 DataFrame
df = pd.DataFrame({
'Date': dates,
'Open': close_prices,
'High': [h + np.random.uniform(0, 0.5) for h in close_prices],
'Low': [l - np.random.uniform(0, 0.5) for l in close_prices],
'Close': close_prices,
'Volume': np.random.randint(1000000, 5000000, size=len(close_prices))
})
df.set_index(, inplace=)
(df.head())


