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 present_customer_data_layout(): '''This is the screen layout for the customer data. This has not been implemented yet.''' return html.Div([ html.Br(), html.Br(), html.H5('Client Information', style = TEXT_ALIGN_CENTER ), html.Br(), dash_table.DataTable( id='record', columns = [ {'name': 'Customer Name', 'id' : 'name'}, {'name': 'Account Number', 'id': 'account number'}, {'name': 'Account Balance', 'id' : 'account balance', 'type' : 'numeric', 'format': FormatTemplate.money(2)}, {'name': 'Date of Transaction', 'id' : 'date of entry'}, {'name': 'Transaction Type', 'id' : 'transaction type'}, {'name': 'Transaction Amount', 'id' : 'transaction amount', 'type' : 'numeric', 'format': FormatTemplate.money(2)}, ], style_header = { 'backgroundColor': 'rgb(230,230,230)', 'font-weight' : 'bold', }, style_cell = { 'textAlign' : 'center' }, style_data_conditional= [ {'if': {'row_index': 'odd'}, 'backgroundColor': 'rgb(248, 248, 248)'}, ], style_table = { 'maxHeight': '300px', 'overflowY' : 'scroll', 'font-family': 'sans-serif', 'font-size': '24', } ), html.Div(id = 'customer_record') ])
def selects_callback(node_status, session_id): if session_id in pyplan_sessions and pyplan_sessions[session_id].is_ready( ): pyplan = pyplan_sessions[session_id] # get values from Pyplan print(f"Get values from Pyplan for session: {session_id}") df_json = pyplan.getResult('p_l_report_for_dash') df = pd.read_json(df_json, orient='table') sorted_values = df.index.get_level_values( "Report index").unique().tolist() df = pd.pivot_table(df, values="value", index=["Report index"], columns=["time"], aggfunc="sum") #fix index order after pivot df = df.reindex(index=sorted_values).reset_index() # create columns for table columns = [] for nn, col in enumerate(df.columns): column_definition = None if nn == 0: column_definition = { "name": 'P&L Accounts', "id": 'Report index', "type": "text" } else: column_definition = { "name": col, "id": col, "type": "numeric", "format": FormatTemplate.money(0) } columns.append(column_definition) data = df.to_dict("records") value_columns = [cc for nn, cc in enumerate(df.columns) if nn > 0] df_chart = df.melt(id_vars=["Report index"], value_vars=value_columns, var_name='time') # create chart fig = px.line(df_chart, x="time", y="value", color='Report index', color_discrete_sequence=default_colors) default_layout(fig) fig.update_layout(height=390, xaxis_type="category", title_text=f"P&L Report") return columns, data, fig return dash.no_update, dash.no_update, dash.no_update
def initalization(_): columns = [{ 'name': 'Period', 'id': 'period', 'type': 'numeric', }, { 'name': 'Value', 'id': 'value', 'type': 'numeric', 'format': FormatTemplate.money(2) }] return columns
def budget_columns(cols): data = [] for c in cols: if c == 'amount': data.append({ "name": c, "id": c, 'type': 'numeric', 'format': FormatTemplate.money(0) }) else: data.append({"name": c, "id": c}) data.append({'deletable': True}) return data
def column_prep(cols): data = [] for c in cols: if c == 'date': data.append({"name": c, "id": c, "type": "datetime"}) elif c == 'amount': data.append({ "name": c, "id": c, 'type': 'numeric', 'format': FormatTemplate.money(0) }) else: data.append({"name": c, "id": c}) return data
def update_table_columns(cols): if cols is None: raise PreventUpdate columns = [] for i in range(cols + 1): columns.append({ 'name': str(i), 'id': str(i), 'type': 'numeric', 'format': FormatTemplate.money(2) }) return columns
def get_columns_for_summary(): money = FormatTemplate.money(2) columns = [ dict(id='type', name='Type'), dict(id='profit', name='Profit', type='numeric', format=money), dict(id='max_dd', name='Max Drawdown', type='numeric', format=money), dict(id='slippage_paid', name='Slippage', type='numeric', format=money), dict(id='np_maxdd', name='NP / Max DD', type='numeric'), dict(id='num_trades', name='Trades', type='numeric'), dict(id='avg_trade', name='Avg Trade', type='numeric'), dict(id='profit_factor', name='Profit Factor', type='numeric'), dict(id='k_ratio', name='K-Ratio', type='numeric'), dict(id='worst_trade', name='Worst Trade', type='numeric', format=money), dict(id='worst_month', name='Worst Month', type='numeric', format=money), dict(id='profit_1m', name='Profit 1 Month', type='numeric', format=money), dict(id='profit_3m', name='Profit 3 Month', type='numeric', format=money), dict(id='profit_6m', name='Profit 6 Month', type='numeric', format=money), dict(id='profit_9m', name='Profit 9 Month', type='numeric', format=money), dict(id='profit_1y', name='Profit 1 Year', type='numeric', format=money), ] return columns
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)
}, ), className="row", style={"marginBottom": "10"}, ), modal(), html.Div( [ html.Div( dtbl.DataTable( id='trans-df', columns=[{ 'id': 'amount', 'name': 'Price ($)', 'type': 'numeric', 'format': FormatTemplate.money(2) }, { 'id': 'Date', 'name': 'Date' }, { 'id': 'Place', 'name': 'Place' }, { 'id': 'City', 'name': 'City' }, { 'id': 'Category', 'name': 'Category' }], data=df.to_dict('records'), sorting=True,
def layout(app): from app import db from app.models import Transaction def gen_conditionals_categories(category_column, sub_category_column): categories = { "Income": [ "Salary", "Bonuses", "Gifts", "Dividends", "Savings", "Tax Return", "Sold Item", ], "Credit Card": ["Bill", "Payment"], "Insurance": [ "Health Insurance", "Bike Insurance", "Car Insurance", "Pet Insurance", "Home Insurance", "Mortgage Insurance", "Life Insurance", ], "Housing": [ "Mortgage", "Rent", "Accountant Fee", "Security", "Home maintenance", ], "Children": [ "Childcare", "School Fees", "School activities", "Toys", "Allowance", "School supplies", "Babysitter", "Daycare", ], "Entertainment": [ "Events", "Movies", "Charity Rides", "Experiences", "Games", ], "Health Beauty": [ "Health Fitness", "Hairdresser", "Optical", "Medical", "Medication", "Dental", ], "Utilities": [ "Gas Bill", "Water Bill", "Rates", "Electricity", "Phone Bill", ], "Memberships": [ "Music subscription", "Internet", "Strava", "Google storage", "Media subscription", ], "Travel": ["Accommodation", "Flights", "Airbnb"], "Food": [ "Cafe Coffee", "Resturants", "Takeaway", "Bars Pubs", "Groceries", "Alcohol", ], "Shopping": [ "Bike Stuff", "Clothing Footwear", "Beauty", "Books", "Electronics Software", "Home supplies", "Birthday gifts", "Christmas gifts", "Wedding gifts", "Anniversary", "Other shopping", ], "Transportation": [ "Uber Taxi", "Car Loan", "Car maintenance", "Car registration", "Bike maintenance", "Public transport", "Roadside assistance", "Parking", ], "Pets": ["Vet", "Emergency", "Pet supplies", "Pet sitter", "Pet food"], "Education": ["Work", "Other"], "Miscellaneous": ["Charity Donations", "Hecs", "Fines"], } conditional_dict = { category_column: { "options": [{ "label": i, "value": i } for i in sorted(categories.keys())] } } sub_conditional_list = [{ "if": { "column_id": sub_category_column, "filter_query": f'{{{category_column}}} eq "{category}"', }, "options": [{ "label": i, "value": i } for i in sorted(categories[category])], } for category in categories.keys()] return conditional_dict, sub_conditional_list conditional_dict, sub_conditional_list = gen_conditionals_categories( "category", "sub_category") with app.server.app_context(): transactions = db.session.query(Transaction) df = pd.read_sql(transactions.statement, transactions.session.bind) accounts = Transaction.query.with_entities( Transaction.account).distinct() layout = html.Div([ dcc.Location(id="location"), html.Div(id="current_location"), html.Details([ html.Summary("Filters"), html.Div( [ dcc.Dropdown( id="account_selector", options=[{ "label": a[0], "value": a[0] } for a in accounts], placeholder="Select account...", ), dcc.Dropdown( id="uncategorised_selector", options=[ { "label": "Uncategorised", "value": "uncategorised", }, { "label": "All", "value": "all" }, ], value="uncategorised", clearable=False, ), ], style={ "width": "100%", "display": "inline-block" }, ), html.Div(id="selection"), ]), html.Div( [ dash_table.DataTable( id="transaction_table", data=df.sort_values("added_date").to_dict("rows"), columns=[ { "id": "id", "name": "Hash", "type": "text", "hidden": True, }, { "id": "added_date", "name": "Added", "type": "text", "hidden": True, }, { "id": "date", "name": "Date", "type": "text" }, { "id": "narration", "name": "Narration", "type": "text" }, { "id": "amount", "name": "Amount", "type": "numeric", "format": FormatTemplate.money(2), }, { "id": "category", "name": "Category", "presentation": "dropdown", "min-width": "200px", }, { "id": "sub_category", "name": "Sub-category", "presentation": "dropdown", "min-width": "200px", }, ], # style_cell={"padding": "5px"}, style_header={ "backgroundColor": "white", "fontWeight": "bold" }, editable=True, filter_action="native", sort_action="native", sort_mode="multi", page_action="native", page_current=0, page_size=15, dropdown=conditional_dict, dropdown_conditional=sub_conditional_list, style_data={"whiteSpace": "normal"}, css=[{ "selector": ".dash-cell div.dash-cell-value", "rule": "display: inline; white-space: inherit; overflow: inherit; text-overflow: inherit;", }], ) ], id="main", style={"width": "95%"}, ), ]) return layout
def test_money_template(self): res = FormatTemplate.money(2).to_plotly_json() self.assertEqual(res["specifier"], "$,.2f")
def sample_portfolio_layout(app, df_portfolio): # def sample_portfolio_layout(): '''This is the layout of the sample portfolio.''' return html.Div([ html.Br(), html.Br(), html.H5(children = ['Please enter your age (minimum 18 and maximum 99): ', dcc.Input(style = {'width': 80}, id = 'my-age', value = 25, type = 'number', min = 18, max = 99, debounce = True ), html.H6(id = 'id-age') ], style = PORTFOLIO_LAYOUT ), html.Br(), html.H5(children = ['Enter the amount of money would you like to invest $): ', dcc.Input(style = {'width': 125}, id = 'my-amount', value = 5000, type = 'number', min = 5000, max = 100000, debounce=True ), html.H6(id = 'id-amount') ], style = PORTFOLIO_LAYOUT ), html.Br(), html.Div(children = ['What is your risk tolerance (1 is the lowest, \ 10 is the highest and 5 is neutral)', dcc.Slider( id = 'risk-tolerance-slider', min = 1, max = 10, step = 1, value = 5, marks = {i: '{}'.format(i) for i in range(11)}, ), html.Div(id = 'risk-tolerance-output-slider'), ], style = SLIDER_LAYOUT ), html.Br(), html.Br(), html.H5(children = ['The dollar allocation to each sector will change every day \ that the financial markets are open at approximately 6:45 pm.'], style = TEXT_ALIGN_CENTER ), html.H5(children = ['This is the time that we get new market data'], style = TEXT_ALIGN_CENTER ), html.Br(), dash_table.DataTable( id='df_portfolio', columns = [ {'name': 'Security', 'id' : 'security'}, {'name': 'Category', 'id': 'category'}, {'name': 'Shares', 'id' : 'shares'}, {'name': 'Share Price', 'id' : 'share price', 'type' : 'numeric', 'format': FormatTemplate.money(2) }, {'name': 'Total Cost', 'id' : 'total cost', 'type' : 'numeric', 'format': FormatTemplate.money(2) }, ], style_header = { 'backgroundColor': 'rgb(230,230,230)', 'font-weight' : 'bold', }, style_cell = { 'textAlign' : 'center' }, style_data_conditional= [ {'if': {'row_index': 'odd'}, 'backgroundColor': 'rgb(248, 248, 248)'}, ], style_table = { 'maxHeight': '300px', 'overflowY' : 'scroll', 'font-family': 'sans-serif', 'font-size': '24', } ), html.Div(id = 'portfolio_layout') ])
import re import json import urllib import urllib.parse from functools import reduce mapbox_access_token = 'pk.eyJ1IjoiY2FscmVtbWVsIiwiYSI6ImNqc25scWtiMzBkcGI0M3BtNDRrbnFvNGoifQ.qmi7OtQn6vIJbHbbTZs2MQ' # Define format for table columns, including currency formatting. TABLE_COLS = [ "Parcel ID", "Address", "Property Value", "Listed Owner", "Principals" ] FORMAT_COLS = [{"name": i, "id": i} for i in TABLE_COLS] FORMAT_COLS[2]['type'] = 'numeric' FORMAT_COLS[2]['format'] = FormatTemplate.money(0) # Load data. geocodes = pd.read_csv('data/csvs/geocoded_properties.csv') principals = pd.read_csv('data/csvs/props_to_principals.csv') # Define color list for city wards. colors = [ "rgba(251,180,174,0.5)", "rgba(179,205,227,0.5)", "rgba(204,235,197,0.5)", "rgba(222,203,228,0.5)", "rgba(254,217,166,0.5)", "rgba(255,255,204,0.5)", "rgba(229,216,189,0.5)", "rgba(253,218,236,0.5)" ] # GeoJSON files for city wards. files = [ 'ward1.json', 'ward2.json', 'ward3.json', 'ward4.json', 'ward5.json', 'ward6.json', 'ward7.json', 'ward8.json'
options=[ {'label': ' Fondos de Deuda ', 'value': 'D'}, {'label': ' Fondos de Renta Variable ', 'value': 'RV'}], value=['RV', 'D'], labelStyle={'display': 'inline-block'} ) ]) ]), dbc.Row([ dbc.Col([ dash_table.DataTable(id='tabla1', columns=[{"name": i, "id": i, "hideable": True, "type": "numeric", "format": FormatTemplate.money(2)} if i == "Fondo" or i == "id" else {"name": i, "id": i, "hideable": True, "type": "numeric", "format": FormatTemplate.money(2)} for i in dff], style_cell={'textAlign': 'left', "maxWidth": "250px"}, sort_action="native", sort_mode="multi", page_action="native", page_current=0, page_size=20, row_selectable='single', selected_rows=[], style_data={ # overflow cells' content into multiple lines 'whiteSpace': 'normal', 'height': 'auto'
def make_table(dff): dff = dff.groupby(["State"]).sum().reset_index() dff["sparkline"] = make_sparkline(dff, "Per Capita", YEARS) dff = table_yr(dff, START_YR) return html.Div( [ dash_table.DataTable( id="table", columns=[ { "id": "State", "name": "State", "type": "text" }, { "id": "Category", "name": "Category", "type": "text" }, { "id": "Description", "name": "Sub Category", "type": "text" }, { "id": "State/Local", "name": "State or Local ", "type": "text" }, { "id": "Amount", "name": "Total Amount", "type": "numeric", "format": FormatTemplate.money(0), }, { "id": "Per Capita", "name": "Per Capita", "type": "numeric", "format": FormatTemplate.money(0), }, { "id": "sparkline", "name": "Per Capita 2012-2017", "type": "numeric", "format": FormatTemplate.money(0), }, ], data=dff.to_dict("records"), sort_action="native", sort_mode="multi", export_format="xlsx", export_headers="display", is_focused=False, cell_selectable=False, style_table={ "overflowY": "scroll", "border": "thin lightgrey solid", "maxHeight": "450px", }, style_cell={ "textAlign": "left", "font-family": "arial", "font-size": "16px", }, style_cell_conditional=[{ "if": { "column_id": c }, "textAlign": "right" } for c in ["Per Capita", "Amount"]], style_data_conditional=[ { "if": { "state": "active" }, "backgroundColor": "rgba(150, 180, 225, 0.2)", "border": "1px solid blue", }, { "if": { "state": "selected" }, "backgroundColor": "rgba(0, 116, 217, .03)", "border": "1px solid blue", }, { "if": { "column_id": "sparkline" }, "width": 100, "font-family": "Sparks-Bar-Extrawide", "padding-right": "20px", "padding-left": "20px", }, ], ) ], id="table_div", )
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)
'font-weight': '600', 'height': '38px', 'margin-bottom': '2px', 'margin-top': '2px', 'margin-left': '2px', 'margin-right': '2px' } input_table = dash_table.DataTable( id='input-table', columns=([ { 'id': 'capital', 'name': 'capital', 'type': 'numeric', 'format': FormatTemplate.money(money_precision) }, { 'id': 'risk_percent', 'name': 'risk %', 'type': 'numeric', 'format': FormatTemplate.percentage(2) }, { 'id': 'current_price', 'name': 'MKT', 'type': 'numeric', 'format': FormatTemplate.money(price_precision) }, { 'id': 'SL',
def make_table(df): table = dash_table.DataTable( id='child_level', data=df.to_dict('records'), columns=[ { 'id': 'name', 'name': 'Child name', 'type': 'text' }, { 'id': 'case_number', 'name': 'Case number', 'type': 'text' }, { 'id': 'biz_name', 'name': 'Business', 'type': 'text' }, { 'id': 'attendance_category', 'name': 'Attendance risk', 'type': 'text' }, { 'id': 'attendance_rate', 'name': 'Attendance rate', 'type': 'numeric', 'format': {'nully':'-%', 'prefix': None, 'specifier': '.0%'} }, { 'id': 'min_revenue', 'name': 'Guaranteed revenue', 'type': 'numeric', 'format': FormatTemplate.money(2) }, { 'id': 'potential_revenue', 'name': 'Potential revenue', 'type': 'numeric', 'format': FormatTemplate.money(2) }, { 'id': 'max_revenue', 'name': 'Max. approved revenue', 'type': 'numeric', 'format': FormatTemplate.money(2) }, { 'id': 'e_learning_revenue_potential', 'name': 'Potential e-learning revenue', 'type': 'numeric', 'format': FormatTemplate.money(2) } ], style_data_conditional=[ { 'if': { 'filter_query': '{attendance_category} = "Not enough info"', 'column_id': 'attendance_category' }, 'backgroundColor': 'rgb(248, 248, 248)', 'color': 'rgb(128,128,128)' }, { 'if': { 'filter_query': '{attendance_category} = "Sure bet"', 'column_id': 'attendance_category' }, 'color': '#0f8c48' }, { 'if': { 'filter_query': '{attendance_category} = "Sure bet"', 'column_id': 'attendance_rate' }, 'color': '#0f8c48' }, { 'if': { 'filter_query': '{attendance_category} = "Not met"', 'column_id': 'attendance_category' }, 'color': '#da5d4f' }, { 'if': { 'filter_query': '{attendance_category} = "Not met"', 'column_id': 'attendance_rate' }, 'color': '#da5d4f' }, { 'if': { 'filter_query': '{attendance_category} = "At risk"', 'column_id': 'attendance_category' }, 'color': '#da5d4f' }, { 'if': { 'filter_query': '{attendance_category} = "At risk"', 'column_id': 'attendance_rate' }, 'color': '#da5d4f' }, { 'if': { 'filter_query': '{attendance_category} = "On track"', 'column_id': 'attendance_category' }, 'color': '#0f8c48' }, { 'if': { 'filter_query': '{attendance_category} = "On track"', 'column_id': 'attendance_rate' }, 'color': '#0f8c48' }, ], style_header={ 'whiteSpace': 'normal', 'height': 'auto', 'maxWidth': '100px', }, style_table={ 'padding': '20px', 'overflowX': 'auto', }, sort_action='native', sort_mode='single', ) return table
def layout(app): from app import db from app.models import Transaction with app.server.app_context(): transactions = db.session.query(Transaction) df = pd.read_sql(transactions.statement, transactions.session.bind) df = df[(df.amount < 0) & (df.category != "Credit Card")] df_monthly = df.groupby(df.date.dt.month).agg({"amount": "sum"}) df_cat = (df.groupby(df.category).agg({ "amount": "sum" }).sort_values("amount", ascending=False)) df_subcat = (df.groupby(df.sub_category).agg({ "amount": "sum" }).sort_values("amount", ascending=False)) layout = html.Div([ html.Div( [ html.Div( [ dcc.Graph( id="expenses_chart", figure={ "data": [ go.Bar(x=df_monthly.index, y=df_monthly.amount * -1) ], "layout": go.Layout( xaxis={ "title": "Month", "tickmode": "array", "tickvals": df_monthly.index, "ticktext": df_monthly.index.to_series().apply( lambda x: calendar.month_name[x]), }, yaxis={"title": "Expenses $"}, margin={ "t": 10, "r": 10 }, dragmode="select", hovermode="closest", clickmode="event+select", ), }, ) ], className="col-sm border", ), html.Div( [ dcc.Graph( id="categories_chart", figure={ "data": [ go.Bar( x=df_cat.amount * -1, y=df_cat.index, orientation="h", ) ], "layout": go.Layout( xaxis={"title": "Expenses $"}, margin={ "t": 10, "r": 10 }, dragmode="select", hovermode="closest", clickmode="event+select", ), }, ) ], className="col-sm border", ), ], className="row", style={"width": "95%"}, ), html.Div( [ html.Div( [ dcc.Graph( id="sub_categories_chart", figure={ "data": [ go.Bar( x=df_subcat.amount * -1, y=df_subcat.index, orientation="h", ) ], "layout": go.Layout( xaxis={"title": "Expenses $"}, margin={ "t": 10, "r": 10 }, dragmode="select", hovermode="closest", clickmode="event+select", ), }, ) ], className="col-sm border", ), html.Div( [ dash_table.DataTable( id="transaction_table", data=df.sort_values("added_date").to_dict("rows"), columns=[ { "id": "id", "name": "Hash", "type": "text", "hidden": True, }, { "id": "date", "name": "Date", "type": "text" }, { "id": "narration", "name": "Narration", "type": "text", }, { "id": "amount", "name": "Amount", "type": "numeric", "format": FormatTemplate.money(2), }, ], style_cell={"padding": "5px"}, style_header={ "backgroundColor": "white", "fontWeight": "bold", }, page_size=10, sort_action="native", ) ], className="col-sm border", ), ], className="row", style={"width": "95%"}, ), ]) return layout
def create_dashboard(server): """Create a Plotly Dash dashboard.""" dash_app = dash.Dash( server=server, routes_pathname_prefix='/projects/covid-19-dashboards/', external_stylesheets=[ '/static/css/custom_dash.css', '/static/css/custom.css', '/static/css/bootstrap.min.css' ]) dash_app.index_string = html_layout colors = {'background': '#111111', 'text': '#111111'} #today = datetime.datetime.now().strftime('%d %B') #markdown_text = ''' #Update #''' dash_app.layout = html.Div([ dcc.Tabs( id="tabs-with-classes", #value='tab-2', parent_className='custom-tabs', className='custom-tabs-container', children=[ dcc.Tab( label='COVID-19 visualisation by country', #value='tab-1', className='custom-tab', selected_className='custom-tab--selected', children=[ html.Div( id='dash-container', children=[ # html.H2(children=''' # COVID-19 visualisation by country''', # style={'textAlign': 'center'}), dcc.Markdown('Updated {}'.format(df_max_date), style={ 'textAlign': 'center', 'font-weight': 'bold', 'font-family': 'system-ui', 'font-size': '16', 'margin-top': '10px' }), html.Div( id='covid-dropdown', children=[ html.Div( [ dcc.Dropdown( id='input-covid-dropdown', options=[{ 'label': i, 'value': i } for i in df.location. unique()], value='the World', style={ 'textAlign': 'center', 'verticalAlign': 'middle', 'margin-top': '5px', 'border-color': '#3f85f7', 'font-weight': 'bold' }) ], className='col-md-6 offset-md-3') ], className='row'), html.Div( id='graph-styles', children=[ html.Div([ dcc.Graph(id='output-covid-graph') ], className='col-sm-6'), html.Div([ dcc.Graph(id='output-covid-graph2') ], className='col-sm-6') ], className='row') ]) ]), dcc.Tab( label='COVID-19 cases by population percentage', #value='tab-1', className='custom-tab', selected_className='custom-tab--selected', children=[ html.Div( id='dash-container_tab2-main', children=[ html.Div([ dcc.Graph( id='output-covid-graph3', figure={ "data": [{ "x": df_table.sort_values( by= '% total cases to population', ascending=False)[:50] ["location"], "y": df_table.sort_values( by= '% total cases to population', ascending=False)[:50] ['% total cases to population'] * 100, "type": "bar", "name": "cases to pop (%)", "marker": { "color": '#3f85f7', 'font': dict(family='system-ui') } } #, # { # "x": df_table.sort_values(by='population',ascending=False)[:10]["location"], # "y": df_table['% total deaths to population'], # "type": "bar", # "name": "deaths to pop (%)" # #"marker": {"color": colors}, # } ], "layout": { "xaxis": { "automargin": True, 'tickfont': dict(family='system-ui', size=13) }, "yaxis": { "automargin": True }, # "title": 'column'}, "title": dict( text= "<b>Total Cases per Population (%)<br>(top 50 countries)</b>", font=dict( family='system-ui', size=16)), "legend": { "x": '0', 'y': '1.2' } # "height": 250, # "margin": {"t": 10, "l": 10, "r": 10}, } }) ]), html.Div([ dash_table.DataTable( id='datatable-row-ids', columns=[ #{"name": i, "id": i} for i in df_table.columns { 'id': 'Rank (total cases %)', #'name': 'Location', 'type': 'numeric', 'format': FormatTemplate.money(0).symbol( Symbol.no) }, { 'id': 'location', 'name': 'Location', 'type': 'text' }, { 'id': 'population', 'name': 'Population', 'type': 'numeric', 'format': FormatTemplate.money(0).symbol( Symbol.no) }, { 'id': 'total_cases', 'name': 'Total Cases', 'type': 'numeric', 'format': FormatTemplate.money(0).symbol( Symbol.no) }, { 'id': '% total cases to population', 'name': 'Cases per population (%)', 'type': 'numeric', 'format': FormatTemplate.percentage(4) }, { 'id': 'total_deaths', 'name': 'Total Deaths', 'type': 'numeric', 'format': FormatTemplate.money(0).symbol( Symbol.no) }, { 'id': '% total deaths to total cases', 'name': 'Death rate (%)', 'type': 'numeric', 'format': FormatTemplate.percentage(4) } ], data=df_table.sort_values( by='% total cases to population', ascending=False).to_dict( 'records'), style_table={ 'margin-top': '10px', 'overflowX': 'auto' }, style_data={ 'border': '1px solid white' }, style_data_conditional=[{ 'if': { 'row_index': 'odd' }, 'backgroundColor': 'rgb(248, 248, 248)' }], style_cell={ 'textAlign': 'center', 'minWidth': '50px', 'width': '50px', 'maxWidth': '50px', 'whiteSpace': 'normal', 'font-family': 'system-ui', 'font-size': 12 }, style_header={'fontWeight': 'bold'}, editable=True, # filter_action="native", sort_action="native", sort_mode="multi", column_selectable="single", # row_selectable="multi", # row_deletable=True, selected_columns=[], # selected_rows=[], page_action="native", page_current=0, page_size=10, ) ]) #close div id datatable-rows-id ]) #close div ]), #close tab2 dcc.Tab( label='COVID-19 death rate percentage', #value='tab-1', className='custom-tab', selected_className='custom-tab--selected', children=[ html.Div( id='dash-container_tab3-main', children=[ html.Div([ dcc.Graph( id='output-covid-graph4', figure={ "data": [{ "x": df_table.sort_values( by= '% total deaths to total cases', ascending=False)[:50] ["location"], "y": df_table.sort_values( by= '% total deaths to total cases', ascending=False)[:50] ['% total deaths to total cases'] * 100, "type": "bar", # "name": " (%)", "marker": { "color": '#3f85f7', 'font': dict(family='system-ui') } } #, ], "layout": { "xaxis": { "automargin": True, 'tickfont': dict(family='system-ui', size=13) }, "yaxis": { "automargin": True }, # "title": 'column'}, "title": dict( text= "<b>Death Rate (%)<br>(top 50 coutries)</b>", font=dict( family='system-ui', size=16)), # "legend": {"x":'0','y':'1.2'} # "height": 250, # "margin": {"t": 10, "l": 10, "r": 10}, } }) ]), html.Div([ dash_table.DataTable( id='datatable-row-ids2', columns=[ #{"name": i, "id": i} for i in df_table.columns { 'id': 'Rank (death rate %)', #'name': 'Location', 'type': 'numeric', 'format': FormatTemplate.money(0).symbol( Symbol.no) }, { 'id': 'location', 'name': 'Location', 'type': 'text' }, { 'id': 'population', 'name': 'Population', 'type': 'numeric', 'format': FormatTemplate.money(0).symbol( Symbol.no) }, { 'id': 'total_cases', 'name': 'Total Cases', 'type': 'numeric', 'format': FormatTemplate.money(0).symbol( Symbol.no) }, { 'id': '% total cases to population', 'name': 'Cases per population (%)', 'type': 'numeric', 'format': FormatTemplate.percentage(4) }, { 'id': 'total_deaths', 'name': 'Total Deaths', 'type': 'numeric', 'format': FormatTemplate.money(0).symbol( Symbol.no) }, { 'id': '% total deaths to total cases', 'name': 'Death rate (%)', 'type': 'numeric', 'format': FormatTemplate.percentage(4) } ], data=df_table.sort_values( by='% total deaths to total cases', ascending=False).to_dict( 'records'), style_table={ 'margin-top': '10px', 'overflowX': 'auto' }, style_data={ 'border': '1px solid white' }, style_data_conditional=[{ 'if': { 'row_index': 'odd' }, 'backgroundColor': 'rgb(248, 248, 248)' }], style_cell={ 'textAlign': 'center', 'minWidth': '50px', 'width': '50px', 'maxWidth': '50px', 'whiteSpace': 'normal', 'font-family': 'system-ui', 'font-size': 12 }, style_header={'fontWeight': 'bold'}, editable=True, # filter_action="native", sort_action="native", sort_mode="multi", column_selectable="single", # row_selectable="multi", # row_deletable=True, selected_columns=[], # selected_rows=[], page_action="native", page_current=0, page_size=10, ) ]) #close div id datatable-rows-id ]) ]) #close tab3 ]) #close Tabs ]) #close main div @dash_app.callback(Output('output-covid-graph', 'figure'), [Input('input-covid-dropdown', 'value')]) def update_value(input_data): dff = df[df['location'] == input_data] df_max_date = df[(df['date'] == df['date'].max())] total_cases_for_today = 1 return { 'data': [ dict(x=df[df['location'] == input_data]['date'], y=df[df['location'] == input_data]['total_cases'], type='line', fill='tozeroy', marker={'color': '#3f85f7'}, fillcolor='e7f4fa', text={'color': '#111111'}) ], 'layout': { 'title': dict(text=('<b>Total cases in ' + input_data + '<br>{}</b>').format( format( list(df[(df['date'] == df['date'].max()) & (df['location'] == input_data)] ['total_cases'])[0], ',d')), font=dict(family='system-ui', size=16)), #'plot_bgcolor': colors['background'], 'font': { 'color': colors['text'] } } } @dash_app.callback(Output('output-covid-graph2', 'figure'), [Input('input-covid-dropdown', 'value')]) def update_value(input_data): dff = df[df['location'] == input_data] return { 'data': [ dict( x=df[df['location'] == input_data]['date'], y=df[df['location'] == input_data]['new_cases'], type='bar', name='New Cases', marker={'color': '#3f85f7'} #, 'color:hover':'#111111'} wyp: ededed ), dict( x=df[df['location'] == input_data]['date'], y=df[df['location'] == input_data]['moving_average'], type='scatter', name='Mean', marker={'color': '#fa501f'} #, 'color:hover':'#111111'} wyp: ededed ) ], 'layout': { 'title': dict(text=('<b>Daily increase for ' + input_data + '<br>{}</b>').format( format( list(df[(df['date'] == df['date'].max()) & (df['location'] == input_data)] ['new_cases'])[0], ',d')), font=dict(family='system-ui', size=16)), #'plot_bgcolor': colors['background'], #'showlegend':False, 'legend': dict(orientation='h'), 'font': { 'color': colors['text'] }, } } @dash_app.callback( Output('datatable-interactivity', 'style_data_conditional'), [Input('datatable-interactivity', 'selected_columns')]) def update_styles(selected_columns): return [{ 'if': { 'column_id': i }, 'background_color': '#D2F3FF' } for i in selected_columns] return dash_app.server
def back_test(n_clicks, alpha, N, n, lot_size, start_cash, start_date, end_date): gc.collect() m = Model(alpha=alpha, N=N, n=n, lot_size=lot_size, start_cash=start_cash, start_date=start_date, end_date=end_date) df = pd.read_csv('data/IVV.csv') fig = go.Figure( data=[ go.Candlestick( x=df['Date'], open=df['Open'], high=df['High'], low=df['Low'], close=df['Close'] ) ] ) fig.update_layout(title="IVV Candlestick Plot") ledger, blotter, portfolio, final_msg = m.run_back_test() trade_ledger = ledger.to_dict('records') trade_ledger_columns = [ dict(id="ID", name="Trade ID"), dict(id="Date Created", name="Date Created"), dict(id="Date Closed", name="Date Closed"), dict(id="Position Type", name="Position Type"), dict(id="Entry Price", name="Entry Price", type='numeric', format=FormatTemplate.money(2)), dict(id="Exit Price", name="Exit Price", type='numeric', format=FormatTemplate.money(2)), dict(id="Benchmark Entry", name="Benchmark Entry", type='numeric', format=FormatTemplate.money(2)), dict(id="Benchmark Exit", name="Benchmark Exit", type='numeric', format=FormatTemplate.money(2)), dict(id="Return on Trade", name="Return on Trade", type='numeric', format=FormatTemplate.percentage(3)), dict(id="Benchmark Return", name="Benchmark Return", type='numeric', format=FormatTemplate.percentage(3)) ] trade_blotter = blotter.to_dict("records") trade_blotter_columns = [ dict(id="ID", name="Trade ID"), dict(id="Date Created", name="Date Created"), dict(id="Action", name="Action"), dict(id="Size", name="Size"), dict(id="Symbol", name="Symbol"), dict(id="Order 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="Fill/Cancelled Date", name="Fill/Cancelled Date") ] trade_portfolio = portfolio.to_dict("records") trade_portfolio_columns = [ dict(id="Date", name="Date"), dict(id="Cash", name="Available Cash", type='numeric', format=FormatTemplate.money(2)), dict(id="Num Shares", name="Number of Shares"), dict(id="Share total Value", name="Total Value of Shares", type='numeric', format=FormatTemplate.money(2)), dict(id="Total Port Value", name="Total Value", type='numeric', format=FormatTemplate.money(2)) ] clean_ledger = ledger.dropna() X = clean_ledger["Benchmark Return"].values.reshape(-1, 1) lin_reg = LinearRegression().fit(X, clean_ledger["Return on Trade"]) x_range = np.linspace(X.min(), X.max(), 100) y_range = lin_reg.predict(x_range.reshape(-1, 1)) fig2 = px.scatter( clean_ledger, title="Performance against Benchmark", x='Benchmark Return', y='Return on Trade', color="Position Type" ) fig2.add_traces(go.Scatter(x=x_range, y=y_range, name='OLS Fit')) alpha = str(round(lin_reg.intercept_ * 100, 3)) + "% / trade" beta = round(lin_reg.coef_[0], 3) gmrr = (clean_ledger['Return on Trade'] + 1).product() ** ( 1 / len(clean_ledger)) - 1 bench_gmr = (clean_ledger['Benchmark Return'] + 1).product() ** ( 1 / len(clean_ledger)) - 1 avg_trades_per_yr = round( clean_ledger['Date Created'].groupby( pd.DatetimeIndex(clean_ledger['Date Created']).year ).agg('count').mean(), 0 ) vol = stdev(clean_ledger['Return on Trade']) sharpe = round(gmrr / vol, 3) gmrr_str = str(round(gmrr, 3)) vol_str = str(round(vol, 3)) bal = start_cash for i in clean_ledger['Benchmark Return']: bal += lot_size * (1+i) final_msg += f" with GMMR {round(gmrr*100, 2)}%, Benchmark final balance ${round(bal, 2)} with GMMR {round(bench_gmr*100, 2)}%" return trade_blotter, trade_blotter_columns, trade_portfolio, trade_portfolio_columns, trade_ledger, trade_ledger_columns, fig, fig2, alpha, beta, gmrr_str, avg_trades_per_yr, vol_str, sharpe, final_msg
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
def get_table(df, ema, ticker): df.columns = [ 'Date', 'Portfolio Value ($USD)', 'Net Shares', 'Net Cash', 'Trade Signal', 'Pre-market P/L ($USD)', 'Trade Session P/L ($USD)', 'Total Day P/L ($USD)', 'Cumulative P/L ($USD)' ] df.drop(['Pre-market P/L ($USD)', 'Trade Session P/L ($USD)'], axis=1) # df["Date"] = df["Date"].apply(lambda x: x.date()) data = df.to_dict('rows') columns = [{ 'id': df.columns[0], 'name': 'Date', 'type': 'datetime' }, { 'id': df.columns[4], 'name': 'Trade Signal', 'type': 'text' }, { 'id': df.columns[1], 'name': 'Portfolio Value ($USD)', 'type': 'numeric', 'format': FormatTemplate.money(0) }, { 'id': df.columns[2], 'name': 'Net Shares', 'type': 'numeric', }, { 'id': df.columns[3], 'name': 'Net Cash', 'type': 'numeric', 'format': FormatTemplate.money(0) }, { 'id': df.columns[7], 'name': 'Daily P/L ($USD)', 'type': 'numeric', 'format': FormatTemplate.money(0) }, { 'id': df.columns[8], 'name': 'Cumulative P/L ($USD)', 'type': 'numeric', 'format': FormatTemplate.money(0) }] package = html.Div([ dbc.Col(html.H4(f'EMA {ema} Trade Log ({ticker})')), dbc.Col( dt.DataTable(data=data, columns=columns, id='table', fixed_rows={'headers': True}, style_table={'height': 350}, style_header={ 'fontWeight': 'bold', 'backgroundColor': 'black', 'color': 'white' }, style_cell_conditional=[{ 'if': { 'column_id': c }, 'textAlign': 'left' } for c in ['Date', 'Region']], style_data_conditional=[{ 'if': { 'row_index': 'odd' }, 'backgroundColor': 'rgb(248, 248, 248)' }], style_cell={ 'whiteSpace': 'normal', 'textAlign': 'left', 'height': 'auto' })) ]) return package
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
def render_page(capital, risk, num_strategies): data = CalculateDataService.load_data(capital, risk) sl = data['strategy'].unique() all_strategies = [] for s in sl: selected_trade = data[data.strategy == s].copy() selected_trade = selected_trade[selected_trade.oosis == 'oos'] CalculateDataService.calculate_values(selected_trade, False, capital, risk, True, False) strategy = pd.DataFrame() first_trade = selected_trade.iloc[1:2, :] strategy['name'] = first_trade['strategy'] strategy['symbol'] = first_trade['d1_symbol'] strategy['class'] = first_trade['strategy_type'] CalculateDataService.calculate_strategy_summary( strategy, first_trade, selected_trade) all_strategies.append(strategy) strategy_list = pd.concat(all_strategies) money = FormatTemplate.money(2) # percentage = FormatTemplate.percentage(2) columns = [ dict(id='name', name='Strategy'), #dict(id='enabled', name='Enabled'), dict(id='symbol', name='Symbol'), dict(id='class', name='Class'), dict(id='slippage', name='Slippage', type='numeric', format=money), dict(id='stop_loss', name='Stop Loss', type='numeric', format=money), #dict(id='oos_from', name='OOS From'), dict(id='profit', name='Profit', type='numeric', format=money), dict(id='max_dd', name='Max Drawdown', type='numeric', format=money), dict(id='np_maxdd', name='NP / Max DD', type='numeric'), dict(id='avg_dd', name='Avg Drawdown', type='numeric', format=money), dict(id='np_avg_dd', name='NP / Avg DD', type='numeric'), dict(id='num_trades', name='Trades', type='numeric'), dict(id='avg_trade', name='Avg Trade', type='numeric'), # dict(id='perc_profit', name='% Profitable', type='numeric', format=percentage), dict(id='worst_trade', name='Worst Trade', type='numeric', format=money), dict(id='worst_month', name='Worst Month', type='numeric', format=money), #dict(id='avg_loosing_month', name='Avg Loosing Month', type='numeric', format=money), dict(id='profit_1m', name='Profit 1 Month', type='numeric', format=money), dict(id='profit_3m', name='Profit 3 Month', type='numeric', format=money), dict(id='profit_6m', name='Profit 6 Month', type='numeric', format=money), dict(id='profit_9m', name='Profit 9 Month', type='numeric', format=money), dict(id='profit_1y', name='Profit 1 Year', type='numeric', format=money), ] layout = dash_table.DataTable( id='strategy_list_table', columns=columns, data=strategy_list.to_dict('records'), sort_action='native', row_selectable='multi', selected_rows=[], style_header={ 'backgroundColor': 'rgb(230, 230, 230)', 'fontWeight': 'bold' }, style_data_conditional=([{ 'if': { 'row_index': 'odd' }, 'backgroundColor': 'rgb(248, 248, 248)' }] + [{ 'if': { 'filter_query': '{enabled} < 1', }, 'backgroundColor': '#000000', 'color': 'yellow' }] + [{ 'if': { 'filter_query': '{profit_1m} <= 0', 'column_id': 'profit_1m' }, 'backgroundColor': '#FF4136', 'color': 'white' }] + [{ 'if': { 'filter_query': '{profit_1m} > 0', 'column_id': 'profit_1m' }, 'backgroundColor': '#3D9970', 'color': 'white' }] + [{ 'if': { 'filter_query': '{profit_6m} <= 0', 'column_id': 'profit_6m' }, 'backgroundColor': '#FF4136', 'color': 'white' }] + [{ 'if': { 'filter_query': '{profit_6m} > 0', 'column_id': 'profit_6m' }, 'backgroundColor': '#3D9970', 'color': 'white' }] + [{ 'if': { 'filter_query': '{profit_1y} <= 0', 'column_id': 'profit_1y' }, 'backgroundColor': '#FF4136', 'color': 'white' }] + [{ 'if': { 'filter_query': '{profit_1y} > 0', 'column_id': 'profit_1y' }, 'backgroundColor': '#3D9970', 'color': 'white' }] + [{ 'if': { 'filter_query': '{profit_3m} <= 0', 'column_id': 'profit_3m' }, 'backgroundColor': '#FF4136', 'color': 'white' }] + [{ 'if': { 'filter_query': '{profit_3m} > 0', 'column_id': 'profit_3m' }, 'backgroundColor': '#3D9970', 'color': 'white' }] + [{ 'if': { 'filter_query': '{profit_9m} <= 0', 'column_id': 'profit_9m' }, 'backgroundColor': '#FF4136', 'color': 'white' }] + [{ 'if': { 'filter_query': '{profit_9m} > 0', 'column_id': 'profit_9m' }, 'backgroundColor': '#3D9970', 'color': 'white' }])) div_modal = html.Div(id="div_modal", children=pasm.render_modal(pd.DataFrame(), False, True, capital, risk, num_strategies)) ret = html.Div([ dbc.Row([ dbc.Col(layout, width=12), ]), dbc.Row([ dbc.Col(dbc.Button( "Simulate Portfolio", id="open", color="primary"), width=12), ], style={'margin-top': '15px'}), div_modal # dbc.Row({ # dbc.Col(div_modal, width=12), # }) ]) return ret
========================================================================== Tables """ total_returns_table = html.Div([ dash_table.DataTable( id="total_returns", columns=[{ "id": "Year", "name": "Year", "type": "text" }] + [{ "id": col, "name": col, "type": "numeric", "format": FormatTemplate.money(0), } for col in ["Cash", "Bonds", "Stocks", "Total"]], style_table={ "overflowY": "scroll", "border": "thin lightgrey solid", "maxHeight": "425px", }, style_cell={ "textAlign": "right", "font-family": "arial" }, style_cell_conditional=[{ "if": { "column_id": "Year" }, "type": "text"
def make_table(dff): dff = dff.groupby(["State"]).sum().reset_index() dff["sparkline"] = du.make_sparkline(dff, "Per Capita", du.YEARS) dff = table_yr(dff, du.START_YR) return html.Div( [ dash_table.DataTable( id="table", columns=[ { "id": "State", "name": [" ", "State"], "type": "text" }, { "id": "Category", "name": [" ", "Category"], "type": "text" }, { "id": "Description", "name": [" ", "Sub Category"], "type": "text", }, # {"id": "State/Local", "name": [' ', "State or Local" ] , "type": "text"}, { "id": "Amount", "name": [ " ", "Total Amount", ], "type": "numeric", "format": FormatTemplate.money(0), }, { "id": "Per Capita", "name": [" ", "Per Capita"], "type": "numeric", "format": FormatTemplate.money(0), }, { "id": "sparkline", "name": ["Per Capita", "2012-2017"], "type": "numeric", "format": FormatTemplate.money(0), }, ], merge_duplicate_headers=True, data=dff.to_dict("records"), # filter_action='native', sort_action="native", # sort_mode="multi", default is "single" export_format="xlsx", export_headers="display", is_focused=False, cell_selectable=False, style_table={ "overflowY": "scroll", "border": "thin lightgrey solid", "maxHeight": "425px", }, style_cell={ "textAlign": "left", "font-family": "arial", "font-size": "14px", }, style_cell_conditional=[{ "if": { "column_id": c }, "textAlign": "right" } for c in ["Per Capita", "Amount"]], style_data_conditional=[ { "if": { "column_id": "sparkline" }, "width": 100, "font-family": "Sparks-Bar-Extrawide", "font-size": "18px", "padding-right": "15px", "padding-left": "15px", }, ], ) ], # className="mb-2", )