小弟最近在试用WL5,以港股为例,想要摆脱仅测试单一股票的单一交易策略。而是完成Pair Trading. 例如,策略Dollar Neutral, 50万买XX股票, 50万卖空YY股票,设定一套规则使XX股在获利某某元的时候开始减仓,YY则买回相应的金额 (反之亦然)。 如遇走势背离,采取BB规则减仓。 等等其他规则。 还望高人指点,类似这样的交易策略如何测试。 小弟拜谢了
上次怎么没上传上。补一下 using System; using System.Collections.Generic; using System.Text; using System.Drawing; using WealthLab; using WealthLab.Indicators;namespace WealthLab.Strategies { public class PairsTrading : WealthScript { protected override void Execute() { double OptVar1 = 1.5; double OptVar2 = 1.5; int OptVar3 = 30; int MAPeriod; double upThreshold, downThreshold; string stock1, stock2, longSymbol, shortSymbol; // enter your symbols here stock1 = "INTC"; stock2 = "MSFT"; // temporary longSymbol = stock1; shortSymbol = stock2; upThreshold = OptVar1; downThreshold = -OptVar2; MAPeriod = OptVar3; // compute series DataSeries close1; DataSeries close2; SetContext( stock1, true ); close1 = Close; //RestoreContext(); SetContext( stock2, true ); close2 = Close; RestoreContext(); DataSeries ActualRatio = close1 / close2; ActualRatio.Description = "ActualRatio"; DataSeries ActualRatioSMA = SMA.Series( ActualRatio, MAPeriod ); ActualRatioSMA.Description = "ActualRatioSMA"; DataSeries Delta = ActualRatio - ActualRatioSMA; Delta.Description = "Delta"; DataSeries DeltaSMA = SMA.Series( Delta, MAPeriod ); DeltaSMA.Description = "DeltaSMA"; DataSeries DeltaDifference = Delta - DeltaSMA; DeltaDifference.Description = "DeltaDifference"; DataSeries DeltaNorm = DeltaDifference / StdDev.Series( Delta, MAPeriod, WealthLab.Indicators.StdDevCalculation.Sample ); DeltaNorm.Description = "DeltaNorm"; // graphics ChartPane RatioPane = CreatePane( 30, true, true ); ChartPane StDevPane = CreatePane( 30, true, true ); PlotSeries( RatioPane, ActualRatio, Color.Navy, WealthLab.LineStyle.Solid, 2 ); PlotSeries( RatioPane, ActualRatioSMA, Color.Blue, WealthLab.LineStyle.Solid, 2 ); DrawLabel( RatioPane, "Ratio " + stock1 + "/" + stock2 ); PlotSeries( StDevPane, DeltaNorm, Color.Red, WealthLab.LineStyle.Histogram, 2 ); DrawHorzLine( StDevPane, upThreshold, Color.Black, WealthLab.LineStyle.Solid, 2 ); DrawHorzLine( StDevPane, downThreshold, Color.Black, WealthLab.LineStyle.Solid, 2 ); DrawLabel( StDevPane, "Number of standard deviations" ); for(int bar = MAPeriod; bar < Bars.Count; bar++) { if (IsLastPositionActive) { SetContext( shortSymbol, true ); CoverAtClose( bar, Position.AllPositions, "Cover " + shortSymbol ); SellAtClose( bar, Position.AllPositions, "Sell " + longSymbol ); RestoreContext(); } { if( DeltaNorm[bar] > upThreshold ) { shortSymbol = stock1; longSymbol = stock2; SetContext( stock1, true ); ShortAtClose( bar, "ShortSell " + stock1 ); SetContext( stock2, true ); BuyAtClose( bar, "Buy " + stock2 ); } else if( DeltaNorm[bar] < downThreshold ) { shortSymbol = stock2; longSymbol = stock1; SetContext( stock2, true ); ShortAtClose( bar, "ShortSell " + stock2 ); SetContext( stock1, true ); BuyAtClose( bar, "Buy " + stock1 ); } RestoreContext(); } } } } }