How can I fix a incorrect coloring of floats using openpyxl?

60 Views Asked by At

I have problem with my code. The code is supposed to run a different script that scrapes two match betting websites and then writes the matches and rates in xlsx file. The code I have problem with is supposed to edit the file and arrange the matches and color bigger rates green and smaller rates red (the rates are compared from specific columns). The problem is with the coloring, it seems that it's random, it's fixed after I run the code again but only without subprocess and the first match is always missing after the second run. It was working fine before I added Fuzzywuzzy library, if that helps, (using other library didn't help). Also, I made this using ChatGPT and it didn't know how to fix it too. Sorry if my explanation is bad, I'm noob in coding and I don't speak english very well. This is the code:

import subprocess
from openpyxl import load_workbook
from plyer import notification
from openpyxl.styles import Font, Color
from fuzzywuzzy import fuzz
from operator import itemgetter

# Run some code
subprocess.run(['python', r'C:\Users\Kryštof\PycharmProjects\pythonProject2\Combined sure bets.py'])

# Load the XLSX file
xlsx_file = r'C:\Users\Kryštof\Desktop\Sure Bets\match_details.xlsx'
wb = load_workbook(xlsx_file)

# Get the active worksheet
ws = wb.active

# Create dictionaries to store the matches and their rates
tip_sport_matches = {}
betano_matches = {}

# Iterate over the rows and store the matches and rates in the dictionaries
for row in ws.iter_rows(min_row=2, max_row=ws.max_row, min_col=1, max_col=7, values_only=True):
    tip_sport_name = row[0]
    betano_name = row[4]
    tip_sport_rate1 = row[1]
    tip_sport_rate2 = row[2]
    betano_rate1 = row[5]
    betano_rate2 = row[6]

    # Store TipSport matches and rates
    if tip_sport_name:
        tip_sport_matches[tip_sport_name] = {
            'rate1': tip_sport_rate1,
            'rate2': tip_sport_rate2
        }

    # Store Betano matches and rates
    if betano_name:
        betano_matches[betano_name] = {
            'rate1': betano_rate1,
            'rate2': betano_rate2
        }

# Clear the worksheet
ws.delete_rows(2, ws.max_row)

# Move the matched names and rates to the worksheet
row_num = 1
percentage_list = []  # List to store percentages and corresponding data

# Move the matched names and rates to the worksheet
for tip_sport_match in tip_sport_matches.copy():
    for betano_match in betano_matches.copy():
        # Calculate the similarity ratio between the matches
        similarity_ratio = fuzz.token_set_ratio(tip_sport_match, betano_match)
        if similarity_ratio >= 80:  # Adjust the threshold as needed
            ws.cell(row=row_num, column=1).value = tip_sport_match
            if tip_sport_match in tip_sport_matches:
                ws.cell(row=row_num, column=2).value = tip_sport_matches[tip_sport_match]['rate1']
                ws.cell(row=row_num, column=3).value = tip_sport_matches[tip_sport_match]['rate2']
                del tip_sport_matches[tip_sport_match]
            ws.cell(row=row_num, column=5).value = betano_match
            if betano_match in betano_matches:
                ws.cell(row=row_num, column=6).value = betano_matches[betano_match]['rate1']
                ws.cell(row=row_num, column=7).value = betano_matches[betano_match]['rate2']
                del betano_matches[betano_match]
            row_num += 1

# Move the unmatched TipSport matches to the worksheet
for tip_sport_match in tip_sport_matches:
    ws.cell(row=row_num, column=1).value = tip_sport_match
    ws.cell(row=row_num, column=2).value = tip_sport_matches[tip_sport_match]['rate1']
    ws.cell(row=row_num, column=3).value = tip_sport_matches[tip_sport_match]['rate2']
    row_num += 1

# Move the unmatched Betano matches to the worksheet
for betano_match in betano_matches:
    ws.cell(row=row_num, column=5).value = betano_match
    ws.cell(row=row_num, column=6).value = betano_matches[betano_match]['rate1']
    ws.cell(row=row_num, column=7).value = betano_matches[betano_match]['rate2']
    row_num += 1

GREEN = '00FF00'  # Green color (hex code)
RED = 'FF0000'  # Red color (hex code)

# Compare rates and apply formatting
for row_num in range(1, ws.max_row + 1):
    rate1_tip_sport = ws.cell(row=row_num, column=2).value
    rate2_tip_sport = ws.cell(row=row_num, column=3).value
    rate1_betano = ws.cell(row=row_num, column=6).value
    rate2_betano = ws.cell(row=row_num, column=7).value

    # Convert rate values to numeric types
    if rate1_tip_sport is not None:
        rate1_tip_sport = float(rate1_tip_sport)
    if rate2_tip_sport is not None:
        rate2_tip_sport = float(rate2_tip_sport)
    if rate1_betano is not None:
        rate1_betano = float(rate1_betano)
    if rate2_betano is not None:
        rate2_betano = float(rate2_betano)

    if rate1_tip_sport is not None and rate1_betano is not None:
        if rate1_tip_sport > rate1_betano:
            ws.cell(row=row_num, column=2).font = Font(color=Color(rgb=GREEN))
            ws.cell(row=row_num, column=6).font = Font(color=Color(rgb=RED))
        elif rate1_tip_sport < rate1_betano:
            ws.cell(row=row_num, column=2).font = Font(color=Color(rgb=RED))
            ws.cell(row=row_num, column=6).font = Font(color=Color(rgb=GREEN))

    if rate2_tip_sport is not None and rate2_betano is not None:
        if rate2_tip_sport > rate2_betano:
            ws.cell(row=row_num, column=3).font = Font(color=Color(rgb=GREEN))
            ws.cell(row=row_num, column=7).font = Font(color=Color(rgb=RED))
        elif rate2_tip_sport < rate2_betano:
            ws.cell(row=row_num, column=3).font = Font(color=Color(rgb=RED))
            ws.cell(row=row_num, column=7).font = Font(color=Color(rgb=GREEN))

        # Calculate percentage differences
        percentage_diff1 = abs((rate1_tip_sport - rate1_betano) / rate1_tip_sport * 100)
        percentage_diff2 = abs((rate2_tip_sport - rate2_betano) / rate2_tip_sport * 100)

        # Calculate the sum of percentage differences
        percentage_sum = percentage_diff1 + percentage_diff2

        # Append the percentage sum and corresponding data to the percentage list
        tip_sport_match = ws.cell(row=row_num, column=1).value
        betano_match = ws.cell(row=row_num, column=5).value
        percentage_list.append((percentage_sum, tip_sport_match, rate1_tip_sport, rate2_tip_sport,
                                betano_match, rate1_betano, rate2_betano))

        # Record the sum of percentage differences in column 4
        ws.cell(row=row_num, column=4).value = f"{percentage_sum:.2f}%"

# Sort the percentage list in descending order based on the first element (percentage_sum)
percentage_list.sort(reverse=True, key=itemgetter(0))

# Move the percentages and corresponding data to the worksheet
for idx, (percentage_sum, tip_sport_match, rate1_tip_sport, rate2_tip_sport,
          betano_match, rate1_betano, rate2_betano) in enumerate(percentage_list):
    ws.cell(row=idx + 1, column=4).value = f"{percentage_sum:.2f}%"
    ws.cell(row=idx + 1, column=1).value = tip_sport_match
    ws.cell(row=idx + 1, column=2).value = rate1_tip_sport
    ws.cell(row=idx + 1, column=3).value = rate2_tip_sport
    ws.cell(row=idx + 1, column=5).value = betano_match
    ws.cell(row=idx + 1, column=6).value = rate1_betano
    ws.cell(row=idx + 1, column=7).value = rate2_betano

# Save the changes
wb.save(xlsx_file)

# Display a notification when the code execution is complete
notification.notify(
    title='Code Execution Complete',
    message='The code has finished executing.',
    app_icon=None,  # You can specify an icon file (.ico) path here if desired
    timeout=10  # The notification will disappear after 10 seconds
)
1

There are 1 best solutions below

0
Kryštof Bochníček On

Sorry for not reacting, I fixed it and then forgot about this. Anyway It was caused by two element having the number 2 insted of 1, so i put it in a loop and it's working now. It's probably not ideal to have it in a loop but it works so I think it's good. These are the elements:

# Iterate over the rows and store the matches and rates in the dictionaries
for row in ws.iter_rows(min_row=1, max_row=ws.max_row, min_col=1, max_col=7, values_only=True):

# Clear the worksheet
ws.delete_rows(1, ws.max_row)