Back

Capture opening price

Simple question I am sure, but this newbie is stuck! What Voodoo magic can I use to capture the opening price of the day for a particular stock? Something to do with DateTime I suspect, but I haven't found it. Any help would be appreciated.
Update Backtest








What frequency are you using?
If you're using Daily, then you'll get the day's open by doing data["GOOG"].Open
If you're using Minute data and want to remember what was the open of the day, I would try something like:

string currentDay = data [_symbol].Time.ToString("yyyyMMdd");
if (currentDay != previousDay) {
previousDay = currentDay;
open = data[_symbol].Open;
}
0

Josh - I hadn't. Sebastien - Thanks, I'll try that. I'm using minute resolution and I want to know at what price "XXX" opens each day, capture that price and use it as a reference for all day, then reset it each day for that day's use. After I get this working, I plan to reset the price level each hour. I'm just playing, trying to learn how to write algorithms. Right now it's all Voodoo magic :) I'm trying to teach an old dog new tricks - and failing miserably! Thanks again for the hint. I'll play around with it.
0

Another thought - resolution really shouldn't matter. Daily or minute or whatever, the open is the open, right?
0

You could also use the scheduled events feature to fire off some code every day just after the market opens to get the opening prices for every securitySchedule.Event("Get Open Prices")
.EveryDay("SPY")
.AfterMarketOpen("SPY", minutesAfterOpen: 1)
.Run(() =>
{
foreach (var security in Securities.Values)
{
// save security.Open somewhere
}
});


This event will fire 1 minute after SPY's market open every day that SPY trades. then inside run you can loop over the securities and save off your opening prices.
2

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.


That looks like a much better solution
1

Thanks Michael, that looks cool. Now if I can decipher what it all does ....
I wish I could take you to a three martini lunch and pick your brain :)
Oh well, back to work.
0

Hi Michael,

     Could you give one example on saving open prices? I want to save the open prices to a dictionary for the following tickers:            

            "AAPL", 
            "SPY", 
            "QQQ", 
            "IWM", 
            "IBM"?

Don't know how it should be coded? Thanks.

 

Mike

 

0

Adapting Mike's code above:

private Dictionary<Symbol, decimal> _openDict;

// In Initialize
_openDict = new Dictionary<Symbol, decimal>();

var tickers = "AAPL, SPY, QQQ, IWM, IBM".Split(',');
foreach (var ticker in tickers)
{
var symbol = AddEquity(ticker).Symbol;
_openDict.Add(symbol, 0);
}

Schedule.Event("Get Open Prices")
.EveryDay("SPY")
.AfterMarketOpen("SPY", minutesAfterOpen: 1)
.Run(() =>
{
foreach (var security in Securities.Values)
{
_openDict[security.Symbol] = security.Open;
}
});

Please note that if there is no information from one of these symbols one minute after the exchange opens, the algorithm will not catch the new opening price.

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.


Thanks a lot, Alex! As you pointed out that there is a disadvantage for using the method above, i.e., if there is no information from one of these symbols one minute after the exchange opens, the algorithm will not catch the new opening price.

Can the logic below overcome that disadvantage?

If yes, how can I change it for multiple symbols and get the open prices for multiple symbols?  Sorry, my C# skill is very rusty.

=================================================

  private TradeBar open;

 public override void Initialize()
        {
            SetStartDate(2004, 01, 1); 
            SetEndDate(2004, 01,3);  
            AddSecurity(SecurityType.Equity, "SPY", Resolution.Minute); 

        }

public void OnData(TradeBars data)
        {
          
            // populate our opening price variable
            if (open == null || open.Time.Date != Time.Date)
            {
                // when TryGetValue succeeds it will populate the 'open'
                // if it fails then 'open' will have a value of null
                data.TryGetValue("SPY", out open);
            }
             
            
 
        }

0

I haven't tested your code, but the logics would overcome that issue.
In the following code, we propose a solution that uses a dictionary to save the information. We set the initial price to zero at the end of the day to know whether we has saved the new the opening price.

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 Alex,
    Thanks for sharing the program. I tried your program but it stopped working when I change from one symbol to multiple symbols. Specifically I changed from:

AddSecurity(SecurityType.Equity, "SPY", Resolution.Minute);

to:
           var tickers = "AAPL, SPY, QQQ, IWM, IBM".Split(',');
            foreach (var ticker in tickers)
            {
                AddSecurity(SecurityType.Equity, ticker, Resolution.Minute);
           }

The error I got:

Runtime Error: 'SPY' wasn't found in the TradeBars 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("SPY")      (Open Stacktrace) 


 

0

In OnData event handler, the algorithm is looking for SPY in the TradeBars object (e.g. data["SPY"].Close) when we haven't subscribed for it in Initialize method.
We need to change the code after this part:

foreach(var item in data.Where(x => _open[x.Key] == 0))
{
_open[item.Key] = item.Value.Open;
}

for logic that will use the subscribed symbols (AAPL, SPY, QQQ, IWM, IBM) instead.

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.


Thanks, Alex!

Finally got it.

 

0

Hi, 

could anyone give a python exampe on how to get the open price ? 

Thanks in advance !

0

Hi Stephane, there are two methods to get the open price 

1) In OnData(self, data), at each time step, data is a trade bar. You can get the open price of the current trade bar with 

if data.Bars.ContainsKey(symbol):
open_price = data[symbol].Open

2) You can use the "Security" object. For example

self.Securities[symbol].Open

For more properties of the Security object

https://www.quantconnect.com/lean/documentation/topic26785.html

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.


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