My python program to pick swing stocks

Discussion in 'Educational videos and material' started by Ridestock, Mar 26, 2023.

  1. Ridestock

    Ridestock Member

    Joined:
    Aug 30, 2018
    Messages:
    116
    Likes Received:
    8
    I put the NASDAQ list of stocks in a text file that it reads and tells me which stocks are over 200 day moving average were the macd crossed for swing trading.

    Please let me know if anyone has ideas for indicators to improve the output as this is a work in progress. Thanks
    ------------------------------------------------------------

    Code:
    import yfinance as yf
    import pandas as pd
    import ta
    import talib
    masterList = []
    master = open("c:\\Stock Auto\\Volume\\master.txt", "r")
    masterSymbols = master.readlines()
    for masterSymbol in masterSymbols:
        masterSymbol = ''.join(char for char in masterSymbol if char.isalnum())
        masterList.append(masterSymbol)
    master.close()
    
    symbols = masterList
    #symbols = ["GOOG"]
    symbolList = []
    
    for symbol in symbols:
        try:
            ticker = yf.Ticker(symbol)
            # get stock info
            # print(msft.info)
            # get historical market data
            # 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo
            hist = ticker.history(period="6mo")
            closeHistory = hist["Close"]
            volumeHistory = hist["Volume"]
            currentPrice = hist["Close"][-1]
    
            # ---------------------------------------------------------
            # Indicators
            # ---------------------------------------------------------
    
            # MACD: Calculate the MACD indicator using a 12-day and 26-day exponential moving average
            exp1 = hist["Close"].ewm(span=12, adjust=False).mean()
            exp2 = hist["Close"].ewm(span=26, adjust=False).mean()
            macd = exp1 - exp2
    
            # EMA 9: Calculate the signal line using a 9-day exponential moving average of the MACD
            signal = macd.ewm(span=9, adjust=False).mean()
    
            # EMA 200: Calculate the 200-day exponential moving average using the ewm() function
            ema200 = hist['Close'].ewm(span=200, adjust=False).mean()
    
            # RSI: Calculate the Relative Strength Index 
            delta = hist['Close'].diff()
            gain = delta.where(delta > 0, 0)
            loss = -delta.where(delta < 0, 0)
            avg_gain = gain.rolling(window=14).mean()
            avg_loss = loss.rolling(window=14).mean()
            rs = avg_gain / avg_loss
            rsiArray = 100 - (100 / (1 + rs))
            rsi = rsiArray.iloc[-1]
    
            # Bollinger Bands: Calculate the rolling mean and standard deviation of the closing prices
            rolling_mean = hist['Close'].rolling(window=20).mean()
            rolling_std = hist['Close'].rolling(window=20).std()
            upper_band = rolling_mean + 2 * rolling_std
            lower_band = rolling_mean - 2 * rolling_std
           
            # Stock is in UpTrend
            hist['ema20'] = ta.trend.EMAIndicator(close=hist['Close'], window=20).ema_indicator()
            current_close = hist['Close'].iloc[-1]
            current_ema20 = hist['ema20'].iloc[-1]
    
            # Breakout Indicators
            atr_period = 14
            hist['ATR'] = talib.ATR(hist['High'], hist['Low'], hist['Close'], timeperiod=atr_period)
            ema_period = 5
            hist['ATR_EMA'] = talib.EMA(hist['ATR'], timeperiod=ema_period)
            multiplier = 2.5
            hist['upper_band'] = hist['Close'] + multiplier * hist['ATR_EMA']
            hist['lower_band'] = hist['Close'] - multiplier * hist['ATR_EMA']
    
            # --------------------------------------------------------
            # Conditions
            #---------------------------------------------------------
    
            # Price broke upper indicator
            priceBrokeUpperInd = current_close>hist['upper_band'][-1]
    
            # Price broke lower Indicator
            priceBrokeLowerInd = current_close<hist['lower_band'][-1]
    
            # UpTrend: Check if the current closing price is above the 20-day EMA
            upTrend = current_close > current_ema20
    
            # Bollinger Band price is in the lower band
            priceInLowerBollingerBand = currentPrice <= lower_band[-1]
    
            # RSI < 30
            rsiLessThan30 = rsi<30
    
            # Condition: Determine if the MACD has crossed the signal line (a bullish signal)
            macdAboveSignalLine = macd[-1] > signal[-1] and macd[-2] < signal[-2]
    
            # Condition: Last close price above 200 day moving average
            priceAbove200ema = currentPrice > ema200[-1]
    
            allMatch = upTrend\
                    and macdAboveSignalLine\
                    and priceAbove200ema\
                    and rsiLessThan30\
                    and priceInLowerBollingerBand\
                    and (priceBrokeUpperInd or priceBrokeLowerInd)
                   
            matchCount = 0
           
            # Check Indicators
            if(upTrend):
                matchCount+=1
            if(macdAboveSignalLine):
                matchCount+=1
            if(priceAbove200ema):
                matchCount+=1
            if(rsiLessThan30):
                matchCount+=1
            if(priceInLowerBollingerBand):
                matchCount+=1
            if(priceBrokeLowerInd):
                matchCount+=1
            if(priceBrokeUpperInd):
                matchCount+=1
           
           
            if(matchCount>=3):
                symbolList.append(symbol)
                if(allMatch):
                    print(symbol + ": ALL MATCH")
                else:
                    if(upTrend):
                        print(symbol + ": Uptrend")
                    if(macdAboveSignalLine):
                        print(symbol + ": MacD above Signal")
                    if(priceAbove200ema):
                        print(symbol + ": Price above 200 ema")
                    if(rsiLessThan30):
                        print(symbol + ": RSI less than 30")
                    if(priceInLowerBollingerBand):
                        print(symbol + ": price in lower bollinger") 
                    if(priceBrokeUpperInd):
                        print(symbol +": Price broke upper indicator")
                    if(priceBrokeLowerInd):
                        print(symbol +": Price broke lower indicator")
        except:
            print("Fail")
            pass
       
    print("")
    for s in symbolList:
        print(s)
    print("Finished")
    
    
    
     
    #1 Ridestock, Mar 26, 2023
    Last edited: Mar 31, 2023

Share This Page