OK,还有没有更好玩的对
量化策略开发,高质量社群,交易思路分享等相关内容
『正文』
ˇ
最近比较火的OpenAI-ChatGPT,太有意思了。尝试让它写了几个策略,您别说,还真是有模有样。我们来看看吧。
模型一:均值回归模型
源码:
import numpy as np
import pandas as pd
from sklearn import linear_model
import numpy as np
import pandas as pd
from sklearn import linear_model# 定义交易资金
capital = 100000# 定义每次交易的数量
trade_qty = 1000# 定义交易费用
trade_fee = 0.003# 定义时间跨度
time_span = 10# 计算交易收益
def calc_profit(open_price, close_price):return (close_price - open_price) * trade_qty - trade_qty * trade_fee * 2# 计算交易均值回归模型
def calc_linear_model(df):X = np.array(df['open']).reshape(-1, 1)y = np.array(df['close']).reshape(-1, 1)model = linear_model.LinearRegression()model.fit(X, y)return model.coef_[0][0], model.intercept_[0]# 读入交易数据
df = pd.read_csv('trade_data.csv')# 计算交易均值回归模型参数
slope, intercept = calc_linear_model(df)# 初始化资产和交易结果
capital_list = []
result_list = []# 开始交易
for i in range(time_span, len(df)):# 计算收益open_price = df.iloc[i-time_span]['open']close_price = df.iloc[i]['close']profit = calc_profit(open_price, close_price)# 更新资产capital += profit# 记录交易结果capital_list.append(capital)result_list.append(profit)# 输出交易结果
print('Final capital:', capital)
模型二:一个均线策略
源码:
# 导入需要的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt# 导入股票数据
stock_data = pd.read_csv('stock_data.csv')# 计算移动平均线
ma_5 = stock_data['close'].rolling(5).mean()
ma_10 = stock_data['close'].rolling(10).mean()# 绘制移动平均线图
plt.plot(stock_data['date'], ma_5)
plt.plot(stock_data['date'], ma_10)
plt.title('Moving Average')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend(['MA5', 'MA10'])# 定义交易策略
def trade(stock_data, ma_5, ma_10):# 创建交易信号数组signals = np.zeros(len(stock_data))# 遍历每个交易日for i in range(len(stock_data)):# 如果MA5大于MA10,则买入if ma_5[i] > ma_10[i]:signals[i] = 1# 如果MA5小于MA10,则卖出elif ma_5[i] < ma_10[i]:signals[i] = -1return signals# 运行交易策略
signals = trade(stock_data, ma_5, ma_10)# 计算持仓和收益
position = 0
profit = 0for i in range(len(signals)):# 买入if signals[i] == 1:position += stock_data['close'][i]# 卖出elif signals[i] == -1:profit += stock_data['close'][i] - positionposition = 0# 输出最终收益
print('Final profit:', profit)
模型三:唐奇安通道+MACD
源码:
import numpy as np
import talib# 定义唐奇安通道函数
def Donchian(close, n):high = talib.MAX(close, n)low = talib.MIN(close, n)return high, low# 定义MACD函数
def MACD(close, n_fast, n_slow, n_signal):macd, signal, hist = talib.MACD(close, n_fast, n_slow, n_signal)return macd, signal, hist# 定义交易函数
def trade(open, close, high, low, macd, signal, hist):# 初始化持仓状态和交易信号position = 0signal = 0# 获取唐奇安通道上轨和下轨donchian_high, donchian_low = Donchian(close, 20)# 计算MACD和信号线macd, signal, hist = MACD(close, 12, 26, 9)# 判断交易信号if position == 0:# 如果当前没有持仓,判断开仓信号if macd[-1] > signal[-1] and hist[-1] > 0 and close[-1] > donchian_high[-1]:# 如果当前MACD大于信号线,且柱状图大于0,且收盘价高于唐奇安通道上轨,则开多仓signal = 1elif macd[-1] < signal[-1] and hist[-1] < 0 and close[-1] < donchian_low[-1]:# 如果当前MACD小于信号线,且柱状图小于0,且收盘价低于唐奇安通道下轨,则开空仓signal = -1else:# 如果当前有持仓,判断平仓信号if position > 0 and close[-1] < donchian_low[-1]:# 如果当前持多仓,且收盘价低于唐奇安通道下轨,则平多仓
模型四:机器学习策略
源码:
编写期货收益率预测模型的过程可能比较复杂,因为这类模型通常需要考虑许多因素。但是,以下是一个简单的Python程序,它使用Scikit-learn库来构建并训练一个期货收益率预测模型:
# Import necessary libraries
from sklearn import linear_model
from sklearn import metrics# Load data
X = ... # Feature data
y = ... # Target data# Split data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)# Train model
model = linear_model.LinearRegression()
model.fit(X_train, y_train)# Evaluate model
y_pred = model.predict(X_test)
print(metrics.mean_squared_error(y_test, y_pred))
这个程序使用线性回归来构建模型,并用均方误差(MSE)来评估模型的性能。在实际应用中,您可能需要使用更复杂的模型,并使用多种指标来评估模型的性能。此外,您还需要准备足够的数据来训练模型,并确保数据的质量和准确性。
哈哈哈,太有意思了铁子们,我们和它聊聊天。
源码:
import matplotlib.pyplot as plt# Set figure size
plt.figure(figsize=(4, 4))# Draw squirrel
plt.plot([1, 1, 2, 2, 3, 3, 4], [1, 2, 2, 3, 3, 2, 2], 'k')
plt.plot([1.5, 1.5, 2.5, 2.5], [1, 2, 2, 1], 'k')
plt.plot([2, 2], [1.5, 2.5], 'k')# Fill in the face and belly
plt.fill([1.5, 1.5, 2.5, 2.5], [1, 2, 2, 1], 'b')
plt.fill([2, 2], [1.5, 2.5], 'b')# Draw the eyes
plt.plot([1.25, 1.75], [1.75, 1.75], 'k')
plt.plot([2.25, 2.75], [1.75, 1.75], 'k')# Show the plot
plt.show()
哈哈哈哈,这也不像松鼠啊。
OK,还有没有更好玩的对话,评论区留言哈。
你要的干货都在这里→关注V V“松鼠宽客”
松鼠宽客:研究04丨波动率与CTA盈利关键https://blog.csdn.net/m0_56236921/article/details/126655526?spm=1001.2014.3001.5502
松鼠宽客:Pro08丨累计概率密度突破策略https://blog.csdn.net/m0_56236921/article/details/126637398?spm=1001.2014.3001.5502松鼠宽客:KD01策略丨SuperTrend+空头波段https://blog.csdn.net/m0_56236921/article/details/126504676?spm=1001.2014.3001.5502
松鼠宽客:加降息与BTC流动性事件策略研究https://blog.csdn.net/m0_56236921/article/details/126136104?spm=1001.2014.3001.5502
松鼠宽客:Pro_06丨重心拐点与高低波出场https://blog.csdn.net/m0_56236921/article/details/126704447?spm=1001.2014.3001.5502
松鼠宽客:基于订单流工具,我们能看到什么?https://blog.csdn.net/m0_56236921/article/details/125478268?spm=1001.2014.3001.5502
松鼠宽客:LM11丨重构K线构建择时交易策略https://blog.csdn.net/m0_56236921/article/details/125632587?spm=1001.2014.3001.5502