Hi,
I'm new on creating algos here on Quantconnect. Tried searching for the answer but got even more confused than before. If this has been answered already please do send me to that thread.
I got 2 questions:
1. I want to compare the current daily close price for a stock to sma200. If it's above I want to buy and if it's below I want to sell. But can't get the backtest to working. I think it has to do with my price formatting?
2. How do I compare today's close price with yesterdays and the day before?
Thanks in advance!
Recordatio
This​​​​​​ is my code below.
import clr
clr.AddReference("System")
clr.AddReference("QuantConnect.Algorithm")
clr.AddReference("QuantConnect.Indicators")
clr.AddReference("QuantConnect.Common")
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
import decimal as d
from datetime import datetime
class FirstAlgo(QCAlgorithm):
def Initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.SetCash(100000) #Set Strategy Cash
self.SetStartDate(2007, 1, 1) #Set Start Date
self.SetEndDate(2011, 1, 1) #Set End Date
self.stock = "spy"
self.AddEquity(self.stock, Resolution.Daily)
### SMA ###
# create a 200 day moving average
self.SMA200 = self.SMA(self.stock, 200, Resolution.Daily);
def OnData(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
# a couple things to notice in this method:
# 1. We never need to 'update' our indicators with the data, the engine takes care of this for us
# 2. We can use indicators directly in math expressions
# 3. We can easily plot many indicators at the same time
### SMA setups ###
# wait for our slow ema to fully initialize
if not self.SMA200.IsReady:
return
### When to buy/sell ###
holdings = self.Portfolio[self.stock].Quantity
# buy when close price is above SMA200
if holdings <= 0:
#Got an error on the line below...
if self.SMA200[self.stock].Current.Value < [self.stock].Ask.Close:
self.Log("BUY >> {0}".format(self.Equity[self.stock].Price))
self.SetHoldings(self.stock, 1)
# sell when close price is under SMA200
if self.SMA200[self.stock].Current.Value > [self.stock].Ask.Close:
self.Log("SELL >> {0}".format(self.Equity[self.stock].Price))
self.Liquidate(self.stock)
Recordatio
Solved the first question. Still wondering how to compare different days closes?
Jing Wu
To get the history of the closing price, you can use the RollingWindow. The first step is creating the rolling window in Initialize(),
self.window = RollingWindow[Decimal](3)
In OnData(self, data), you can add the close price in the current slice to this window
self.window.Add(self.Securities["SPY"].Close)
When the window is ready(the window was populated with at least three price values), you can get the close history with
if self.window.IsReady: self.window[0] # Current close price self.window[1] # yesterday's close self.window[2] # close the day before
Recordatio
Thanks Jing!
It worked!
Recordatio
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.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!