How to let function run with for loop for other elements in list even if one element in the list gives out an error?

Question:

I am preparing a stock screener project based on technical analysis and want to pass a list of stocks in a for loop created under a function.
E.g. If the stock list has 15 stock codes but 1 stock in the list has a wrong code where price data cannot be extracted using tvdatafeed module tv.get_hist() function, I still want to create a function called def filter_technical(TA_stocks) and pass a for loop for each element in the list to extract historical price data. And I want to print error for the stock code not able to pass through the function and print remaining list.

stock_list = ['AXISBANK', 'MAHABANK', 'CANFINHOME', 'CANBK', 'DCBBANK', 'FEDERALBNK', 'ICICIBANK', 'IDBI', 'IDFCFIRSTB', 'INDIANB', 'INDUSINDBK', 'J&KBANK', 'KARURVYSYA', 'PNBHOUSING', 'PSB', 'UNIONBANK']

## J&KBANK is the wrong stock code because TradingView has the code J_KBANK

def filter_technical(TA_stocks):
    for stock in TA_stocks:
        week_df = tv.get_hist(symbol = stock, exchange = 'NSE', interval = Interval.in_weekly, n_bars = 1500)
        all_time_high = week_df.high.max()
        condition_1A = week_df.close[-1]/all_time_high < 0.5 
        if condition_1A == True:
            print('Buy Stock', stock)
        else:
            print('Don't Buy Stock', stock)
    return stock
filter_technical(stock_list)

The function does not run the remaining elements in the list and shows error for the whole function:
ERROR:tvDatafeed.main:Connection timed out
ERROR:tvDatafeed.main:no data, please check the exchange and symbol

I want to incorporate try/except into this function and print following example outputs

  1. Buy AXISBANK
  2. Don’t Buy MAHABANK
  3. J&KBANK data does not exist
Asked By: Sandeep Pai

||

Answers:

You can just wrap each iteration of the for loop in a try except block to continue when you run into errors and still receive the error message:

stock_list = ['AXISBANK', 'MAHABANK', 'CANFINHOME', 'CANBK', 'DCBBANK', 'FEDERALBNK', 'ICICIBANK', 'IDBI', 'IDFCFIRSTB', 'INDIANB', 'INDUSINDBK', 'J&KBANK', 'KARURVYSYA', 'PNBHOUSING', 'PSB', 'UNIONBANK']

## J&KBANK is the wrong stock code because TradingView has the code J_KBANK

def filter_technical(TA_stocks):
    for stock in TA_stocks:
        try:
            week_df = tv.get_hist(symbol = stock, exchange = 'NSE', interval = Interval.in_weekly, n_bars = 1500)
            all_time_high = week_df.high.max()
            condition_1A = week_df.close[-1]/all_time_high < 0.5 
            if condition_1A == True:
                print('Buy Stock', stock)
            else:
                print("Don't Buy Stock", stock)
        except Exception as e:
            print(stock,': ', e)
    return stock
filter_technical(stock_list)
Answered By: Jacob Kearney

What you are looking for is exception handling.

  1. Identify which part of your code might throw an error
    week_df = tv.get_hist(symbol = stock, exchange = 'NSE', interval = Interval.in_weekly, n_bars = 1500)
    all_time_high = week_df.high.max()
    condition_1A = week_df.close[-1]/all_time_high < 0.5
    
  2. Put that code into a try block, and handle the error
    try:
        <code that will produce an error>
    except Exception as e:
        <do something with your exception>
    
    
  3. After the try-except block, continue your program
Answered By: John Ingram
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.