增加交易策略、交易指标、量化库代码等文件夹

This commit is contained in:
Win_home
2025-04-27 15:54:09 +08:00
parent ca3b209096
commit f57150dae8
589 changed files with 854346 additions and 1757 deletions

View File

@@ -0,0 +1,273 @@
//------------------------------------------------------------------------
// 简称: VIP17_duo
// 名称: VIP17_duo
// 类别: 公式应用
// 类型: 用户应用
// 输出: Void
//------------------------------------------------------------------------
Params
Numeric Fund(20000); // 投入保证金
Vars
Numeric Lots(0); // 交易手数
Numeric totalScore(5); // 开仓分数阈值目前都是等权分配总共6个指标及6分。
Numeric rpmPeriod(14); // RPM Period
Numeric bboPeriod(16); // BBO Period
Numeric macdFastPeriod(12); // MACD Fast Period
Numeric macdSlowPeriod(24); // MACD Slow Period
Numeric macdSignalPeriod(9); // MACD Signal Period
Numeric rsiPeriod(14); // RSI Period
Numeric cciPeriod(14); // CCI Period
Numeric stochasticKLength(14); // Stochastic %K Length
Numeric stochasticKSmoothing(1); // Stochastic %K Smoothing
Numeric stochasticDSmoothing(3); // Stochastic %D Smoothing
Numeric supertrendPeriod(10); // SUPERTREND Period
Numeric supertrendFactor(2); // SUPERTREND Factor
Series<Numeric> rpmValue; // RPM Value
Series<Numeric> bboValue; // BBO Value
Series<Numeric> macdValue; // MACD Value
Series<Numeric> macdSignal; // MACD Signal Line
Series<Numeric> macdHist; // MACD Histogram
Series<Numeric> rsiValue; // RSI Value
Series<Numeric> stochasticValue; // Stochastic Value
Series<Numeric> cciValue; // CCI Value
Series<Numeric> supertrendValue; // SUPERTREND Value
Series<Numeric> netChgAvg ;
Series<Numeric> totChgAvg ;
Series<Numeric> score;
Numeric EntryStrength(90); // 趋势强度的进场值
Numeric Length(5); // 强弱指标和通道计算的周期值
Series<Numeric> CloseChange; // 收盘价变动值
Numeric i; // 循环控制变量
Numeric UpCloses; // 收盘价上涨累计值
Numeric DnCloses; // 收盘价下跌累计值
Numeric SumChange; // 收盘价变动累计值
Series<Numeric> MarketStrength; // 市场强弱指标
Plot plt1; // 用于画图的对象
Events
OnInit()
{
Range[0:DataCount-1]
{
//=========数据源相关设置==============
AddDataFlag(Enum_Data_RolloverBackWard()); //设置后复权
AddDataFlag(Enum_Data_RolloverRealPrice()); //设置映射真实价格
AddDataFlag(Enum_Data_AutoSwapPosition()); //设置自动换仓
//AddDataFlag(Enum_Data_IgnoreSwapSignalCalc()); //设置忽略换仓信号计算
}
// 创建第一个副图
plt1.figure(0); // 独立副图区域
plt1.setOption("Score", "width", Enum_7Pix); // 将指标“MA1”的输出线宽设置为3像素
plt1.setOption("Score","color",Blue);
}
OnBar(ArrayRef<Integer> indexs)
{
// 计算交易手数
Lots = Max(1, Round(Fund/(O*ContractUnit*BigPointValue* MarginRatio/rollover), 0));
// 计算市场强弱指标
CloseChange = Close - Close[1];
UpCloses = 0;
DnCloses = 0;
For i = 0 To Length-1
{
// 收盘价上涨计入涨幅累计
If(CloseChange[i] > 0)
UpCloses = UpCloses + CloseChange[i];
// 否则计入跌幅累计
Else
DnCloses = DnCloses + CloseChange[i];
}
// 计算周期内涨跌
SumChange = Summation(CloseChange, Length);
// 周期内上涨计算上涨强度0-100之间
If(SumChange >= 0)
{
MarketStrength = SumChange / UpCloses * 100;
}
// 周期内下跌计算下跌强度0-100之间
Else
{
MarketStrength = SumChange / Abs(DnCloses) * 100;
}
// 计算 MACD 值
Numeric emaFast = XAverage(Close, macdFastPeriod);
Numeric emaSlow = XAverage(Close, macdSlowPeriod);
macdValue = emaFast - emaSlow;
macdSignal = XAverage(macdValue, macdSignalPeriod);
macdHist = macdValue - macdSignal;
// 计算 RSI 值
Numeric SF = 1 / rsiPeriod;
Numeric change = Close - Close[1];
If(CurrentBar <= rsiPeriod - 1)
{
netChgAvg = (Close - Close[rsiPeriod]) / rsiPeriod;
totChgAvg = Average(Abs(Close - Close[1]), rsiPeriod);
}
Else
{
netChgAvg = netChgAvg[1] + SF * (change - netChgAvg[1]);
totChgAvg = totChgAvg[1] + SF * (Abs(change) - totChgAvg[1]);
}
If(totChgAvg <> 0)
{
rsiValue = 50 * (netChgAvg / totChgAvg + 1);
}
Else
{
rsiValue = 50;
}
// 计算 Stochastic 值
Numeric highestHigh = Highest(High, stochasticKLength);
Numeric lowestLow = Lowest(Low, stochasticKLength);
Numeric stochasticRaw = (Close - lowestLow) / (highestHigh - lowestLow) * 100;
stochasticValue = Average(stochasticRaw, stochasticKSmoothing);
// 计算 CCI 值
Numeric typicalPrice = (High + Low + Close) / 3;
Numeric smaTypicalPrice = Average(typicalPrice, cciPeriod);
Numeric meanDeviation = Summation(Abs(typicalPrice - smaTypicalPrice), cciPeriod) / cciPeriod;
If(meanDeviation <> 0)
{
cciValue = (typicalPrice - smaTypicalPrice) / (0.015 * meanDeviation);
}
Else
{
cciValue = 0;
}
// 计算 SUPERTREND 值
Numeric atr = AvgTrueRange(supertrendPeriod);
Numeric basicUpperBand = (High + Low) / 2 + supertrendFactor * atr;
Numeric basicLowerBand = (High + Low) / 2 - supertrendFactor * atr;
Numeric finalUpperBand = IIF(basicUpperBand < supertrendValue[1] || Close[1] > supertrendValue[1], basicUpperBand, supertrendValue[1]);
Numeric finalLowerBand = IIF(basicLowerBand > supertrendValue[1] || Close[1] < supertrendValue[1], basicLowerBand, supertrendValue[1]);
supertrendValue = IIF(Close > supertrendValue[1], finalLowerBand, finalUpperBand);
// 设置多头条件
Bool macdCondition = macdValue > macdSignal;
Bool rsiCondition = rsiValue >50;
Bool stochasticCondition = stochasticValue > 50;
Bool cciCondition = cciValue >0;
Bool supertrendCondition = Close > supertrendValue;
Bool Marketbool = MarketStrength >= EntryStrength;
// 计算得分
score = 0;
If(macdCondition)
{
score = score + 1;
}
If(rsiCondition)
{
score = score + 1;
}
If(stochasticCondition)
{
score = score + 1;
}
If(cciCondition)
{
score = score + 1;
}
If(supertrendCondition)
{
score = score + 1;
}
if(Marketbool)
{
score = score + 1;
}
// 在副图显示得分
Commentary("Score: " + Text(score));
plt1.barv("Score",score);
// 判断是否达到条件数量
If(score == totalScore)
{
Commentary("All conditions met!");
}
// 开多条件
If(score[1] >= totalScore And MarketPosition == 0 ) //
{
Buy(Lots, Open);
}
// 平仓条件
If(score[1] == 0 And MarketPosition == 1)
{
Sell(0, Open);
}
// 在副图显示条件成立和不成立
If(macdCondition)
{
PlotAuto("MACD_Condition",1,1,Green,Enum_Line,Enum_Solid,Enum_7Pix);
}
Else
{
PlotAuto("MACD_Condition",1,1,Red,Enum_Line,Enum_Solid,Enum_7Pix);
}
If(rsiCondition)
{
PlotAuto("RSI_Condition",2,2,Green,Enum_Line,Enum_Solid,Enum_7Pix);
}
Else
{
PlotAuto("RSI_Condition",2,2,Red,Enum_Line,Enum_Solid,Enum_7Pix);
}
If(stochasticCondition)
{
PlotAuto("Stochastic_Condition", 3,3,Green,Enum_Line,Enum_Solid,Enum_7Pix);
}
Else
{
PlotAuto("Stochastic_Condition", 3,3,Red,Enum_Line,Enum_Solid,Enum_7Pix);
}
If(cciCondition)
{
PlotAuto("CCI_Condition", 4,4,Green,Enum_Line,Enum_Solid,Enum_7Pix);
}
Else
{
PlotAuto("CCI_Condition", 4,4,Red,Enum_Line,Enum_Solid,Enum_7Pix);
}
If(supertrendCondition)
{
PlotAuto("Supertrend_Condition", 5,5,Green,Enum_Line,Enum_Solid,Enum_7Pix);
}
Else
{
PlotAuto("Supertrend_Condition", 5,5,Red,Enum_Line,Enum_Solid,Enum_7Pix);
}
If(Marketbool)
{
PlotAuto("Marketbool", 6,6,Green,Enum_Line,Enum_Solid,Enum_7Pix);
}
Else
{
PlotAuto("Marketbool", 6,6,Red,Enum_Line,Enum_Solid,Enum_7Pix);
}
}
//------------------------------------------------------------------------
// 编译版本 2024/11/27 145803
// 版权所有 songshu123
// 更改声明 TradeBlazer Software保留对TradeBlazer平台
// 每一版本的TradeBlazer公式修改和重写的权利
//------------------------------------------------------------------------

View File

@@ -0,0 +1,274 @@
//------------------------------------------------------------------------
// 简称: vip17_kong
// 名称: vip17_kong
// 类别: 公式应用
// 类型: 用户应用
// 输出: Void
//------------------------------------------------------------------------
Params
Numeric Fund(20000); // 投入保证金
Vars
Numeric Lots(0); // 交易手数
Numeric totalScore(5); // 开仓分数阈值目前都是等权分配总共6个指标及6分。
Numeric rpmPeriod(14); // RPM Period
Numeric bboPeriod(16); // BBO Period
Numeric macdFastPeriod(12); // MACD Fast Period
Numeric macdSlowPeriod(24); // MACD Slow Period
Numeric macdSignalPeriod(9); // MACD Signal Period
Numeric rsiPeriod(14); // RSI Period
Numeric cciPeriod(14); // CCI Period
Numeric stochasticKLength(14); // Stochastic %K Length
Numeric stochasticKSmoothing(1); // Stochastic %K Smoothing
Numeric stochasticDSmoothing(3); // Stochastic %D Smoothing
Numeric supertrendPeriod(10); // SUPERTREND Period
Numeric supertrendFactor(2); // SUPERTREND Factor
Series<Numeric> rpmValue; // RPM Value
Series<Numeric> bboValue; // BBO Value
Series<Numeric> macdValue; // MACD Value
Series<Numeric> macdSignal; // MACD Signal Line
Series<Numeric> macdHist; // MACD Histogram
Series<Numeric> rsiValue; // RSI Value
Series<Numeric> stochasticValue; // Stochastic Value
Series<Numeric> cciValue; // CCI Value
Series<Numeric> supertrendValue; // SUPERTREND Value
Series<Numeric> netChgAvg ;
Series<Numeric> totChgAvg ;
Series<Numeric> score;
Numeric EntryStrength(90); // 趋势强度的进场值
Numeric Length(5); // 强弱指标和通道计算的周期值
Series<Numeric> CloseChange; // 收盘价变动值
Numeric i; // 循环控制变量
Numeric UpCloses; // 收盘价上涨累计值
Numeric DnCloses; // 收盘价下跌累计值
Numeric SumChange; // 收盘价变动累计值
Series<Numeric> MarketStrength; // 市场强弱指标
Plot plt1; // 用于画图的对象
Events
OnInit()
{
Range[0:DataCount-1]
{
//=========数据源相关设置==============
AddDataFlag(Enum_Data_RolloverBackWard()); //设置后复权
AddDataFlag(Enum_Data_RolloverRealPrice()); //设置映射真实价格
AddDataFlag(Enum_Data_AutoSwapPosition()); //设置自动换仓
//AddDataFlag(Enum_Data_IgnoreSwapSignalCalc()); //设置忽略换仓信号计算
}
// 创建第一个副图
plt1.figure(0); // 独立副图区域
plt1.setOption("Score", "width", Enum_7Pix); // 将指标“MA1”的输出线宽设置为3像素
plt1.setOption("Score","color",Blue);
}
OnBar(ArrayRef<Integer> indexs)
{
// 计算交易手数
Lots = Max(1, Round(Fund/(O*ContractUnit*BigPointValue* MarginRatio/rollover), 0));
// 计算市场强弱指标
CloseChange = Close - Close[1];
UpCloses = 0;
DnCloses = 0;
For i = 0 To Length-1
{
// 收盘价上涨计入涨幅累计
If(CloseChange[i] > 0)
UpCloses = UpCloses + CloseChange[i];
// 否则计入跌幅累计
Else
DnCloses = DnCloses + CloseChange[i];
}
// 计算周期内涨跌
SumChange = Summation(CloseChange, Length);
// 周期内上涨计算上涨强度0-100之间
If(SumChange >= 0)
{
MarketStrength = SumChange / UpCloses * 100;
}
// 周期内下跌计算下跌强度0-100之间
Else
{
MarketStrength = SumChange / Abs(DnCloses) * 100;
}
// 计算 MACD 值
Numeric emaFast = XAverage(Close, macdFastPeriod);
Numeric emaSlow = XAverage(Close, macdSlowPeriod);
macdValue = emaFast - emaSlow;
macdSignal = XAverage(macdValue, macdSignalPeriod);
macdHist = macdValue - macdSignal;
// 计算 RSI 值
Numeric SF = 1 / rsiPeriod;
Numeric change = Close - Close[1];
If(CurrentBar <= rsiPeriod - 1)
{
netChgAvg = (Close - Close[rsiPeriod]) / rsiPeriod;
totChgAvg = Average(Abs(Close - Close[1]), rsiPeriod);
}
Else
{
netChgAvg = netChgAvg[1] + SF * (change - netChgAvg[1]);
totChgAvg = totChgAvg[1] + SF * (Abs(change) - totChgAvg[1]);
}
If(totChgAvg <> 0)
{
rsiValue = 50 * (netChgAvg / totChgAvg + 1);
}
Else
{
rsiValue = 50;
}
// 计算 Stochastic 值
Numeric highestHigh = Highest(High, stochasticKLength);
Numeric lowestLow = Lowest(Low, stochasticKLength);
Numeric stochasticRaw = (Close - lowestLow) / (highestHigh - lowestLow) * 100;
stochasticValue = Average(stochasticRaw, stochasticKSmoothing);
// 计算 CCI 值
Numeric typicalPrice = (High + Low + Close) / 3;
Numeric smaTypicalPrice = Average(typicalPrice, cciPeriod);
Numeric meanDeviation = Summation(Abs(typicalPrice - smaTypicalPrice), cciPeriod) / cciPeriod;
If(meanDeviation <> 0)
{
cciValue = (typicalPrice - smaTypicalPrice) / (0.015 * meanDeviation);
}
Else
{
cciValue = 0;
}
// 计算 SUPERTREND 值
Numeric atr = AvgTrueRange(supertrendPeriod);
Numeric basicUpperBand = (High + Low) / 2 + supertrendFactor * atr;
Numeric basicLowerBand = (High + Low) / 2 - supertrendFactor * atr;
Numeric finalUpperBand = IIF(basicUpperBand < supertrendValue[1] || Close[1] > supertrendValue[1], basicUpperBand, supertrendValue[1]);
Numeric finalLowerBand = IIF(basicLowerBand > supertrendValue[1] || Close[1] < supertrendValue[1], basicLowerBand, supertrendValue[1]);
supertrendValue = IIF(Close > supertrendValue[1], finalLowerBand, finalUpperBand);
// 设置空头条件
Bool macdCondition = macdValue < macdSignal;
Bool rsiCondition = rsiValue <50;
Bool stochasticCondition = stochasticValue < 50;
Bool cciCondition = cciValue <0;
Bool supertrendCondition = Close < supertrendValue;
Bool Marketbool = MarketStrength >= EntryStrength;
// 计算得分
score = 0;
If(macdCondition)
{
score = score + 1;
}
If(rsiCondition)
{
score = score + 1;
}
If(stochasticCondition)
{
score = score + 1;
}
If(cciCondition)
{
score = score + 1;
}
If(supertrendCondition)
{
score = score + 1;
}
if(Marketbool)
{
score = score + 1;
}
// 在副图显示得分
Commentary("Score: " + Text(score));
plt1.barv("Score",score);
// 判断是否达到条件数量
If(score == totalScore)
{
Commentary("All conditions met!");
}
// 开空条件
If(score[1] >= totalScore And MarketPosition == 0 ) //
{
SellShort(Lots, Open);
}
// 平仓条件
If(score[1] == 0 And MarketPosition == -1)
{
BuyToCover(0, Open);
}
// 在副图显示条件成立和不成立
If(macdCondition)
{
PlotAuto("MACD_Condition",1,1,Green,Enum_Line,Enum_Solid,Enum_7Pix);
}
Else
{
PlotAuto("MACD_Condition",1,1,Red,Enum_Line,Enum_Solid,Enum_7Pix);
}
If(rsiCondition)
{
PlotAuto("RSI_Condition",2,2,Green,Enum_Line,Enum_Solid,Enum_7Pix);
}
Else
{
PlotAuto("RSI_Condition",2,2,Red,Enum_Line,Enum_Solid,Enum_7Pix);
}
If(stochasticCondition)
{
PlotAuto("Stochastic_Condition", 3,3,Green,Enum_Line,Enum_Solid,Enum_7Pix);
}
Else
{
PlotAuto("Stochastic_Condition", 3,3,Red,Enum_Line,Enum_Solid,Enum_7Pix);
}
If(cciCondition)
{
PlotAuto("CCI_Condition", 4,4,Green,Enum_Line,Enum_Solid,Enum_7Pix);
}
Else
{
PlotAuto("CCI_Condition", 4,4,Red,Enum_Line,Enum_Solid,Enum_7Pix);
}
If(supertrendCondition)
{
PlotAuto("Supertrend_Condition", 5,5,Green,Enum_Line,Enum_Solid,Enum_7Pix);
}
Else
{
PlotAuto("Supertrend_Condition", 5,5,Red,Enum_Line,Enum_Solid,Enum_7Pix);
}
If(Marketbool)
{
PlotAuto("Marketbool", 6,6,Green,Enum_Line,Enum_Solid,Enum_7Pix);
}
Else
{
PlotAuto("Marketbool", 6,6,Red,Enum_Line,Enum_Solid,Enum_7Pix);
}
}
//------------------------------------------------------------------------
// 编译版本 2024/11/27 150615
// 版权所有 songshu123
// 更改声明 TradeBlazer Software保留对TradeBlazer平台
// 每一版本的TradeBlazer公式修改和重写的权利
//------------------------------------------------------------------------

View File

@@ -0,0 +1,210 @@
from vnpy_ctastrategy import (
CtaTemplate,
TargetPosTemplate,
StopOrder,
TickData,
BarData,
TradeData,
OrderData,
BarGenerator,
ArrayManager,
)
import pandas as pd
import numpy as np
import talib
class vip17_duo(CtaTemplate):
"""
VIP17多头策略
基于多个技术指标的多头策略,当满足一定数量的多头条件时开仓
"""
author = "松鼠Quant"
# 策略参数
total_score = 5 # 开仓分数阈值
entry_strength = 90 # 趋势强度的进场值
length = 5 # 强弱指标和通道计算的周期值
# 指标参数
rpm_period = 14 # RPM Period
bbo_period = 16 # BBO Period
macd_fast_period = 12 # MACD Fast Period
macd_slow_period = 24 # MACD Slow Period
macd_signal_period = 9 # MACD Signal Period
rsi_period = 14 # RSI Period
cci_period = 14 # CCI Period
stoch_k_period = 14 # Stochastic %K Length
stoch_k_smooth = 1 # Stochastic %K Smoothing
stoch_d_smooth = 3 # Stochastic %D Smoothing
supertrend_period = 10 # SUPERTREND Period
supertrend_factor = 2 # SUPERTREND Factor
parameters = ["total_score", "entry_strength", "length",
"macd_fast_period", "macd_slow_period", "macd_signal_period",
"rsi_period", "cci_period", "stoch_k_period"]
variables = ["current_score"]
def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
super().__init__(cta_engine, strategy_name, vt_symbol, setting)
self.bg = BarGenerator(self.on_bar)
self.am = ArrayManager(size=100)
# 指标变量
self.current_score = 0
self.market_strength = 0
self.supertrend_value = 0
def on_init(self):
"""
策略初始化
"""
self.write_log("策略初始化")
self.load_bar(100)
def on_start(self):
"""
策略启动
"""
self.write_log("策略启动")
def on_stop(self):
"""
策略停止
"""
self.write_log("策略停止")
def on_tick(self, tick: TickData):
"""
Tick数据更新
"""
self.bg.update_tick(tick)
def calculate_market_strength(self):
"""计算市场强度指标"""
close_change = self.am.close_array[1:] - self.am.close_array[:-1]
up_closes = 0
dn_closes = 0
for i in range(self.length):
if close_change[-i-1] > 0:
up_closes += close_change[-i-1]
else:
dn_closes += close_change[-i-1]
sum_change = np.sum(close_change[-self.length:])
if sum_change >= 0:
self.market_strength = (sum_change / up_closes * 100) if up_closes != 0 else 0
else:
self.market_strength = (sum_change / abs(dn_closes) * 100) if dn_closes != 0 else 0
return self.market_strength >= self.entry_strength
def calculate_supertrend(self):
"""计算SuperTrend指标"""
atr = talib.ATR(self.am.high_array, self.am.low_array,
self.am.close_array, self.supertrend_period)
basic_upper = (self.am.high_array + self.am.low_array) / 2 + self.supertrend_factor * atr
basic_lower = (self.am.high_array + self.am.low_array) / 2 - self.supertrend_factor * atr
# 简化的SuperTrend计算
self.supertrend_value = basic_lower[-1]
return self.am.close_array[-1] > self.supertrend_value
def calculate_score(self):
"""
计算综合得分
"""
score = 0
# MACD条件 - 多头信号
# 使用talib直接计算MACD
macd, signal, hist = talib.MACD(
self.am.close_array,
fastperiod=self.macd_fast_period,
slowperiod=self.macd_slow_period,
signalperiod=self.macd_signal_period
)
if not np.isnan(macd[-1]) and not np.isnan(signal[-1]):
if macd[-1] > signal[-1]: # 多头信号MACD线在信号线上方
score += 1
# RSI条件 - 多头信号
rsi = talib.RSI(self.am.close_array, timeperiod=self.rsi_period)
if not np.isnan(rsi[-1]) and rsi[-1] > 50: # 多头信号RSI大于50
score += 1
# Stochastic条件 - 多头信号
k, d = talib.STOCH(
self.am.high_array,
self.am.low_array,
self.am.close_array,
fastk_period=self.stoch_k_period,
slowk_period=self.stoch_k_smooth,
slowd_period=self.stoch_d_smooth
)
if not np.isnan(k[-1]) and k[-1] > 50: # 多头信号K值大于50
score += 1
# CCI条件 - 多头信号
cci = talib.CCI(
self.am.high_array,
self.am.low_array,
self.am.close_array,
timeperiod=self.cci_period
)
if not np.isnan(cci[-1]) and cci[-1] > 0: # 多头信号CCI大于0
score += 1
# Supertrend条件
if self.calculate_supertrend():
score += 1
# 市场强度条件
if self.calculate_market_strength():
score += 1
return score
def on_bar(self, bar: BarData):
"""
K线更新回调
"""
self.am.update_bar(bar)
if not self.am.inited:
return
# 计算当前得分
self.current_score = self.calculate_score()
# 交易信号
if self.current_score >= self.total_score and not self.pos:
self.buy(bar.close_price + 5, 1)
elif self.current_score == 0 and self.pos > 0:
self.sell(bar.close_price - 5, abs(self.pos))
# 输出当前得分
self.put_event()
def on_trade(self, trade: TradeData):
"""
成交回调
"""
self.put_event()
def on_order(self, order: OrderData):
"""
委托回调
"""
pass
def on_stop_order(self, stop_order: StopOrder):
"""
停止单回调
"""
pass

View File

@@ -0,0 +1,208 @@
from vnpy_ctastrategy import (
CtaTemplate,
TargetPosTemplate,
StopOrder,
TickData,
BarData,
TradeData,
OrderData,
BarGenerator,
ArrayManager,
)
import pandas as pd
import numpy as np
import talib
class vip17_kong(CtaTemplate):
"""
VIP17空头策略
基于多个技术指标的空头策略,当满足一定数量的空头条件时开仓
"""
author = "松鼠Quant"
# 策略参数
total_score = 5 # 开仓分数阈值
entry_strength = 90 # 趋势强度的进场值
length = 5 # 强弱指标和通道计算的周期值
# 指标参数
rpm_period = 14 # RPM Period
bbo_period = 16 # BBO Period
macd_fast_period = 12 # MACD Fast Period
macd_slow_period = 24 # MACD Slow Period
macd_signal_period = 9 # MACD Signal Period
rsi_period = 14 # RSI Period
cci_period = 14 # CCI Period
stoch_k_period = 14 # Stochastic %K Length
stoch_k_smooth = 1 # Stochastic %K Smoothing
stoch_d_smooth = 3 # Stochastic %D Smoothing
supertrend_period = 10 # SUPERTREND Period
supertrend_factor = 2 # SUPERTREND Factor
parameters = ["total_score", "entry_strength", "length",
"macd_fast_period", "macd_slow_period", "macd_signal_period",
"rsi_period", "cci_period", "stoch_k_period"]
variables = ["current_score"]
def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
super().__init__(cta_engine, strategy_name, vt_symbol, setting)
self.bg = BarGenerator(self.on_bar)
self.am = ArrayManager(size=100)
# 指标变量
self.current_score = 0
self.market_strength = 0
self.supertrend_value = 0
def on_init(self):
"""
策略初始化
"""
self.write_log("策略初始化")
self.load_bar(100)
def on_start(self):
"""
策略启动
"""
self.write_log("策略启动")
def on_stop(self):
"""
策略停止
"""
self.write_log("策略停止")
def on_tick(self, tick: TickData):
"""
Tick数据更新
"""
self.bg.update_tick(tick)
def calculate_market_strength(self):
"""计算市场强度指标"""
close_change = self.am.close_array[1:] - self.am.close_array[:-1]
up_closes = 0
dn_closes = 0
for i in range(self.length):
if close_change[-i-1] > 0:
up_closes += close_change[-i-1]
else:
dn_closes += close_change[-i-1]
sum_change = np.sum(close_change[-self.length:])
if sum_change >= 0:
self.market_strength = (sum_change / up_closes * 100) if up_closes != 0 else 0
else:
self.market_strength = (sum_change / abs(dn_closes) * 100) if dn_closes != 0 else 0
return self.market_strength <= -self.entry_strength # 改为判断下跌强度
def calculate_supertrend(self):
"""计算SuperTrend指标"""
atr = talib.ATR(self.am.high_array, self.am.low_array,
self.am.close_array, self.supertrend_period)
basic_upper = (self.am.high_array + self.am.low_array) / 2 + self.supertrend_factor * atr
basic_lower = (self.am.high_array + self.am.low_array) / 2 - self.supertrend_factor * atr
# 简化的SuperTrend计算
self.supertrend_value = basic_upper[-1] # 改为上轨
return self.am.close_array[-1] < self.supertrend_value # 改为判断价格低于上轨
def calculate_score(self):
"""
计算综合得分
"""
score = 0
# MACD条件 - 空头信号
# 使用talib直接计算MACD
macd, signal, hist = talib.MACD(
self.am.close_array,
fastperiod=self.macd_fast_period,
slowperiod=self.macd_slow_period,
signalperiod=self.macd_signal_period
)
if not np.isnan(macd[-1]) and not np.isnan(signal[-1]):
if macd[-1] < signal[-1]: # 空头信号
score += 1
# RSI条件 - 空头信号
rsi = talib.RSI(self.am.close_array, timeperiod=self.rsi_period)
if not np.isnan(rsi[-1]) and rsi[-1] < 50:
score += 1
# Stochastic条件 - 空头信号
k, d = talib.STOCH(
self.am.high_array,
self.am.low_array,
self.am.close_array,
fastk_period=self.stoch_k_period,
slowk_period=self.stoch_k_smooth,
slowd_period=self.stoch_d_smooth
)
if not np.isnan(k[-1]) and k[-1] < 50:
score += 1
# CCI条件 - 空头信号
cci = talib.CCI(
self.am.high_array,
self.am.low_array,
self.am.close_array,
timeperiod=self.cci_period
)
if not np.isnan(cci[-1]) and cci[-1] < 0:
score += 1
# Supertrend条件 - 空头信号
if self.calculate_supertrend():
score += 1
# 市场强度条件 - 空头信号
if self.calculate_market_strength():
score += 1
return score
def on_bar(self, bar: BarData):
"""
K线更新回调
"""
self.am.update_bar(bar)
if not self.am.inited:
return
# 计算当前得分
self.current_score = self.calculate_score()
# 交易信号
if self.current_score >= self.total_score and not self.pos:
self.short(bar.close_price - 5, 1) # 改为做空
elif self.current_score == 0 and self.pos < 0: # 改为判断空仓
self.cover(bar.close_price + 5, abs(self.pos)) # 改为平空
self.put_event()
def on_trade(self, trade: TradeData):
"""
成交回调
"""
self.put_event()
def on_order(self, order: OrderData):
"""
委托回调
"""
pass
def on_stop_order(self, stop_order: StopOrder):
"""
停止单回调
"""
pass

View File

@@ -0,0 +1,7 @@
通过网盘分享的文件VIP15参数文件.rar
链接: https://pan.baidu.com/s/1liwdmvmGJ7wjHWVewZUUWA?pwd=7777 提取码: 7777
--来自百度网盘超级会员v7的分享
如果过期了不能用了联系小松鼠微信viquant01
quant789.com可以使用参数选取工具