- ago
I have A / B / C / D / E / F six symbols in Dataset.

All money has gone to buy three (A / B / C) symbols, there are three other (D / E / F) symbols buying signals today,

I have to sell A / B / C symbols first in Execute before buy D / E / F symbols to avoid NSF, What should i do?

Thx
0
1,001
Solved
6 Replies

Reply

Bookmark

Sort
Cone8
 ( 25.44% )
- ago
#1
Not enough information about the buys and sells.

But, if we're talking about market orders, if I'm not mistaken, exits at market will occur first by backtest design. If I am mistaken (don't think so, but possible), you can set the Transaction.Weight for all trades. The highest Weights are executed first.
0
- ago
#2
This strategy buys only one symbol.

Strategy description:

DataSet : two symbols

calculate 5-day return timeseries

select are two symbols maximum value ( return ) on Thursday

buy the symbol with all capital.

CODE:
using WealthLab.Backtest; using System; using WealthLab.Core; using System.Collections.Generic; namespace WealthScript4 {       public class NSF_strategy : UserStrategyBase    {             private static List<BarHistory> Buys = new List<BarHistory>();       TimeSeries _Ts_Rtn;       double _TE_val;              public NSF_strategy()       {          AddParameter(" Window ", ParameterTypes.Int32, 5, 5, 60, 1);       }              public override void Initialize(BarHistory bars)       {          StartIndex = Parameters[0].AsInt;          _Ts_Rtn = new TimeSeries(bars.DateTimes, 0);                    for (int i = StartIndex; i < bars.Count -1; i++)             _Ts_Rtn[i] = (bars.Close[i] - bars.Close[i - StartIndex]) / bars.Close[i - StartIndex];          bars.Cache["Return"] = _Ts_Rtn;          PlotTimeSeries(_Ts_Rtn, "T(5)-T(0)", "ReturnTimeSeries_Pane");       }        public override void PreExecute(DateTime dt, List<BarHistory> participants) {          foreach (BarHistory bh in participants)          {                TimeSeries _TE = (TimeSeries)bh.Cache["Return"];                int idx = GetCurrentIndex(bh);                _TE_val = _TE[idx];                bh.UserData = _TE_val;          }          participants.Sort((a, b) => -a.UserDataAsDouble.CompareTo(b.UserDataAsDouble)); //H to L                    Buys.Clear();          Buys.Add(participants[0]); } public override void Execute(BarHistory bars, int idx)       {          bool _BuyList = Buys.Contains(bars);                    if(((int)bars.GetDate(idx).DayOfWeek).ToString() == "4")          {             if (!_BuyList)             {                if (HasOpenPosition(bars, PositionType.Long))                   ClosePosition(LastPosition, OrderType.Market);             }             else if (_BuyList)             {                if (!HasOpenPosition(bars, PositionType.Long))                {                   var Q = Math.Floor(CurrentEquity * 1 / bars.Close[idx]);                   PlaceTrade(bars, TransactionType.Buy, OrderType.Market).Quantity = Q;                }             }          }       }    } }


Strategy Settings :



problem 1. Why buy two symbols ( See Backtest Results Equity Curve image )



problem 2. Why is NSF produced ( See Backtest Results Metrics Report image )



Thx.
0
Cone8
 ( 25.44% )
- ago
#3
The NSF issue is easy. You're using 100% equity but the Basis Price is "Market Close this Bar". To avoid NSF with 100% sizing:
1. select Basis Price "Market Open Next Bar", OR,
2. reduce the sizing to account for gaps, OR,
3. Use some Margin, like 1.20

I'll have to look more closely at the script to see how you can end up with 2 positions.
1
Cone8
 ( 25.44% )
- ago
#4
I actually can't duplicate the 2-symbol issue with the 2 instruments I tested with (ZS, TTD).

However, your logic requires a DayOfWeek = 4 to execute. That would be a problem if one of the instruments doesn't trade on that day. Check the questionable trades and the data for that week. Maybe there's a day or two missing.
1
- ago
#5
Hi, Cone

QUOTE:

I actually can't duplicate the 2-symbol issue with the 2 instruments I tested with (ZS, TTD).

However, your logic requires a DayOfWeek = 4 to execute. That would be a problem if one of the instruments doesn't trade on that day. Check the questionable trades and the data for that week. Maybe there's a day or two missing.


I use the IsTradingDay function to determine whether the next day is a trading day

but the symbol (SH600196) date 2010/1/8 does not exist in the data

print out IsTradingDay is true, Why?

CODE:
         string Result = string.Format(" {0:20} {1:20} \r\n {2:20} {3:20} \r\n {4:20} {5:20} \r\n {6:20} {7:20} \r\n {8:20} {9:20}"             , " Today = ", bars.GetDate(idx).ToString("yyyy/M/d")             , " Symbol = ", bars.Symbol             , " NextDayIsTrading = ", bars.Market.IsTradingDay(bars.GetDate(idx).AddDays(1))             , " NextDate = ", bars.GetDate(idx).AddDays(1).ToString("yyyy/M/d")             , " NextDateOfWeek = ", ((int)bars.GetDate(idx).AddDays(1).DayOfWeek).ToString());          WriteToDebugLog("----------------------------------");          WriteToDebugLog(Result);




0
- ago
#6
QUOTE:
but the symbol (SH600196) date 2010/1/8 does not exist in the data

print out IsTradingDay is true, Why?

Because as far the U.S. market schedule is concerned, it's a business day. Apparently, your ASCII symbols are assigned the default market (US Stocks) whereas you're trading Chinese markets.

You could create a new market for Chinese stocks in Tools > Markets and Symbols and configure its properties. Then use its Symbols tab to set up a pattern for stocks like SH###### (assuming all your stocks follow this pattern).

Pay attention to entering holidays so that 2010/1/8 would be recognized. If you did everything right, all symbols starting with SH... and having 6 digits will be assigned to the newly defined China market.

Finally, if you know a reliable historical source of holiday dates for the Chinese market, please let us know so we could beef up WL7 with a new market and include the holiday schedule.
1
Best Answer

Reply

Bookmark

Sort