Back

"wasn't found in the Slice object"..."data.ContainsKey(" ")"

Hi !

I am new in the community and happy to write my first message !

I am here to convert a backtest that i make on excel and i am going to have your help ;)

When i run the code below, it doesn't find the symbol ES to order. Could you help me.

Runtime Error: ' ' wasn't found in the Slice object, likely because there was no-data at this moment in time and it wasn't possible to fillforward historical data. Please check the data exists before accessing it with data.ContainsKey(" ") (Open Stacktrace)

I have probably missed something about the use of symbol or consolidation of data.

using System;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Orders;

namespace QuantConnect.Algorithm.CSharp
{
    public class TestAlgorithm : QCAlgorithm
    {
        public RollingWindow<decimal> Open;
        public RollingWindow<decimal> Close;
        public RollingWindow<decimal> High;
        public RollingWindow<decimal> Low;
        public RollingWindow<decimal> Volume;
        
        public override void Initialize()
        {
            SetStartDate(2019, 01, 08);
            SetEndDate(2019, 10, 10);
            SetCash(1000000);

            var future = AddFuture("ES", Resolution.Minute);
            future.SetFilter(TimeSpan.Zero, TimeSpan.FromMinutes(182));
            
            Open = new RollingWindow<decimal>(4);
            Low = new RollingWindow<decimal>(4);
            High = new RollingWindow<decimal>(4);
            Close = new RollingWindow<decimal>(4);
            Volume = new RollingWindow<decimal>(4);

        }

        public override void OnData(Slice data)
        {
            
        if (data.ContainsKey("ES"))
        
        Open.Add(data["ES"].Open);
        Low.Add(data["ES"].Low);
        High.Add(data["ES"].High);
        Close.Add(data["ES"].Close);
        Volume.Add(data["ES"].Volume);
        
        var CurrentClose = Close[0];
        var OneBarAgoClose = Close[1];
        var TwoBarAgoClose = Close[2];
        var ThreeBarAgoClose = Close[3];

        var CurrentOpen = Open[0];
        var OneBarAgoOpen = Open[1];
        var TwoBarAgoOpen = Open[2];
        var ThreeBarAgoOpen = Open[3];
        
        var CurrentHigh = High[0];
        var OneBarAgoHigh = High[1];
        var TwoBarAgoHigh = High[2];
        var ThreeBarAgoHigh = High[3];
        
        var CurrentLow = Low[0];
        var OneBarAgoLow = Low[1];
        var TwoBarAgoLow = Low[2];
        var ThreeBarAgoLow = Low[3];
        
        var CurrentVolume = Volume[0];
        var OneBarAgoVolume = Volume[1];
        var TwoBarAgoVolume = Volume[2];
        var ThreeBarAgoVolume = Volume[3];
        
        
        if (CurrentClose > OneBarAgoClose)
        {
        MarketOrder("ES", 1);
        
        }
        else
        {
        Liquidate();
        }
        }
    }
}

Update Backtest







0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Hi Gmamuze Cht:

 

Could you attach the backtest so we can run it and find the issue?

0

Hi Dave !

I have made some changes, i can run a backtest now but condition to place an order doesn't work.

 

0


Hi Gmamuze,

Please check out this documentation page. A future contract needs to be selected before using futures data. Please also check out this template algorithm for how to select future contracts.

I hope this helps!

0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Hi Xin, thank you for these link.

I follow these but doesn't work and know i can't show you a backtest because I have the same runtime error :

Runtime Error: '/ES' wasn't found in the Slice object, ...

I think I am not using the function RollingWindow correctly, but don't know how use it well, even with doc.

My code :

###

using System;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using System.Linq;
using QuantConnect.Interfaces;
using QuantConnect.Indicators;
using QuantConnect.Securities;
using QuantConnect.Orders;
using QuantConnect.Data.Consolidators;

namespace QuantConnect.Algorithm.CSharp
{
    public class TestAlgo : QCAlgorithm, IRegressionAlgorithmDefinition
    {
        
        private const string RootSP500 = Futures.Indices.SP500EMini;
        public Symbol SP500 = QuantConnect.Symbol.Create(RootSP500, SecurityType.Future, Market.USA);
        
        public RollingWindow<decimal> Open;
        public RollingWindow<decimal> Close;
        public RollingWindow<decimal> High;
        public RollingWindow<decimal> Low;
        public RollingWindow<decimal> Volume;
        
        public override void Initialize()
        {
            SetStartDate(2010, 01, 08);
            SetEndDate(DateTime.Now);
            SetCash(1000000);
            
            var futureSP500 = AddFuture(RootSP500, Resolution.Daily);
            futureSP500.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));

            Open = new RollingWindow<decimal>(4);
            Low = new RollingWindow<decimal>(4);
            High = new RollingWindow<decimal>(4);
            Close = new RollingWindow<decimal>(4);
            Volume = new RollingWindow<decimal>(4);
            
            var benchmark = AddEquity("SPY");
            SetBenchmark(benchmark.Symbol);
        }
        public override void OnData(Slice slice)
        {
            
        Close.Add(slice[SP500].Close);
        Open.Add(slice[SP500].Open);
        High.Add(slice[SP500].High);
        Low.Add(slice[SP500].Low);
        Volume.Add(slice[SP500].Volume);
        
        var CurrentClose = Close[0];
        Console.WriteLine(CurrentClose);
        var OneBarAgoClose = Close[1];
        Console.WriteLine(OneBarAgoClose);
        var TwoBarAgoClose = Close[2];
        Console.WriteLine(TwoBarAgoClose);
        var ThreeBarAgoClose = Close[3];
        Console.WriteLine(ThreeBarAgoClose);

        var CurrentOpen = Open[0];
        var OneBarAgoOpen = Open[1];
        var TwoBarAgoOpen = Open[2];
        var ThreeBarAgoOpen = Open[3];
        
        var CurrentHigh = High[0];
        var OneBarAgoHigh = High[1];
        var TwoBarAgoHigh = High[2];
        var ThreeBarAgoHigh = High[3];
        
        var CurrentLow = Low[0];
        var OneBarAgoLow = Low[1];
        var TwoBarAgoLow = Low[2];
        var ThreeBarAgoLow = Low[3];
        
        var CurrentVolume = Volume[0];
        var OneBarAgoVolume = Volume[1];
        var TwoBarAgoVolume = Volume[2];
        var ThreeBarAgoVolume = Volume[3];
        
        var Order = CurrentClose > OneBarAgoClose;
        
            if (!Portfolio.Invested)
            {
                foreach(var chain in slice.FutureChains)
                {
                    // find the front contract expiring no earlier than in 90 days
                    var contract = (
                        from futuresContract in chain.Value.OrderBy(x => x.Expiry)
                        where futuresContract.Expiry > Time.Date.AddDays(90)
                        select futuresContract
                    ).FirstOrDefault();

                    // if found, trade it
                    if (contract != null)
                    {
                        MarketOrder(contract.Symbol, 1);
                    }
                }
            }
            else
            {
                Liquidate();
            }
        }
        /// <summary>
        /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
        /// </summary>
        public bool CanRunLocally { get; } = true;

        /// <summary>
        /// This is used by the regression test system to indicate which languages this algorithm is written in.
        /// </summary>
        public Language[] Languages { get; } = { Language.CSharp };

        /// <summary>
        /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
        /// </summary>
        public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
        {
            {"Total Trades", "0"},
            {"Average Win", "0%"},
            {"Average Loss", "0%"},
            {"Compounding Annual Return", "0%"},
            {"Drawdown", "0%"},
            {"Expectancy", "0"},
            {"Net Profit", "0%"},
            {"Sharpe Ratio", "0"},
            {"Loss Rate", "0%"},
            {"Win Rate", "0%"},
            {"Profit-Loss Ratio", "0"},
            {"Alpha", "0"},
            {"Beta", "0"},
            {"Annual Standard Deviation", "0"},
            {"Annual Variance", "0"},
            {"Information Ratio", "0"},
            {"Tracking Error", "0"},
            {"Treynor Ratio", "0"},
            {"Total Fees", "$0.00"}
        };
    }
}

###

0

Probably not relevant but I had a similar problem when I was using single quotes instead of double quotes for symbols

0

Hi both,

You can use the Insert Code Snippet 37376_1567627855.jpg button to insert code in a way which makes it more readable.

Using the example files from GitHub can be confusing as they contain additional methods you do not need to run an algorithm (but that are used for internal testing purposes).

I also strongly recommend checking the readiness of your rolling windows. In the code you submitted, you would have tried accessing entries in the window that were not yet populated. I've also made some general optimisations to your code and fixed problems. Futures contracts do not have open/low/highs, only BidPrice and AskPrice.

The code still doesn't trade, but that's likely due to it not finding any suitable contracts. You will have to look into what contracts are available for the time range you're specifying, and possibly use a different filter.

Indentation is messed up, but that's outside of my control and happened when uploading it to the forums.

hello you should never access data slices by strings, you should use symbols. Accessing by strings/tickers may work most of the time but it may break at some unexpected point.

 

0


Hi Douglas, many thanks for your help !

Srry for don't using code snippet icone, i didn't know.

Question :

Have I to use consolidator to create bars ? Or resolution is by default used for ?

0

The data resolution you've selected is the default bar resolution, so yes, bars will be created from that - you do not need to create consolidators for that. If you need to create bars at other, lower resolutions (i.e. subscribing to hourly but wanting daily bars), then you can use consolidators.

0

Hi all !

I have updated my code with modification above, and I still can not trigger an order in function of my condition. But thanks to douglas, all data-points are analysed in hourly and daily, don't ask in minute or tick, it seems not avaible yet.

I begin to understand why there are no Alpha to buy in the store for future :p.

If Bars are made on the base of resolution, I don't understand why it doesn't work.

Backtest below.

0


Hi Gmamuze,

I'm not sure why you've re-added the extra code I told you was not needed.

Also, the !.IsReady checks must be done before you try to access any entries in the rolling window.

I've made some modifications to your code to clean it up - it contains a lot of unnecessary stuff.

The reason your code doesn't trade is because Resolution.Hour is not available for futures. Only Resolution.Minute and higher is available (see the data page for proof). This was a mistake on my part - in my original code I gave you Resolution.Daily which also does not work.

1


Hi Douglas, one more time thanks ! :)

I am following your code and integrated stop market orders, the result is rather good for these two simple conditions.

But my path is still long to integrate everything that is asked.
0


Update Backtest





0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Loading...

This discussion is closed