您好,以下是一些股票量化交易的源代码示例:
1.多因子选股策略源码
```python
import numpy as np
import pandas as pd
# 假设我们有两个因子:PE和PB
data = pd.DataFrame({
'Stock': ['A', 'B', 'C', 'D'],
'PE': [10, 15, 8, 12],
'PB': [2, 1.5, 2.5, 2]
})
# 根据PE和PB因子计算得分
data['Score'] = data['PE'] + data['PB']
# 选择得分最高的股票
selected_stocks = data.sort_values(by='Score', ascending=False).head(2)
print(selected_stocks)
```
2.简单的均线策略源码
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.DataFrame({
'Date': pd.date_range(start='2023-01-01', periods=100),
'Close': np.random.normal(100, 10, 100) # 生成一些模拟数据
})
data.set_index('Date', inplace=True)
# 计算20日移动均线
data['Moving Average'] = data['Close'].rolling(window=20).mean()
# 生成交易信号
data['Position'] = 0
data.loc[data['Close'] > data['Moving Average'], 'Position'] = 1 # 买入信号
data.loc[data['Close'] < data['Moving Average'], 'Position'] = -1 # 卖出信号
# 绘制价格和均线
plt.figure(figsize=(14, 7))
plt.plot(data['Close'], label='Close Price')
plt.plot(data['Moving Average'], label='Moving Average')
plt.legend()
plt.show()
```
3.统计套利策略源码
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
np.random.seed(42)
data = pd.DataFrame({
'Date': pd.date_range(start='2023-01-01', periods=250),
'Stock_A': np.random.normal(0, 1, 250).cumsum() + 50,
'Stock_B': np.random.normal(0, 1, 250).cumsum() + 50
})
data.set_index('Date', inplace=True)
# 计算两个股票的价差
data['Spread'] = data['Stock_A'] - data['Stock_B']
# 计算价差的移动平均和标准差
window = 20
data['Spread Mean'] = data['Spread'].rolling(window=window).mean()
data['Spread Std'] = data['Spread'].rolling(window=window).std()
# 设置买入和卖出的阈值
entry_z = 2 # 买入Z分数
exit_z = 0 # 卖出Z分数
data['Upper Threshold'] = data['Spread Mean'] + entry_z * data['Spread Std']
data['Lower Threshold'] = data['Spread Mean'] - entry_z * data['Spread Std']
# 生成交易信号
data['Position'] = 0
data.loc[data['Spread'] > data['Upper Threshold'], 'Position'] = -1 # 做空Stock A,做多Stock B
data.loc[data['Spread'] < data['Lower Threshold'], 'Position'] = 1 # 做多Stock A,做空Stock B
# 绘制股票价格和交易信号
plt.figure(figsize=(14, 7))
plt.subplot(211)
plt.plot(data['Stock_A'], label='Stock A')
plt.plot(data['Stock_B'], label='Stock B')
plt.title('Stock Prices')
plt.legend()
plt.subplot(212)
plt.plot(data['Spread'], label='Spread')
plt.plot(data['Spread Mean'], label='Mean Spread')
plt.fill_between(data.index, data['Upper Threshold'], data['Lower Threshold'], color='gray', alpha=0.3, label='Entry Zone')
plt.plot(data.index, data['Position'] * 10, label='Trading Signal', color='magenta', marker='o', linestyle='None')
plt.title('Spread and Trading Signals')
plt.legend()
plt.show()
``
这些代码示例提供了不同量化交易策略的基本框架,您可以根据自己的需求进行修改和扩展。希望对您有所帮助!
本文作者可以追加内容哦 !