tpy:
from S22.trends import query from S22.trends import pull_trends import PyQL.py_tools from datetime import datetime import traceback import glob, time, os, re import PyQL.py_tools import cPickle import urllib import KS2.ks from KS2.ks import TREND_TOP,TREND_SUP,TREND_TYPES,trend_file_top,current_season from KS2.page_logger import visitor_log import string import pandas as pd import numpy as np from MLB.formatsV2 import probability import KS2.client_tools from KS2.subscriber_tools import beta_testers, kspro_access client_info = KS2.client_tools.client_info({'client': __d.get("client","guest")}) box_s = { 'nfl': '/home/jameyer/S2/NFL/Source/Data/NFL/Box/_Column/', 'nba': '/home/jameyer/S2/NBA/Source/Data/NBA/Box/_Column/Game/', 'ncaafb': '/home/jameyer/S2/NCAAFB/Source/Data/Covers/Box/_Column/', 'ncaabb': '/home/jameyer/S2/NCAABB/Data/Covers/Box/_Column/Game/', 'mlb': '/home/jameyer/S2/MLB/Source/Data/MLB/Box/_Column/Game/', 'nhl': '/home/jameyer/S2/NHL/Data/Covers/Box/_Column/Game/', 'wnba': '/home/jameyer/S2/WNBA/Source/Data/WNBA/Box/_Column/Game/' } trend_sets = { 'NFL': '/home/jameyer/S2/NFL/Source/Data/NFL/Schedule/_Column/', 'NBA': '/home/jameyer/S2/NBA/Source/Data/NBA/Schedule/_Column/', 'MLB': '/home/jameyer/S2/MLB/Source/Data/MLB/Schedule/_Column/', 'NCAAFB': '/home/jameyer/S2/NCAAFB/Source/Data/Covers/Schedule/_Column/', 'NCAABB': '/home/jameyer/S2/NCAABB/Data/Schedule/_Column/', 'NHL': '/home/jameyer/S2/NHL/Data/Covers/Schedule/_Column/', 'WNBA': '/home/jameyer/S2/WNBA/Source/Data/WNBA/Schedule/_Column/' } if datetime.now().month in [2, 3, 4, 5]: default = 'NBA' elif datetime.now().month in [9, 10, 11, 12, 1]: default = 'NFL' else: default = 'MLB' client = 'admin' sport = __d.get("filter", default) owner = client _date_ = __d.get("date", int(PyQL.py_tools.today())) #int(PyQL.py_tools.today()) _type_ = __d.get("typ", ".*") _foc_ = __d.get("foc", "*") _per_ = __d.get("per", "FG") period = _per_ _page_ = __d.get("pg", 1) _sort_ = __d.get("sort", '_pval') ascending=False with open('%steam.pkl'%box_s[sport.lower()], 'rb') as f: teams = cPickle.load(f) teams = [x for x in list(set(teams)) if x] pth = glob.glob("/home/jameyer/KS/Trends/"+sport.upper()+"/Trend/"+client+"_*/_Pickle/*.pkl") if ((len(pth) > 0) and (client != 'guest')): info = "KS-Pro Indicators were last run at "+str(time.strftime("%Y-%m-%d %I:%M %p %Z", time.localtime(os.path.getmtime(pth[0])))) visitor_log('kspro',client,1) elif client == 'guest': info = 'Viewing in Guest Mode, please log-in to access and save personal trends' owner = 'admin' else: info = '' with open(''.join([trend_sets[sport.upper()],'date.pkl']), 'rb') as f: scheduled_dates = cPickle.load(f) if sport in ['NFL','NCAAFB']: if sport == 'NFL': import NFL.date_tools as week_calc else: import NCAAFB.date_tools as week_calc if scheduled_dates: if (_date_ > 10000000 and _date_ not in scheduled_dates): _date_ = week_calc.find_week_from_date(scheduled_dates[0]) else: _date_ = 0 def GVT(owner, sport): TREND_TOP = os.path.join('/home/jameyer/KS','Trends') client_trend_globber = os.path.join(TREND_TOP,sport,"Trend","%s_*.trend"%owner) # bgcolors = ["FFFFFF","DDDDDD"] # bgcolor = bgcolors[0] i = -1 filenames = glob.glob(client_trend_globber) filenames.sort() pat = re.compile('\((.*)\) as ".*=>(.*)"') available = {} for filename in filenames: ftype = filename.split('/')[-1][:-6] available[ftype] = [] for line in map(string.strip,open(filename).readlines()): mo = pat.findall(line) if len(mo) > 0: available[ftype] += [mo[0][0].replace(' ','')] return available # ensure still a live trend available = GVT(owner, sport) lock_options = [] lock_date = 0 global weeks if sport in ['NFL','NCAAFB']: # if sport == 'NFL': # import NFL.date_tools as week_calc # else: # import NCAAFB.date_tools as week_calc # if _date_ > 10000000: # _date_ = week_calc.find_week_from_date(_date_) # else: options = [] for s in scheduled_dates: if int(s) not in options: options += [s] if options: lock_options = options[0] lock_date = _date_ if _date_ < 10000000 and _date_ != 0: week = _date_ else: week = week_calc.find_week_from_date(options[0]) if _date_ != 0 and not __d.get('pyql'): _date_ = week weeks = {} for option in options: week = week_calc.find_week_from_date(option) if week not in weeks: weeks[week] = [] weeks[week] += [option] else: pass pyql_url = '' try: trends = pull_trends(str(sport), owner) kwargs = {} kwargs['sport'] = sport if 'pyql' in __d: kwargs['pyql'] = urllib.unquote(__d['pyql']) pyql_url = '&pyql=%s'%urllib.quote(__d['pyql']) kwargs["show_form"] = 9 kwargs["result_only" ] = 1 kwargs["api_key" ] = "179" kwargs["client"] = "KSC" kwargs["owner_pats_request"] = ["KSC::"+owner+"_"+_type_] # if sport in ['NFL','NCAAFB'] and _date_ != 0: if sport in ['NFL','NCAAFB'] and _date_ < 1000000 and _date_ != 0: kwargs['date']=weeks[_date_] else: kwargs['date']=[_date_] kwargs['output'] = 'python' #kwargs['output'][0] #list res = query(trends,**kwargs) #do query #jqa except Exception: res = traceback.format_exc() jqa = '' def sdql_locate(x, client, trends): for client_bet in list(trends['KSC']): headers = trends['KSC'][client_bet].headers i_sdql = headers.index('sdql') if x in trends['KSC'][client_bet].data[i_sdql]: return client_bet.split('_')[-1] return '-' def sdql_record(x, client, bet, trends): headers = trends['KSC']['%s_%s'%(client,bet)].headers i_sdql = headers.index('sdql') i_wins = headers.index('wins') i_losses = headers.index('losses') if x in trends['KSC']['%s_%s'%(client,bet)].data[i_sdql]: i = list(trends['KSC']['%s_%s'%(client,bet)].data[i_sdql]).index(x) c0 = trends['KSC']['%s_%s'%(client,bet)].data[i_wins][i] c1 = trends['KSC']['%s_%s'%(client,bet)].data[i_losses][i] if c1 > c0: return '1' return '0' def eval_focus(x, teams=teams): x = ' and %s'%x n = 0 if re.findall('|'.join(teams), x): n += 1 if re.findall('and ([A-z\s]+):', x): for y in re.findall('and ([A-z\s]+):', x): X = y.split(' and ')[-1].replace('not', '') if re.sub('[tpPnNosS ]','',X) != '': n += 2 return n if n < 2: if re.findall('name(?:\s|)=(?:\s|)[A-z]+', x): n += 2 elif re.findall('starter(?:\s|)=(?:\s|)[A-z]+', x): n += 2 if re.findall('coach(?:\s|)=(?:\s|)[A-z]+', x): n += 4 elif re.findall('manager(?:\s|)=(?:\s|)[A-z]+', x): n += 4 return n def eval_roi(side, rec): R = rec.split(' ')[0].split('-') if side in ['ON','OVER']: profit = (int(R[0]) * 100)-(int(R[1]) * 110) invest = (int(R[0]) + int(R[1])) * 110 elif side in ['AGST','UNDER']: profit = (int(R[1]) * 100)-(int(R[0]) * 110) invest = (int(R[0]) + int(R[1])) * 110 else: return '-', '-' return '{:.1%}'.format((profit+0.0)/invest), '${:,.0f}'.format(profit) sup_dir = os.path.join(TREND_SUP,sport.upper()) sup_file = '%s.pkl'%owner if sup_file in os.listdir(sup_dir): with open(os.path.join(sup_dir, sup_file),'rb') as f: metrics = cPickle.load(f) else: metrics = {} options = list(trends['_schedule']) options.sort() if sport in ['NFL','NCAAFB'] and options: if sport == 'NFL': import NFL.date_tools as week_calc else: import NCAAFB.date_tools as week_calc week = week_calc.find_week_from_date(options[0]) weeks = {} for option in options: week = week_calc.find_week_from_date(option) if week not in weeks: weeks[week] = [] weeks[week] += [option] options = list(weeks) options.sort() # options = [option for option in options if week_calc.find_week_from_date(option) == week] else: pass activeTrends = 10000 if sport in ['NFL','NCAAFB'] and 'weeks' in locals() or 'week' in locals(): # _date_ = week date_dropdown = """ <div class="dropdown"> <button onclick="myFunction(0)" class="dropdown-btn dropdown-toggle" data-toggle="dropdown" id="date-sel">Week <span class="caret"></span></button> <div id="myDropdown_0" class="dropdown-content" style="width: 225px"> <div class="option-bord" onclick="setDate(event)" style="cursor:pointer"> <a class="drop-option" name="0">All Research</a> </div> """ for w in list(weeks)[:10]: date_dropdown += '<div class="option-bord" onclick="setDate(event)"><a class="drop-option" name="%s">Active in Week %s</a></div>'%(w,w) date_dropdown += "</div></div>" _date_ = __d.get("date", options[0]) #int(PyQL.py_tools.today()) else: date_dropdown = """ <div class="dropdown"> <button onclick="myFunction(0)" class="dropdown-btn dropdown-toggle" data-toggle="dropdown" id="date-sel">Date <span class="caret"></span></button> <div id="myDropdown_0" class="dropdown-content" style="width: 225px"> <div class="option-bord" onclick="setDate(event)" style="cursor:pointer"> <a class="drop-option" name="0">All Trends</a> </div> """ for i in options: date_dropdown += """ <div class="option-bord" onclick="setDate(event)" style="cursor:pointer"> <a class="drop-option" name="%s">Active on %s</a> </div>"""%(i, PyQL.py_tools.nice_date(i) if i > 10000000 else i) date_dropdown += "</div></div>" plays = ['ats', 'su', 'ou'] if sport in ['MLB']: plays = ['rl', 'ml', 'ou'] elif sport in ['NHL']: plays = ['pl', 'ml', 'ou'] typ_dropdown = """ <div class="dropdown"> <button onclick="myFunction(1)" class="dropdown-btn dropdown-toggle" data-toggle="dropdown" id="typ-sel">All Types <span class="caret"></span></button> <div id="myDropdown_1" class="dropdown-content" style="width: 225px"> <div class="option-bord" onclick="setType(event)" style="cursor:pointer"> <a class="drop-option" name=".*">All Types</a> </div> <div class="option-bord" onclick="setType(event)" style="cursor:pointer"> <a class="drop-option" name="%s">%s</a> </div> <div class="option-bord" onclick="setType(event)" style="cursor:pointer"> <a class="drop-option" name="%s">%s</a> </div> <div class="option-bord" onclick="setType(event)" style="cursor:pointer"> <a class="drop-option" name="%s">%s</a> </div> """%(plays[0], plays[0].upper(), plays[1], plays[1].upper(), plays[2], plays[2].upper()) typ_dropdown += "</div></div>" foc_dropdown = """ <div class="dropdown"> <button onclick="myFunction(2)" class="dropdown-btn dropdown-toggle" data-toggle="dropdown" id="foc-sel">Any Focus <span class="caret"></span></button> <div id="myDropdown_2" class="dropdown-content" style="width: 225px"> <div class="option-bord" onclick="setFocus(event)" style="cursor:pointer"> <a class="drop-option" name="*">All Categories</a> </div> <div class="option-bord" onclick="setFocus(event)" style="cursor:pointer"> <a class="drop-option" name="league">League-Wide</a> </div> <div class="option-bord" onclick="setFocus(event)" style="cursor:pointer"> <a class="drop-option" name="team">Team Specific</a> </div> <div class="option-bord" onclick="setFocus(event)" style="cursor:pointer"> <a class="drop-option" name="coach">Coach Specific</a> </div> <div class="option-bord" onclick="setFocus(event)" style="cursor:pointer"> <a class="drop-option" name="player">Player Specific</a> </div> """ foc_dropdown += "</div></div>" if sport in ['ATP','WTA']: per_dropdown = """ <div class="dropdown"> <button onclick="myFunction(3)" class="dropdown-btn dropdown-toggle" data-toggle="dropdown" id="per-sel">Focus <span class="caret"></span></button> <div id="myDropdown_3" class="dropdown-content" style="width: 225px"> """ else: per_dropdown = """ <div class="dropdown"> <button onclick="myFunction(3)" class="dropdown-btn dropdown-toggle" data-toggle="dropdown" id="per-sel">Period <span class="caret"></span></button> <div id="myDropdown_3" class="dropdown-content" style="width: 225px"> <div class="option-bord" onclick="setPeriod(event)" style="cursor:pointer"> <a class="drop-option" name="FG">Full Game</a> </div> <div class="option-bord" onclick="setPeriod(event)" style="cursor:pointer"> <a class="drop-option" name="H1">1st Half</a> </div> <div class="option-bord" onclick="setPeriod(event)" style="cursor:pointer"> <a class="drop-option" name="Q1">1st Quarter</a> </div> """ per_dropdown += "</div></div>" trend_table = """ <table id="DT_Table" class="table table-striped"> <thead class="table-header"> <tr> <th style="cursor:pointer" onclick="trendSort('pval')">P val<span class="sorting-arrow ml-3"></span></th> <th>Type</span></th> <th>Play</span></th> <th>Focus</span></th> <th style="cursor:pointer" onclick="trendSort('record')">Record<span class="sorting-arrow ml-3"></span></th> <th style="cursor:pointer" onclick="trendSort('profit')">Profit<span class="sorting-arrow ml-3"></span></th> <th style="cursor:pointer" onclick="trendSort('roi')">ROI<span class="sorting-arrow ml-3"></span></th> <th style="width: 35%;">Indicator Description</th> <th>SDQL</span></th> <th style="width: 20px;"></th> </tr> </thead> <tbody class="table-body">""" save_message = '' TREND_TOP = os.path.join('/home/jameyer/KS','Trends') client_trend_globber = os.path.join(TREND_TOP,sport,"Trend","%s_*.trend"%owner) keys = __d.keys() keys.sort() ttypes = TREND_TYPES[sport] N = 0 translated = {'ats': 'Spread', 'rl': 'Run Line', 'su': 'Moneyline', 'ou': 'Over/Under', 'ml': 'Moneyline', 'pl': 'Puck Line'} for bet in ttypes: filename = string.replace(client_trend_globber,"*",bet) N = len([x for x in open(filename,'r').readlines() if x[0] not in '@#.']) save_message += "%s (%s) - %d&emsp;|&emsp;"%(translated[bet], bet.upper(), N) save_message = "<br><br><u><span style='font-size: 18px;font-weight: 700;'>KS-Pro Indicator Inventory:</u>&emsp;%s</span>"%save_message[:-13] info += save_message sides = {'ATS': {'0': 'ON', '1': 'AGST'},'OU': {'0': 'OVER', '1': 'UNDER'},'SU': {'0': 'ON', '1': 'AGST'}, 'RL': {'0': 'ON', '1': 'AGST'}, 'PL': {'0': 'ON', '1': 'AGST'}, 'ML': {'0': 'ON', '1': 'AGST'}} def pwr(x, metrics = metrics, sides = sides): desc = x[1] sdql = x[0] search = '(%s) as "%s=>%s"' % (sdql, sdql, desc) if search in metrics: play = metrics[search]['type'].upper() side = sides[play][metrics[search]['side']] rtg = str(metrics[search]['rtg']) if rtg == 'NR': rtg = 0 else: rtg = 0 return rtg def per(x, metrics = metrics, sides = sides): desc = x[1] sdql = x[0] search = '(%s) as "%s=>%s"' % (sdql, sdql, desc) if search in metrics: play = metrics[search]['type'].upper() side = sides[play][metrics[search]['side']] rtg = str(metrics[search]['rtg']) if rtg == 'NR': rtg = 0 per = metrics[search].get('per','FG') else: rtg = 0 per = 'FG' return per def play(x, sides = sides): if play != '-': if play in ['ML','RL','PL']: if wins[i] < 0 : side = sides[play]['1'] else: side = sides[play]['0'] else: side = sides[play][sdql_record(sdql, owner, play.lower(), trends)] return side def line_dependent_play(w, l, play, sides = sides): if play != '-': if play in ['ML','RL','PL']: if w < 0 : side = sides[play]['1'] else: side = sides[play]['0'] else: if l > w: side = sides[play]['1'] else: side = sides[play]['0'] return side def roiCalc(w, l, side): R = [w, l] if side in ['ON','OVER']: profit = (int(R[0]) * 210) profit_v = (int(R[0]) * 100) - (int(R[1]) * 110) invest = (int(R[0]) + int(R[1])) * 110 elif side in ['AGST','UNDER']: profit = (int(R[1]) * 210) profit_v = (int(R[1]) * 100) - (int(R[0]) * 110) invest = (int(R[0]) + int(R[1])) * 110 else: return '-', '-' return ((profit+0.0)/invest)-1.0, profit_v def correct_pct(w, l, side, sport=sport): if side in ['AGST','UNDER'] and sport in ['MLB','NHL']: pct = (abs(w)+0.0)/(abs(l) + abs(w)) elif side in ['AGST','UNDER']: pct = (l+0.0)/(l + w) else: pct = (w+0.0)/(w + l) return pct if res != {}: DF = {} for x in list(res): t = x.split('_')[-1] global line_dependent_play global roiCalc global correct_pct global probability global t DF[t] = pd.DataFrame(columns = list(res[x][0].headers)) for y in xrange(len(list(DF[t]))): DF[t][res[x][0].headers[y]] = list(res[x][0].data[y]) # get power ratings DF[t]['rtg'] = DF[t]['link'].apply(pwr) DF[t]['per'] = DF[t]['link'].apply(per) DF[t]['side'] = DF[t].apply(lambda x: line_dependent_play(x['wins'], x['losses'], t.upper()), axis=1) DF[t]['pct'] = DF[t].apply(lambda x: correct_pct(x['wins'], x['losses'], x['side']), axis=1) if sport in ['MLB', 'NHL']: DF[t]['pvW'] = DF[t]['wins'].abs() DF[t]['pvT'] = (DF[t]['wins'] + DF[t]['losses']).abs() DF[t]['p val'] = DF[t].apply(lambda x: probability(x['pvT'], x['pvW']), axis=1) DF[t]['ROI'] = DF[t]['ROI']/100.0 else: values = DF[t].apply(lambda x: roiCalc(x['wins'], x['losses'], x['side']), axis=1) DF[t]['ROI'] = values.str[0] DF[t]['$'] = values.str[1] DF[t]['play'] = t.upper() DF[t] = DF[t][DF[t]['per'] == _per_] # compiled res = pd.concat(DF, ignore_index=True) # do the sort sort_arrows = ['','','',''] arrow_dir = '' ascending = False; _lsort_ = _sort_ if _sort_[0] == '_': ascending = True; _sort_ = _sort_[1:] arrow_dir = ' sorting-arrow-up' pageT = len(res) i0 = min(max(0, 100*(_page_-1)), pageT) if _sort_ == 'pval': sort_arrows[0] = ' active%s'%arrow_dir res = res.sort_values('p val', ascending=ascending) #.iloc[i0:i0+100] elif _sort_ == 'record': sort_arrows[1] = ' active%s'%arrow_dir res = res.sort_values('pct', ascending=ascending) #.iloc[i0:i0+100] elif _sort_ == 'profit': sort_arrows[2] = ' active%s'%arrow_dir res = res.sort_values('$', ascending=ascending) #.iloc[i0:i0+100] elif _sort_ == 'roi': sort_arrows[3] = ' active%s'%arrow_dir res = res.sort_values('ROI', ascending=ascending) #.iloc[i0:i0+100] res = res.reset_index(drop=True) # res = res.sort_values('p val', ascending = True) trend_table = """ <table id="DT_Table" class="table table-striped"> <thead class="table-header"> <tr> <th style="cursor:pointer" onclick="trendSort('pval')">P val<span class="sorting-arrow ml-3%s"></span></th> <th>Type</span></th> <th>Play</span></th> <th>Focus</span></th> <th style="cursor:pointer" onclick="trendSort('record')">Record<span class="sorting-arrow ml-3%s"></span></th> <th style="cursor:pointer" onclick="trendSort('profit')">Profit<span class="sorting-arrow ml-3%s"></span></th> <th style="cursor:pointer" onclick="trendSort('roi')">ROI<span class="sorting-arrow ml-3%s"></span></th>"""%(sort_arrows[0], sort_arrows[1], sort_arrows[2], sort_arrows[3]) trend_table += """ <th style="width: 35%;">Trend Description</th> <th>SDQL</span></th> <th style="width: 20px;"></th> </tr> </thead> <tbody class="table-body">""" else: pageT = 0 _lsort_ = _sort_ i0 = -1 if ((__d.get("client","guest") in beta_testers or KS2.ks.SUBSCRIBE_SYSTEM) and not kspro_access[client_info.tier]): filter_notice = "" trend_table = """<h1 class="color-yellow" style="padding-top: 100px; text-align: center">Upgrade to access KS-Pro Indicators</h1> <h3 class='help-title-color' style='padding-top: 10px; text-align: center'> This feature requires a Pro or Premium tier subscription. Click <a href='plans-premium' class='color-yellow' target='_blank'>here</a> to upgrade</h3>""" elif (('KSC' in trends) and (len(res) > 0)): #shut down for new method # #overlycomplex # headers = res['%s'%(list(res)[0])][0].headers # i_wins = headers.index('wins') # i_losses = headers.index('losses') # i_percents = headers.index(' % ') # i_link = headers.index('link') # if sport not in ['MLB', 'NHL']: # i_roi = None # i_profit = None # i_pval = headers.index('p val') # else: # i_roi = headers.index('ROI') # i_profit = headers.index('$') # i_pval = None # pvals = []; wins = []; losses = []; percents = []; links = []; profits = []; rois = [] # for x in list(res): # wins += list(res[x].data[0][i_wins]) # losses += list(res[x].data[0][i_losses]) # percents += list(res[x].data[0][i_percents]) # links += list(res[x].data[0][i_link]) # if i_pval != None: # pvals += list(res[x].data[0][i_pval]) # if i_roi != None: # rois += list(res[x].data[0][i_roi]) # profits += list(res[x].data[0][i_profit]) # # sides += [x.split('_')[-1].upper()]*len(res[x].data[0][0]) # sides = {'ATS': {'0': 'ON', '1': 'AGST'},'OU': {'0': 'OVER', '1': 'UNDER'},'SU': {'0': 'ON', '1': 'AGST'}, 'RL': {'0': 'ON', '1': 'AGST'}, 'PL': {'0': 'ON', '1': 'AGST'}, 'ML': {'0': 'ON', '1': 'AGST'}} foci = {0: 'League-Wide', 1: 'Team', 2: 'Player', 3: 'Player, Team', 4: 'Coach', 5: 'Coach, Team', 6: 'Coach, Player', 7: 'Coach, Player, Team'} for i in range(i0,min(i0+100,pageT)): if (res['p val'].loc[i] < 0.00000001): pval = '{:.4e}'.format(res['p val'].loc[i]) else: pval = '{:.8f}'.format(res['p val'].loc[i]) # if pvals: # if (pvals[i] < 0.00000001): # pval = '{:.4e}'.format(pvals[i]) # else: # pval = '{:.8f}'.format(pvals[i]) # else: # pval = '-' play = res['play'].loc[i] side = res['side'].loc[i] rec = '%s-%s'%(res['wins'].loc[i], res['losses'].loc[i]) + ' ('+"{:.1%}".format(res[' % '].loc[i]/100)+')' # play = '-' # side = '-' # rec = '%s-%s'%(wins[i], losses[i]) + ' ('+"{:.1%}".format(percents[i]/100)+')' roi = '{:.1%}'.format(res['ROI'].loc[i]) profit = '${:,.0f}'.format(res['$'].loc[i]) # if rois: # roi = '{:.1%}'.format(rois[i]/100.0) # profit = '${:,.0f}'.format(profits[i]) # else: # roi = '-'; profit = '-' desc = res['link'].loc[i][1] sdql = res['link'].loc[i][0] # desc = links[i][1] # sdql = links[i][0] foc = foci[eval_focus(sdql)] if _foc_ != '*': if _foc_ not in foc.lower(): continue # search = '(%s) as "%s=>%s"' % (sdql, sdql, desc) # if search in metrics: # play = metrics[search]['type'].upper() # side = sides[play][metrics[search]['side']] # rtg = str(metrics[search]['rtg']) # if rtg == 'NR': rtg = '-' # else: # play = sdql_locate(sdql, owner, trends).upper() # if play != '-': # if play in ['ML','RL','PL']: # if wins[i] < 0 : side = sides[play]['1'] # else: side = sides[play]['0'] # # side = sides[play][roi_record(sdql, owner, play.lower(), res)] # else: # side = sides[play][sdql_record(sdql, owner, play.lower(), trends)] # else: # side = '-' # rtg = '-' rtg = res['rtg'].loc[i] if rtg == 0: rtg = '-' # continue if trend was delete if sdql.replace(' ','') not in available['%s_%s'%(owner, play.lower())]: continue # calculate ROI # if ((play in ['ATS','OU', 'RL', 'PL']) and (roi == '-')): # roi, profit = eval_roi(side, rec) pct = res['pct'].loc[i] if side in ['AGST','UNDER'] and sport in ['MLB','NHL']: rec = '%s-%s'%(abs(res['wins'].loc[i]), abs(res['losses'].loc[i])) + ' ('+"{:.1%}".format(pct)+')' elif side in ['AGST','UNDER']: rec = '%s-%s'%(res['losses'].loc[i], res['wins'].loc[i]) + ' ('+"{:.1%}".format(pct)+')' else: rec = '%s-%s'%(res['wins'].loc[i], res['losses'].loc[i]) + ' ('+"{:.1%}".format(pct)+')' if ((sport.upper() in ['MLB','NHL']) and (play == 'SU')): play = 'ML' href = '/query?sdql='+urllib.quote_plus(sdql) + '&filter=%s'%sport + '&name=%s%s&init=1'%(urllib.quote_plus(desc.replace('>','&gt;').replace('<','&lt;')), '' if period == 'FG' else '&period=%s'%period) sdql = sdql.replace('<','&lt;').replace('>','&gt;') trend_table += """ <tr class="align-middle"> <td>""" + pval + """</td> <td>""" + play + """</td> <td>""" + side + """</td> <td>""" + foc + """</td> <td>""" + rec + """</td> <td>""" + profit + """</td> <td>""" + roi + """</td> <td class="text-start" style="white-space:pre-wrap">""" + desc.replace('>','&gt;').replace('<','&lt;') + """</td> <td class="text-start"> <div class="help-title-color"> <div class="flex align-items-center"> <div class=""> <p><a class="help-title-color" style="white-space:pre-wrap" href='""" + href + """'>""" + sdql + """</a></p> </div> </div> </div> </td> <td class="small-card-cell-content"> <a href='""" + href + """'><img src="KS/Images/trend/play.svg" style="max-width: unset;"></a> </td> </tr> """ filter_notice = "" if 'pyql' in __d: if sport in ['NFL','NCAAFB']: _date_ = week_calc.find_week_from_date(_date_) filter_team = None if _type_ == 'ou' and re.findall('active', __d['pyql']): if re.findall('\(wins>losses\)', __d['pyql']): filter_team = urllib.unquote('OVER') elif re.findall('\(wins<losses\)', __d['pyql']): filter_team = urllib.unquote('UNDER') else: if re.findall('\(team=(.*?)\)', __d['pyql']): filter_team = urllib.unquote(re.findall('\((team=.*?)\)', __d['pyql'])[0]) elif re.findall('\,(.*?)\) in active', __d['pyql']): filter_team = urllib.unquote('team='+re.findall('\,(.*?)\) in active', __d['pyql'])[0]) if filter_team: filter_notice = """ <div class="flex align-items-center small-card-cell" style="color: #77DCEA;cursor: pointer" onclick="noPYQL()"> <div class=""> <p class="small-card-cell-content">%s</p> </div> <span class="small-card-icon">&times;</span> </div>"""%filter_team # for game in games: # date = datetime.strptime(str(_date_), '%Y%m%d').strftime('%m/%d/%Y'); divider = '' # trend_table += """ # <tr class="align-middle"> # <th scope="row">0.0755</th> # <td> # UNDER # </td> # <td>90-64 (58.4%)</td> # <td>11.5%</td> # <td class="w-40 text-start"> # Lorem ipsum dolor sit amet consectetur. Augue maecenas semper nunc consequat egestas proin a aliquam augue. Ut amet felis in adipiscing. # </td> # <td class="text-start"> # <div class="flex align-items-center gap-8 pb-8 help-title-color"> # <div class="flex align-items-center small-card-cell"> # <div class=""> # <p class="small-card-cell-content">team=Bears</p> # </div> # <span class="small-card-icon">&times;</span> # </div> # <p class="color-yellow">and</p> # <div class="flex align-items-center small-card-cell"> # <div class=""> # <p class="small-card-cell-content">Season = 2023</p> # </div> # <span class="small-card-icon">&times;</span> # </div> # </div> # </td> # <td> # <a href="sdql"><img src="KS/Images/trend/play.svg"></a> # </td> # </tr> # """ # t_vals = {'ats': '-', 'ml': '-', 'ou': '-'} # p_vals = {'ats': '-', 'ml': '-', 'ou': '-'} # for typ in ['ats', 'ml', 'ou']: # if typ in games[game]: # t_vals[typ] = games[game][typ] # rec0 = t_vals[typ].split(' (')[-1][:-5].split(' - ') # rec = [int(x) for x in rec0] # # rec = [5, 15] # p_vals[typ] = round(math.log(1/probability(sum(rec),rec[0],0.5)),1) # if ((int(game) % 2 == 1) and ('None' not in teams)): # date = '@' # divider = ' style="border-bottom: #ABABABC9 1px solid;"' # if teams[0] == 'None': # if games[game]['team'] == 'None': # trend_table = """ # <table class="table table-striped"> # <thead class="table-header"> # <tr> # <th>Team</th> # <th>ATS</th> # <th>AVG Power</th> # <th>ML</th> # <th>AVG Power</th> # <th>OU</th> # <th>AVG Power</th> # </tr> # </thead> # <tbody class="table-body">""" # trend_table += """ # <tr class="align-middle"%s > # <td class="flex align-items-center"> # <img class="pr-11" width="70"></a> # %s # </td> # <td>%s</td> # <td>%s</td> # <td>%s</td> # <td>%s</td> # <td>%s</td> # <td>%s</td> # </tr>"""%(divider, 'Non-specific', t_vals['ats'], p_vals['ats'], t_vals['ml'], p_vals['ml'], t_vals['ou'], p_vals['ou']) # else: # trend_table += """ # <tr class="align-middle"%s > # <td class="flex align-items-center"> # <img class="pr-11" width="70" src="KS/Images/trend/%s/%s.png" alt="#"> # %s # </td> # <td>%s</td> # <td>%s</td> # <td>%s</td> # <td>%s</td> # <td>%s</td> # <td>%s</td> # </tr>"""%(divider, sport, games[game]['team'], games[game]['team'], t_vals['ats'], p_vals['ats'], t_vals['ml'], p_vals['ml'], t_vals['ou'], p_vals['ou']) # else: # line = odds['line'][(odds['team']==games[game]['team']) & (odds['date']==_date_)].iloc[0] # total = odds['total'][(odds['team']==games[game]['team']) & (odds['date']==_date_)].iloc[0] # trend_table += """ # <tr class="align-middle"%s > # <th scope="row">%s</th> # <td class="flex align-items-center"> # <img class="pr-11" width="70" src="KS/Images/trend/%s/%s.png" alt="#"> # %s # </td> # <td>+%s</td> # <td><b>O</b> %s</td> # <td>%s</td> # <td>%s</td> # <td>%s</td> # <td>%s</td> # <td>%s</td> # <td>%s</td> # </tr>"""%(divider, date, sport, games[game]['team'], games[game]['team'], line, total, t_vals['ats'], p_vals['ats'], t_vals['ml'], p_vals['ml'], t_vals['ou'], p_vals['ou']) # # trend_table += "</tbody></table>" # trend_table = trend_table.replace('+-','-').replace('+nan','').replace('+None','').replace('<b>O</b> nan','').replace('<b>O</b> None','') else: filter_notice = "" trend_table = """<h1 class="color-yellow" style="padding-top: 100px; text-align: center">No Trends to Show</h1> <h3 class="help-title-color" style="padding-top: 10px; text-align: center"> Looks like there's no active %s trends from our PROs on this date</h3>"""%(sport) activeTrends = 0 prior_button = """ <a href="/ks-pro-trend?filter=%s&date=%s&typ=%s&foc=%s&per=%s%s&pg=1&sort=%s" style="color: #F3D527;padding: 8px 16px;">&#8249;&#8249;</a> <a href="/ks-pro-trend?filter=%s&date=%s&typ=%s&foc=%s&per=%s%s&pg=%s&sort=%s" style="color: #F3D527;border-radius: 8px;padding: 8px 16px;border: 1px solid #F3D527;"> &#8249; Last 100 </a>"""%(sport, _date_,_type_,_foc_,_per_,pyql_url,_lsort_,sport, _date_,_type_,_foc_,_per_,pyql_url,_page_-1,_lsort_) next_button = """ <a href="/ks-pro-trend?filter=%s&date=%s&typ=%s&foc=%s&per=%s%s&pg=%s&sort=%s" style="color: #F3D527;border-radius: 8px;padding: 8px 16px;border: 1px solid #F3D527;"> Next 100 &#8250; </a>"""%(sport, _date_,_type_,_foc_,_per_,pyql_url,_page_+1,_lsort_) if pageT < 100: prior_button = ""; next_button = "" elif i0 == 0: prior_button = "" elif i0 > pageT-100: next_button = ""
error:
exception:
message: invalid syntax (, line 3)
traceback:


error:
exception:
message: list index out of range
traceback: