def get_league_odds_table(league, sport=None, team=None): if league == "politics": sport = "politics" league = "us-politics" url = _build_url(sport, league=league) odds = utils.get_json(url) outstr = "" labels = ['name', 'odds'] for cat in odds: if 'Exotics' not in cat['path'][0]['description']: for event in cat['events']: lines = list() outcomes = event['displayGroups'][0]['markets'][0][ 'outcomes'] for outcome in outcomes: line = dict() line['name'] = outcome['description'] line['odds'] = outcome['price']['american'] lines.append(line) outstr += event['description'] + "\n" + utils.format_table( labels, lines, left_list=labels) + "\n\n" return outstr games, valid = get_league_odds(league, sport=sport) if not valid: return games labels = ["status", "name", "spread", "ml", "total"] left = ["status", "name"] if team is not None: team = team.lower() newgames = list() for i in range(len(games)): if i % 3 == 0: if team in games[i]['name'].lower() or \ team in games[i+1]['name'].lower(): if games[i]['status'] == "Live": score = get_game_score(games[i]['eventid']) games[i]['score'] = score['away'] games[i + 1]['score'] = score['home'] games[i]['status'] = score['period'] games[i + 1]['status'] = score['time'] games[i]['name'] = score['awayteam'] games[i + 1]['name'] = score['hometeam'] newgames.append(games[i]) newgames.append(games[i + 1]) newgames.append({}) labels.insert(1, "score") ret = utils.format_table(labels, newgames, left_list=left).rstrip() else: ret = utils.format_table(labels, games, left_list=left).rstrip() if len(ret) > 2000: return "list of events is too long, use a more restrictive search" return ret
def get_info_str(game_json): home = dict() away = dict() home['team'] = game_json['home_team_data']['abbreviation'] away['team'] = game_json['away_team_data']['abbreviation'] home['r'] = game_json['scoreboard']['linescore']['teams']['home']['runs'] home['h'] = game_json['scoreboard']['linescore']['teams']['home']['hits'] home['e'] = game_json['scoreboard']['linescore']['teams']['home']['errors'] home['lob'] = game_json['scoreboard']['linescore']['teams']['home'][ 'leftOnBase'] if 'home' in game_json['scoreboard']['stats']['exitVelocity']['xbaTeam']: home['xba'] = game_json['scoreboard']['stats']['exitVelocity'][ 'xbaTeam']['home']['xba'] away['r'] = game_json['scoreboard']['linescore']['teams']['away']['runs'] away['h'] = game_json['scoreboard']['linescore']['teams']['away']['hits'] away['e'] = game_json['scoreboard']['linescore']['teams']['away']['errors'] away['lob'] = game_json['scoreboard']['linescore']['teams']['away'][ 'leftOnBase'] away['xba'] = game_json['scoreboard']['stats']['exitVelocity']['xbaTeam'][ 'away']['xba'] if len(game_json['scoreboard']['stats']['wpa']['gameWpa']) > 0: home['wp'] = round( game_json['scoreboard']['stats']['wpa']['gameWpa'][-1] ['homeTeamWinProbability'], 2) away['wp'] = round( game_json['scoreboard']['stats']['wpa']['gameWpa'][-1] ['awayTeamWinProbability'], 2) cols = ['team', 'r', 'h', 'e', 'lob', 'xba', 'wp'] left = ['team'] dicts = [away, home] # WPA leaders lastplays = game_json['scoreboard']['stats']['wpa']['lastPlays'] for p in lastplays: p['wpa'] = round(p['wpa'], 2) topwpa = game_json['scoreboard']['stats']['wpa']['topWpaPlayers'] for i in range(len(topwpa)): lastplays[i]['top_name'] = topwpa[i]['name'] lastplays[i]['topwpa'] = round(topwpa[i]['wpa'], 2) lastplays[i]['space'] = ' | ' labs = ['name', 'wpa', 'space', 'top_name', 'topwpa'] repl_map = { 'name': 'Last 3 WPA', 'wpa': '', 'top_name': 'WPA Leaders', 'topwpa': '', 'space': '' } return (utils.format_table(cols, dicts, left_list=left), utils.format_table(labs, lastplays, left_list=['name', 'top_name'], repl_map=repl_map))
def test_format_table(): actual = utils.format_table([['looooong', 'y', 'z'], ['a', 'looooong', 'c'], ['j', 'k', 'looooong']]) expected = [ 'looooong y z', 'a looooong c', 'j k looooong', ] assert actual == expected assert ["a b c"] == utils.format_table([['a', 'b', 'c']], min_spacing=5)
def test_format_table(): actual = utils.format_table( [ ['looooong', 'y', 'z'], ['a', 'looooong', 'c'], ['j', 'k', 'looooong'] ] ) expected = [ 'looooong y z', 'a looooong c', 'j k looooong', ] assert actual == expected assert ["a b c"] == utils.format_table([['a', 'b', 'c']], min_spacing=5)
def get_player_contract_table(html, url): # html = utils.get_page(url) # with open('spotrac.txt', 'r') as w: # html = w.read() bs = BeautifulSoup(html, 'html.parser') blurb = bs.find("p", {"class":"currentinfo"}) output = "" if blurb is not None: output = blurb.get_text() + "\n\n" table = bs.find("table", {"class":"salaryTable salaryInfo current visible-xs"}) rows = table.find_all("tr") contract_table = [] for row in rows: cells = row.find_all('td') r = {'0':cells[0].get_text(), '1':cells[1].get_text()} contract_table.append(r) output = output + "```python\n%s```" % utils.format_table(['0','1'], contract_table, showlabels=False) table = bs.find("table", {"class":"salaryTable current"}) rows = table.find_all("tr") salary_table = [] salary_th = [] for header in rows[0].find_all('th'): salary_th.append(header.get_text()) print(salary_th) for row in rows[1:]: year_row = {} cells = row.find_all('td') # print(cells) for i in range(len(salary_th)): try: if 'noborder' not in cells[i]['class'] or 'fayear' in cells[i]['class']: data = cells[i].get_text().lstrip() if data.startswith('$'): if '(' in data: data = data[:data.find('(')] data = utils.human_format(data) year_row[salary_th[i]] = data except: pass if len(year_row.keys()) > 0: salary_table.append(year_row) print(salary_table) labs = ['Year', 'Age', 'Base Salary','Luxury Tax Salary','Payroll Salary', 'Adjusted Salary', 'Yearly Cash'] repl = {"Base Salary":"Base", "Luxury Tax Salary":"Luxury Tax", "Payroll Salary":"Payroll", "Adjusted Salary":"Adjusted", "Yearly Cash":"Take home"} output = output + "\n```python\n%s```" % utils.format_table(labs, salary_table, repl_map=repl) output = output + "\n<%s>" % url return output
def fas_schedule(week=""): url = "http://www.fairfaxadultsoftball.com/c.php?p=365&Season=F&League=FMC&Division=T1&SelectedTeam=All+Teams" req = Request(url) req.headers["User-Agent"] = "windows 10 bot" parser = TableParser("stand-sched") parser.feed(urlopen(url).read().decode("utf-8")) try: week = int(week) except ValueError: # comb through to find the current week week = 1 now = datetime.now().date() for row in parser.dicts: if "Date" in row: # whenever we see a date that hasn't happened yet, or is today, break out if len(row["Date"]) > 6 and month_lookup[row["Date"][-6:-3].lower()] >= now.month and int(row["Date"][-2:]) >= now.day: break # update the week as we go elif "Visitor" in row: if len(row["Visitor"]) > 5 and row["Visitor"][:5] == "Week ": week = int(row["Visitor"][5:]) start = len(parser.dicts) end = len(parser.dicts) for i, row in enumerate(parser.dicts): if row["Visitor"] == "Week "+str(week): start = i+1 elif row["Visitor"] == "Week "+str(week+1): end = i parser.dicts = parser.dicts[start:end] return "```python\n%s\n```" % format_table(parser.labels[:-3], parser.dicts, repl_map={"Score_":"score"})
def _print_stats_game_line(list_of_stats, type='hitting', include_gp=False, include_slash=False, include_start_end=False, reddit=False): """ print stats game-line style: [GP] [S E] AB H 2B 3B HR R RBI BB SO SB CS [AVG OBP SLG] """ labels = ['atBats', 'hits', 'doubles', 'triples', 'homeRuns', 'baseOnBalls', 'strikeOuts'] if 'stolenBases' in list_of_stats[0]: labels.append('stolenBases') if 'caughtStealing' in list_of_stats[0]: labels.append('caughtStealing') if include_slash: slash = ['avg','obp','slg'] for s in slash: if s in list_of_stats[0]: labels.append(s) if include_start_end: labels.insert(0, 'end') labels.insert(0, 'start') if include_gp: labels.insert(0, 'gamesPlayed') if len(list_of_stats) > 1: labels.insert(0, 'name') labels.insert(0, 'team') replace = _get_common_replace_map() left = ['name', 'team'] return utils.format_table(labels, list_of_stats, repl_map=replace, left_list=left, reddit=reddit)
def get_indexes(): indexes = {'Dow', 'S&P 500', 'Nasdaq'} labels = ['Index', 'Last', 'Change', '%'] left = [labels[0]] url = "https://money.cnn.com/data/markets" req = Request(url, headers={'User-Agent': "ubuntu"}) data = urlopen(req).read().decode('utf-8') soup = BeautifulSoup(data, 'html.parser') l = soup.find("ul", class_="three-equal-columns wsod") # print(l) items = l.findAll('li') rows = list() for item in items: ticker = dict() ticker['Index'] = item.find("span", class_="ticker-name").get_text() ticker['Last'] = item.find("span", class_="ticker-points").get_text() ticker['%'] = item.find("span", class_="ticker-name-change").get_text() ticker['Change'] = item.find("span", class_="ticker-points-change").get_text() rows.append(ticker) # table_data = [[cell.text.strip() for cell in row("td")] # for row in table("tr")] # rows = [] # for row in table_data: # if row[1] in indexes: # idx = {} # idx[labels[0]] = row[1] # idx[labels[1]] = row[2] # idx[labels[2]] = row[3] # idx[labels[3]] = row[4] # rows.append(idx) return "```%s```" % utils.format_table(labels, rows, left_list=left)
def fas_standings(): url = "http://www.fairfaxadultsoftball.com/c.php?p=365&Season=F&League=FMC&Division=T1&SelectedTeam=All+Teams" req = Request(url) req.headers["User-Agent"] = "windows 10 bot" parser = TableParser("StandingsTable") parser.feed(urlopen(url).read().decode("utf-8")) return "```python\n%s\n```" % format_table(parser.labels, parser.dicts)
def get_stocks(): output = "Latest quotes:\n```python\n" stocks = [] for symbol in ["DIA","VOO","VTI","ONEQ","VXUS"]: url = "https://api.iextrading.com/1.0/stock/"+symbol+"/quote?displayPercent=true" req = Request(url) req.headers["User-Agent"] = "windows 10 bot" # Load data quote = json.loads(urlopen(req).read().decode("utf-8")) stock = dict() change = float(quote['change']) ch = "%0.2f" %(change) chper = "%0.2f" %(quote['changePercent']) chytd = "%0.2f" % (quote['ytdChange']) if change > 0: ch = "+" + ch chper = "+" + chper stock['symbol'] = symbol.upper() stock['price'] = "%.2f" % float(quote['latestPrice']) stock['change'] = ch stock['%'] = chper stock['% YTD'] = chytd stock['description'] = quote['companyName'] stocks.append(stock) # output = output + "%s - %s (%s, %s%%, %s%% YTD) - %s\n" % (symbol.upper(),quote['latestPrice'],ch,chper,chytd,quote['companyName']) # output = "%s - %s:```python\n Last price: %s (%s, %s%%, %s%% YTD" % (symbol.upper(),quote['companyName'],quote['latestPrice'],ch,chper,chytd)+")" labels = ['symbol','price','change','%','% YTD','description'] left = ['symbol','description'] output = output + utils.format_table(labels, stocks, left_list=left) output = output + "```" return output
def _get_multiple_stats_string(playerlist, group=None, include_gp=False, reddit=False): output = "" while group is None: if 'stats' in playerlist[0]: group = playerlist[0]['stats'][0]['group']['displayName'] else: output += "No stats for %s\n" % playerlist[0]['fullName'] playerlist.pop(0) if group == "hitting": labels = ['atBats', 'hits', 'doubles', 'triples', 'homeRuns', 'runs', 'rbi', 'baseOnBalls', 'strikeOuts', 'stolenBases', 'caughtStealing', 'avg', 'obp', 'slg' ,'ops'] elif group == "pitching": labels = ['wins', 'losses', 'gamesPlayed', 'gamesStarted', 'saveOpportunities', 'saves', 'inningsPitched', 'strikeOuts', 'baseOnBalls', 'homeRuns', 'era', 'whip'] repl = {'atBats':'ab', 'plateAppearances':'pa','hits':'h','doubles':'2B','triples':'3b','homeRuns':'hr', 'runs':'r', 'baseOnBalls':'bb','strikeOuts':'so', 'stolenBases':'sb', 'caughtStealing':'cs', 'wins':'w', 'losses':'l', 'gamesPlayed':'g', 'gamesStarted':'gs', 'saveOpportunities':'svo', 'saves':'sv', 'inningsPitched':'ip', 'lastName':'name'} left = ['lastName', 'season'] if include_gp: labels.insert(0, 'gamesPlayed') if len(playerlist) > 1: labels.insert(0, 'lastName') statrows = [] removelist = [] insert_season = False for player in playerlist: if 'stats' in player: for g in player['stats']: rnge = [0] if len(playerlist) == 1 and len(g['splits']) > 2: rnge = range(len(g['splits'])) insert_season = True for i in rnge: if g['group']['displayName'] == group and ('sport' not in g['splits'][i] or g['splits'][i]['sport']['id'] != 0): row = g['splits'][i]['stat'] # row['season'] = g['splits'][i]['season'] row['lastName'] = player['lastName'] if not reddit: row['lastName'] = row['lastName'][:5] statrows.append(row) else: output += "No stats for %s\n" % player['fullName'] removelist.append(player) if insert_season: labels.insert(0, 'season') for player in removelist: playerlist.remove(player) if len(output) > 0: output += "\n" bold = False if len(playerlist) > 1: bold = True return output + utils.format_table(labels, statrows, repl_map=repl, left_list=left, reddit=reddit, bold=bold)
def get_odds_pp(league, team=None): if league == "nba": games = get_nba_odds() elif league == "nhl": games = get_nhl_odds() elif league == "xfl": games = get_xfl_odds() elif league == "nfl": if team == "super bowl": games = get_nfl_odds(superbowl=True) team = None else: games = get_nfl_odds() elif league == "cbb": if team is None: return "cbb team is required" games = get_cbb_odds() labels = ["status", "name", "spread", "ml", "total"] left = ["status", "name"] if team is not None: team = team.lower() newgames = list() for i in range(len(games)): if i % 3 == 0: if team in games[i]['name'].lower() or \ team in games[i+1]['name'].lower(): if games[i]['status'] == "Live": score = get_game_score(games[i]['eventid']) games[i]['score'] = score['away'] games[i + 1]['score'] = score['home'] games[i]['status'] = score['period'] games[i + 1]['status'] = score['time'] games[i]['name'] = score['awayteam'] games[i + 1]['name'] = score['hometeam'] newgames.append(games[i]) newgames.append(games[i + 1]) newgames.append({}) labels.insert(1, "score") ret = utils.format_table(labels, newgames, left_list=left).rstrip() else: ret = utils.format_table(labels, games, left_list=left).rstrip() return ret
def print_stat_leaders(statquery_list, season=None): league = None if 'al' in statquery_list: league = 'al' statquery_list.remove('al') elif 'nl' in statquery_list: league = 'nl' statquery_list.remove('nl') want_group = None groups = ['hitting', 'pitching', 'fielding', 'catching'] for i in statquery_list: if i in groups: want_group = i statquery_list.remove(i) break positions = ['c','1b','2b','3b','ss','lf','cf','rf','of','p','dh'] pos = None for i in statquery_list: if i.lower() in positions: pos = i.upper() statquery_list.remove(i) stat = statquery_list.pop() team = None if len(statquery_list) > 0: team = mymlbstats.get_teamid(' '.join(statquery_list)) print(stat) leaders = get_stat_leaders(stat, season=season, league=league, position=pos, teamid=team) if leaders is None: return "Stat not found" group = None for statgroup in leaders: if statgroup['statGroup'] == want_group or want_group is None: group = (statgroup['statGroup'], list()) for leader in statgroup['leaders'][:10]: player = dict() player['team'] = leader['team']['abbreviation'] player['name'] = leader['person']['fullName'] player[stat] = leader['value'] group[1].append(player) break if group is not None: output = "" output += "%s:\n```python\n" % group[0] labels = ['team', 'name', 'gamesPlayed', stat] left = ['team', 'name'] output += utils.format_table(labels, group[1], left_list=left) output += "```\n" return output else: return "problem finding leaders"
def get_oaa_leaders(year=None): now = datetime.now() if year is None: year = now.year url = "https://baseballsavant.mlb.com/outs_above_average?type=player&year=%s&min=q&csv=true" % ( str(year)) players = utils.csv_to_dicts(url)[:10] cols = ['last_name', 'name_abbrev', 'oaa'] replace = {'last_name': 'player', 'name_abbrev': 'team'} left = ['last_name', 'name_abbrev'] return "```python\n%s```" % utils.format_table( cols, players, repl_map=replace, left_list=left)
def test_format_table_with_interjected_lines(): actual = utils.format_table([['looooong', 'y', 'z'], 'interjection', ['a', 'looooong', 'c'], u'unicode interjection', ['j', 'k', 'looooong']]) expected = [ 'looooong y z', 'interjection', 'a looooong c', u'unicode interjection', 'j k looooong', ] assert actual == expected
def _demo(): with Hub() as hub: password = os.environ.get('HUB_PASSWORD') if password: hub.login(password=password) print('Demo Properties:') for name in sorted(HUB_PROPERTIES): try: val = getattr(hub, name) if isinstance(val, snmp.Table): print('-', name, '(', val.__class__.__name__, ") :") print(utils.format_table(val)) else: print('-', name, ":", val.__class__.__name__, ":", val) except Exception: print("Problem with property", name) raise print("Port Forwardings") print(hub.portforwards.format()) print("Clients:") print(utils.format_table(hub.clients))
def print_savant_advanced_stats(savant_json, year=None, reddit=None): type = None if savant_json['statcast'][0]['grouping_cat'] == "Batter": labels = [ 'ba', 'xba', 'woba', 'xwoba', 'wobadif', 'bb_percent', 'k_percent' ] type = "batting" elif savant_json['statcast'][0]['grouping_cat'] == "Pitcher": labels = [ 'woba', 'xwoba', 'wobadif', 'bb_percent', 'k_percent', 'era', 'xera' ] type = "pitching" if type is None: return "Error getting advanced stats" repls = {'bb_percent': 'bb%', 'k_percent': 'k%'} this_year = datetime.now().year stats = None if year is None: year = this_year for year_entry in savant_json['statcast']: if year_entry['aggregate'] == "0" and this_year == int( year_entry['year']): stats = [year_entry] else: if '-' in year: startyear, stopyear = year.split('-') labels.insert(0, 'year') else: startyear, stopyear = year, year startyear = int(startyear) stopyear = int(stopyear) stats = list() for year_entry in savant_json['statcast']: if year_entry['aggregate'] == "0" and \ int(year_entry['year']) >= startyear and \ int(year_entry['year']) <= stopyear: stats.append(year_entry) player_line = f"{year} {type} advanced stats for {savant_json['playerName']}" if stats is None: return "Cannot find year in stats" return "```python\n%s\n\n%s```" % ( player_line, utils.format_table(labels, stats, repl_map=repls, reddit=reddit))
def print_player_rankings(player, year=None): savant_json = get_player_savant_stats(player) type = savant_json['statcast'][0]['grouping_cat'] stats = None if type == "Pitcher": stats = [ "percent_rank_exit_velocity_avg", "percent_rank_barrel_batted_rate", "percent_rank_xwoba", "percent_rank_xera", "percent_rank_k_percent", "percent_rank_bb_percent", "percent_rank_chase_percent", "percent_rank_whiff_percent" ] elif type == "Batter": stats = [ "percent_rank_exit_velocity_avg", "percent_rank_barrel_batted_rate", "percent_rank_xwoba", "percent_rank_xba", "percent_rank_k_percent", "percent_rank_bb_percent", "percent_rank_chase_percent", "percent_rank_whiff_percent", "percent_rank_sprint_speed", "percent_rank_oaa", "percent_rank_framing" ] if stats is None: return "error getting player rankings" if year is None: year = datetime.now().year stats_dict = None for year_stats in savant_json['statcast']: if year_stats['aggregate'] == "0" and int(year) == int( year_stats['year']): stats_dict = year_stats if stats_dict is None: return f"No stats for {year}" # build dict for table table_rows = list() for stat in stats: if stat in stats_dict and stats_dict[stat] is not None: d = dict() d['stat'] = stat.replace("percent_rank_", "") d['value'] = int(stats_dict[stat]) table_rows.append(d) # sort by value (desc) table_rows = sorted(table_rows, key=lambda i: i["value"], reverse=True) player_line = f"{year} {type} percentile rankings for {savant_json['playerName']}" table_output = utils.format_table(['stat', 'value'], table_rows, showlabels=False) return f"```python\n{player_line}\n\n{table_output}```"
def test_format_table_with_interjected_lines(): actual = utils.format_table( [ ["looooong", "y", "z"], "interjection", ["a", "looooong", "c"], u"unicode interjection", ["j", "k", "looooong"], ] ) expected = [ "looooong y z", "interjection", "a looooong c", u"unicode interjection", "j k looooong", ] assert actual == expected
def format(self): """Get a string representation of the table for human consumption. This is nicely ordered in auto-sized columns with headers and (almost) graphics: +-------------+--------+---------------+-----------------------------------------+ | IPAddr | Prefix | NetMask | GW | +-------------+--------+---------------+-----------------------------------------+ | 86.21.83.42 | 21 | 255.255.248.0 | 86.21.80.1 | | | 0 | | 0000:000c:000f:cea0:000f:caf0:0000:0000 | +-------------+--------+---------------+-----------------------------------------+ This format is best suited for tables with a limited number of columns and/or wide terminals. """ return utils.format_table(self)
def test_format_table_with_interjected_lines(): actual = utils.format_table( [ ['looooong', 'y', 'z'], 'interjection', ['a', 'looooong', 'c'], u'unicode interjection', ['j', 'k', 'looooong'] ] ) expected = [ 'looooong y z', 'interjection', 'a looooong c', u'unicode interjection', 'j k looooong', ] assert actual == expected
def get_todays_scores(team=None): url = "https://worldcup.sfg.io/matches/today" games = utils.get_json(url) gameslist = [] for game in games: if team is not None: if team.lower() in game['home_team']['code'].lower() or \ team.lower() in game['away_team']['code'].lower() or \ team.lower() in game['home_team']['country'].lower() or \ team.lower() in game['away_team']['country'].lower(): if game['status'] != 'future': return format_single_game(game) else: continue else: if game['status'] != 'future' and len(games) == 1: return format_single_game(game) home = dict() away = dict() home['team'] = game['home_team']['code'] away['team'] = game['away_team']['code'] if game['status'] == 'future': home['score'] = "" away['score'] = "" else: home['score'] = game['home_team']['goals'] away['score'] = game['away_team']['goals'] if game['status'] == 'completed' or game['time'] == 'full-time': away['time'] = 'Final' elif game['time'] is not None: away['time'] = "%s" % game['time'] elif game['status'] == 'future': away['time'] = utils.get_ET_from_timestamp(game['datetime']) # else: # away['time'] = gameslist.append(away) gameslist.append(home) labels = ['team', 'score', 'time'] return utils.format_table(labels, gameslist, showlabels=False, linebreaknum=2)
def print_pitch_arsenal(pitcher, season=None, reddit=False): print(pitcher) player = _new_player_search(pitcher) if player is None: return "could not find pitcher" if season is None: now = datetime.now() season = str(now.year) player_info = "%s pitch arsenal for %s (%s)\n\n" % (season, player['fullName'], player['currentTeam']['abbreviation']) pitches = get_pitch_arsenal(player['id'], season=season) pitches = sorted(pitches, key = lambda k: float(k['percentage']), reverse=True) labels = ['description', 'percentage', 'averageSpeed'] left = ['description'] repl = {'description':'pitch', 'percentage':'%', 'averageSpeed':'avg mph'} return "```python\n%s%s```" % (player_info, utils.format_table(labels, pitches, left_list=left, repl_map=repl, reddit=reddit))
def format_single_game(game): line = dict() line['5'] = game['home_team']['code'] line['1'] = game['away_team']['code'] line['4'] = game['home_team']['goals'] line['2'] = game['away_team']['goals'] if game['status'] == 'completed' or game['time'] == 'full-time': line['time'] = ' | Final | ' elif game['time'] is not None: line['time'] = " | %s | " % game['time'] elif game['status'] == 'future': line['time'] = utils.get_ET_from_timestamp(game['datetime']) rows = [line] home_goals = [] away_goals = [] for event in game['home_team_events']: if 'goal' in event['type_of_event']: if event['type_of_event'] == 'goal': home_goals.append("%s (%s)" % (event['player'], event['time'])) if event['type_of_event'] == 'goal-penalty': home_goals.append("%s (%s PEN)" % (event['player'], event['time'])) for event in game['away_team_events']: if 'goal' in event['type_of_event']: if event['type_of_event'] == 'goal': away_goals.append("%s (%s)" % (event['player'], event['time'])) if event['type_of_event'] == 'goal-penalty': away_goals.append("%s (%s-PEN)" % (event['player'], event['time'])) lines = max(len(home_goals), len(away_goals)) for i in range(lines): a = dict() if i < len(away_goals): a['1'] = away_goals[i] if i < len(home_goals): a['5'] = home_goals[i] rows.append(a) labels = ['1', '2', 'time', '4', '5'] return utils.format_table(labels, rows, showlabels=False, left_list=['5'])
def get_last_five(game_json): ev = game_json['exit_velocity'] events = [] for event in ev[-5:]: events.append(event) events.reverse() cols = [ 'batter_name', 'result', 'hit_speed', 'hit_distance', 'hit_angle', 'xba' ] repl = { 'batter_name': 'last bb', 'hit_speed': 'EV', 'hit_distance': 'dist', 'hit_angle': 'LA' } left = ['batter_name', 'result'] return "```python\n%s```" % utils.format_table( cols, events, repl_map=repl, left_list=left)
def get_top_five(game_json): ev = game_json['exit_velocity'] ev = sorted(ev, key=lambda k: float(k['hit_speed']), reverse=True)[:5] # for event in ev: # events.append(event) # events.reverse() cols = [ 'batter_name', 'result', 'hit_speed', 'hit_distance', 'hit_angle', 'xba' ] repl = { 'batter_name': 'Top EV', 'hit_speed': 'EV', 'hit_distance': 'dist', 'hit_angle': 'LA' } left = ['batter_name', 'result'] return "```python\n%s```" % utils.format_table( cols, ev, repl_map=repl, left_list=left)
def get_crypto_yahoo(): url = "https://query1.finance.yahoo.com/v7/finance/quote?symbols=btc-usd,eth-usd,ltc-usd,xlm-usd,doge-usd" results = utils.get_json(url)['quoteResponse']['result'] if len(results) > 0: for res in results: price = res['regularMarketPrice'] if price < 1.0: res['regularMarketPrice'] = str(round(price, 3)) res['regularMarketDayLow'] = str( round(res['regularMarketDayLow'], 3)) res['regularMarketDayHigh'] = str( round(res['regularMarketDayHigh'], 3)) else: res['regularMarketPrice'] = int(price) res['regularMarketDayLow'] = int(res['regularMarketDayLow']) res['regularMarketDayHigh'] = int(res['regularMarketDayHigh']) res['marketCap'] = simpleMarketCap(res['marketCap']) labels = [ "fromCurrency", "regularMarketPrice", "regularMarketDayHigh", "regularMarketDayLow", "marketCap" ] left_labels = ["fromCurrency"] replace = { "fromCurrency": "coin", "regularMarketPrice": "Price", "regularMarketDayHigh": "24h high", "regularMarketDayLow": "24h low", "marketCap": "market cap" } out = "```python\n" out += utils.format_table(labels, results, left_list=left_labels, repl_map=replace) out += "```" return out else: return "error"
def get_cryptocurrency_data(text): if len(text) == 0: text = "?limit=10" # req = Request("https://api.coinmarketcap.com/v1/ticker/" +text) # req.headers["User-Agent"] = "windows 10 bot" # data = json.loads(urlopen(req).read().decode("utf-8")) url = "https://api.coinmarketcap.com/v1/ticker/" + text data = utils.get_json(url) if "error" in data: return # output = "```python\n" # for coin in data: # name = coin["name"] # price = coin["price_usd"] # change = coin["percent_change_24h"] # change7 = coin["percent_change_7d"] # output = output + name.ljust(12) + " $" + price.ljust(10) + change.rjust(6) + "% last 24h\t" + change7.rjust(6) + "% last 7d\n" # return output+"```" labels = ["Name", "Price", "Change", "24h", "7d"] data = ['name', 'price_usd', 'percent_change_24h', 'percent_change_7d'] output = utils.format_table()
def get_state(state, delta=None): url = URL + "states" if delta is None: data = utils.get_json(url) state_entry = None for st in data: if st['state'].lower() == state.lower(): state_entry = st break if state_entry is not None: l = format_data(state_entry) l.append({'name': 'data quality', 'total': state_entry['grade']}) l.append({'name': 'updated', 'total': state_entry['lastUpdateEt']}) labels = ['name', 'total'] repl_map = {'name': ''} return "```python\n%s\n\n%s```" % ( "%s current totals:" % state_entry['state'], utils.format_table( labels, l, repl_map=repl_map, left_list=['name'])) else: return "State not found."
def get_cryptocurrency_data(text): if len(text) == 0: text = "?limit=10" url = "https://api.coinmarketcap.com/v1/ticker/" + text data = utils.get_json(url) if "error" in data: return for coin in data: coin["price_usd"] = "%.02f" % float(coin["price_usd"]) coin["percent_change_24h"] = "%.02f" % float( coin["percent_change_24h"]) coin["percent_change_7d"] = "%.02f" % float(coin["percent_change_7d"]) repl = { "price_usd": "price", "percent_change_24h": "% 24h", "percent_change_7d": "% 7d" } labels = ['name', 'price_usd', 'percent_change_24h', 'percent_change_7d'] left = ['name'] output = utils.format_table(labels, data, repl_map=repl, left_list=left) return "```python\n" + output + "```"
def get_player(game_json, playerid): ev = game_json['exit_velocity'] events = [] for e in ev: if e['batter'] == playerid: events.append(e) cols = [ 'inning', 'batter_name', 'result', 'hit_speed', 'hit_distance', 'hit_angle', 'xba' ] repl = { 'inning': 'inn', 'batter_name': 'batter', 'hit_speed': 'EV', 'hit_distance': 'dist', 'hit_angle': 'LA' } left = ['batter_name', 'result'] output = "```python\n%s```" % utils.format_table( cols, events, repl_map=repl, left_list=left) return output
def get_index_futures(): indexes = { 'ES=F': 'S&P Futures', 'YM=F': 'Dow Futures', 'NQ=F': 'Nasdaq Futures' } url = "https://query1.finance.yahoo.com/v7/finance/quote?symbols=" for index in indexes.keys(): url = url + index + "," url = url[:-1] # remove trailing comma data = utils.get_json(url) idxs = list() for future in data['quoteResponse']['result']: idx = dict() idx['name'] = indexes[future['symbol']] idx['price'] = future['regularMarketPrice'] idx['change'] = future['regularMarketChange'] idx['%'] = round(future['regularMarketChangePercent'], 2) idxs.append(idx) labels = ['name', 'price', 'change', '%'] left = ['name'] return "```%s```" % (utils.format_table(labels, idxs, left_list=left))
def _get_stats_string(stats, group=None, include_gp=False): if group is None: group = stats[0]['group']['displayName'] if group == "hitting": labels = ['atBats', 'hits', 'doubles', 'triples', 'homeRuns', 'runs', 'rbi', 'baseOnBalls', 'strikeOuts', 'stolenBases', 'caughtStealing', 'avg', 'obp', 'slg' ,'ops'] elif group == "pitching": labels = ['wins', 'losses', 'gamesPlayed', 'gamesStarted', 'saveOpportunities', 'saves', 'inningsPitched', 'strikeOuts', 'baseOnBalls', 'homeRuns', 'era', 'whip'] repl = {'atBats':'ab', 'plateAppearances':'pa','hits':'h','doubles':'2B','triples':'3b','homeRuns':'hr', 'runs':'r', 'baseOnBalls':'bb','strikeOuts':'so', 'stolenBases':'sb', 'caughtStealing':'cs', 'wins':'w', 'losses':'l', 'gamesPlayed':'g', 'gamesStarted':'gs', 'saveOpportunities':'svo', 'saves':'sv', 'inningsPitched':'ip'} if include_gp: labels.insert(0, 'gamesPlayed') statrows = [] for g in stats: if g['group']['displayName'] == group: row = g['splits'][0]['stat'] row['season'] = g['splits'][0]['season'] statrows.append(row) return utils.format_table(labels, statrows, repl_map=repl)
def test_format_table(): actual = utils.format_table([["looooong", "y", "z"], ["a", "looooong", "c"], ["j", "k", "looooong"]]) expected = ["looooong y z", "a looooong c", "j k looooong"] assert actual == expected assert ["a b c"] == utils.format_table([["a", "b", "c"]], min_spacing=5)
def test_format_table_all_strings(): actual = utils.format_table(["foo", "bar", "baz"]) expected = ["foo", "bar", "baz"] assert actual == expected
def format_table_page(*args, **kwargs): import utils preamble = utils.format_table([('Start:', as_local_time(START_TIME)), ('End:', as_local_time(END_TIME))]) return utils.format_table_page(preamble, *args, **kwargs)
def test_format_table_all_strings(): actual = utils.format_table(['foo', 'bar', 'baz']) expected = ['foo', 'bar', 'baz'] assert actual == expected