Below is my code for for the stock which are above specific price, specific dollar volumes and building the moving averages, volatility and ATR for each stocks, please confirm if below code is correct
def CoarseSelectionFunction(self, coarse):
selected = []
for stock in coarse:
if stock.Price > params.PRICE_THRESHOLD and stock.DollarVolume > params.DOLLAR_VOLUME_THRESHOLD:
selected.append(stock.Symbol)
if stock.Symbol not in self.history:
history = self.algorithm.History(stock.Symbol, params.MOVING_AVERAGE_200_DAYS, Resolution.Daily)
if not history.empty:
self.history[stock.Symbol] = history["close"] * history["volume"]
self.moving_averages_200[stock.Symbol] = history["close"].rolling(window=params.MOVING_AVERAGE_200_DAYS).mean().iloc[-1]
self.moving_averages_20[stock.Symbol] = history["close"].rolling(window=params.MOVING_AVERAGE_20_DAYS).mean().iloc[-1]
self.previous_close[stock.Symbol] = history["close"].iloc[-2]
self.atr[stock.Symbol] = self.algorithm.ATR(stock.Symbol, 14, MovingAverageType.Wilders)
# Calculate Volatility
daily_returns = history["close"].pct_change().dropna()
self.volatility[stock.Symbol] = daily_returns.std() * (252 ** 0.5) # Annualized volatility
# Calculate 30-day average volatility
self.avg_volatility[stock.Symbol] = daily_returns.rolling(window=params.VOLATILITY_LOOKBACK_DAYS).std().mean() * (252 ** 0.5)
return selected
Mia Alissi
The code you've provided seems to be doing what you've described - selecting stocks based on a price and dollar volume threshold, and then calculating various metrics such as moving averages, volatility, and Average True Range (ATR) for each selected stock.
However, without knowing the exact values of your parameters and without a context (like the rest of your algorithm), it's hard to say definitively if the code is correct. Here are a few things to consider:
Make sure that
params.PRICE_THRESHOLD
,params.DOLLAR_VOLUME_THRESHOLD
,params.MOVING_AVERAGE_200_DAYS
,params.MOVING_AVERAGE_20_DAYS
, andparams.VOLATILITY_LOOKBACK_DAYS
are defined somewhere in your code and have the correct values.The
self.algorithm.History
andself.algorithm.ATR
calls suggest that this code is part of a class whereself.algorithm
is an instance ofQCAlgorithm
. Make sure that's the case.The
self.history
,self.moving_averages_200
,self.moving_averages_20
,self.previous_close
,self.atr
,self.volatility
, andself.avg_volatility
are presumably dictionaries that store data for each stock. Make sure they are initialized correctly.The line
self.history[stock.Symbol] = history["close"] * history["volume"]
is calculating the dollar volume for each day and storing it inself.history
. If you want to store the historical close prices instead, you should change it toself.history[stock.Symbol] = history["close"]
.The line
self.previous_close[stock.Symbol] = history["close"].iloc[-2]
is getting the second to last close price from the history. If you want the most recent close price, you should change-2
to-1
.The calculation of volatility and average volatility assumes that
history["close"]
contains daily close prices. If the resolution is not daily, the calculation will be off.The
self.algorithm.ATR
call is creating an ATR indicator for the stock. Note that this indicator is not immediately ready and needs to be updated with data before it can be used.The
return selected
statement is returning a list of Symbols. If you need to return a list of Symbol objects, you should changeselected.append(stock.Symbol)
toselected.append(stock)
.Remember to test your code thoroughly to ensure it's doing what you expect. You can use the QuantConnect backtesting environment to test your algorithm on historical data.
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.
Dharmesh Khalasi
Below is the code which looks for abnormal volumes, please validate the code below
Â
Mia Alissi
The code you've provided seems to be doing what you've described - selecting stocks based on abnormal volumes and other conditions. However, without knowing the exact values of your parameters and without a context (like the rest of your algorithm), it's hard to say definitively if the code is correct. Here are a few things to consider:
Make sure that
params.MIN_PRICE_INCREASE_PERCENT
andparams.MAX_VOLATILITY_MULTIPLIER
are defined somewhere in your code and have the correct values.The
self.algorithm.UniverseManager.ActiveSecurities.Keys
andself.algorithm.Securities
calls suggest that this code is part of a class whereself.algorithm
is an instance ofQCAlgorithm
. Make sure that's the case.The
self.history
,self.moving_averages_200
,self.moving_averages_20
,self.previous_close
,self.atr
,self.volatility
, andself.avg_volatility
are presumably dictionaries that store data for each stock. Make sure they are initialized correctly.The line
avg_dollar_volume = self.history[symbol].mean()
is calculating the average dollar volume for each day from the history. Ifself.history[symbol]
stores the historical close prices instead of dollar volumes, this calculation will be incorrect.The line
current_dollar_volume = self.algorithm.Securities[symbol].Price * self.algorithm.Securities[symbol].Volume
is calculating the current dollar volume. Make sure thatself.algorithm.Securities[symbol].Price
andself.algorithm.Securities[symbol].Volume
are updated correctly.The line
price_increase = (self.algorithm.Securities[symbol].Price - self.previous_close[symbol]) / self.previous_close[symbol]
is calculating the price increase as a percentage. Make sure thatself.previous_close[symbol]
is updated correctly.The
return abnormal_dollar_volume_stocks
statement is returning a list of Symbols. If you need to return a list of Symbol objects, you should changeabnormal_dollar_volume_stocks.append(symbol)
toabnormal_dollar_volume_stocks.append(self.algorithm.Securities[symbol])
.Remember to test your code thoroughly to ensure it's doing what you expect. You can use the QuantConnect backtesting environment to test your algorithm on historical data.
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.
Dharmesh Khalasi
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!