Back

¿could anyone help me with a couple details on a very simple strategy?

 

 

hello to everyone,

 

while i have some experience developing automated strategies, i'm completely new to quantconnect and could use some help in order to finalize a very simple strategy. i have been making modifications to one of the sample strategies that are included with the lean platform but there are some errors and i can't finalize it.

 

i have two issues i haven't been able to solve, even when i have searched the documentation and sample code. 1) ¿what changes should be made to this strategy so that everything ran in 6 minute bars (the trade bars, the indicators, everything)? 2) and the second thing i have had trouble with is the logic for the entries and exits: (_hmav[0] > _hmav[1]). ¿how could i get the strategy to go long if the current value of the hma is greater than one period ago, and short if the inverse is true?

 

/*
*
*/

using System;
using System.Linq;
using QuantConnect.Data.Market;
using QuantConnect.Indicators;

namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
///
/// </summary>
/// <meta name="tag" content="indicators" />
/// <meta name="tag" content="indicator classes" />

public class hmarevdaily : QCAlgorithm
{
private string _symbol = "NVDA";
private DateTime _previous;
private HullMovingAverage _hmav;
private SimpleMovingAverage[] _ribbon;

/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
// set up our analysis span
SetStartDate(2013, 01, 01);
SetEndDate(2019, 01, 15);
SetCash(10000); //Set Strategy Cash

// request SPY data with minute resolution
AddSecurity(SecurityType.Equity, _symbol, Resolution.Minute);

// create a 15 day exponential moving average
_hmav = HMA(_symbol, 15, Resolution.Minute);


}


/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">TradeBars IDictionary object with your stock data</param>
public void OnData(TradeBars data)
{


//
if (!_hmav.IsReady) return;




var holdings = Portfolio[_symbol].Quantity;

// we only want to go long if we're currently short or flat
if (holdings <= 0)
{
// if the fast is greater than the slow, we'll go long
if (_hmav[0] > _hmav[1])
{
Log("BUY >> " + Securities[_symbol].Price);
SetHoldings(_symbol, 1.0);
}
}

// we only want to liquidate if we're currently long
// if the fast is less than the slow we'll liquidate our long
if (holdings > 0 && __hmav[0] < __hmav[1])
{
Log("SELL >> " + Securities[_symbol].Price);
SetHoldings(_symbol, -1.0);
}

Plot(_symbol, "Price", data[_symbol].Price);

// easily plot indicators, the series name will be the name of the indicator
Plot(_symbol, _hmav);


_previous = Time;
}
}
}

 

 

very well, thanks, regards.

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.


Welcome!

1) You would need a Consolidator to do this. This is a class that "stores" incoming data and releases it when x minutes/hours/days have passed. You can also register indicators to use the consolidator, meaning they will calculate their values based on this "released" data (instead of on every tick). Check out this documentation page for how to set this up, and let us know if you have any issues: 

https://www.quantconnect.com/docs/algorithm-reference/consolidating-data

2) You can't use the [0] and [1] indexers like this - by default, indicators only show you the current value. To store previous values, you will need a RollingWindow. Please check out this link: 

https://www.quantconnect.com/docs/algorithm-reference/rolling-window
0

 

 

good day once again,

 

 

i'm still having a lot of problems with the quantconnect platforms. i have been trying for almost a week but the lean platform won't build correctly on my laptop and putting together a simple hull moving average reversal strategy is proving really complicated.

 

this code below either results in internal server errors or the backtests will abort halfway.

 

https://www.quantconnect.com/backtest/68566/2241082/c9bd730fd31f2620a0218c1167cef112-log.txt


https://www.quantconnect.com/backtest/68566/2241082/591014f8a667bddeb1dd053c73436cf7-log.txt


https://www.quantconnect.com/backtest/68566/2241082/155503b0b4fe82e995fafea0353eb018-log.txt

 

 

/*
*
*/

using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Indicators;

namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Using rolling windows for efficient storage of historical data; which automatically clears after a period of time.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="history and warm up" />
/// <meta name="tag" content="history" />
/// <meta name="tag" content="warm up" />
/// <meta name="tag" content="indicators" />
/// <meta name="tag" content="rolling windows" />
public class nvdahmarevdaily : QCAlgorithm
{
private RollingWindow<TradeBar> _window;
private RollingWindow<IndicatorDataPoint> _hmaWin;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 01, 01); // Set Start Date
SetEndDate(2019, 01, 16); // Set End Date
SetCash(10000); // Set Strategy Cash

// Find more symbols here: http://quantconnect.com/data
AddEquity("NVDA", Resolution.Daily);

// Creates a Rolling Window indicator to keep the 2 TradeBar
_window = new RollingWindow<TradeBar>(2); // For other security types, use QuoteBar

// Creates an indicator and adds to a rolling window when it is updated
var hma = HMA("NVDA", 25);
hma.Updated += (sender, updated) => _hmaWin.Add(updated);
_hmaWin = new RollingWindow<IndicatorDataPoint>(2);
}

/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
// Add SPY TradeBar in rollling window
_window.Add(data["NVDA"]);

// Wait for windows to be ready.
if (!_window.IsReady || !_hmaWin.IsReady) return;

var currBar = _window[0]; // Current bar had index zero.
var pastBar = _window[1]; // Past bar has index one.
Log($"Price: {pastBar.Time} -> {pastBar.Close} ... {currBar.Time} -> {currBar.Close}");

var currhma = _hmaWin[0]; // Current hma had index zero.
var pasthma = _hmaWin[1]; // Oldest hma has index of window count minus 1.
Log($"hma: {pasthma.Time} -> {pasthma.Value} ... {currhma.Time} -> {currhma.Value}");

var holdings = Portfolio["NVDA"].Quantity;

if (holdings <= 0)
{
// if the fast is greater than the slow, we'll go long
if (currhma > pasthma)
{
Log("buy >> " + Securities["NVDA"].Price);
SetHoldings("NVDA", 1.0);
}
}

if (holdings >= 0)
{
if (currhma < pasthma)
{
Log("sell short >> " + Securities["NVDA"].Price);
SetHoldings("NVDA", -1.0);
}
}

Plot("NVDA", "Price", data["NVDA"].Price);
}
}
}

 

¿could i get some support to get this strategy to work? thanks.

0

Hi,

On line 86, you're assuming that the data object contains a price. This isn't necessarily the case, and you need to be careful with assuming that certain properties exist in the incoming slice.

I've edited that line on my end to query the Price property from Securities instead and it works nicely. I've also commented out the Log lines but feel free to re-add them.

0


 

 

mr. Douglas,

 

 

thanks a lot for your assistance. this is an elementary strategy which should run without any problem in any platform. however, i have been having an exceedingly hard time with qc; for starters, the lean platform won't build correctly on my laptop and the qc documentation and code can be confusing as different examples use quite different structures.

 

in this case, i wasn't making any assumptions about anything, i just took the rolling window sample algorithm as it is and worked directly on top of it. i now realize that a lot of crap that was included in that excerpt is superfluous and removed it all.

 

this algorithm now runs on daily bars - intervals as it stands but i want code that will operate on 6 minute bars. i will now try to get the data consolidation sample algorithm to work and then will try to reconcile the logic for both rolling windows and data consolidation into one single excerpt. this isn't the easiest thing in the world as both examples have vastly different structures, anyone can corroborate this by looking at the two links you kindly provided before.

 

very well, thanks again, i will report on any progress i make, regards.

0

Hi Marcos,

I understand your plight. Lean is an incredibly flexible and powerful framework, and with that comes a certain learning curve. I can only say that the learning is worth it but comes in "thresholds" - at least for me, there were "jumps" in my learning where I suddenly realised many things at once.

One of the reasons the examples are structured differently is to show how things can be done in a multitude of ways.

What you're doing now - implementing a simple strategy and then incrementally extending its functionality - is a great way to do it. Also, if you are giving Lean locally a shot, that's great, and Visual Studio's code hinting, debugging etc. can be very useful. But remember you can always develop in Visual Studio and backtest via the terminal, which would probably eliminate your compile issues.

Feel free to post your compile issues here on the forum, happy to take a look!

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

 
";