用python 写一个双均线交易策略
时间: 2023-10-01 08:09:26 浏览: 118
基于GUI编程的python股票量化交易策略之双均线策略源代码
5星 · 资源好评率100%
好的,下面是一个简单的双均线交易策略的Python代码示例:
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 读取数据
df = pd.read_csv('data.csv')
# 计算移动平均线
def MA(df, n):
MA = pd.Series(df['Close'].rolling(n, min_periods=n).mean(), name='MA_' + str(n))
df = df.join(MA)
return df
# 计算交易信号
def signals(df, short_window=20, long_window=50):
signals = pd.DataFrame(index=df.index)
signals['signal'] = 0.0
# 计算短期均线和长期均线
signals['short_ma'] = df['Close'].rolling(window=short_window, min_periods=1, center=False).mean()
signals['long_ma'] = df['Close'].rolling(window=long_window, min_periods=1, center=False).mean()
# 交叉信号
signals['signal'][short_window:] = np.where(signals['short_ma'][short_window:]
> signals['long_ma'][short_window:], 1.0, 0.0)
# 计算买入和卖出信号
signals['positions'] = signals['signal'].diff()
return signals
# 回测策略
def backtesting(df, signals):
# 初始化资本规模,交易方向和股票持仓
initial_capital = 10000.0
positions = pd.DataFrame(index=signals.index).fillna(0.0)
positions['Position'] = 100 * signals['positions']
portfolio = positions.multiply(df['Close'], axis=0)
pos_diff = positions.diff()
# 计算资本和持仓的变化
portfolio['holdings'] = (positions.multiply(df['Close'], axis=0)).sum(axis=1)
portfolio['cash'] = initial_capital - (pos_diff.multiply(df['Close'], axis=0)).sum(axis=1).cumsum()
portfolio['total'] = portfolio['cash'] + portfolio['holdings']
portfolio['returns'] = portfolio['total'].pct_change()
return portfolio
# 绘制交易曲线
def plot_strategy(df, signals, portfolio):
fig = plt.figure(figsize=(12, 8))
ax1 = fig.add_subplot(111, ylabel='Price')
df['Close'].plot(ax=ax1, color='black', lw=2.)
signals[['short_ma', 'long_ma']].plot(ax=ax1, lw=2.)
ax1.plot(signals.loc[signals.positions == 1.0].index,
signals.short_ma[signals.positions == 1.0],
'^', markersize=10, color='g')
ax1.plot(signals.loc[signals.positions == -1.0].index,
signals.short_ma[signals.positions == -1.0],
'v', markersize=10, color='r')
ax2 = fig.add_subplot(212, ylabel='Portfolio value in $')
portfolio['total'].plot(ax=ax2, lw=2.)
plt.show()
# 运行交易策略
df = MA(df, 20)
df = MA(df, 50)
s = signals(df)
p = backtesting(df, s)
plot_strategy(df, s, p)
```
其中,`data.csv` 是包含了股票价格数据的CSV文件,包括 `Date` 和 `Close` 列。以上的交易策略是一个简单的双均线交易策略,如果短期均线在长期均线的上方,则发出买入信号,如果短期均线在长期均线的下方,则发出卖出信号。策略会进行回测,并绘制交易曲线。
阅读全文