0

I am trying to achieve a tuple which I eventually would be uploading to PostgreSQL database as a Bulk Update. Do let me know if I am going wrong or if there are better ways to achieve my goal.

My code is as below:


index = []
n = -1
for stock in stocklist[0:2000]:
    n += 1
    time.sleep(1)

    # RS_Rating code begins here
    data = get_history(stock, start=start_date, end=end_date)

    if not data.empty:
        row_count = 0
        day_prices = []
        for row in data.itertuples():
            row_data = "("  + str(row.Index) + ", '" + row.Symbol + "', " + str(row.Open) + ", " + str(row.High) + ", " + str(row.Low) + ", " + str(row.Last) + ')'
            
            if day_prices==[]:
                day_prices = row_data
            else:
                day_prices = day_prices + ", "+  row_data

            row_count = row_count + 1 # TO MAKE IT EASIER FOR TESTING WITH LIMITED CODE
            if row_count == 5:
                break

        # type(day_prices)
        # <class 'str'>
        
        day_prices_post = day_prices

        # WHAT I AM GETTING IS AS BELOW. 
        # ALL PERFECT BUT I NEED TO GET RID OF THE QUOTES " ... "

        day_prices_post = "(
            ('SBIN', 198.50, 202.50),
            ('RELIANCE', 1910.50, 1930.50),
            ('RELIANCE', 1925.60, 1933.00)
        )"
        
        # I NEED A TUPLE IN THIS LAYOUT
        # SIMILAR TO ABOVE BUT WITHOUT QUOTES " ... "
        day_prices_test = (
            ('SBIN', 198.50, 202.50),
            ('RELIANCE', 1910.50, 1930.50),
            ('RELIANCE', 1925.60, 1933.00)
        )
        
        # type(day_prices_test)
        # <class 'tuple'>
Fred
  • 211
  • 2
  • 9

1 Answers1

1

You don't need strings to begin with. For each row you can just create a tuple, like you want to, and then add it to the list. In the end you can use the tuple function to convert the list to a tuple:

index = []
n = -1
for stock in stocklist[0:2000]:
    n += 1
    time.sleep(1)

    # RS_Rating code begins here
    data = get_history(stock, start=start_date, end=end_date)

    if not data.empty:
        row_count = 0
        day_prices = []
        for row in data.itertuples():
            row_data = (row.Index , row.Symbol , row.Open , row.High, row.Low, row.Last)            
            day_prices.append(row_data)
            row_count += 1 # TO MAKE IT EASIER FOR TESTING WITH LIMITED CODE
            if row_count == 5:
                break
        day_prices = tuple(day_prices)
        # type(day_prices)
        # <class 'tuple'>
        

Marko
  • 372
  • 2
  • 7