参考视频
import yfinance as yf
import matplotlib.pyplot as plt
import pandas as pd
# 获取股票数据(使用yfinance支持的股票代码),要vpn才能得到数据
symbol = "600519.SS"
start_date = "2022-01-01"
end_date = "2023-01-01"
data = yf.download(symbol, start=start_date, end=end_date)
# print(data.head())
# [*********************100%%**********************] 1 of 1 completed
# Open High ... Adj Close Volume
# Date ...
# 2022-01-04 2055.00000 2068.949951 ... 1950.997192 3384262
# 2022-01-05 2045.00000 2065.000000 ... 1925.097778 2839551
# 2022-01-06 2022.01001 2036.000000 ... 1885.359375 5179475
# 2022-01-07 1975.00000 1988.880005 ... 1847.104614 2981669
# 2022-01-10 1928.01001 1977.000000 ... 1869.932007 2962670
#
# [5 rows x 6 columns]
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# 简单的数据分析和可视化
# print(data.describe())
# [*********************100%%**********************] 1 of 1 completed
# Open High ... Adj Close Volume
# count 242.000000 242.000000 ... 242.000000 2.420000e+02
# mean 1798.663387 1820.485125 ... 1719.834817 3.385434e+06
# std 143.731246 140.473200 ... 134.905926 1.778336e+06
# min 1350.000000 1382.010010 ... 1297.890625 1.354417e+06
# 25% 1729.954956 1755.500000 ... 1666.434082 2.216221e+06
# 50% 1808.000000 1833.494995 ... 1718.770935 2.835084e+06
# 75% 1899.654999 1911.869995 ... 1814.796753 3.929750e+06
# max 2055.000000 2077.000000 ... 1966.063965 1.320980e+07
#
# [8 rows x 6 columns]
# 绘制股价走势图
# data['Close'].plot(figsize=(10, 6), label=symbol)
# plt.title(f'{symbol} Stock Price')
# plt.xlabel('Date')
# plt.ylabel('Price')
# plt.legend()
# plt.show()
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# 移动平均交叉策略回测
# 计算移动平均
data['SMA_50'] = data['Close'].rolling(window=50).mean()
data['SMA_200'] = data['Close'].rolling(window=200).mean()
# 初始化交叉信号列
data['Signal'] = 0
# 计算交叉信号
data.loc[data['SMA_50'] > data['SMA_200'], 'Signal'] = 1
data.loc[data['SMA_50'] < data['SMA_200'], 'Signal'] = -1
# 计算每日收益率
data['Daily_Return'] = data['Close'].pct_change()
# 计算策略信号的收益率(shift(1) 是为了避免未来数据的偏差)
data['Strategy_Return'] = data['Signal'].shift(1) * data['Daily_Return']
# 计算累计收益
data['Cumulative_Return'] = (1 + data['Strategy_Return']).cumprod()
# 输出策略表现
strategy_performance = {
'Total Return': data['Cumulative_Return'].iloc[-1] - 1,
'Annualized Return': (data['Cumulative_Return'].iloc[-1] ** (252 / len(data))) - 1,
'Max Drawdown': (data['Cumulative_Return'] / data['Cumulative_Return'].cummax() - 1).min(),
}
print("策略表现:")
for key, value in strategy_performance.items():
print(f"{key}: {value:.4f}")
# 绘制累计收益曲线
plt.figure(figsize=(10, 6))
plt.plot(data['Cumulative_Return'], label='Strategy Cumulative Return', color='b')
plt.plot(data['Close'] / data['Close'].iloc[0], label='Stock Cumulative Return', color='g')
plt.title("Cumulative Return of Strategy vs. Stock")
plt.xlabel("Date")
plt.ylabel("Cumulative Return")
plt.legend()
plt.show()
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 3415226167@qq.com