def format_columns(df): columns = df.columns type_dict = dict( df.iloc[0].map(lambda x: 'text' if isinstance(x, str) else 'numeric')) col_styles = [{"name": i, "id": i, "type": type_dict[i]} for i in columns] format_dict = { 'price': FormatTemplate.money(0), 'pct': FormatTemplate.percentage(1).sign(Sign.positive) } for i in col_styles: col_name = i['name'] if any([x in col_name for x in ('pct', 'return')]): i['format'] = FormatTemplate.percentage(2).sign(Sign.positive) elif any([ x in col_name for x in ('price', 'value', 'gain', 'wealth', 'cash') ]): i['format'] = FormatTemplate.money(2) elif 'weight' in col_name: i['format'] = FormatTemplate.percentage(2) elif 'quantity' in col_name: i['format'] = Format( precision=4, # scheme=Scheme.fixed, # symbol=Symbol.yes, # symbol_suffix=u'˚F' ) return col_styles
def update_yield_curve(n_clicks, value, md): model_data, test_data = strategy(value, md) blotter, ledger, test, sharp = backtest1(model_data, test_data) if test['Response'][-1] > 0.5: ac = 'BUY' tp = 'MKT' else: ac = 'SELL' tp = 'LMT' fig = go.Figure(data=[ go.Scatter(x=ledger['Date'], y=ledger['Revenue'], name='Asset Return'), go.Scatter(x=ledger['Date'], y=ledger['IVV Yield'], name='IVV Return') ]) fig.update_layout(title='Back-Test-Yield', yaxis={'hoverformat': '.2%'}) # data = df.dropna(axis=0) blotter.reset_index() blotter = blotter.to_dict('records') blotter_columns = [ dict(id='Date', name='Date'), dict(id='ID', name='ID'), dict(id='Type', name='order type'), dict(id='actn', name='Action'), dict(id='Price', name='Order Price', type='numeric', format=FormatTemplate.money(2)), dict(id='size', name='Order Amount', type='numeric'), dict(id='symb', name='Symb') ] ledger = ledger.to_dict('records') ledger_columns = [ dict(id='Date', name='Date'), dict(id='position', name='position'), dict(id='Cash', name='Cash'), dict(id='Stock Value', name='Stock Value', type='numeric', format=FormatTemplate.money(2)), dict(id='Total Value', name='Total Value', type='numeric', format=FormatTemplate.money(2)), dict(id='Revenue', name='Revenue', type='numeric', format=FormatTemplate.percentage(2)), dict(id='IVV Yield', name='IVV Yield', type='numeric', format=FormatTemplate.percentage(2)) ] return ('Successfully trained model with window size ' + str(value), fig, blotter_columns, blotter, ledger_columns, ledger, ac, tp, test['Close'][-1])
def yrly_sum_stat_tbl_fmt(df): return DataTable( columns=[{'name': 'Year', 'id': 'Date'}, {'name': 'Average Daily Return', 'id': 'Average Daily Return', 'type': 'numeric', 'format': FormatTemplate.percentage(4)}, {'name': 'Standard Deviation of Daily Returns', 'id': 'Standard Deviation of Daily Returns', 'type': 'numeric', 'format': FormatTemplate.percentage(4)}, {'name': 'Annualized Average Daily Return', 'id': 'Annualized Average Daily Return', 'type': 'numeric', 'format': FormatTemplate.percentage(4)}, {'name': 'Annualized Standard Deviation of Daily Returns', 'id': 'Annualized Standard Deviation of Daily Returns', 'type': 'numeric', 'format': FormatTemplate.percentage(4)}, {'name': 'Annualized Sharpe Ratio', 'id': 'Annualized Sharpe Ratio', 'type': 'numeric', 'format': FormatTemplate.percentage(4)} ], data=df.to_dict('records'), style_cell={ 'textAlign': 'center', 'whiteSpace': 'normal', 'height': 'auto', 'color': 'white', 'backgroundColor': '#696969', }, style_header={'backgroundColor': '#000000'}, style_data_conditional=[ { 'if': { 'filter_query': '{{Annualized Sharpe Ratio}} < {}'.format(0.00), }, 'backgroundColor': '#FF4136', }, { 'if': { 'filter_query': '{{Annualized Sharpe Ratio}} > {}'.format(0.00), }, 'backgroundColor': '#3cb371', }, { 'if': { 'state': 'active' # 'active' | 'selected' }, 'backgroundColor': '#696969', 'border': '#ffffff', } ], style_as_list_view=True, page_size=20, export_format='csv', style_table={'overflowX': 'auto'} )
def generic_tbl_fmt(df): return DataTable( columns=[{'name': i, 'id': i, 'type': 'numeric', 'format': FormatTemplate.percentage(4)} for i in df.columns], data=df.to_dict('records'), style_cell={ 'textAlign': 'center', 'whiteSpace': 'normal', 'height': 'auto', 'color': 'white', 'backgroundColor': '#696969', }, style_header={'backgroundColor': '#000000'}, style_data_conditional=[ { 'if': { 'state': 'active' # 'active' | 'selected' }, 'backgroundColor': '#8140CF' } ], style_as_list_view=True, page_size=20, export_format='csv', style_table={'overflowX': 'auto'} )
def update_figure4(in_sample, period): in_sample = True if in_sample == 'in_sample' else False worst_periods = pd.read_csv('data/absorption_ratio_worst_return_periods_list.csv') # subset the data for the user specification df = worst_periods.copy() df = df[df['period'] == period] df = df[df['in_sample'] == in_sample] df = df[df['overlapping'] == True] if in_sample: df = df[df['rank'] >= 0.95] else: df = df[df['rank_oos'] >= 0.95] df.sort_values(by='^GSPC', inplace=True, ascending=True) df.reset_index(inplace=True, drop=True) df['rank'] = df.index + 1 # set the columns to show in table df.rename(columns={'rank': 'Rank', '^GSPC': 'Return', 'ar': 'AR', 'ar_shift': 'AR Shift', 'date': 'Date'}, inplace=True) cols = [{'name': 'Rank', 'id': 'Rank'}, {'name': 'Date', 'id': 'Date'}, {'name': 'Return', 'id': 'Return', 'type': 'numeric', 'format': FormatTemplate.percentage(1)}, {'name': 'AR', 'id': 'AR', 'type': 'numeric'}, {'name': 'AR Shift', 'id': 'AR Shift', 'type': 'numeric'}] # format to 2 decimals places for presentation for var in ['AR', 'AR Shift']: df[var] = df[var].map(lambda x: round(x,2)) return df.to_dict('records'), df.to_dict('records')
def choose_libor_currency(currency): if currency: dfs = scrape_libor()[currency] cols = [{'id': dfs.columns[0], 'name': dfs.columns[0]}] + [ {'id': col, 'name': col.title(), 'type': 'numeric', "format": FormatTemplate.percentage(4)} for col in dfs.columns[1:]] return cols, dfs.to_dict('records') else: return [], []
def update_netric_table(days_since_d1, metric): df = update_df(metric, days_since_d1) cols=[ {'name': 'Rank', 'id': 'Rank', 'type': 'numeric'}, {'name': 'State', 'id': 'State'}, {'name': metric, 'id': metric, 'type': 'numeric', 'format': Format(group=',')}, {'name': '1D | # Delta', 'id': '1D | # Delta', 'type': 'numeric', 'format': Format(group=',')}, {'name': '1W | # Delta', 'id': '1W | # Delta', 'type': 'numeric', 'format': Format(group=',')}, {'name': '1D | % Delta', 'id': '1D | % Delta', 'type': 'numeric', 'format': FormatTemplate.percentage(1).sign(Sign.positive)}, {'name': '1W | % Delta', 'id': '1W | % Delta', 'type': 'numeric', 'format': FormatTemplate.percentage(1).sign(Sign.positive)} ] da = df.to_dict('records') output = dash_table.DataTable( columns = cols, data = da, sort_action='native', filter_action='native', style_cell={'fontSize':15, 'font-family':'sans-serif', 'textAlign': 'left', 'padding':'8px'}, style_header={'backgroundColor': 'white', 'fontWeight': 'bold'}, style_as_list_view=True, ) return output
def make_dcc_country_tab(countryName, dataframe): '''This is for generating tab component for country table''' return dcc.Tab(label=countryName, value=countryName, className='custom-tab', selected_className='custom-tab--selected', children=[dash_table.DataTable( id='datatable-interact-location-{}'.format(countryName), # Don't show coordinates columns=[{"name": i, "id": i, "type": "numeric","format": FormatTemplate.percentage(2)} if i == 'Death rate' else {"name": i, "id": i} for i in dataframe.columns[0:6]], # But still store coordinates in the table for interactivity data=dataframe.to_dict("rows"), row_selectable="single" if countryName != 'Schengen' else False, sort_action="native", style_as_list_view=True, style_cell={'font_family': 'Arial', 'font_size': '1.1rem', 'padding': '.1rem', 'backgroundColor': '#f4f4f2', }, fixed_rows={'headers': True, 'data': 0}, style_table={'minHeight': '800px', 'height': '800px', 'maxHeight': '800px', #'overflowX': 'scroll' }, style_header={'backgroundColor': '#f4f4f2', 'fontWeight': 'bold'}, style_cell_conditional=[{'if': {'column_id': 'Province/State'}, 'width': '26%'}, {'if': {'column_id': 'Country/Region'}, 'width': '26%'}, {'if': {'column_id': 'Active'}, 'width': '14.2%'}, {'if': {'column_id': 'Confirmed'}, 'width': '15.8%'}, {'if': {'column_id': 'Recovered'}, 'width': '15.8%'}, {'if': {'column_id': 'Deaths'}, 'width': '14.2%'}, {'if': {'column_id': 'Death rate'}, 'width': '14%'}, {'if': {'column_id': 'Active'}, 'color':'#e36209'}, {'if': {'column_id': 'Confirmed'}, 'color': '#d7191c'}, {'if': {'column_id': 'Recovered'}, 'color': '#1a9622'}, {'if': {'column_id': 'Deaths'}, 'color': '#6c6c6c'}, {'textAlign': 'center'}], ) ] )
def get_data_table(total_cities_for_table): dash_table_columns = [] for col in total_cities_for_table.columns: if col == "unemployment_pct": f = FormatTemplate.percentage(2) t = "numeric" elif col == "people_count" or col == UNEMPLOYED_COL_NAME: f = Format( precision=0, scheme=Scheme.fixed, ) t = "numeric" else: f = {} t = "text" col_info = dict(name=COLUMN_NAMES_MAPPING[col], id=col, type=t, format=f) dash_table_columns.append(col_info) dash_t = dash_table.DataTable( id="table", columns=dash_table_columns, data=total_cities_for_table.to_dict("rows"), # row_selectable="multi", # selected_rows=[], filtering=False, sorting=True, editable=False, #style_as_list_view=True, pagination_mode="fe", pagination_settings={ "displayed_pages": 1, "current_page": 0, "page_size": 35, }, navigation="page", ) return dash_t
def total_money_table(data): table = DataTable( id='total_money_table', columns=[ dict(id='Type', name='Type'), dict(id='Total', name='Total', type='numeric', format=Format(scheme=Scheme.fixed, precision=2, group=Group.yes, groups=3, group_delimiter=' ', decimal_delimiter=',', symbol=Symbol.no)), dict(id='Percentage', name='Percentage', type='numeric', format=FormatTemplate.percentage(2)) ], data=data.to_dict('records'), style_cell={ 'fontFamily': 'Rubik', 'textAlign': 'right', 'height': 'auto', # all three widths are needed 'minWidth': '120px', 'width': '120px', 'maxWidth': '120px', 'whiteSpace': 'normal' }, style_cell_conditional=[ { 'if': { 'column_id': 'Type' }, 'textAlign': 'left' }, ], style_as_list_view=True, fill_width=False) return table
def update_processes_table(n): df = create_system_table(pi.get_current_processes()) # format percentage currently defined for ALL columns. However only applied for numeric (as per DataTable # documentation) columns = [{ "name": i, "id": i, "type": lambda i: 'numeric' if i in ['cpu_percent', 'memory_percent'] else 'text', "format": FormatTemplate.percentage(2) } for i in df.columns] # returns df in dict format data = df.to_dict("records") return (columns, data)
def contrarian_portfolio_tbl_fmt(df): return DataTable( columns=[{'name': i, 'id': i, 'type': 'numeric', 'format': FormatTemplate.percentage(4)} for i in df.columns], data=df.to_dict('records'), style_cell={ 'textAlign': 'center', 'whiteSpace': 'normal', 'height': 'auto', 'color': 'white', 'backgroundColor': '#696969', }, style_header={'backgroundColor': '#000000'}, style_data_conditional=[ { 'if': { 'filter_query': '{{Strategy Daily Return}} < {}'.format(0.00), }, 'backgroundColor': '#FF4136', }, { 'if': { 'filter_query': '{{Strategy Daily Return}} > {}'.format(0.00), }, 'backgroundColor': '#3cb371', }, { 'if': { 'state': 'active' # 'active' | 'selected' }, 'backgroundColor': '#696969', 'border': '#ffffff', } ], style_as_list_view=True, page_size=20, export_format='csv', style_table={'overflowX': 'auto'} )
def sum_stat_tbl_fmt(df): return DataTable( columns=[{'name': i, 'id': i, 'type': 'numeric', 'format': FormatTemplate.percentage(4)} for i in df.columns], data=df.to_dict('records'), style_cell={ 'textAlign': 'center', 'whiteSpace': 'normal', 'height': 'auto', 'color': 'white', 'backgroundColor': '#696969', }, style_header={'backgroundColor': '#000000'}, style_data_conditional=[ { 'if': { 'filter_query': '{{Annualized Sharpe Ratio}} < {}'.format(0.00), }, 'backgroundColor': '#FF4136', }, { 'if': { 'filter_query': '{{Annualized Sharpe Ratio}} > {}'.format(0.00), }, 'backgroundColor': '#3cb371', }, { 'if': { 'state': 'active' # 'active' | 'selected' }, 'backgroundColor': '#696969', 'border': '#ffffff', } ], style_as_list_view=True, )
def update_output(n_clicks, boro, spc_common): if n_clicks>0: url = "https://data.cityofnewyork.us/resource/nwxe-4ae8.json?$limit=1000000&$where=boroname='" + boro + "'" trees = pd.read_json(url) species_list = pd.Series(trees['spc_common'].unique()).dropna().sort_values().tolist() species_string = str(species_list)[2:-2].replace(" \'", " ").replace("\',", ",").replace('\",', ',') try: df = trees.query('spc_common == "' + spc_common + '"') df_cont = pd.crosstab(df.health, df.steward, margins=True, normalize=True).round(3) df_cont.columns = df_cont.columns + ' Stewards' df_cont = df_cont.rename(columns={'All Stewards': 'All'}) df_cont.index.name = 'Health' df_cont.reset_index(inplace = True) first_col_format = {"name": df_cont.columns[0], "id": df_cont.columns[0], "type": "text"} col_format = [{"name": i, "id": i, "type": "numeric", "format": FormatTemplate.percentage(1)} for i in df_cont.columns[1:]] col_format.insert(0, first_col_format) return (html.Iframe(srcDoc=boro.replace('%20', ' ') + " species choices: <br><br>" + species_string), html.H3("Two Way Contingency Table:"), dash_table.DataTable( id='table', columns=col_format, data=df_cont.to_dict('records'), ) ) except: return (dcc.Markdown(''' *Error: Check syntax of tree species.* '''), html.Iframe(srcDoc=boro.replace('%20', ' ') + " species choices: <br><br>" + species_string) )
def generate_table_from_data_province(self, data: pd.DataFrame) -> dt.DataTable: dtp = data[[ # 'formatted_date', 'denominazione_provincia', 'denominazione_regione', 'totale_casi', 'variazione_totale_casi', 'percentuale_variazione_totale_casi', 'incidenza', 'incidenza_7d', ]] codice_regione = data.codice_regione.iloc[0] data_table = dt.DataTable( id=f'rdtp_{codice_regione}', columns=([ # {'id': 'formatted_date', 'name': 'Data'}, { 'id': 'denominazione_provincia', 'name': 'Provincia' }, { 'id': 'denominazione_regione', 'name': 'Regione' }, { 'id': 'totale_casi', 'name': 'Casi', 'type': 'numeric' }, { 'id': 'variazione_totale_casi', 'name': 'Var. Casi', 'type': 'numeric' }, { 'id': 'percentuale_variazione_totale_casi', 'name': 'Perc. incremento', 'type': 'numeric', 'format': FormatTemplate.percentage(2, rounded=False) }, { 'id': 'incidenza', 'name': 'Incidenza /10000 abitanti', 'type': 'numeric' }, { 'id': 'incidenza_7d', 'name': 'Incidenza a 7gg /10000 abitanti', 'type': 'numeric' }, ]), data=dtp.to_dict(orient='records'), editable=False, style_table={ 'height': 'auto', 'maxWidth': '90%', 'whiteSpace': 'normal', 'overflowX': 'scroll', 'maxHeight': self._default_height, 'overflowY': 'scroll', 'textAlign': 'left' }, style_data_conditional=[{ 'if': { 'row_index': 'odd' }, 'backgroundColor': 'rgb(248, 248, 248)' }], style_cell={ 'overflow': 'hidden', 'textOverflow': 'ellipsis', 'maxWidth': 0, }, tooltip_data=[{ column: { 'value': str(value), 'type': 'markdown' } for column, value in row.items() } for row in dtp.to_dict(orient='records')], style_cell_conditional=[{ 'if': { 'column_id': c }, 'width': '10%', 'minWidth': '20px', 'textAlign': 'left' } for c in [ 'denominazione_provincia', 'denominazione_regione', 'totale_casi', 'variazione_totale_casi', 'percentuale_variazione_totale_casi', 'incidenza,' ]], style_header={ 'whiteSpace': 'normal', 'height': 'auto', 'lineHeight': '15px', 'backgroundColor': 'rgb(230, 230, 230)', 'fontWeight': 'bold' }, # fixed_columns={'headers': True, 'data': 1}, # fixed_rows={'headers': True, 'data': 0}, filter_action="native", sort_action="native", sort_mode="multi", ) return data_table
def test_percentage_template(self): res = FormatTemplate.percentage(1).to_plotly_json() self.assertEqual(res["specifier"], ".1%")
def pages_table(self): return dash_table.DataTable( id='dataset_by_page_table', columns=[ {'name': '', 'id': 'index'}, # {'name': 'Publisher', 'id': 'publisher'}, {'name': 'URL', 'id': 'source url'}, {'name': 'Score', 'id': 'weighted score', 'format': Format(precision=2, scheme=Scheme.decimal)}, {'name': 'Percent', 'id': 'weighted score ratio', 'type': 'numeric', 'format': FormatTemplate.percentage(1)}, ], data=self.df.to_dict('records'), sort_action='native', style_cell={'textAlign': 'left', 'whiteSpace': 'normal'}, # virtualization=True, style_cell_conditional=[ {'if': {'column_id': 'index'}, 'width': '2%', 'textAlign': 'right'}, {'if': {'column_id': 'source url'}, 'width': '30%'}, {'if': {'column_id': 'weighted score'}, 'width': '5%'}, {'if': {'column_id': 'weighted score ratio'}, 'width': '5%'} ], style_data_conditional=[ {'if': {'column_id': 'weighted score ratio', 'filter_query': '{weighted score ratio} > 0.5'}, # 'backgroundColor': '#238823'}, 'backgroundColor': '#7cd992'}, {'if': {'column_id': 'weighted score ratio', 'filter_query': '{weighted score ratio} > 0.2'}, 'backgroundColor': '#f7e463'}, {'if': {'column_id': 'weighted score ratio', 'filter_query': '{weighted score ratio} < 0.2'}, 'backgroundColor': '#eb6060', 'color': 'white'}, ], style_as_list_view=True, sort_by=[{'column_id': 'weighted score ratio', 'direction': 'desc'}], style_table={ # 'maxHeight': '300px', # 'maxWidth': '100%', # 'overflowY': 'scroll', # 'overflowX': 'hidden', 'margin': 0, 'padding': 0})
def main_table(tickers, start_date): columns = [ { 'name': ['', 'Stock'], 'id': 'Stock', 'type': 'text', # 'presentation':'markdown', }, { 'name': ['', 'ROI'], 'id': 'ROI', 'type': 'numeric', 'format': FormatTemplate.percentage(1).sign(Sign.positive), }, { 'name': ['Forecast', 'Score'], 'id': 'Score', 'type': 'numeric', 'format': Format(precision=2, scheme=Scheme.fixed), }, # { # 'name': ['Forecast','N'], # 'id':'N', # 'type':'numeric', # }, { 'name': ['Forecast', 'NTM ROI'], 'id': 'NTM ROI', 'type': 'numeric', 'format': FormatTemplate.percentage(1).sign(Sign.positive), }, { 'name': ['Growth Estimate', 'Qrt'], 'id': 'Quarter', 'type': 'numeric', 'format': FormatTemplate.percentage(2).sign(Sign.positive), }, { 'name': ['Growth Estimate', 'Next Qtr'], 'id': 'NextQuarter', 'type': 'numeric', 'format': FormatTemplate.percentage(2).sign(Sign.positive), }, { 'name': ['Growth Estimate', 'Year'], 'id': 'Year', 'type': 'numeric', 'format': FormatTemplate.percentage(2).sign(Sign.positive), }, { 'name': ['Growth Estimate', 'Next Year'], 'id': 'NextYear', 'type': 'numeric', 'format': FormatTemplate.percentage(2).sign(Sign.positive), }, ] data = [] for t in tickers: if t not in STOCKS or t not in RATINGS: print('{} is not found.'.format(t)) continue # start = determine_start_date(start_date) start = start_date end = datetime.datetime.today() stock_df = STOCKS[t][start:end] rating_df = RATINGS[t][start:end] trends = FINANCIALS[t]['trends'] if len(stock_df) > 0: latest_price = stock_df.iloc[-1]['Adj Close'] target_price = rating_df[rating_df.Price > 0].Price if len(target_price) == 0: med_roi = 0 # min_roi, med_roi, max_roi = 0, 0, 0 else: med_roi = target_price.median() / latest_price - 1 # min_roi = target_price.min()/latest_price-1 # max_roi = target_price.max()/latest_price-1 # return_at_forecast = [] gaps = [] for i in range(len(target_price)): date = target_price.index[i] idx = min(np.searchsorted(stock_df.index, date), len(stock_df) - 1) price_at_forecast = stock_df.iloc[idx]['Adj Close'] # return_at_forecast.append(target_price.iloc[i]/price_at_forecast-1) t_at_forecast = stock_df.index[idx] t_latest = stock_df.index[-1] p_star = price_at_forecast + ( target_price.iloc[i] - price_at_forecast) * (t_latest - t_at_forecast).days / 365 gap = (latest_price - p_star) / latest_price gaps.append(gap) if len(rating_df[rating_df.Rating >= 0]) > 0: score = rating_df[rating_df.Rating >= 0].Rating.mean() else: score = -1 data.append({ 'Stock': t, 'ROI': stock_df.iloc[-1]['Adj Close'] / stock_df.iloc[0]['Adj Close'] - 1, 'Score': score, # 'N' : len(rating_df.Price), 'NTM ROI': med_roi, 'Quarter': trends['Growth_Quarter'] / 100, 'NextQuarter': trends['Growth_NextQuarter'] / 100, 'Year': trends['Growth_Year'] / 100, 'NextYear': trends['Growth_NextYear'] / 100, }) else: Debug('No data for', t, 'within range.') data.sort(key=lambda c: c['Score'], reverse=True) return data, columns, 'single'
class intercepts(): ''' Shows intercepts of satellites using SOCRATES and TLE data ''' # Intercept Table Columns intercept_columns = [{ 'id': 'sat_pair', 'name': 'Satellite Pair' }, { 'id': 'tca_time', 'name': 'Intercept Date/Time' }, { 'id': 'max_prob', 'name': 'Max Probabilty (%)', 'type': 'numeric', 'format': FormatTemplate.percentage(5) }, { 'id': 'min_rng_km', 'name': 'Minimum Distance (km)', 'type': 'numeric', 'format': Format(precision=5) }, { 'id': 'rel_velo_kms', 'name': 'Relative Velocity (kms)', 'type': 'numeric', 'format': Format(precision=5) }, { 'id': 'index', 'name': 'Index' }] intercept_df = None sat_df = None def __init__(self, intercept_df, sat_df): ''' Initialize ''' self.intercept_df = intercept_df self.sat_df = sat_df def generate_intercept_table(self, start_date, end_date, max_prob, min_dist, sat_name): ''' Generates the table on the dashboard that displays intercepts ''' if start_date is None: start_date_obj = min(self.intercept_df['tca_time'].dt.date) else: start_date_obj = date.fromisoformat(start_date) if end_date is None: end_date_obj = max(self.intercept_df['tca_time'].dt.date) else: end_date_obj = date.fromisoformat(end_date) if sat_name is None: sat_name = '' df = self.intercept_df[ (self.intercept_df['tca_time'].dt.date >= start_date_obj) & (self.intercept_df['tca_time'].dt.date <= end_date_obj) & (self.intercept_df['max_prob'] >= max_prob[0]) & (self.intercept_df['max_prob'] <= max_prob[1]) & (self.intercept_df['min_rng_km'] >= min_dist[0]) & (self.intercept_df['min_rng_km'] <= min_dist[1]) & (self.intercept_df['sat_pair'].str.contains(sat_name.upper()))] return df.reset_index().to_dict('records') def get_page_content(self): ''' Generates the dashboard page content ''' return [ html.Section( className='content-header', children=[ html.H1(children='Intercepts'), html.Ol( className='breadcrumb', children=[ html.Li(children=[ html.I(className='fa fa-dashboard'), ' Home' ]), html.Li(className='active', children='Intercepts'), ]) ]), html.Section( className='content', children=[ html.Div( className='row', children=[ html.Div( className='col-md-12', children=[ html.Div( className='box', children=[ html.Div( className= 'box-header with-border', children=[ html.H3( className='box-title', children='About'), html.Div( className= 'box-tools pull-right', children=[ html.Button( className= 'btn btn-box-tool', **{ 'data-widget': 'collapse' }, children=[ html. I(className= 'fa fa-minus' ) ]) ]) ]), html.Div( className='box-body', children=[ html.Div( className= 'table-responsive', children=[ html. P("This is a visualization tool used animate two satellites that came within close proximity of eachother for a specific date/time. Choose a date range or try some of the other filtering criteria. The table on the right will update the top close-encounters as reported by SOCRATES on that day for your filter criteria. The table is automatically sorted by highest priority. Select one of the satellite pairs to visualize them below using Cesium's 3D world viewer and watch them animate as they come within close proximity of eachother." ), html. P("SUGGESTION: specify a window of 1 week or less to not overload the server. If the table returns nothing, make sure the sliders aren't overly restrictive and try a smaller date range." ), ]) ]) ]) ]) ]), html.Div( className='row', children=[ html.Div( className='col-md-4', children=[ html.Div( className='box', children=[ html.Div( className= 'box-header with-border', children=[ html.H3( className='box-title', children='Filter'), html.Div( className= 'box-tools pull-right', children=[ html.Button( className= 'btn btn-box-tool', **{ 'data-widget': 'collapse' }, children=[ html. I(className= 'fa fa-minus' ) ]) ]) ]), html.Div( className='box-body', children=[ html.Div( className= 'table-responsive', children=[ html.Table( className= 'table', children=[ html. Tr(children=[ html. Th(children ='Date' ), html. Td(children=[ ########################################################## # Date Picker dcc . DatePickerRange( id ='date-picker', with_portal =True, minimum_nights =0, min_date_allowed = min(self . intercept_df[ 'tca_time'] . dt . date ), start_date = min(self . intercept_df[ 'tca_time'] . dt . date ), end_date = min(self . intercept_df[ 'tca_time'] . dt . date ), max_date_allowed = max(self . intercept_df[ 'tca_time'] . dt . date ), initial_visible_month = min(self . intercept_df[ 'tca_time'] . dt . date ) ) ]) ]), html. Tr(children=[ html. Th(children ='Max Probability' ), html. Td(children=[ html . Div( style ={ 'padding': '20px 0px 0px' }, children =[ ########################################################## # Max Probability Range Slider dcc . RangeSlider( id ='max-prob-slider', min = min(self . intercept_df[ 'max_prob'] ), max = max(self . intercept_df[ 'max_prob'] ), step =0.001, value =[ min(self . intercept_df[ 'max_prob'] ), max(self . intercept_df[ 'max_prob'] ) ], tooltip ={ 'always_visible': True, 'placement': 'bottom' } ) ] ) ]) ]), html. Tr(children=[ html. Th(children ='Min Distance' ), html. Td(children=[ html . Div( style ={ 'padding': '20px 0px 0px' }, children =[ ########################################################## # Min Distance Range Slider dcc . RangeSlider( id ='min-dist-slider', min = min(self . intercept_df[ 'min_rng_km'] ), max = max(self . intercept_df[ 'min_rng_km'] ), step =0.001, value =[ min(self . intercept_df[ 'min_rng_km'] ), max(self . intercept_df[ 'min_rng_km'] ) ], tooltip ={ 'always_visible': True, 'placement': 'bottom' } ) ] ) ]) ]), html. Tr(children=[ html. Th(children=[ html . Div(style={ 'padding': '20px 0px 0px' }, children =[ 'Satellite Name' ] ) ]), html. Td(children=[ html . Div( style ={ 'padding': '20px 0px 0px' }, children =[ ########################################################## # Satellite Name dcc . Input( id ='satellite-name', type ='text', className ='form-control input-lg', placeholder ='e.g. Starlink' ) ] ) ]) ]), ]) ]) ]) ]) ]), html.Div( className='col-md-8', children=[ html.Div( className='box', children=[ html.Div( className= 'box-header with-border', children=[ html.H3( className='box-title', children= 'Intercept Table'), html.Div( className= 'box-tools pull-right', children=[ html.Button( className= 'btn btn-box-tool', **{ 'data-widget': 'collapse' }, children=[ html. I(className= 'fa fa-minus' ) ]) ]) ]), html.Div( className='box-body', children=[ html.Div( className= 'table-responsive', children=[ ########################################################## # Intercept Table dcc.Loading( id= 'intercept-table-load', type="circle", children=[ dash_table. DataTable( id= 'intercept-table', columns =self. intercept_columns, style_as_list_view =True, style_header ={ 'backgroundColor': 'white', 'fontSize': '14px', 'fontWeight': 'bold', 'textAlign': 'left' }, style_cell ={ 'padding': '0px', 'fontSize': '12px', 'textAlign': 'left' }, row_selectable ="single", page_size =10, sort_action ="native", selected_rows =[], hidden_columns =[ 'index' ]) ]) ]) ]) ]) ]) ]), html.Div( className='row', children=[ html.Div( className='col-md-12', children=[ html.Div( className='box', children=[ html.Div( className= 'box-header with-border', children=[ html.H3( className='box-title', children= 'Intercepting Orbits') ]), html.Div( className='box-body', children=[ html.Div( className= 'table-responsive', children=[ ########################################################## # Cesium dcc.Loading( id= 'cesium-intercept', type="circle", children=[ html.Div( id= 'cesiumContainer' ), html.Div( id= 'czml', style={ 'display': 'none' }) ]) ]) ]) ]) ]) ]) ]) ] def generate_intercept_czml(self, rows, index): ''' Generates the CZML (time animation) in Cesium of the intercept ''' if index is not None and len(index) > 0: u = oc_dash_utils.utils(self.intercept_df, self.sat_df) idx = rows[index[0]]['index'] sat_names = [ self.intercept_df.loc[idx]['sat1_name'], self.intercept_df.loc[idx]['sat2_name'] ] sat_tles = [ self.intercept_df.loc[idx]['sat1_tle'].split(','), self.intercept_df.loc[idx]['sat2_tle'].split(',') ] sat_descs = [ u.generate_satellite_description( row=self.intercept_df.loc[idx], sat='sat1'), u.generate_satellite_description( row=self.intercept_df.loc[idx], sat='sat2') ] start_time = self.intercept_df.loc[idx]['tca_time'] - timedelta( hours=0.5) end_time = self.intercept_df.loc[idx]['tca_time'] + timedelta( hours=0.5) czml = satellite_czml(tle_list=sat_tles, start_time=start_time, end_time=end_time, name_list=sat_names, description_list=sat_descs).get_czml() return czml
def publishers_table(self): return dash_table.DataTable( id='dataset_by_publisher_table', columns=[ #{'name': '', 'id': 'index'}, { 'name': 'Publisher', 'id': 'publisher' }, #{'name': 'Score', 'id': 'weighted score', 'format': Format(precision=2, scheme=Scheme.decimal)}, { 'name': 'Score', 'id': 'weighted score ratio', 'type': 'numeric', 'format': FormatTemplate.percentage(1) }, ], data=self.df.groupby('publisher', as_index=False).mean().round({ 'weighted score': 2 }).to_dict('records'), sort_action='native', style_cell={ 'textAlign': 'left', 'whiteSpace': 'normal' }, # virtualization=True, style_cell_conditional=[ { 'if': { 'column_id': 'weighted score ratio' }, 'fontWeight': 'bold', 'textAlign': 'center' }, #{'if': {'row_index': 'odd'},'backgroundColor': 'rgb(248, 248, 248)'}, ], style_data_conditional=[ { 'if': { 'column_id': 'weighted score ratio', 'filter_query': '{weighted score ratio} > 0.5' }, 'backgroundColor': '#238823' }, { 'if': { 'column_id': 'weighted score ratio', 'filter_query': '{weighted score ratio} > 0.2' }, 'backgroundColor': '#FFBF00' }, { 'if': { 'column_id': 'weighted score ratio', 'filter_query': '{weighted score ratio} < 0.2' }, 'backgroundColor': '#D2222D', 'color': 'white' }, ], style_as_list_view=True, style_table={ 'margin': 0, 'padding': 0, }, style_header={ 'backgroundColor': 'rgb(230, 230, 230)', 'fontWeight': 'bold', })
def secondary_table(ticker, start_date): rating_label = { 0: '?', 1: 'Sell', 2: 'Hold', 3: 'Buy', 4: 'Outperform', 5: 'Strong Buy' } columns = [ { 'name': 'Date', 'id': 'Date', }, { 'name': 'Forecaster', 'id': 'Forecaster', }, { 'name': 'Trust', 'id': 'Trust', 'type': 'numeric', }, { 'name': 'Rating', 'id': 'Rating', }, { 'id': 'ROI', 'name': 'ROI', 'type': 'numeric', 'format': FormatTemplate.percentage(1).sign(Sign.positive), }, ] # start = determine_start_date(start_date) start = start_date end = datetime.datetime.today() stock = STOCKS[ticker] series = stock['Adj Close'][start:end] df = RATINGS[ticker][start:end] df = df.sort_index(ascending=False) data = [] for i in range(len(df)): date = df.index[i] idx = min(np.searchsorted(series.index, date), len(series) - 1) date_nearest = series.index[idx] close_price = stock['Adj Close'].loc[date_nearest] item = df.iloc[i] trust = round(get_analyst_score(item.Analyst), 2) data.append({ 'Date': datetime.datetime.strftime(item.name, '%m.%d'), 'Forecaster': item.Analyst, 'Trust': trust, 'Rating': rating_label[item.Rating], 'ROI': 0 if item.Price == 0 else item.Price / close_price - 1, }) return data, columns
}], ) ]) annual_returns_pct_table = html.Div([ dash_table.DataTable( id="annual_returns_pct", columns=([{ "id": "Year", "name": "Year", "type": "text" }] + [{ "id": col, "name": col, "type": "numeric", "format": FormatTemplate.percentage(1), } for col in df.columns[1:]]), style_cell={ "textAlign": "right", "font-family": "arial" }, style_table={ "overflowY": "scroll", "border": "thin lightgrey solid", "maxHeight": "400px", }, data=df.to_dict("records"), ) ], )
def update_chart(start_date, end_date, reporting_l1_dropdown, reporting_l2_dropdown): start = dt.strptime(start_date, '%Y-%m-%d') end = dt.strptime(end_date, '%Y-%m-%d') # Filter based on the dropdowns isselect_all_l1 = 'Start' #Initialize isselect_all isselect_all_l2 = 'Start' #Initialize isselect_all ## L1 selection (dropdown value is a list!) for i in reporting_l1_dropdown: if i == 'All': isselect_all_l1 = 'Y' break elif i != '': isselect_all_l1 = 'N' else: pass # Filter df according to selection if isselect_all_l1 == 'N': sales_df_1 = sales_import.loc[ sales_import[sales_fields['reporting_group_l1']]. isin(reporting_l1_dropdown), :].copy() else: sales_df_1 = sales_import.copy() ## L2 selection (dropdown value is a list!) for i in reporting_l2_dropdown: if i == 'All': isselect_all_l2 = 'Y' break elif i != '': isselect_all_l2 = 'N' else: pass # Filter df according to selection if isselect_all_l2 == 'N': sales_df = sales_df_1.loc[ sales_df_1[sales_fields['reporting_group_l2']]. isin(reporting_l2_dropdown), :].copy() else: sales_df = sales_df_1.copy() del sales_df_1 # Filter based on the date filters df_1 = sales_df.loc[(sales_df[sales_fields['date']] >= start) & (sales_df[sales_fields['date']] <= end), :].copy() del sales_df # Aggregate df metrics = ['Sales (M u)', 'Revenues (M €)', 'Customers (M)'] result = [ df_1[sales_fields['sales']].sum() / 1000000, df_1[sales_fields['revenues']].sum() / 1000000, df_1[sales_fields['num clients']].sum() / 1000000 ] target = [ df_1[sales_fields['sales target']].sum() / 1000000, df_1[sales_fields['rev target']].sum() / 1000000, '' ] performance = [ df_1[sales_fields['sales']].sum() / df_1[sales_fields['sales target']].sum(), df_1[sales_fields['revenues']].sum() / df_1[sales_fields['rev target']].sum(), '' ] df = pd.DataFrame({ 'KPI': metrics, 'Result': result, 'Target': target, 'Target_Percent': performance }) # Configure table data data = df.to_dict('records') columns = [{ 'id': 'KPI', 'name': 'KPI' }, { 'id': 'Result', 'name': 'Result', 'type': 'numeric', 'format': Format(scheme=Scheme.fixed, precision=2, group=Group.yes, group_delimiter=',', decimal_delimiter='.') }, { 'id': 'Target', 'name': 'Target', 'type': 'numeric', 'format': Format(scheme=Scheme.fixed, precision=2, group=Group.yes, group_delimiter=',', decimal_delimiter='.') }, { 'id': 'Target_Percent', 'name': '% Target', 'type': 'numeric', 'format': FormatTemplate.percentage(2) }] # Configure conditional formatting conditional_style = [ { 'if': { 'filter_query': '{Result} >= {Target} && {Target} > 0', 'column_id': 'Target_Percent' }, 'backgroundColor': corporate_colors['light-green'], 'color': corporate_colors['dark-green'], 'fontWeight': 'bold' }, { 'if': { 'filter_query': '{Result} < {Target} && {Target} > 0', 'column_id': 'Target_Percent' }, 'backgroundColor': corporate_colors['pink-red'], 'color': corporate_colors['dark-green'], 'fontWeight': 'bold' }, ] return data, columns, conditional_style
from dash_bootstrap_components._components.Card import Card from dash_bootstrap_components._components.CardBody import CardBody from dash_bootstrap_components._components.CardHeader import CardHeader from dash_bootstrap_components._components.Col import Col from dash_bootstrap_components._components.Row import Row import dash_html_components as html import dash_bootstrap_components as dbc import dash_core_components as dcc from dash_table import DataTable, FormatTemplate from app_server import main_service main_service.top_investiment('Ação') money = FormatTemplate.money(2) percentage = FormatTemplate.percentage(2) cols1 = [ #dict(id='Tipo', name='Tipo'), dict(id='Nome', name='Nome'), dict(id='financeiro', name='Posição atual', type='numeric', format=money), dict(id='aporte', name='Aporte', type='numeric', format=money), dict(id='retirada', name='Retirada', type='numeric', format=money), dict(id='rendimento', name='Rendimento', type='numeric', format=money), dict(id='%', name='%', type='numeric', format=percentage) ] top5_cols = [ dict(id='Nome', name='Nome'), dict(id='rendimento', name='Rendimento', type='numeric', format=money), dict(id='%', name='%', type='numeric', format=percentage)
def generate_pf_content(): day, pf_sym_view = df_pf_symbol() pf_sym_view.reset_index(inplace=True) xirr_timeseries = get_xirr_timeseries() return_timeseries = get_returns_timeseries() xirr_traces = [] for column in xirr_timeseries.columns: xirr_traces.append( go.Scatter(x=xirr_timeseries.index, y=xirr_timeseries[column], name=column)) xirr_data = xirr_traces return_traces = [] for column in return_timeseries.columns: return_traces.append( go.Scatter(x=return_timeseries.index, y=return_timeseries[column], name=column)) return_data = return_traces xirr_fig = go.Figure(data=xirr_data, layout=get_table_layout()) return_fig = go.Figure(data=return_data, layout=get_table_layout()) tab1_content = html.Div(children=[ html.H1(children=["Portfolio Data from " + day.strftime("%d.%m.%y")], style={'textAlign': 'center'}), html.Div( style={ 'width': '75%', 'margin': 'auto' }, children=[ dash_table.DataTable( id='table', columns=[ { 'id': "Portfolio", 'name': "Portfolio", 'type': "text" }, { 'id': "Symbol", 'name': "Symbol", 'type': "text" }, { 'id': "Holdings", 'name': "Holdings", 'type': "numeric" }, { 'id': "Price", 'name': "Price", 'type': "numeric", 'format': euro(2) }, { 'id': "Value", 'name': "Value", 'type': "numeric", 'format': euro(2) }, { 'id': "Turnover", 'name': "Turnover", 'type': "numeric", 'format': euro(2) }, { 'id': "Fees", 'name': "Fees", 'type': "numeric", 'format': euro(2) }, { 'id': "Return(tot)", 'name': "Return(tot)", 'type': "numeric", 'format': euro(2) }, { 'id': "Return(rel)", 'name': "Return(rel)", 'type': "numeric", 'format': FormatTemplate.percentage(1) }, { 'id': "XIRR", 'name': "XIRR", 'type': "numeric", 'format': FormatTemplate.percentage(1) }, ], data=pf_sym_view.round(2).to_dict("records"), style_as_list_view=True, style_cell={ "textAlign": 'right', "padding": '5px', 'fontSize': 14, 'font-family': 'sans-serif' }, style_header={ 'backgroundColor': 'darkgrey', 'fontWeight': 'bold', 'color': 'white' }, style_cell_conditional=[{ 'if': { 'column_id': header }, 'textAlign': 'left', 'width': '50px' } for header in ["Portfolio", "Symbol"]] + [{ 'if': { 'column_id': data_header }, 'textAlign': 'right', 'width': '20px' } for data_header in pf_sym_view.columns.drop( ["Portfolio", "Symbol"])], style_data_conditional=[{ 'if': { 'filter_query': '{Symbol} = ""' }, 'backgroundColor': 'lightgrey', 'fontWeight': 'bold' }], ) ]), html.H4(children="Time Series"), html.H5(children="XIRR Chart"), dcc.Graph(figure=xirr_fig), html.H5(children="Total Returns Chart"), dcc.Graph(figure=return_fig) ]) return tab1_content
def get_columns(): the_date = "Return % as at {}".format(get_data_date()) size_cols = [{ 'id': 'investment_name', 'name': 'Investment Name', 'type': 'text' }, { 'id': 'superfund_type', 'name': 'Super Fund Type', 'type': 'text' }, { 'id': 'asset_class', 'name': 'Asset Class', 'type': 'text' }, { 'id': 'fund_assets', 'name': 'Fund Assets ($)', 'type': 'numeric', 'format': FormatTemplate.money(2) }, { 'id': 'investment_size', 'name': 'Investment Size ($)', 'type': 'numeric', 'format': FormatTemplate.money(2) }] performance_cols = [{ 'id': 'investment_name', 'name': ['', 'Fund'], 'type': 'text' }, { 'id': 'return_5yr', 'name': [the_date, '5 Year'], 'type': 'numeric', 'format': FormatTemplate.percentage(2) }, { 'id': 'return_3yr', 'name': [the_date, '3 Year'], 'type': 'numeric', 'format': FormatTemplate.percentage(2) }, { 'id': 'return_1yr', 'name': [the_date, '1 Year'], 'type': 'numeric', 'format': FormatTemplate.percentage(2) }, { 'id': 'fee', 'name': ['Fee', '$'], 'type': 'numeric', 'format': FormatTemplate.money(0) }] # performance_cols = [{ # 'id': 'investment_name', # 'name': 'Investment Name', # 'type': 'text' # }, { # 'id': 'superfund_type', # 'name': 'Super Fund Type', # 'type': 'text' # }, { # 'id': 'asset_class', # 'name': 'Asset Class', # 'type': 'text' # }, { # 'id': 'fee', # 'name': 'Fee ($)', # 'type': 'numeric', # 'format': FormatTemplate.money(0) # }, { # 'id': 'risk_label', # 'name': 'Risk', # 'type': 'text' # }, { # 'id': 'targetreturn', # 'name': 'Target Return (%)', # 'type': 'numeric', # 'format': FormatTemplate.percentage(2) # }, { # 'id': 'return_1yr', # 'name': '1 Year Return (%)', # 'type': 'numeric', # 'format': FormatTemplate.percentage(2) # }, { # 'id': 'return_3yr', # 'name': '3 Year Return (%)', # 'type': 'numeric', # 'format': FormatTemplate.percentage(2) # }, { # 'id': 'return_5yr', # 'name': '5 Year Return (%)', # 'type': 'numeric', # 'format': FormatTemplate.percentage(2) # }, { # 'id': 'invfee', # 'name': 'Investment Fee (%)', # 'type': 'numeric', # 'format': FormatTemplate.percentage(4) # }, { # 'id': 'admin_fee', # 'name': 'Admin Fee (%)', # 'type': 'numeric', # 'format': FormatTemplate.percentage(4) # }] details_cols = [{ 'id': 'investment_name', 'name': 'Fund', 'type': 'text' }, { 'id': 'superfund_type', 'name': 'Fund Type', 'type': 'text' }, { 'id': 'asset_class', 'name': 'Asset Class', 'type': 'text' }, { 'id': 'fund_assets', 'name': 'Fund Assets', 'type': 'numeric', 'format': FormatTemplate.money(2) }] objective_cols = [{ 'id': 'investment_name', 'name': 'Fund', 'type': 'text' }, { 'id': 'targetreturn', 'name': 'Target Return', 'type': 'numeric', 'format': FormatTemplate.percentage(2) }, { 'id': 'risk_label', 'name': 'Risk', 'type': 'text' }] return performance_cols, size_cols, details_cols, objective_cols
}, { 'name': 'Income', 'id': 'job_transformed', 'type': 'text', 'editable': False }, { 'name': 'Previously Contacted', 'id': 'poutcome', 'type': 'text', 'editable': False }, { 'name': 'Probability of Success', 'id': 'prob_1', 'type': 'numeric', 'editable': False, 'format': FormatTemplate.percentage(1) }, { 'name': 'Call Result', 'id': 'is_called', 'type': 'any', 'editable': True, 'presentation': 'dropdown' }], data=df.to_dict('records'), filter_action='native', dropdown={ 'is_called': { 'options': [{ 'label': i, 'value': i } for i in ['Not Called', 'Success', 'Failure']]
def generate_table_from_data(self) -> dt.DataTable: data = self.data_manager.dati_completi_latest dtf = data[[ # 'formatted_date', 'ricoverati_con_sintomi', 'terapia_intensiva', 'totale_ospedalizzati', 'isolamento_domiciliare', 'totale_positivi', 'variazione_totale_positivi', 'nuovi_positivi', 'nuovi_positivi_7dma', 'nuovi_positivi_3dma', 'dimessi_guariti', 'deceduti', 'CFR', 'casi_da_sospetto_diagnostico', 'casi_da_screening', 'totale_casi', 'tamponi', 'casi_testati', 'denominazione_regione', 'variazione_tamponi', 'variazione_casi_testati', 'variazione_terapia_intensiva', 'variazione_ricoverati_con_sintomi', 'variazione_deceduti', 'variazione_dimessi_guariti', 'variazione_isolamento_domiciliare', 'variazione_casi_da_screening', 'variazione_casi_da_sospetto_diagnostico', 'percentuale_positivi_tamponi', 'percentuale_positivi_tamponi_giornaliera', 'percentuale_positivi_casi', 'percentuale_positivi_casi_giornaliera', 'incidenza', 'incidenza_7d', ]] data_table = dt.DataTable( id='rdt', columns=([ # {'id': 'formatted_date', 'name': 'Data'}, { 'id': 'denominazione_regione', 'name': 'Regione' }, { 'id': 'nuovi_positivi', 'name': 'Nuovi positivi', 'type': 'numeric' }, { 'id': 'nuovi_positivi_7dma', 'name': 'Nuovi positivi (7DMA)', 'type': 'numeric' }, { 'id': 'nuovi_positivi_3dma', 'name': 'Nuovi positivi (3DMA)', 'type': 'numeric' }, { 'id': 'variazione_tamponi', 'name': 'Var. Tamponi', 'type': 'numeric' }, { 'id': 'variazione_casi_testati', 'name': 'Var. Persone', 'type': 'numeric' }, { 'id': 'variazione_terapia_intensiva', 'name': 'Var. T.I.', 'type': 'numeric' }, { 'id': 'variazione_ricoverati_con_sintomi', 'name': 'Var Sintomi', 'type': 'numeric' }, { 'id': 'variazione_deceduti', 'name': 'Var. Decessi', 'type': 'numeric' }, { 'id': 'variazione_dimessi_guariti', 'name': 'Var. Guariti', 'type': 'numeric' }, { 'id': 'percentuale_positivi_tamponi_giornaliera', 'name': 'Positivi/Tamponi oggi', 'type': 'numeric', 'format': FormatTemplate.percentage(2, rounded=False) }, { 'id': 'percentuale_positivi_casi_giornaliera', 'name': 'Positivi/Persone oggi', 'type': 'numeric', 'format': FormatTemplate.percentage(2, rounded=False) }, { 'id': 'ricoverati_con_sintomi', 'name': 'Ricoverati con sintomi', 'type': 'numeric' }, { 'id': 'terapia_intensiva', 'name': 'Terapia Intensiva', 'type': 'numeric' }, { 'id': 'totale_ospedalizzati', 'name': 'Ospedalizzati', 'type': 'numeric' }, { 'id': 'isolamento_domiciliare', 'name': 'Isolamento', 'type': 'numeric' }, { 'id': 'totale_positivi', 'name': 'Positivi', 'type': 'numeric' }, { 'id': 'variazione_totale_positivi', 'name': 'Var. Positivi', 'type': 'numeric' }, { 'id': 'dimessi_guariti', 'name': 'Guariti', 'type': 'numeric' }, { 'id': 'deceduti', 'name': 'Decessi', 'type': 'numeric' }, { 'id': 'CFR', 'name': 'Case Fatality Rate', 'type': 'numeric', 'format': FormatTemplate.percentage(2, rounded=False) }, { 'id': 'casi_da_sospetto_diagnostico', 'name': 'Sospetto diagnostico', 'type': 'numeric' }, { 'id': 'casi_da_screening', 'name': 'Screening', 'type': 'numeric' }, { 'id': 'totale_casi', 'name': 'Casi', 'type': 'numeric' }, { 'id': 'tamponi', 'name': 'Tamponi', 'type': 'numeric' }, { 'id': 'casi_testati', 'name': 'Persone', 'type': 'numeric' }, { 'id': 'variazione_isolamento_domiciliare', 'name': 'Var. Isolamento', 'type': 'numeric' }, { 'id': 'variazione_casi_da_screening', 'name': 'Var. Screening', 'type': 'numeric' }, { 'id': 'variazione_casi_da_sospetto_diagnostico', 'name': 'Var. Sospetto diagnostico', 'type': 'numeric' }, { 'id': 'percentuale_positivi_tamponi', 'name': 'Positivi/Tamponi', 'type': 'numeric', 'format': FormatTemplate.percentage(2, rounded=False) }, { 'id': 'percentuale_positivi_casi', 'name': 'Positivi/Persone', 'type': 'numeric', 'format': FormatTemplate.percentage(2, rounded=False) }, { 'id': 'incidenza', 'name': 'Incidenza /10000 abitanti', 'type': 'numeric' }, { 'id': 'incidenza_7d', 'name': 'Incidenza a 7gg /10000 abitanti', 'type': 'numeric' }, ]), data=dtf.to_dict(orient='records'), editable=False, style_table={ # 'height': 'auto', 'minWidth': '500px', 'maxWidth': '99%', 'whiteSpace': 'normal', 'overflowX': 'scroll', # 'maxHeight': self._default_height, 'overflowY': 'scroll', 'textAlign': 'left' }, style_data_conditional=[{ 'if': { 'row_index': 'odd' }, 'backgroundColor': 'rgb(248, 248, 248)' }], style_cell={ 'overflow': 'hidden', 'textOverflow': 'ellipsis', 'maxWidth': 0, }, style_cell_conditional=[ { 'if': { 'column_id': 'denominazione_regione' }, 'width': '10%' }, ], tooltip_data=[{ column: { 'value': str(value), 'type': 'markdown' } for column, value in row.items() } for row in dtf.to_dict(orient='records')], style_header={ 'whiteSpace': 'normal', 'height': 'auto', 'lineHeight': '15px', 'backgroundColor': 'rgb(230, 230, 230)', 'fontWeight': 'bold' }, # fixed_columns={'headers': True, 'data': 1}, # fixed_rows={'headers': True, 'data': 0}, filter_action="native", sort_action="native", sort_mode="multi", ) return data_table
def update_fig_table(n_clicks, start, end, starting_cash, risk_free, md): if start is not None: start = date.fromisoformat(start) if end is not None: end = date.fromisoformat(end) # run the backtest test, blotter, calender, daily_return, monthly_return, monthly_expected_return, monthly_volatility, \ monthly_sharpe_ratio = backtest2(starting_cash, logistic_strategy, start, end, risk_free, train_window=100, maxPoints=2000) # figure1 line1 = go.Scatter(x=test['date'], y=test['acc_return'], name='strategy cumulative return', mode='lines+markers') line2 = go.Scatter(x=test['date'], y=test['ivv_acc_return'], name='IVV cumulative return', mode='lines+markers') fig1 = go.Figure() fig1.add_traces(data=[line1, line2]) fig1.update_layout(title='Back-Test-Cumulative-Return', yaxis={'hoverformat': '.2%'}, xaxis=dict(rangeslider=dict(visible=True), type="date")) # figure2 line1 = go.Bar(x=test['date'], y=test['daily_return'], name='strategy return') line2 = go.Bar(x=test['date'], y=test['ivv_daily_return'], name='IVV return') fig2 = go.Figure() fig2.add_traces(data=[line1, line2]) fig2.update_layout(title='Back-Test-Daily-Return', yaxis={'hoverformat': '.2%'}, xaxis=dict(rangeslider=dict(visible=True), type="date")) # blotter blotter = blotter.to_dict('records') blotter_columns = [ dict(id='Created', name='Created'), dict(id='Action', name='Action'), dict(id='Size', name='Size'), dict(id='Symbol', name='Symb'), dict(id='Order Price', name='Order Price', type='numeric', format=FormatTemplate.money(2)), dict(id='Type', name='Type'), dict(id='Filled / Cancelled', name='Filled/Cancelled'), dict(id='Filled Price', name='Filled Price', type='numeric', format=FormatTemplate.money(2)) ] # calender calender = calender.to_dict('records') calender_columns = [ dict(id='date', name='Date'), dict(id='close', name='Stock Close', type='numeric', format=FormatTemplate.money(2)), dict(id='cash', name='Cash', type='numeric', format=FormatTemplate.money(2)), dict(id='ivv_value', name='Stock Value', type='numeric', format=FormatTemplate.money(2)), dict(id='total_value', name='Total Value', type='numeric', format=FormatTemplate.money(2)) ] daily_return = daily_return.to_dict('records') daily_return_columns = [ dict(id='date', name='Date'), dict(id='daily_return', name='Strategy Daily Return', type='numeric', format=FormatTemplate.percentage(2)), dict(id='acc_return', name='Strategy Cumulative Return', type='numeric', format=FormatTemplate.percentage(2)), dict(id='ivv_daily_return', name='IVV Daily Return', type='numeric', format=FormatTemplate.percentage(2)), dict(id='ivv_acc_return', name='IVV Cumulative Return', type='numeric', format=FormatTemplate.percentage(2)) ] monthly_return = monthly_return.to_dict('records') monthly_return_columns = [ dict(id='mon_date', name='Date'), dict(id='strategy_return', name='Strategy Monthly Return', type='numeric', format=FormatTemplate.percentage(2)), dict(id='ivv_return', name='IVV Monthly Return', type='numeric', format=FormatTemplate.percentage(2)) ] # gmrr, vol and shapre ratio gmrr = 253 * ( (test.acc_return[len(test.index) - 1] + 1)**(1 / len(test.index)) - 1) gmrr_str = str(round(gmrr * 100, 3)) + "%" vol = (253**0.5) * stdev(test.daily_return) vol_str = str(round(vol * 100, 3)) + "%" rf = risk_free / 100 sharpe = round((gmrr - rf) / vol, 3) # alpha & beta X = test['ivv_daily_return'].values.reshape(-1, 1) linreg_model = linear_model.LinearRegression() linreg_model.fit(X, test['daily_return']) alpha = str(round(linreg_model.intercept_ * 100, 3)) + "%" beta = round(linreg_model.coef_[0], 3) x_range = np.linspace(X.min(), X.max(), 100) y_range = linreg_model.predict(x_range.reshape(-1, 1)) fig3 = px.scatter(test, title="Performance against Benchmark", x='ivv_daily_return', y='daily_return') fig3.add_traces(go.Scatter(x=x_range, y=y_range, name='OLS Fit')) # data = data.drop(labels='Rate of Return(%)', axis=1, inplace=True) # Return your updated text to currency-output, and the figure to candlestick-graph outputs return (fig1, fig2, fig3, blotter, blotter_columns, calender, calender_columns, daily_return, daily_return_columns, monthly_return, monthly_return_columns, alpha, beta, gmrr_str, vol_str, sharpe, monthly_expected_return, monthly_volatility, monthly_sharpe_ratio)
def calculate_backtest( ivv_hist, bonds_hist, n, N, alpha, rho, CI , lot_size, starting_cash, start_date, end_date ): features_and_responses, blotter, calendar_ledger, trade_ledger = backtest( ivv_hist, bonds_hist, n, N, alpha, rho, CI, lot_size, start_date, end_date, starting_cash ) features_and_responses_columns = [ {"name": i, "id": i} for i in features_and_responses.columns ] features_and_responses = features_and_responses.to_dict('records') blotter = blotter.to_dict('records') blotter_columns = [ dict(id='ID', name='ID'), dict(id='ls', name='long/short'), dict(id='submitted', name='Created'), dict(id='action', name='Action'), dict(id='size', name='Size'), dict(id='symbol', name='Symb'), dict( id='price', name='Order Price', type='numeric', format=FormatTemplate.money(2) ), dict(id='type', name='Type'), dict(id='status', name='Status'), dict(id='fill_price', name='Fill Price', type='numeric', format=FormatTemplate.money(2) ), dict(id='filled_or_cancelled', name='Filled/Cancelled') ] calendar_ledger = calendar_ledger.to_dict('records') calendar_ledger_columns = [ dict(id='Date', name='Date'), dict(id='position', name='position'), dict(id='ivv_close', name='IVV Close', type='numeric', format=FormatTemplate.money(2)), dict(id='cash', name='Cash', type='numeric', format=FormatTemplate.money(2)), dict(id='stock_value', name='Stock Value', type='numeric', format=FormatTemplate.money(2)), dict(id='total_value', name='Total Value', type='numeric', format=FormatTemplate.money(2)) ] trade_ledger = trade_ledger.to_dict('records') trade_ledger_columns = [ dict(id='trade_id', name="ID"), dict(id='open_dt', name='Trade Opened'), dict(id='close_dt', name='Trade Closed'), dict(id='trading_days_open', name='Trading Days Open'), dict(id='buy_price', name='Entry Price', type='numeric', format=FormatTemplate.money(2)), dict(id='sell_price', name='Exit Price', type='numeric', format=FormatTemplate.money(2)), dict(id='benchmark_buy_price', name='Benchmark Buy Price', type='numeric', format=FormatTemplate.money(2)), dict(id='benchmark_sell_price', name='Benchmark sell Price', type='numeric', format=FormatTemplate.money(2)), dict(id='trade_rtn', name='Return on Trade', type='numeric', format=FormatTemplate.percentage(3)), dict(id='benchmark_rtn', name='Benchmark Return', type='numeric', format=FormatTemplate.percentage(3)), dict(id='trade_rtn_per_trading_day', name='Trade Rtn / trd day', type='numeric', format=FormatTemplate.percentage(3)), dict(id='benchmark_rtn_per_trading_day', name='Benchmark Rtn / trd day', type='numeric', format=FormatTemplate.percentage(3)) ] return features_and_responses, features_and_responses_columns, blotter, \ blotter_columns, calendar_ledger, calendar_ledger_columns, \ trade_ledger, trade_ledger_columns