Hey Guys, I have been having issues getting a code to work properly. So, I started from scrach and in a notebook. I have found how to call the Relative Strenght Index (RSI), Bollinger Bands, MACD, but I cannot figure out how to call the Stochastic indicator in the notebook.
I have tried, Stochastic(xxx), Sto, qb.Indicator.Sto and a number of other variants.
I keep getting the following error:
no constructor matches given arguments Thoughs?qb = QuantBook()
# Parameters for Indicators
Boll_Length = 20 # Number of days back
Boll_STD = 2.1 # Standard deviation used for upper/lower bands
RSI_Lenght = 14 # Number of days taken into account
Sto_K = 10 # K lenght
Sto_D = 10 # D lenght
MACD_Fast = 12 # Fast length
MACD_Slow = 26 # Slow length
MACD_Signal = 9 # Signal lenght
# Add Equity
spy = qb.AddEquity("SPY", Resolution.Daily).Symbol
# Relative Strength Index (RSI)
rsi = RelativeStrengthIndex(RSI_Lenght)
# Bollinger Band
BollBand = BollingerBands(Boll_Length, Boll_STD, MovingAverageType.Exponential)
# Stochastic
Stoch = Stochastic(Sto_K, Sto_D)
#Stoch = qb.Indicator(STO(Sto_K, Sto_D))
# Moving Average Convergence Divergence (MACD)
Macd = MovingAverageConvergenceDivergence(MACD_Fast, MACD_Slow, MACD_Signal, MovingAverageType.Exponential)
# Create Monthly calendar consolidator
MonthlyConsolidator = TradeBarConsolidator(Calendar.Monthly)
# Define DataConsolidated event handler to track RSI values
def OnMonthlyData(sender, updated):
if rsi.IsReady:
print(f"{updated.Time} RSI VALUE: {rsi.Current.Value}")
if BollBand.IsReady:
print(f"{updated.Time} Bollinger Band: {BollBand.UpperBand}")
MonthlyConsolidator.DataConsolidated += OnMonthlyData
# Register rsi to Monthly consolidator
qb.RegisterIndicator(spy, rsi, MonthlyConsolidator)
qb.RegisterIndicator(spy, BollBand, MonthlyConsolidator)
qb.RegisterIndicator(spy, Stoch, MonthlyConsolidator)
qb.RegisterIndicator(spy, Macd, MonthlyConsolidator)
# Make history call to update consolidator, 1800 days guarantees at least 14 weeks of data
history = qb.History(spy, 1800, Resolution.Daily)
opens = history.loc["SPY"]["open"]
closes = history.loc["SPY"]["close"]
lows = history.loc["SPY"]["low"]
highs = history.loc["SPY"]["high"]
volumes = history.loc["SPY"]["volume"]
times = history.unstack(0).index.values
# Update consolidator with historical data
for i in range(len(history)):
bar = TradeBar(times[i], spy, opens[i], highs[i], lows[i], closes[i], volumes[i])
MonthlyConsolidator.Update(bar)
Derek Melchin
Hi Chad,
The Stochastic class expects three arguments:
See the docs here.
Best,
Derek Melchin
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.
Chad Westfall
Thanks for the reply Derek. I have used that document a lot. Stochastic in it twice.
First time:
var sto = STO(Symbol symbol, int period, int kPeriod, int dPeriod, Resolution resolution = null)Second time:var sto = STO(Symbol symbol, int period, Resolution resolution = null)I thought I had tried both ways, but when I just added three integers it spit out numbers. So, THANK YOU!
The formula I'm used to for Stochastic is the one below.
%K = (Current close – lowest low)/(highest high – lowest low) * 100
%D = 3-day simple moving average (SMA) of %K
Lowest low = Lowest low for the user-defined look-back period
Highest high = Highest high for the user-defined look-back period
Given your comment:
Is the dPeriod the same calculation as listed above for %D? (Moving average of the K)
Which period is the period for? High or low? Then is the KPeriod the other or which variable?
Chad Westfall
Derek,
So, I printed out the values that I'm getting and I noticed that I'm quite off on a couple of these. Below is for SPY.
Close price for December 2020 is correct.
RSI is close to my TD Ameritrade account (67.44 vs 68.086). I'm sure there is some smoothing or something going on here.
Stochastic is slightly off but I think if you answer the above question, I can get these more inline.
MACD Fast and Slow are way out of wack with what I'm getting over at TD. I have 23.6328 nowhere near the 304 or 328. Below this is the updated code producing this printout. I'm sure it is something on my end (like calling the wrong variable), but something is off here.
2020-12-01 00:00:00 RSI VALUE: 68.08696810977077 2020-12-01 00:00:00 Bollinger Band: 373.38257 2020-12-01 00:00:00 Stochastic K Value: 72.20335 2020-12-01 00:00:00 Stochastic D Value: 71.74219 2020-12-01 00:00:00 Stochastic Fast Value: 88.41747 2020-12-01 00:00:00 MACD Fast: 328.14062 2020-12-01 00:00:00 MACD Slow: 304.71568 2020-12-01 00:00:00 MACD Signal: 18.27782 2020-12-01 00:00:00 Close Price: 373.88)TD Ameritrade's values based on monthly. RSI = 67.4407 Bollinger Band Upper = 372.05Stochastic: 90.8755/73.4943 (Close, but not sure my variables are correct.)MACD = 20.9753/15.7306 (not sure I'm requesting the right variables.)qb = QuantBook() # Parameters for Indicators Boll_Length = 20 # Number of days back Boll_STD = 2.1 # Standard deviation used for upper/lower bands RSI_Lenght = 14 # Number of days taken into account Period = 3 # Period/Window Sto_K = 10 # K lenght Sto_D = 10 # D lenght MACD_Fast = 12 # Fast length MACD_Slow = 26 # Slow length MACD_Signal = 9 # Signal lenght # Add Equity spy = qb.AddEquity("SPY", Resolution.Daily).Symbol # Relative Strength Index (RSI) rsi = RelativeStrengthIndex(RSI_Lenght) # Bollinger Band BollBand = BollingerBands(Boll_Length, Boll_STD, MovingAverageType.Exponential) # Stochastic Stoch = Stochastic(Period,Sto_K, Sto_D) # Moving Average Convergence Divergence (MACD) Macd = MovingAverageConvergenceDivergence(MACD_Fast, MACD_Slow, MACD_Signal, MovingAverageType.Exponential) # Create Monthly calendar consolidator MonthlyConsolidator = TradeBarConsolidator(Calendar.Monthly) # Define DataConsolidated event handler to track RSI values def OnMonthlyData(sender, updated): if rsi.IsReady: print(f"{updated.Time} RSI VALUE: {rsi.Current.Value}") if BollBand.IsReady: print(f"{updated.Time} Bollinger Band: {BollBand.UpperBand}") if Stoch.IsReady: print(f"{updated.Time} Stochastic K Value: {Stoch.StochK}") print(f"{updated.Time} Stochastic D Value: {Stoch.StochD}") print(f"{updated.Time} Stochastic Fast Value: {Stoch.FastStoch}") if Macd.IsReady: print(f"{updated.Time} MACD Fast: {Macd.Fast}") print(f"{updated.Time} MACD Slow: {Macd.Slow}") print(f"{updated.Time} MACD Signal: {Macd.Signal}") print(f"{updated.Time} Close Price: {bar.Close})") MonthlyConsolidator.DataConsolidated += OnMonthlyData # Register rsi to Monthly consolidator qb.RegisterIndicator(spy, rsi, MonthlyConsolidator) qb.RegisterIndicator(spy, BollBand, MonthlyConsolidator) qb.RegisterIndicator(spy, Stoch, MonthlyConsolidator) qb.RegisterIndicator(spy, Macd, MonthlyConsolidator) # Make history call to update consolidator, 1800 days guarantees at least 14 weeks of data history = qb.History(spy, 1800, Resolution.Daily) opens = history.loc["SPY"]["open"] closes = history.loc["SPY"]["close"] lows = history.loc["SPY"]["low"] highs = history.loc["SPY"]["high"] volumes = history.loc["SPY"]["volume"] times = history.unstack(0).index.values # Update consolidator with historical data for i in range(len(history)): bar = TradeBar(times[i], spy, opens[i], highs[i], lows[i], closes[i], volumes[i]) MonthlyConsolidator.Update(bar)
On a side note, is there a way to clean up the area where I"m registering the indicator. Seems like this could be done is a single line.
Also from here, I want to use a list of variables. Can I just do something like:
symbols = [ "symbol1", "symbol2", "symbolN"]
Then change all of the spy variables to symbols or do I have to run this in a loop?
I really appreciate your help!
Chad Westfall
Sorry, the TD Ameritrade images didn't attach.
http://www.highperformanceprose.com/Test%20Folder/images/Different_Values.jpgNot sure it attached this time either???
http://www.highperformanceprose.com/Test%20Folder/images/Different_Values.jpg
Derek Melchin
Hi Chad,
> I have used that document a lot. Stochastic in it twice.
Thanks, we've created a GitHub Issue to have this duplicate removed. (Will add on approval)
> Is the dPeriod the same calculation as listed above for %D? (Moving average of the K)
Yes.
> Which period is the period for? High or low? Then is the KPeriod the other or which variable?
The `period` argument is for both the highest high and lowest low indicators.
The `KPeriod` is for computing the SMA of the Fast Stochastics %K value
The source code for the Stochastic class is available here.
> MACD Fast and Slow are way out of wack with what I'm getting over at TD. I have 23.6328 nowhere near the 304 or 328.
The upper and lower MACD lines should be above and below the closing price, respectively. Therefore, a value of ~23 suggests incorrect variables are being selected on TD's platform.
> Is there a way to clean up the area where I'm registering the indicator?
Since there are 4 indicators, we need to call the `RegisterIndicator` 4 times. These docs explain how to get the indicator values into a DataFrame instead of printing them.
> I want to use a list of variables...
Consider doing it in a loop. All of the symbols will need their own instance of each indicator anyways. In addition, the `RegisterIndicator` method won't accept a list of symbols.
Best,
Derek Melchin
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.
Chad Westfall
Thanks for getting back to me Derek.
I think I figured out the Stochastic stuff. I just need to tweak the variables a little.
As far as the MACD, I was looking for the signal and MACD values originally. After doing a bunch of research, I think I figured it out.
Below is what I switched the code to. Is the Macd.Current.Value the MACD value? I'm assuming the "Signal" is the signal? Does the MACD value have a specific variable I should be calling (i.e. Macd.MACD.Current.Value) or is it the default variable?
print(f"{updated.Time} MACD Fast: {Macd.Fast.Current.Value}")
print(f"{updated.Time} MACD Slow: {Macd.Slow.Current.Value}")
print(f"{updated.Time} MACD Current: {Macd.Current.Value}")
print(f"{updated.Time} MACD Histogram: {Macd.Histogram.Current.Value}")
print(f"{updated.Time} MACD Signal: {Macd.Signal.Current.Value}")
I went to the link you posted on the indicators. I noticed that there is a macd mentioned on line 112 (of MovingAverageConvergenceDivergence.cs). Is macd being initialized on line 102? I don't something that looks like " public IndicatorBase<IndicatorDataPoint> Fast { get; } " resuling in a Macd.macd variable being created.
Currently Macd.Current.Value returns the variable, but I want to make sure I'm calling the right variable.
I appears that all of the codes in the QuantConnect/Lean/Indicators are written in C. Is there a Python area?
Again, I really apprecaite the help!
Derek Melchin
Hi Chad,
> Below is what I switched the code to. Is the Macd.Current.Value the MACD value? I'm assuming the "Signal" is the signal?
Correct. See the attached backtest plots for reference.
> Does the MACD value have a specific variable I should be calling (i.e. Macd.MACD.Current.Value) or is it the default variable?
Macd.Current.Value
> Is macd being initialized on line 102?
Line 102 calculates the macd value of the indicator. Note how we return this value at the end of the `ComputeNextValue` method. The value we return from this method is what's set as the indicator's `Current.Value` member.
> Is there a Python area?
All of our built-in indicators are currently written in C#. This related thread demonstrates how to make a python indicator.
Best,
Derek Melchin
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.
John Ener
😊
Chad Westfall
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!