Esempio n. 1
0
def select_range(game_range):
    print("How would you like to specify the number of games to analyse?")
    print("1) By days from now")
    print("2) By games from now")
    print("M) Previous menu")
    valid_options = ["1", "2", "m"]
    while True:
        option = input().lower()
        if option == "1" or option == "2" or option == "m":
            break
    if option == "1":
        while True:
            print("\nEnter range in days (between 1 and 365):")
            option2 = input()
            if cf.is_number(option2):
                if int(option2) > 0 and int(option2) < 366:
                    game_range = timedelta(int(option2))
                    return game_range
        
    if option == "2":
        while True:
            print("\nEnter range in games per team (between 1 and 50):")
            option2 = input()
            if cf.is_number(option2):
                if int(option2) > 0 and int(option2) < 51:
                    game_range = int(option2)
                    return game_range

    if option == "m":
        return game_range
Esempio n. 2
0
    def format_datetime(dt):
        """
        Helper function to convert date and time value for a
        game from the SoccerStats scraper and converts it into
        a valid datetime object. The object is returned.
        """

        today = datetime.today()
        date_months = [
            "Jan.", "Feb.", "Mar.", "Apr.", "May.", "Jun.", "Jul.", "Aug.",
            "Sep.", "Oct.", "Nov.", "Dec."
        ]
        days = ["Mon.", "Tue.", "Wed.", "Thu.", "Fri.", "Sat.", "Sun."]

        # Game date day (1-31) number
        if cf.is_number(dt[5]):
            game_date_day = dt[5]
            if cf.is_number(dt[6]):
                game_date_day += dt[6]
                month_index = 8
            else:
                month_index = 7
        game_date_day = int(game_date_day)

        # Game day (0 - 6) number
        game_day = dt[0:4]
        for day in days:
            if game_day == day:
                game_day_number = days.index(day)
                break

        # Month number
        for date_month in date_months:
            if dt[month_index:month_index + 4] == date_month:
                game_month = date_months.index(date_month) + 1
                break

        # Time
        game_hour = int(dt[month_index + 6:month_index + 8])
        game_min = int(dt[month_index + 10:month_index + 12])

        # Year number
        game_date = datetime(today.year, game_month, game_date_day, game_hour,
                             game_min)

        if days[game_date.weekday()] != game_day:
            game_date = datetime(today.year - 1, game_month, game_date_day,
                                 game_hour, game_min)
        if days[game_date.weekday()] != game_day:
            game_date = datetime(today.year + 1, game_month, game_date_day,
                                 game_hour, game_min)
        if days[game_date.weekday()] != game_day:
            game_date = datetime(1111, game_month, game_date_day, game_hour,
                                 game_min)
        return game_date
Esempio n. 3
0
def main_menu(options):
    """
    Main menu function
    Offers all options in the options list (no need to edit this function)
    Returns the selected funtion to run.
    """
    while True:
        print("Welcome to SportsBook - A sports analysis tool.")
        print("Please select from one of the following sports:")
        # Display all options
        for option in options:
            print(str(option[0]) + " " + str(option[1]))
        # Take user selection
        while True:
            print("Enter option: ")
            selected = input()
            # Quit option
            if selected.lower() == "q":
                exit()
            # If a number has been entered, convert the string to an integer
            if is_number(selected):
                selected = int(selected)
                # If the selection is in the list break out of the infinite loop
                if selected in range(len(options)) and selected != 0:
                    break
        # Having broken out of the loop, run the selected function
        if selected == options[0][0]:
            league_data = {}
            fixtures = []
            predictions = []
            football_menu(league_data, fixtures, predictions)
        if selected == options[1][0]:
            tennis()
Esempio n. 4
0
def select_range(range_in, mode="future"):
    """
    Takes in a range of time and an option mode ("past" or "future").
    Asks the user to select a new range in days or games ( datetime days or an int).
    Returns the updated range.
    """
    print("How would you like to specify the number of games to analyse?")
    if mode == "future":
        print("1) By days from now")
        print("2) By games from now")
        print("M) Previous menu")
    elif mode == "past":
        print("1) By days before now")
        print("2) By games before now")
        print("M) Previous menu")
    else:
        print("Unsupported mode in function select_range")
        return 0
    valid_options = ["1", "2", "m"]
    while True:
        option = input().lower()
        if option in valid_options:
            break
    if option == "1":
        while True:
            print("\nEnter range in days (between 1 and 365):")
            option2 = input()
            if cf.is_number(option2):
                if int(option2) > 0 and int(option2) < 366:
                    range_out = timedelta(int(option2))
                    return range_out

    if option == "2":
        while True:
            print("\nEnter range in games per team (between 1 and 50):")
            option2 = input()
            if cf.is_number(option2):
                if int(option2) > 0 and int(option2) < 51:
                    range_out = int(option2)
                    return range_out

    if option == "m":
        return 0
Esempio n. 5
0
def win_by_x(predictions, applied_filters):
    """
    Takes a list of predictions and the currently applied filters.
    Asks the user to select home team, away team or either.
    Asks the user how many goals the filtered prediction should show that team winning by.
    Returns a list of predictions that fit the requested specification and the
    updated applied filters list.
    """
    filtered_predictions = []
    while True:
        print(
            "Win by x goals\n\n Which team to win?\n(H)ome team, (A)way team or (E)ither?\n"
        )
        print(
            "Enter H, A, E or M to return to previous menu making no changes.")
        s = input().lower()
        if s == "h":
            team = "Home"
            break
        elif s == "a":
            team = "Away"
            break
        elif s == "e":
            team = "Either"
            break
        elif s == "m":
            return (predictions, applied_filters)
    while True:
        print("\nby how many goals? (Please enter a number)")
        x = input()
        if cf.is_number(x):
            x = int(x)
            break

    for p in predictions:
        if s == "h":
            if p["Home team prediction"] - p["Away team prediction"] > x:
                filtered_predictions.append(p)
        elif s == "a":
            if p["Away team prediction"] - p["Home team prediction"] > x:
                filtered_predictions.append(p)
        elif s == "e":
            if p["Home team prediction"] - p["Away team prediction"] > x or p[
                    "Away team prediction"] - p["Home team prediction"] > x:
                filtered_predictions.append(p)

    applied_filters.append(team + " team to score " + str(x) +
                           " goals more than their opponent.")
    return (filtered_predictions, applied_filters)
Esempio n. 6
0
def main_menu(options):
    """
    Main menu function
    Offers all options in the options list (no need to edit this function)
    Returns the selected funtion to run.
    """
    while True:
        print("Welcome to SportsBook - A sports analysis tool.")
        #print("Please select from one of the following sports:") # Menu bypass
        # Display all options
        #for option in options: # Menu bypass
        #print(str(option[0]) + " " + str(option[1])) # Menu bypass
        # Take user selection
        while True:
            #print("Enter option: ") # Menu bypass
            selected = "1"  # = input() - commented out as this is a placeholder menu
            #for development purposes and needs not be shown at this stage.

            # Quit option
            if selected.lower() == "q":
                exit()
            # If a number has been entered, convert the string to an integer
            if is_number(selected):
                selected = int(selected)
                # If the selection is in the list break out of the infinite loop
                if selected in range(len(options)) and selected != 0:
                    break
        # Having broken out of the loop, run the selected function
        if selected == options[0][0]:
            football_data = {
                "league_data": {},  # League tables
                "fixtures": [],  # Upcoming games
                "predictions": [],  # Predictions for all upcoming
                "filtered_predictions": [],  # Reduced predictions
                "predictions_in_range": {},  # Predictions in selected range
                "fixtures_in_range": [],  # Fixtures in selected range
                "future_range": timedelta(
                    7),  # Range of games (future) - Days or number of games
                "applied_filters": [],  # Filters applied to predictions
                "results": [],  # All results for each league
                "results_in_range": [],  # Results in selected results range
                "past_range": timedelta(days=365)
            }  # Selected range of results (past) - Days or number of games
            football_menu(football_data)
        if selected == options[1][0]:
            tennis()
Esempio n. 7
0
def x_or_more_goals_scored(predictions, applied_filters):
    """
    Takes a list of predictions and the list of currently applied filters.
    Asks the user how many goals expected to be scored at least.
    Returns a list of predictions that fit the requested specification and the
    updated applied filters list.
    """
    print("(x or more goals scored)\n")
    filtered_predictions = []
    while True:

        print("Enter the lowest number of goals")
        x = input()
        if cf.is_number(x):
            x = int(x)
            break

    for p in predictions:
        if p["Total goals expected"] >= x:
            filtered_predictions.append(p)
    applied_filters.append("Total number of goals is " + str(x) + " or more.")
    return (filtered_predictions, applied_filters)
Esempio n. 8
0
def form_wins(predictions, results, past_range, applied_filters):
    """
    Takes a list of predictions and the list of currently applied filters.
    Asks the user to select the home team or the away team.
    Asks the user by how many goals (at least) the slected team should have
    won each of their last matches in the provided results range.
    Returns a list of predictions where the specifications are met and the
    updated applied_filters list
    """
    """
    Currently looks at all results in the specified range for the team.
    This can be changed in the future to look only at home or away results.
    """
    """
    Each prediction:
    prediction = {"League": fixture_league, "Date and time": fixture_datetime,
    "Prediction type": prediction_name, "Home team": home_team,
    "Home team prediction": home_team_goals, "Away team": away_team,
    "Away team prediction": away_team_goals, "Total goals expected": total_goals, 
    "Predicted separation": prediction_goal_separation, "Both to score": both_to_score,
    "date_as_dtobject": fixture[4]}
    """
    """
    Each result:
    [league, game_date str, home_team, home_team_score, away_team, away_team_score, game_date_time]
    """

    print("(all previous games in results range won by x goals)\n\n")
    team = cf.home_or_away(either=False)

    print("Enter the lowest number of goals for the " + team +
          " team to have won each game by.")
    x = int(cf.input_number())

    print("Enter the number of results to check.")
    number_of_results = cf.input_number()

    # Ask the user whther they'd like to see relevant results for each team.
    display_results = ""
    while True:
        print(
            "Would you like to see the relevant results of teams that match the search criteria?"
        )
        print("Enter Y or N")
        display_results = input()
        if display_results.lower() == "y" or display_results.lower() == "n":
            break

    filtered_predictions = []
    filter_name = team + " team has won all of their last " + str(
        number_of_results) + " games by " + str(x) + " or more goals"
    # For each prediction
    for p in predictions:
        """
        Get the results for the selected team from the results passed into the function.
        mode = "total" means that one list containing all(home and away) results for the
        selected team from the given results range is returned.
        """
        team_results = f.get_team_results(p["League"],
                                          p[team + " team"],
                                          results,
                                          mode="total")

        # Set a flag for qualifying predictions.
        relevant_prediction = True

        # Create a list to save relevant results.
        relevant_results = []

        # Set the limit of results to check for each iteration of the prediction loop.
        game_limit = number_of_results

        # Set a game counter.
        game_count = 0

        # For each of the results for the selected team.
        for r in team_results:

            # For testing: Display the current team and the current result.
            #shows that if a team displays x wins in a row
            #print(p[team + " team"], r, sep = "\t")

            # Increment the game counter.
            game_count += 1

            # If the selected team is the home team in the result.
            if p[team + " team"] == r[2]:

                # Don't count games that were postponed.
                if cf.is_number(r[5]) == False:
                    game_count -= 1
                    continue

                # If the home team score is greater than the away team score by x or more.
                if int(r[3]) - int(r[5]) >= x:
                    # Add the result to the relevant results list.
                    relevant_results.append(r)
                    # Break out of results loop if game counter exceeds limit.
                    if game_count == game_limit:
                        break
                    # Continue the loop to check the remaining games.
                    continue
                # If not, this is not a relevant selection.
                else:
                    # Mark as not relevant.
                    relevant_prediction = False
                    # Exit the loop
                    break
            # If the team selected is the away team in the result.
            if p[team + " team"] == r[4]:
                # Don't count games that were postponed.
                if cf.is_number(r[5]) == False:
                    game_count -= 1
                    continue

                # If the away team score is greater than the home team score by x or more.
                if int(r[5]) - int(r[3]) >= x:
                    # Add the result to the relevant results list.
                    relevant_results.append(r)
                    # Break out of results loop if game counter exceeds limit.
                    if game_count == game_limit:
                        break
                    # Continue the loop to check the remaining games.
                    continue
                # If not, this is not a relevant selection.
                else:
                    # Mark as not relevant.
                    relevant_prediction = False
                    break

        if relevant_prediction:
            filtered_predictions.append(p)
            if display_results == "y":
                print("\n" + relevant_results[0][0] + "\n" +
                      p[team + " team"] + " qualifying results: \n")
                for result in relevant_results:
                    for item in range(len(result)):
                        if item % 6 == 0:
                            continue
                        else:
                            print(result[item])
                    print()

    if len(filtered_predictions) > 0:
        applied_filters.append(filter_name)
        return (filtered_predictions, applied_filters)
    elif filter_name in applied_filters:
        print("\nFilter has already been applied.")
        print("Press enter to continue.")
        input()
        return (predictions, applied_filters)
    else:
        print("\nFilter not applied as it will remove all remaining games.")
        print("Press enter to continue.")
        input()
        return (predictions, applied_filters)
Esempio n. 9
0
    def format_datetime(dt, mode="rounds"):
        """
        Helper function to convert date and time value for a
        game from the SoccerStats scraper and converts it into
        a valid datetime object. The object is returned.
        
        Runs in rounds mode by default but can be run in mode = "results" for
        the two forms of fixtures founf on the site.
        """
        today = datetime.today()
        date_months = [
            "Jan.", "Feb.", "Mar.", "Apr.", "May.", "Jun.", "Jul.", "Aug.",
            "Sep.", "Oct.", "Nov.", "Dec."
        ]
        days = ["Mon.", "Tue.", "Wed.", "Thu.", "Fri.", "Sat.", "Sun."]
        days1 = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"]
        date_months1 = [
            "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
            "Oct", "Nov", "Dec"
        ]

        if mode == "rounds":

            # Game date day (1-31) number
            if cf.is_number(dt[5]):
                game_date_day = dt[5]
                if cf.is_number(dt[6]):
                    game_date_day += dt[6]
                    month_index = 8
                else:
                    month_index = 7
            game_date_day = int(game_date_day)

            # Game day (0 - 6) number
            game_day = dt[0:4]
            for day in days:
                if game_day == day:
                    game_day_number = days.index(day)
                    break

            # Month number
            for date_month in date_months:
                if dt[month_index:month_index + 4] == date_month:
                    game_month = date_months.index(date_month) + 1
                    break

            # Time
            game_hour = int(dt[month_index + 6:month_index + 8])
            game_min = int(dt[month_index + 10:month_index + 12])

            game_date = datetime(today.year, game_month, game_date_day,
                                 game_hour, game_min)

            if days[game_date.weekday()] != game_day:
                game_date = datetime(today.year - 1, game_month, game_date_day,
                                     game_hour, game_min)
            if days[game_date.weekday()] != game_day:
                game_date = datetime(today.year + 1, game_month, game_date_day,
                                     game_hour, game_min)
            if days[game_date.weekday()] != game_day:
                game_date = datetime(1111, game_month, game_date_day,
                                     game_hour, game_min)
        elif mode == "results":
            # Game date day (1-31) number
            if cf.is_number(dt[4]):
                game_date_day = dt[3:5]
                month_index = 6
            else:
                game_date_day = dt[3]
                month_index = 5
            game_date_day = int(game_date_day)

            # Game day (0-6) number
            game_day = dt[0:2]
            for day in days1:
                if game_day == day:
                    game_day_number = days1.index(day)
                    break

            # Month number
            for date_month in date_months1:
                if dt[month_index:month_index + 3] == date_month:
                    game_month = date_months1.index(date_month) + 1
                    break

            # Time
            game_hour = int(dt[-5:-3])
            game_min = int(dt[-2:])

            # Year number
            game_date = datetime(today.year, game_month, game_date_day,
                                 game_hour, game_min)

            if days1[game_date.weekday()] != game_day:
                game_date = datetime(today.year - 1, game_month, game_date_day,
                                     game_hour, game_min)
            if days1[game_date.weekday()] != game_day:
                game_date = datetime(today.year + 1, game_month, game_date_day,
                                     game_hour, game_min)
            if days1[game_date.weekday()] != game_day:
                game_date = datetime(1111, game_month, game_date_day,
                                     game_hour, game_min)
            """DEBUG CODE
            print("Game day = " + str(game_day))
            print("Date day number = " + str(game_date_day))
            print("Week day number = " + str(game_day_number))
            print("Month number " + str(game_month))
            print("Hour = " + str(game_hour))
            print("Min = " + str(game_min))
            print("Year = " + str(game_date.year))
            """

        return game_date
Esempio n. 10
0
def get_league_data_bet_study(selection, league_data, fixtures, results,
                              available_leagues):
    """
    Takes the key of the selected league from the availableLeagues dictionary.
    Scrapes the selected league information from bedstudy.com.
    Calculates unscraped data (for example, total games won).
    Adds all data to the leagueData dictionary.
    
    Scrapes the all available fixtures of the selected league.
    Adds them to the fixtures list.
    
    Scrapes all available results for the selected league.
    Adds them to the results list.
    """
    today = datetime.today()

    def format_datetime(dt, mode="fixture"):
        """
        Helper function to convert date and time value for a
        game from the BetStudy scraper and converts it into
        a valid datetime object. The object is returned.
        
        Takes the scraped date (and time if available) and an
        optional string for mode (default "fixture").
        
        Behaves differently for each mode.
        """
        if mode == "fixture":
            # Game date day (1-31) number
            game_date_day = int(dt[:2])

            # Month number
            game_date_month = int(dt[3:5])

            # Year number
            game_date_year = int(dt[6:10])

            # Time
            # Default time 0000 when no time present
            if "-" in dt[12:14]:
                game_hour = 00
                game_min = 00
            else:
                game_hour = int(dt[12:14])
                game_min = int(dt[15:17])

            game_date = datetime(game_date_year, game_date_month,
                                 game_date_day, game_hour, game_min)

        elif mode == "result":

            date = dt.split(".")

            # Game date day (1-31) number
            game_date_day = int(date[0])

            # Month number
            game_date_month = int(date[1])

            # Year number
            game_date_year = int(date[2])

            game_date = datetime(game_date_year, game_date_month,
                                 game_date_day)
        return game_date

    bet_study_main = "https://www.betstudy.com/soccer-stats/"
    season = "c/"  # c is current
    full_url = bet_study_main + season + available_leagues[selection]
    web_client = uReq(full_url)
    #print(full_url)
    if web_client.getcode() != 200:
        print("\n" + selection +
              " league data error: Cannot retrieve data, webpage is down")
        return "Scrape error"
    web_html = web_client.read()
    web_client.close()
    web_soup = soup(web_html, "html.parser")
    table = web_soup.find("div", {"id": "tab03_"})

    for i in range(1, 50):  # Support for leagues of up to 50 teams.
        try:
            # Initial scrape also determines if another team is present in the current league
            # Variable only currently used for this error check purpose.
            position = int(table.select('td')[((i - 1) * 16)].text)
        except:
            # If no teams have yet been added, there is an error.
            if i == 1:
                print(
                    "\n" + "\nError scraping " + selection +
                    "\nThe league may be in group or playoff stages or the web site could be experiencing problems."
                )
                return "Scrape error"
            # If teams have been added, the loop has reached the end of the table
            else:
                break

        # Another team is present as "break" hasn't been called - continue scrape

        #position = int(table.select('td')[((i-1)*16)].text) # Commented out as this is now the test for the presence of a team.
        team_name = table.select('td')[((i - 1) * 16) + 1].text
        home_played = int(table.select('td')[((i - 1) * 16) + 2].text)
        home_won = int(table.select('td')[((i - 1) * 16) + 3].text)
        home_drew = int(table.select('td')[((i - 1) * 16) + 4].text)
        home_lost = int(table.select('td')[((i - 1) * 16) + 5].text)
        home_for = int(table.select('td')[((i - 1) * 16) + 6].text)
        home_against = int(table.select('td')[((i - 1) * 16) + 7].text)
        home_points = int(table.select('td')[((i - 1) * 16) + 8].text)
        away_played = int(table.select('td')[((i - 1) * 16) + 9].text)
        away_won = int(table.select('td')[((i - 1) * 16) + 10].text)
        away_drew = int(table.select('td')[((i - 1) * 16) + 11].text)
        away_lost = int(table.select('td')[((i - 1) * 16) + 12].text)
        away_for = int(table.select('td')[((i - 1) * 16) + 13].text)
        away_against = int(table.select('td')[((i - 1) * 16) + 14].text)
        away_points = int(table.select('td')[((i - 1) * 16) + 15].text)

        # Calculated values
        total_played = home_played + away_played
        total_won = home_won + away_won
        total_drew = home_drew + away_drew
        total_lost = home_lost + away_lost
        total_for = home_for + away_for
        total_against = home_against + away_against
        total_points = home_points + away_points

        # Inline code to tidily avoid division by zero errors
        home_won_per_game = 0 if not home_played else round(
            home_won / home_played, 3)
        home_drew_per_game = 0 if not home_played else round(
            home_drew / home_played, 3)
        home_lost_per_game = 0 if not home_played else round(
            home_lost / home_played, 3)
        home_for_per_game = 0 if not home_played else round(
            home_for / home_played, 3)
        home_against_per_game = 0 if not home_played else round(
            home_against / home_played, 3)
        home_points_per_game = 0 if not home_played else round(
            home_points / home_played, 3)
        away_won_per_game = 0 if not away_played else round(
            away_won / away_played, 3)
        away_drew_per_game = 0 if not away_played else round(
            away_drew / away_played, 3)
        away_lost_per_game = 0 if not away_played else round(
            away_lost / away_played, 3)
        away_for_per_game = 0 if not away_played else round(
            away_for / away_played, 3)
        away_against_per_game = 0 if not away_played else round(
            away_against / away_played, 3)
        away_points_per_game = 0 if not away_played else round(
            away_points / away_played, 3)
        total_won_per_game = 0 if not total_played else round(
            total_won / total_played, 3)
        total_drew_per_game = 0 if not total_played else round(
            total_drew / total_played, 3)
        total_lost_per_game = 0 if not total_played else round(
            total_lost / total_played, 3)
        total_for_per_game = 0 if not total_played else round(
            total_for / total_played, 3)
        total_against_per_game = 0 if not total_played else round(
            total_against / total_played, 3)
        total_points_per_game = 0 if not total_played else round(
            total_points / total_played, 3)

        # Add league to the leagueData dictionary if the league does not already exist within it.
        # Any additional stats calculated above must be added to the dictionary generator here.

        if selection not in league_data:
            with league_data_lock:
                league_data[selection] = {
                    team_name: {
                        "Home": {
                            "Played": home_played,
                            "Won": home_won,
                            "Drew": home_drew,
                            "Lost": home_lost,
                            "For": home_for,
                            "Against": home_against,
                            "Points": home_points,
                            "Won per Game": home_won_per_game,
                            "Drew per Game": home_drew_per_game,
                            "Lost per Game": home_lost_per_game,
                            "For per Game": home_for_per_game,
                            "Against per Game": home_against_per_game,
                            "Points per Game": home_points_per_game
                        },
                        "Away": {
                            "Played": away_played,
                            "Won": away_won,
                            "Drew": away_drew,
                            "Lost": away_lost,
                            "For": away_for,
                            "Against": away_against,
                            "Points": away_points,
                            "Won per Game": away_won_per_game,
                            "Drew per Game": away_drew_per_game,
                            "Lost per Game": away_lost_per_game,
                            "For per Game": away_for_per_game,
                            "Against per Game": away_against_per_game,
                            "Points per Game": away_points_per_game
                        },
                        "Total": {
                            "Played": total_played,
                            "Won": total_won,
                            "Drew": total_drew,
                            "Lost": total_lost,
                            "For": total_for,
                            "Against": total_against,
                            "Points": total_points,
                            "Won per Game": total_won_per_game,
                            "Drew per Game": total_drew_per_game,
                            "Lost per Game": total_lost_per_game,
                            "For per Game": total_for_per_game,
                            "Against per Game": total_against_per_game,
                            "Points per Game": total_points_per_game
                        }
                    }
                }
        # If the league does already exist, just update the teams and statistics.
        else:
            with league_data_lock:
                league_data[selection][team_name] = {
                    "Home": {
                        "Played": home_played,
                        "Won": home_won,
                        "Drew": home_drew,
                        "Lost": home_lost,
                        "For": home_for,
                        "Against": home_against,
                        "Points": home_points,
                        "Won per Game": home_won_per_game,
                        "Drew per Game": home_drew_per_game,
                        "Lost per Game": home_lost_per_game,
                        "For per Game": home_for_per_game,
                        "Against per Game": home_against_per_game,
                        "Points per Game": home_points_per_game
                    },
                    "Away": {
                        "Played": away_played,
                        "Won": away_won,
                        "Drew": away_drew,
                        "Lost": away_lost,
                        "For": away_for,
                        "Against": away_against,
                        "Points": away_points,
                        "Won per Game": away_won_per_game,
                        "Drew per Game": away_drew_per_game,
                        "Lost per Game": away_lost_per_game,
                        "For per Game": away_for_per_game,
                        "Against per Game": away_against_per_game,
                        "Points per Game": away_points_per_game
                    },
                    "Total": {
                        "Played": total_played,
                        "Won": total_won,
                        "Drew": total_drew,
                        "Lost": total_lost,
                        "For": total_for,
                        "Against": total_against,
                        "Points": total_points,
                        "Won per Game": total_won_per_game,
                        "Drew per Game": total_drew_per_game,
                        "Lost per Game": total_lost_per_game,
                        "For per Game": total_for_per_game,
                        "Against per Game": total_against_per_game,
                        "Points per Game": total_points_per_game
                    }
                }

    # Get fixtures
    fixtures_url = "d/fixtures/"
    full_url = bet_study_main + season + available_leagues[
        selection] + fixtures_url

    web_client = uReq(full_url)

    if web_client.getcode() != 200:
        print("\n" + selection +
              " fixtures error: Cannot retrieve data, webpage is down")
        return "Scrape error"
    web_html = web_client.read()

    web_client.close()
    web_soup = soup(web_html, "html.parser")
    table = web_soup.find("table", {"class": "schedule-table"})

    number_of_games = 500  # Enough games to include the rest of each season's fixtures

    #fixture list 0.text league, 2.text date and time, 1.text home team, 3.text away team
    #fixture list 5              7                     6                 8
    fixture = []

    while True:
        try:
            # Scrape the number of requested fixtures and then break out of the loop.

            # Each fixture contains 5 cells
            # Multiply the number of games required by 5
            # Produce a list of the 4 of 5 cells needed for each game
            # Add list to fixture list
            for i in range(0, number_of_games * 5, 5):
                date_time_str = str(table.select('td')[i].text)\
                + "  " + str(table.select('td')[i + 2].text)

                game_date_time = format_datetime(date_time_str)

                fixture = [
                    selection,
                    game_date_time.strftime("%d %b %Y %H:%M"),
                    str(table.select('td')[i + 1].text),
                    str(table.select('td')[i + 3].text), game_date_time
                ]

                # Only add the fixture to the fixtures list if it's not already present and it is still to be played.
                if fixture not in fixtures and fixture[4] >= today:
                    with fixtures_lock:
                        fixtures.append(
                            fixture[:])  # add fixture details to fixtures
            break
        except IndexError:
            # Number of requested fixtures exceeds the number of available fixtures, break.
            break

    # Get results
    results_url = "d/results/"
    full_url = bet_study_main + season + available_leagues[
        selection] + results_url

    web_client = uReq(full_url)

    if web_client.getcode() != 200:
        print("\n" + selection +
              " results error: Cannot retrieve data, webpage is down")
        return "Scrape error"
    web_html = web_client.read()
    web_client.close()
    web_soup = soup(web_html, "html.parser")
    table = web_soup.find("table", {"class": "schedule-table"})
    number_of_games = 500  # Enough games to include the rest of each season's results
    #result list 0.text date 04.11.2018, 2.text home team, 1.text score (1 - 0), 3.text away team, 4 icon/link (not used)
    #fixture list 5              7                     6                 8
    result = []

    # DEBUG CODE
    #print("Getting results")

    while True:
        try:
            # Scrape the number of requested results and then break out of the loop.

            # Each result contains 5 cells
            # Multiply the number of games required by 5
            # Produce a list of the 4 of 5 cells needed for each game
            # Add list to results list
            for i in range(0, number_of_games * 5, 5):

                #DEBUG CODE
                #print(str(table.select('td')[i].text))

                game_date = format_datetime(
                    table.select('td')[i].text,
                    mode="result")  # Correct date format for function?
                """
                Sorting the scores
                The scores are not always num - num ( eg. 1 - 1).
                Eg. if a game is postponed, it's Pstp.
                This code checks if a "-" is present and confirms that both scores 
                are numbers.
                If not, it just stores the strings in the most suitable way.
                """
                score_combined = table.select('td')[i + 2].text
                if "-" in score_combined:
                    if cf.is_number(
                            score_combined.split("-")[0]) and cf.is_number(
                                score_combined.split("-")[1]):
                        home_score = int(score_combined.split("-")[0])
                        away_score = int(score_combined.split("-")[1])
                    else:
                        home_score = score_combined.split("-")[0]
                        away_score = score_combined.split("-")[1]
                else:
                    home_score = score_combined
                    away_score = score_combined

                result = [
                    selection,  #League
                    game_date.strftime("%d %b %Y"),  # Date as string
                    str(table.select('td')[i + 1].text),  # Home team
                    home_score,  # Home score
                    str(table.select('td')[i + 3].text),  # Away team
                    away_score,  # Away score
                    game_date
                ]  # Date as datetime object.

                #print(result) # DEBUG CODE

                # Only add the result to the results list if it's not already present.
                if not result in results:

                    #DEBUG CODE
                    #print(str(i) + " added.")

                    with results_lock:
                        results.append(
                            result[:])  # add result details to results.
            break
        except IndexError:
            # Number of requested results exceeds the number of available results, break.
            break

    #print(results) # DEBUG CODE

    return "Success"
Esempio n. 11
0
 def test_is_number_number_int(self):
     self.assertIs(is_number(1970), True)
Esempio n. 12
0
 def test_is_number_str(self):
     self.assertIs(is_number('Eggs'), False)
Esempio n. 13
0
 def test_is_number_number_str(self):
     self.assertIs(is_number('1970'), True)