Bring Drag & Drop to Dash with Dashboard Engine. 💫 Learn how at our next webinar!

How to highlight cell containing the maximum value. My code is not highlighting the maximum value

-- coding: utf-8 --

“”"
Created on Tue Oct 26 22:21:35 2021

@author: Kamlesh Parihar

“”"

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import dash_table.FormatTemplate as FormatTemplate
from dash_table.Format import Format, Group, Prefix, Scheme, Symbol
import plotly.graph_objects as go
import pandas as pd
import numpy as np
from datetime import datetime
from maxdqv import mdp, mdq, sn, mtv,hd,mdb
from plotly.subplots import make_subplots

from plotly import plotly

pip install chart_studio.plotly

import dash_table
import plotly.express as px

print(“FILTERING STOCKS HAVING MAXIMUM DELIVERY BY PERCENTAGE, QUANTITY, VOLUME AND HIGH DELIVERY”)

print(“STEP ONE STARTED.\n\nFILTERING STOCKS HAVING MAXIMUM DELIVERY BY PERCENTAGE, QUANTITY, VOLUME AND HIGH DELIVERY\n\n”)
MDP=mdp()
MDQ=mdq()
MTV=mtv()
HD=hd()
MDPB=mdb(69.9,99)
N5001=pd.read_excel(“D:\to be deleted 6 October 2019\Share Market\Historical Data\Open Interest Sheet\Bhavcopy Data NIFTY500\NIFTY 500.xlsx”,“NIFTY 500”)
N5002=N5001[‘Symbol’].values.flatten().tolist()
List=[‘MDP1’,‘MDQ1’,‘MTV1’,‘HD1’,‘MDPB1’,‘N500’]

df4=sn(‘HDFCBANK’,31)
df4[‘DATE’]=df4[‘DATE’].astype(‘datetime64[ns]’)
df4[‘DATE’]=df4[‘DATE’].dt.strftime(’%d-%b-%y’)
maxdelivper=df4[‘DELIV_PER’].max()

dflist=pd.DataFrame(List,columns=[‘List’])
dfmdp=pd.DataFrame(MDP,columns=[‘MDP1’])
dfmdq=pd.DataFrame(MDQ,columns=[‘MDQ1’])
dfmtv=pd.DataFrame(MTV,columns=[‘MTV1’])
dfhd=pd.DataFrame(HD,columns=[‘HD1’])
dmdpb=pd.DataFrame(MDPB,columns=[‘MDPB1’])
N500=pd.DataFrame(N5002,columns=[‘N500’])
consdf=pd.concat([dfmdp,dfmdq,dfmtv,dfhd,dmdpb,N500],axis=1)

print(“READING FUTURES DATA FROM EXCEL FILE”)

print(“STEP TWO STARTED. \n\nREADING FUTURES DATA FROM EXCEL FILE.\n\n”)

df1=pd.read_excel(“D:\to be deleted 6 October 2019\Share Market\Historical Data\Open Interest Sheet\FUTURES_OI_OCT21.xlsx”,sheet_name=‘OI CHANGE SHEET’)
df1=df1[[‘Serial No’,‘SYMBOL’,‘LTP’,’% PRICE CHANGE’,‘Change in OI %’,‘LAST TRADING DAY BUILDUP’]]
dfbldup1=pd.read_excel(“D:\to be deleted 6 October 2019\Share Market\Historical Data\Open Interest Sheet\FUTURES_OI_OCT21.xlsx”,sheet_name=‘OIBUILDUP’)
dfoicrm=pd.read_excel(“D:\to be deleted 6 October 2019\Share Market\Historical Data\Open Interest Sheet\FUTURES_OI_OCT21.xlsx”,sheet_name=‘OICHANGECRM’)
dfbldup=pd.concat([dfbldup1,dfoicrm])
dfbldup=dfbldup.sort_values(by=[‘Serial No’], ascending=True)
dfsector=pd.read_excel(“D:\to be deleted 6 October 2019\Share Market\Historical Data\Open Interest Sheet\Bhavcopy Data NIFTY500\NIFTY 500.xlsx”,“Nifty500withSectors”)

print(“STEP THREE STARTED.\n\nFILTERING STOCKS HAVING MAXIMUM DELIVERY BY PERCENTAGE, QUANTITY, VOLUME AND HIGH DELIVERY\n\n”)

print(“STEP THREE STARTED.\n\nFILTERING STOCKS HAVING MAXIMUM DELIVERY BY PERCENTAGE, QUANTITY, VOLUME AND HIGH DELIVERY\n\n”)

#============================================================================================================================================

app = dash.Dash(name)

colors = {
‘background’: ‘Black’,
‘text’: ‘#7FDBFF
}

app.layout =html.Div([ # Creates HEADING 1
html.H1(children = ‘STOCK ANALYSIS (NIFTY 500 STOCKS)’,
style = {
‘backgroundColor’:‘Aqua’,
‘textAlign’ : ‘center’,
‘color’ : ‘#456FBV’,
‘marginBottom’: ‘0.01em’
},),

Creates HEADING 2

print("STEP FOUR STARTED.\n\n"),    
html.Div(id="StockDetails", children= "Kamlesh Parihar Creation",
         style = {
             'backgroundColor':'Aqua',
            'textAlign' : 'center',
            'color' : '#456FBV' ,
             'fontSize': 22,
             'fontWeight': 'bold',
             'marginBottom': '0.3em'
         }),  

#============================================================================================================================================
# print(“STEP FOUR STARTED.\n\n”),
html.Div(children= “SELECTION CRITERIA”,
style = {
‘textAlign’ : ‘left’,
‘color’ : ‘#456FBV’,
‘fontSize’: 22,
‘fontWeight’: ‘bold’,
‘marginBottom’: ‘0.3em’,
# ‘backgroundColor’:‘LightSkyBlue’

         }),  



dcc.RadioItems(id ='radio',
               options=[ {'label': x, 'value' : x } for x in (dflist.List.unique())],
               value=dflist['List'].values[0],
                style = {
            'textAlign' : 'left',
            'color' : '#456FBV',
             'fontSize': 18,
             'fontWeight': 'bold',
              # 'backgroundColor':'LightSkyBlue' ,
         }), 

 html.Br(),

#============================================================================================================================================
html.Div(children= “SELECT A STOCK”,
style = {
‘textAlign’ : ‘left’,
‘color’ : ‘#456FBV’,
‘fontSize’: 18,
‘fontWeight’: ‘bold’ ,
# ‘backgroundColor’:‘LightSkyBlue’
}),
#============================================================================================================================================
dcc.Dropdown(id=‘stocks’, options=, #{‘label’:‘HDFCBANK’,‘value’:‘HDFCBANK’}
placeholder=‘SELECT STOCK NAME’,
searchable=True,
style={‘width’:‘40%’,
‘fontSize’: 16,
‘fontWeight’: ‘bold’ },
),
#============================================================================================================================================
html.H1(id=‘charttitle’, children = ‘HDFCBANK CHART’,
style = {
‘textAlign’ : ‘center’,
‘color’ : ‘#456FBV’,
# ‘background’:‘Aquamarine’,
‘marginBottom’: ‘0.05em’,
},),
html.Div(id=‘stock_sector_details1’,children= “(FINANCIAL_SERVICES_PRI/Banks_Private_Sector_Sec/Large Cap)”,
style = {
‘textAlign’ : ‘center’,
‘color’ : ‘#456FBV’,
‘fontSize’: 22,
‘fontWeight’: ‘bold’,
# ‘background’:‘Aquamarine’,
‘marginBottom’: ‘0.3em’,

         }), 

#============================================================================================================================================
dcc.Graph(id=“graph”),
#============================================================================================================================================
html.H1(id=‘stockheadingontable’, children = ‘HDFCBANK’,
style = {
‘textAlign’ : ‘center’,
‘color’ : ‘#456FBV
},),

html.Div(id=‘stock_sector_details2’,children= “(FINANCIAL_SERVICES_PRI/Banks_Private_Sector_Sec/Large Cap)”,
style = {
‘textAlign’ : ‘center’,
‘color’ : ‘#456FBV’,
‘fontSize’: 22,
‘fontWeight’: ‘bold’

         }),       

#============================================================================================================================================
dash_table.DataTable(
id=‘STOCK_LAST_30_DAYS_DATA’,
columns=[{“name”: “S_NO”, “id”: “S_NO”, “deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “DATE”, “id”: “DATE”,“deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “SYMBOL”, “id”: “SYMBOL”,“deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “DELIV_PER”, “id”: “DELIV_PER”,“type”: “numeric”,“format”: Format().symbol(Symbol.yes).symbol_suffix(" %"),‘whiteSpace’: ‘normal’,“deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “DELIV_QTY”, “id”: “DELIV_QTY”,“type”: “numeric”,“format”: Format().group(Group.yes).groups([3, 2,2,2,2,2]),‘whiteSpace’: ‘normal’,“deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “TTL_TRD_QNTY”, “id”: “TTL_TRD_QNTY”,“type”: “numeric”,“format”: Format().group(Group.yes).groups([3, 2,2,2,2,2]),“deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “TPrice_Change”, “id”: “TPrice_Change”,“type”: “numeric”,“format”: Format().symbol(Symbol.yes).symbol_suffix(" %"), “deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “CLOSE_PRICE”, “id”: “CLOSE_PRICE”,“type”: “numeric”,“format”: Format().group(Group.yes).groups([3, 2,2,2,2,2]),“deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “OPEN_PRICE”, “id”: “OPEN_PRICE”,“type”: “numeric”,“format”: Format().group(Group.yes).groups([3, 2,2,2,2,2]),“deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “LOW_PRICE”, “id”: “LOW_PRICE”,“type”: “numeric”,“format”: Format().group(Group.yes).groups([3, 2,2,2,2,2]),“deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “HIGH_PRICE”, “id”: “HIGH_PRICE”,“type”: “numeric”,“format”: Format().group(Group.yes).groups([3, 2,2,2,2,2]),“deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “TURNOVER_LACS”, “id”: “TURNOVER_LACS”,“type”: “numeric”,“format”: Format().group(Group.yes).groups([3, 2,2,2,2,2]),“deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “NO_OF_TRADES”, “id”: “NO_OF_TRADES”,“type”: “numeric”,“format”: Format().group(Group.yes).groups([3, 2,2,2,2,2]),“deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “NPrice_Change”, “id”: “NPrice_Change”, “type”: “numeric”,“format”: Format().symbol(Symbol.yes).symbol_suffix(" %"),“deletable”: False, “selectable”: False, “hideable”: True},

        # if i == "S_NO" or i == "SYMBOL" or i == "DATE" or i == "DELIV_PER" or i == "DELIV_QTY" or i == "TPrice_Change" or i == "NPrice_Change" or i == "LOW_PRICE" or i == "OPEN_PRICE" or i == "CLOSE_PRICE" or i == "HIGH_PRICE" or i == "TTL_TRD_QNTY" or i == "NO_OF_TRADES" or i == "TURNOVER_LACS"
        # else {"name": i, "id": i, "deletable": False, "selectable": False}
        # for i in df4.columns 
       
        
    ],
    data=df4.to_dict('records'),  # the contents of the table
    editable=False,              # allow editing of data inside all cells
    filter_action="native",     # allow filtering of data by user ('native') or not ('none')
    sort_action="native",       # enables data to be sorted per-column by user or not ('none')
    sort_mode="single",         # sort across 'multi' or 'single' columns
    column_selectable="single",  # allow users to select 'multi' or 'single' columns
    row_selectable="single",     # allow users to select 'multi' or 'single' rows
    row_deletable=False,         # choose if user can delete a row (True) or not (False)
    selected_columns=[],        # ids of columns that user selects
    selected_rows=[],           # indices of rows that user selects
    page_action="native",       # all data is passed to the table up-front or not ('none')
    page_current=0,             # page number that user is on
    page_size=31,                # number of rows visible per page
    style_cell={                # ensure adequate header width when text is shorter than cell's text
        'minWidth': 'auto', 'maxWidth': 'auto', 'width': 'auto', 'whitespace':'normal','fontSize':16, 'font-family':'sans-serif'#, 'fontWeight': 'bold'
    },
    style_table={'height': '600px', 'overflowY': 'scroll','width':'2250px','overflowX': 'auto'}, #auto or scroll
    style_cell_conditional=(
        [ {  
            'if': {'column_id': c},
            'textAlign': 'center'  # align text columns to left. By default they are aligned to right
        } for c in df4.columns
        ] 
        +
        [{
        'if': {
        #     # 'filter_query': '{{DELIV_PER}} = {}'.format(df4['DELIV_PER'].max()),
        #     # 'filter_query': '{DELIV_PER}} = 50',
            'filter_query':'{DELIV_PER} = maxdelivper',
            'column_id' : 'DELIV_PER',
        },
        'backgroundColor': 'Lime',
        'color': 'Red'
        }]
        ),  
            
    style_data={                # overflow cells' content into multiple lines
        'whiteSpace': 'normal',
        'height': 'auto'
                },
    
    fixed_rows={ 'headers': True, 'data': 2 },
    style_data_conditional=([
        {
        'if': {'row_index': 'odd'},
        'backgroundColor': 'rgb(220, 220, 220)',
        }]+
        [
    {
        'if': {
            'filter_query': '{DATE} contains "NA"'
        },
        'backgroundColor': '#0074D9',
        'color': 'white'
    }
]
# +
#     [{
#         'if':{'column_id':'TURNOVER_LACS'}
#                     "format": Format()  
#                     .symbol_prefix("$")
#                     .symbol(Symbol.yes)
#                     .symbol_suffix(" CAD")
#                     .group(Group.yes),
        
#     }],
        
        
# +
# [{
#         'if': {
#             'row_index': 0,  # number | 'odd' | 'even'
#         },
#         'backgroundColor': 'hotpink',
#         'color': 'Black'
            
#             }]
),
    
     style_header={            
    'border': 'thin lightgrey solid',
    'backgroundColor': 'Aqua',
    'fontWeight': 'bold'
                },),

#============================================================================================================================================
html.H1(id=‘stockheadingontable2’, children = ‘FUTURES OPEN INTEREST BUILDUP OF CURRENT MONTH’,
style = {
‘textAlign’ : ‘center’,
‘color’ : ‘#456FBV’ ,
‘marginBottom’: ‘0.05em’,
‘background’ :’#ffaa80
},),
#============================================================================================================================================
dash_table.DataTable(
id=‘OIBUILDUP’,
columns=[
{“name”: i, “id”: i, “deletable”: False, “selectable”: False, “hideable”: True}
for i in dfbldup.columns
],
data=dfbldup.to_dict(‘records’), # the contents of the table
editable=False, # allow editing of data inside all cells
filter_action=“native”, # allow filtering of data by user (‘native’) or not (‘none’)
sort_action=“native”, # enables data to be sorted per-column by user or not (‘none’)
sort_mode=“single”, # sort across ‘multi’ or ‘single’ columns
column_selectable=“single”, # allow users to select ‘multi’ or ‘single’ columns
row_selectable=“single”, # allow users to select ‘multi’ or ‘single’ rows
row_deletable=False, # choose if user can delete a row (True) or not (False)
selected_columns=, # ids of columns that user selects
selected_rows=, # indices of rows that user selects
page_action=“native”, # all data is passed to the table up-front or not (‘none’)
page_current=0, # page number that user is on
page_size=31, # number of rows visible per page
style_cell={ # ensure adequate header width when text is shorter than cell’s text
‘minWidth’: ‘100px’, ‘maxWidth’: ‘100px’, ‘width’: ‘100px’, ‘whitespace’:‘normal’, ‘fontSize’:14, ‘font-family’:‘sans-serif’
},
style_table={‘height’: ‘600px’, ‘overflowY’: ‘scroll’,‘width’:‘auto’,‘overflowX’: ‘scroll’}, #auto or scroll
style_cell_conditional=(
[ # align text columns to CENTER. By default they are aligned to right
{
‘if’: {‘column_id’: c},
‘textAlign’: ‘center’
} for c in dfbldup.columns
]),

    style_data={                # overflow cells' content into multiple lines
        'whiteSpace': 'normal',
        'height': 'auto'
                },
    
    fixed_rows={ 'headers': True, 'data': 2 },
    
    style_data_conditional=(
        [{
        'if': {'row_index': 'odd'},
        'backgroundColor': 'rgb(220, 220, 220)',
        }]+
        
        [{
            'if': {
                'filter_query': '{{{col}}} = "LONG-BUILDUP"'.format(col=col),
                'column_id': col
            },
            'backgroundColor': 'Lime',
            'color': 'Black'
        } for col in dfbldup.columns            
        ] +
        
       [{                     
            'if': {
                'filter_query': '{{{col}}} = "SHORT-COVERING"'.format(col=col),
                'column_id': col
            },
            'backgroundColor': 'LightGreen',
            'color': 'Black'
        } for col in dfbldup.columns            
        ] +           
        [{          
            'if': {
                'filter_query': '{{{col}}} = "SHORT-BUILDUP"'.format(col=col),
                'column_id': col
            },
            'backgroundColor': 'OrangeRed',
            'color': 'Black'
        } for col in dfbldup.columns            
        ] +                         
        [{          
        
            'if': {
                'filter_query': '{{{col}}} = "LONG-UNWINDING"'.format(col=col),
                'column_id': col
            },
            'backgroundColor': 'LightPink',
            'color': 'Black'
        } for col in dfbldup.columns            
        ]),
    
     style_header={            
    'border': 'thin lightgrey solid',
    'backgroundColor': 'Aqua',
    'fontWeight': 'bold'
                },),

  html.H1(id='stockheadingontable1', children = 'LAST TRADING DAY FUTURE OI BUILDUP',
        style = {
            'textAlign' : 'center',
            'color' : '#456FBV',
            'marginBottom': '0.05em', 
            'background' :'#ffaa80'
        },),

#============================================================================================================================================

“”“FUTUTRE OI TABLE STARTS FROM HERE “”” “”“FUTUTRE OI TABLE STARTS FROM HERE “”” “”“FUTUTRE OI TABLE STARTS FROM HERE “”” “”“FUTUTRE OI TABLE STARTS FROM HERE “””

dash_table.DataTable(
    id='DAILY_FUT_OI_DATA',
    columns=[
        {"name": i, "id": i, "deletable": False, "selectable": False, "hideable":True}
        if i == "Serial No" or i == "SYMBOL" or i == "LTP" or i == "% PRICE CHANGE" or i == "Change in OI  %" or i == "BUILDUP"
        else {"name": i, "id": i, "deletable": False, "selectable": False}
        for i in df1.columns
        
    ],
    data=df1.to_dict('records'),  # the contents of the table
    editable=False,              # allow editing of data inside all cells
    filter_action="native",     # allow filtering of data by user ('native') or not ('none')
    sort_action="native",       # enables data to be sorted per-column by user or not ('none')
    sort_mode="single",         # sort across 'multi' or 'single' columns
    column_selectable="single",  # allow users to select 'multi' or 'single' columns
    row_selectable="single",     # allow users to select 'multi' or 'single' rows
    row_deletable=False,         # choose if user can delete a row (True) or not (False)
    selected_columns=[],        # ids of columns that user selects
    selected_rows=[],           # indices of rows that user selects
    page_action="native",       # all data is passed to the table up-front or not ('none')
    page_current=0,             # page number that user is on
    page_size=190,                # number of rows visible per page
    style_cell={                # ensure adequate header width when text is shorter than cell's text
        'minWidth': 'auto', 'maxWidth': 'auto', 'width': 'auto', 'whitespace':'normal','fontSize':14, 'font-family':'sans-serif'
    },
    style_table={'height': '600px', 'overflowY': 'scroll','width':'900px','overflowX': 'scroll'}, #auto or scroll
    fixed_rows={ 'headers': True, 'data': 1 },
    
    style_cell_conditional=([    # align text columns to left. By default they are aligned to right
        {
            'if': {'column_id': c},
            'textAlign': 'center'
        } for c in df1.columns
    ]),
    
    style_data={                # overflow cells' content into multiple lines
        'whiteSpace': 'normal',
        'height': 'auto' 
    },
    
     style_data_conditional=([
    {
        'if': {'row_index': 'odd'},
        'backgroundColor': 'rgb(220, 220, 220)',
    }  ] +
        [{
            'if': {
                'filter_query': '{{Change in OI  %}} = {}'.format(i),
                'column_id': 'Change in OI  %',
            },
            'backgroundColor': 'Lime',
            'color': 'Black'
        }
        for i in df1['Change in OI  %'].nlargest(5)
    ] +
    [{
            'if': {
                'filter_query': '{{Change in OI  %}} = {}'.format(i),
                'column_id': 'Change in OI  %',
            },
            'backgroundColor': 'OrangeRed',
            'color': 'Black'
        }
        for i in df1['Change in OI  %'].nsmallest(5)
    ] +
         
         [{
            'if': {
                'filter_query': '{{{col}}} = "LONG-BUILDUP"'.format(col=col),
                'column_id': col
            },
            'backgroundColor': 'Lime',
            'color': 'Black'
        } for col in df1[['LAST TRADING DAY BUILDUP']].columns
        ] +             
         [{
            'if': {
                'filter_query': '{{{col}}} = "SHORT-COVERING"'.format(col=col),
                'column_id': col
            },
            'backgroundColor': 'LightGreen',
            'color': 'Black'
        } for col in df1[['LAST TRADING DAY BUILDUP']].columns
        ] + 
         
        [{                
            'if': {
                'filter_query': '{{{col}}} = "SHORT-BUILDUP"'.format(col=col),
                'column_id': col
            },
            'backgroundColor': 'OrangeRed',
            'color': 'Black'
        } for col in df1[['LAST TRADING DAY BUILDUP']].columns
        ] + 
        
        [{               
            'if': {
                'filter_query': '{{{col}}} = "LONG-UNWINDING"'.format(col=col),
                'column_id': col
            },
            'backgroundColor': 'LightPink',
            'color': 'Black'
        } for col in df1[['LAST TRADING DAY BUILDUP']].columns
        ]),
    
    style_header={
    'backgroundColor': 'Aqua',
    'fontWeight': 'bold'
                },),        

])
#============================================================================================================================================
@app.callback(
dash.dependencies.Output(‘stocks’, ‘options’),
dash.dependencies.Input(‘radio’, ‘value’))
def dropdown_options(listvalues):
return [{‘label’: c, ‘value’: c} for c in consdf[listvalues]]
#============================================================================================================================================
@app.callback(
dash.dependencies.Output(“graph”, “figure”),

dash.dependencies.Output(“graph”, “figure”)],

dash.dependencies.Input("stocks", "value"))

def display_candlestick(value):
print(value)
df=sn(value,87)
df=df.sort_values(by=‘S_NO’,ascending=True,ignore_index=True)
startdt,enddt = [df.iat[0,2],df.iat[-1,2]]
ddf1=df.set_index(‘DATE’) # SETS DATE AS INDEX
ddf1.index = pd.to_datetime(ddf1.index) # CONVERTS INDEX INTO DATE TIME OBJECT
missingdate=pd.date_range(start=startdt, end=enddt).difference(ddf1.index)
missingdate=missingdate.tolist()
for i in range(0,len(missingdate)):
missingdate[i]=missingdate[i].strftime(’%Y-%m-%d’)
df[‘9ema’]=df.CLOSE_PRICE.ewm(span=9, adjust=False).mean().round(2)
df[‘20ema’]=df.CLOSE_PRICE.ewm(span=20, adjust=False).mean().round(2)
# df[‘50sma’]=df.CLOSE_PRICE.rolling(window=50).mean().round(2)
# df[‘100sma’]=df.CLOSE_PRICE.rolling(window=100).mean().round(2)
# df[‘200sma’]=df.CLOSE_PRICE.rolling(window=200).mean().round(2)
df[‘20volsma’]=df.TTL_TRD_QNTY.rolling(window=20).mean().round(2) # moving average on volume
# print(df)
df=df.drop(columns=[‘SYMBOL’,‘S_NO’, ‘DELIV_PER’, ‘DELIV_QTY’,‘NPrice_Change’,‘NO_OF_TRADES’, ‘TURNOVER_LACS’])
print("\n\n\n\nDF after dropping column",df)
fig = make_subplots(rows=2, cols=1, shared_yaxes=(True),vertical_spacing=0.03,row_heights=(1.5,0.5))
fig.add_trace(go.Candlestick(
x=df[‘DATE’],
open=df[‘OPEN_PRICE’],
high=df[‘HIGH_PRICE’],
low=df[‘LOW_PRICE’],
close=df[‘CLOSE_PRICE’]), row=1,col=1)
print(“step1\n”)
fig.update_layout(height=750) # Sets the height of whole figure
df[“Color”] = np.where(df[“TPrice_Change”]<0, ‘OrangeRed’, ‘Lime’)
fig.add_trace(go.Bar( x=df[‘DATE’], y=df[‘TTL_TRD_QNTY’],marker_color=df[‘Color’]), row=2,col=1)
fig.add_trace(go.Scatter( x=df[‘DATE’], y=df[‘9ema’],mode=“lines”,name=“9EMA”,line=dict(color=‘Lime’, width=2)), row=1,col=1,)
fig.add_trace(go.Scatter( x=df[‘DATE’], y=df[‘20ema’],mode=“lines”,name=“20EMA”,line=dict(color=‘OrangeRed’, width=2)), row=1,col=1,)
fig.add_trace(go.Scatter( x=df[‘DATE’], y=df[‘20volsma’],mode=“lines”,name=“Vol.Avg”,line=dict(color=‘royalblue’, width=2)), row=2,col=1,)# mode=‘lines’, name=“vol average”)
# fig.update_traces(mode=“lines”)
# fig.add_trace(go.Scatter( x=df[‘DATE’], y=df[‘50sma’]), row=1,col=1,)
# fig.add_trace(go.Scatter( x=df[‘DATE’], y=df[‘100sma’]), row=1,col=1,)
# fig.add_trace(go.Scatter( x=df[‘DATE’], y=df[‘200sma’]), row=1,col=1,)

fig.update_xaxes(
rangebreaks=[
  
    dict(values=missingdate)
   
    # dict(bounds=["fri", "mon"]), #hide weekends
    # dict(values=["2021-10-09", "2021-10-10","2021-10-11"])  # hide Christmas and New Year's
])
 
fig.update_yaxes(side="right")
fig.update_layout(xaxis_rangeslider_visible=False)
# plot(fig)
print("Step2\n")
return fig

#============================================================================================================================================
@app.callback(
dash.dependencies.Output(“STOCK_LAST_30_DAYS_DATA”, “data”),

dash.dependencies.Output(“graph”, “figure”)],

dash.dependencies.Input("stocks", "value"))

def display_table(value):
df4=sn(value,30)
df4[‘DATE’]=df4[‘DATE’].astype(‘datetime64[ns]’)
df4[‘DATE’]=df4[‘DATE’].dt.strftime(’%d-%b-%y’)
df4[‘TURNOVER_LACS’]= df4[‘TURNOVER_LACS’].round(0)
df4[‘DELIV_PER’]= df4[‘DELIV_PER’].round(0)
df4[‘TPrice_Change’]= df4[‘TPrice_Change’].round(1)
df4[‘NPrice_Change’]= df4[‘TPrice_Change’].round(1)
df4[‘LOW_PRICE’]= df4[‘LOW_PRICE’].round(1)
df4[‘OPEN_PRICE’]= df4[‘OPEN_PRICE’].round(1)
df4[‘CLOSE_PRICE’]= df4[‘CLOSE_PRICE’].round(1)
df4[‘HIGH_PRICE’]= df4[‘HIGH_PRICE’].round(1)
d1=round(df4.DELIV_PER.mean(),0)
d11=round(df4.DELIV_QTY.mean(),0)
d2=round(df4.TTL_TRD_QNTY.mean(),0)
d3=round(df4.NO_OF_TRADES.mean(),0)
d4=round(df4.TURNOVER_LACS.mean(),0)
data ={
‘S_NO’:‘NA’,
‘SYMBOL’ : ‘NA’,
‘DATE’:‘NA’,
‘DELIV_PER’ : d1,
‘DELIV_QTY’ : d11,
‘TPrice_Change’: ‘NA’,
‘NPrice_Change’: ‘NA’,
‘LOW_PRICE’: ‘NA’,
‘OPEN_PRICE’: ‘NA’,
‘CLOSE_PRICE’: ‘NA’,
‘HIGH_PRICE’: ‘NA’,
‘TTL_TRD_QNTY’:d2,
‘NO_OF_TRADES’:d3,
‘TURNOVER_LACS’:d4,
}
maxdelivper=str(df4[‘DELIV_PER’].max())
print(maxdelivper)
type(maxdelivper)
df11=pd.DataFrame(data,index=[31])
df4=pd.concat([df11,df4])
# df4
print(“table is retrievable1”)
# df4.info()
data=df4.to_dict(‘records’)
# data
print(“table is retrievable2”)
return data
#============================================================================================================================================
@app.callback(
[dash.dependencies.Output(“charttitle”, “children”),
dash.dependencies.Output(“stock_sector_details1”, “children”),
dash.dependencies.Output(“stockheadingontable”, “children”),
dash.dependencies.Output(“stock_sector_details2”, “children”),],

dash.dependencies.Output(“graph”, “figure”)],

[dash.dependencies.Input("stocks", "value")])

def display_table(value):
value1=value
dfsec=dfsector.loc[(dfsector[‘SYMBOL’] == value1)]
children=value
children1=" (" + dfsec.iat[0,1]+"/ “+” /" + dfsec.iat[0,2]+"/ “+” /" + dfsec.iat[0,3]+ “/ “+” /” + dfsec.iat[0,4]+") "
return children,children1, children,children1
#============================================================================================================================================

if name == ‘main’:
app.run_server()
# app.run_server(debug=True, use_reloader=False)

Hi,

In the documentation on conditional styling, there is a section named Highlighting the maximum value in the table with an example. Here’s the function that it uses to generate the style_data_conditional :

def style_table_by_max_value(df):
    if 'id' in df:
        numeric_columns = df.select_dtypes('number').drop(['id'], axis=1)
    else:
        numeric_columns = df.select_dtypes('number')
    max_across_numeric_columns = numeric_columns.max()
    max_across_table = max_across_numeric_columns.max()
    styles = []
    for col in max_across_numeric_columns.keys():
        if max_across_numeric_columns[col] == max_across_table:
            styles.append({
                'if': {
                    'filter_query': '{{{col}}} = {value}'.format(
                        col=col, value=max_across_table
                    ),
                    'column_id': col
                },
                'backgroundColor': '#39CCCC',
                'color': 'white'
            })
    return styles

If you want the maximum per column, just replace the for loop to iterate over keys and values and remove the conditional under it.

Thanku Sir for your prompt reply its done now. The code I used is

[
{
‘if’: {
‘column_id’: ‘DELIV_PER’,
‘filter_query’: ‘{{DELIV_PER}} = {}’.format(df4[‘DELIV_PER’].max())
},
‘backgroundColor’: ‘#85144b’,
‘color’: ‘white’
},])

But since my table is changing as per the dropdown values, the conditional formatting is not working on modified table. I have written a callback to update the style_conditional_data , the callback is triggering , but its not returning the values.
The code is below. Can you please help.

@app.callback(
dash.dependencies.Output(“STOCK_LAST_30_DAYS_DATA”, “style_data_conditional”),
dash.dependencies.Input(“stocks”, “value”))
def style_data_conditional1(value):
print(“This is working”)
return ([
{
‘if’: {
‘column_id’: ‘DELIV_PER’,
‘filter_query’: ‘{{DELIV_PER}} = {}’.format(df4[‘DELIV_PER’].max())
},
‘backgroundColor’: ‘#85144b’,
‘color’: ‘white’
},
])

Could you try to remove the parenthesis enclosing the returned array?

Plus, just an off-topic tip: please take a look on the code highlighting syntax. It makes your snippet easier to read and copy.

Thanks a lot sir for your prompt reply, but its still not working. I would humbly request you to my whole code once.

py

-- coding: utf-8 --

“”"
Created on Fri Nov 19 17:48:48 2021

@author: Kamlesh Parihar
“”"

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import dash_table.FormatTemplate as FormatTemplate
from dash_table.Format import Format, Group, Prefix, Scheme, Symbol
import plotly.graph_objects as go
import pandas as pd
import numpy as np
from datetime import datetime
from maxdqv import mdp, mdq, sn, mtv,hd,mdb
from plotly.subplots import make_subplots

from plotly import plotly

pip install chart_studio.plotly

import dash_table
import plotly.express as px

print(“FILTERING STOCKS HAVING MAXIMUM DELIVERY BY PERCENTAGE, QUANTITY, VOLUME AND HIGH DELIVERY”)

print(“STEP ONE STARTED.\n\nFILTERING STOCKS HAVING MAXIMUM DELIVERY BY PERCENTAGE, QUANTITY, VOLUME AND HIGH DELIVERY\n\n”)
MDP=mdp()
MDQ=mdq()
MTV=mtv()
HD=hd()
MDPB=mdb(69.9,99)
N5001=pd.read_excel(“D:\to be deleted 6 October 2019\Share Market\Historical Data\Open Interest Sheet\Bhavcopy Data NIFTY500\NIFTY 500.xlsx”,“NIFTY 500”)
N5002=N5001[‘Symbol’].values.flatten().tolist()
List=[‘MDP1’,‘MDQ1’,‘MTV1’,‘HD1’,‘MDPB1’,‘N500’]

df4=sn(‘HDFCBANK’,31)
df4[‘DATE’]=df4[‘DATE’].astype(‘datetime64[ns]’)
df4[‘DATE’]=df4[‘DATE’].dt.strftime(’%d-%b-%y’)
maxdelivper=df4[‘DELIV_PER’].max()

dflist=pd.DataFrame(List,columns=[‘List’])
dfmdp=pd.DataFrame(MDP,columns=[‘MDP1’])
dfmdq=pd.DataFrame(MDQ,columns=[‘MDQ1’])
dfmtv=pd.DataFrame(MTV,columns=[‘MTV1’])
dfhd=pd.DataFrame(HD,columns=[‘HD1’])
dmdpb=pd.DataFrame(MDPB,columns=[‘MDPB1’])
N500=pd.DataFrame(N5002,columns=[‘N500’])
consdf=pd.concat([dfmdp,dfmdq,dfmtv,dfhd,dmdpb,N500],axis=1)

print(“READING FUTURES DATA FROM EXCEL FILE”)

print(“STEP TWO STARTED. \n\nREADING FUTURES DATA FROM EXCEL FILE.\n\n”)

df1=pd.read_excel(“D:\to be deleted 6 October 2019\Share Market\Historical Data\Open Interest Sheet\FUTURES_OI_OCT21.xlsx”,sheet_name=‘OI CHANGE SHEET’)
df1=df1[[‘Serial No’,‘SYMBOL’,‘LTP’,’% PRICE CHANGE’,‘Change in OI %’,‘LAST TRADING DAY BUILDUP’]]
dfbldup1=pd.read_excel(“D:\to be deleted 6 October 2019\Share Market\Historical Data\Open Interest Sheet\FUTURES_OI_OCT21.xlsx”,sheet_name=‘OIBUILDUP’)
dfoicrm=pd.read_excel(“D:\to be deleted 6 October 2019\Share Market\Historical Data\Open Interest Sheet\FUTURES_OI_OCT21.xlsx”,sheet_name=‘OICHANGECRM’)
dfbldup=pd.concat([dfbldup1,dfoicrm])
dfbldup=dfbldup.sort_values(by=[‘Serial No’], ascending=True)
dfsector=pd.read_excel(“D:\to be deleted 6 October 2019\Share Market\Historical Data\Open Interest Sheet\Bhavcopy Data NIFTY500\NIFTY 500.xlsx”,“Nifty500withSectors”)

print(“STEP THREE STARTED.\n\nFILTERING STOCKS HAVING MAXIMUM DELIVERY BY PERCENTAGE, QUANTITY, VOLUME AND HIGH DELIVERY\n\n”)

print(“STEP THREE STARTED.\n\nFILTERING STOCKS HAVING MAXIMUM DELIVERY BY PERCENTAGE, QUANTITY, VOLUME AND HIGH DELIVERY\n\n”)

#============================================================================================================================================

app = dash.Dash(name)

colors = {
‘background’: ‘Black’,
‘text’: ‘#7FDBFF
}

app.layout =html.Div([ # Creates HEADING 1
html.H1(children = ‘STOCK ANALYSIS (NIFTY 500 STOCKS)’,
style = {
‘backgroundColor’:‘Aqua’,
‘textAlign’ : ‘center’,
‘color’ : ‘#456FBV’,
‘marginBottom’: ‘0.01em’
},),

Creates HEADING 2

print("STEP FOUR STARTED.\n\n"),    
html.Div(id="StockDetails", children= "Kamlesh Parihar Creation",
         style = {
             'backgroundColor':'Aqua',
            'textAlign' : 'center',
            'color' : '#456FBV' ,
             'fontSize': 22,
             'fontWeight': 'bold',
             'marginBottom': '0.3em'
         }),  

#============================================================================================================================================
# print(“STEP FOUR STARTED.\n\n”),
html.Div(children= “SELECTION CRITERIA”,
style = {
‘textAlign’ : ‘left’,
‘color’ : ‘#456FBV’,
‘fontSize’: 22,
‘fontWeight’: ‘bold’,
‘marginBottom’: ‘0.3em’,
# ‘backgroundColor’:‘LightSkyBlue’

         }),  



dcc.RadioItems(id ='radio',
               options=[ {'label': x, 'value' : x } for x in (dflist.List.unique())],
               value=dflist['List'].values[0],
                style = {
            'textAlign' : 'left',
            'color' : '#456FBV',
             'fontSize': 18,
             'fontWeight': 'bold',
              # 'backgroundColor':'LightSkyBlue' ,
         }), 

 html.Br(),

#============================================================================================================================================
html.Div(children= “SELECT A STOCK”,
style = {
‘textAlign’ : ‘left’,
‘color’ : ‘#456FBV’,
‘fontSize’: 18,
‘fontWeight’: ‘bold’ ,
# ‘backgroundColor’:‘LightSkyBlue’
}),
#============================================================================================================================================
dcc.Dropdown(id=‘stocks’, options=, #{‘label’:‘HDFCBANK’,‘value’:‘HDFCBANK’}
placeholder=‘SELECT STOCK NAME’,
searchable=True,
style={‘width’:‘40%’,
‘fontSize’: 16,
‘fontWeight’: ‘bold’ },
),
#============================================================================================================================================
html.H1(id=‘charttitle’, children = ‘HDFCBANK CHART’,
style = {
‘textAlign’ : ‘center’,
‘color’ : ‘#456FBV’,
# ‘background’:‘Aquamarine’,
‘marginBottom’: ‘0.05em’,
},),
html.Div(id=‘stock_sector_details1’,children= “(FINANCIAL_SERVICES_PRI/Banks_Private_Sector_Sec/Large Cap)”,
style = {
‘textAlign’ : ‘center’,
‘color’ : ‘#456FBV’,
‘fontSize’: 22,
‘fontWeight’: ‘bold’,
# ‘background’:‘Aquamarine’,
‘marginBottom’: ‘0.3em’,

         }), 

#============================================================================================================================================
dcc.Graph(id=“graph”),
#============================================================================================================================================
html.H1(id=‘stockheadingontable’, children = ‘HDFCBANK’,
style = {
‘textAlign’ : ‘center’,
‘color’ : ‘#456FBV
},),

html.Div(id=‘stock_sector_details2’,children= “(FINANCIAL_SERVICES_PRI/Banks_Private_Sector_Sec/Large Cap)”,
style = {
‘textAlign’ : ‘center’,
‘color’ : ‘#456FBV’,
‘fontSize’: 22,
‘fontWeight’: ‘bold’

         }),       

#============================================================================================================================================
dash_table.DataTable(
id=‘STOCK_LAST_30_DAYS_DATA’,
columns=[{“name”: “S_NO”, “id”: “S_NO”, “deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “DATE”, “id”: “DATE”,“deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “SYMBOL”, “id”: “SYMBOL”,“deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “DELIV_PER”, “id”: “DELIV_PER”, ‘width’:‘200px’, ‘whiteSpace’: ‘normal’,“deletable”: False, “selectable”: False, “hideable”: True}, #“type”: “numeric”,“format”: Format().symbol(Symbol.yes).symbol_suffix(" %")
{“name”: “DELIV_QTY”, “id”: “DELIV_QTY”,“type”: “numeric”,“format”: Format().group(Group.yes).groups([3, 2,2,2,2,2]),‘whiteSpace’: ‘normal’,“deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “TTL_TRD_QNTY”, “id”: “TTL_TRD_QNTY”,“type”: “numeric”,“format”: Format().group(Group.yes).groups([3, 2,2,2,2,2]),“deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “TPrice_Change”, “id”: “TPrice_Change”,“type”: “numeric”,“format”: Format().symbol(Symbol.yes).symbol_suffix(" %"), “deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “CLOSE_PRICE”, “id”: “CLOSE_PRICE”,“type”: “numeric”,“format”: Format().group(Group.yes).groups([3, 2,2,2,2,2]),“deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “OPEN_PRICE”, “id”: “OPEN_PRICE”,“type”: “numeric”,“format”: Format().group(Group.yes).groups([3, 2,2,2,2,2]),“deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “LOW_PRICE”, “id”: “LOW_PRICE”,“type”: “numeric”,“format”: Format().group(Group.yes).groups([3, 2,2,2,2,2]),“deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “HIGH_PRICE”, “id”: “HIGH_PRICE”,“type”: “numeric”,“format”: Format().group(Group.yes).groups([3, 2,2,2,2,2]),“deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “TURNOVER_LACS”, “id”: “TURNOVER_LACS”,“type”: “numeric”,“format”: Format().group(Group.yes).groups([3, 2,2,2,2,2]),“deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “NO_OF_TRADES”, “id”: “NO_OF_TRADES”,“type”: “numeric”,“format”: Format().group(Group.yes).groups([3, 2,2,2,2,2]),“deletable”: False, “selectable”: False, “hideable”: True},
{“name”: “NPrice_Change”, “id”: “NPrice_Change”, “type”: “numeric”,“format”: Format().symbol(Symbol.yes).symbol_suffix(" %"),“deletable”: False, “selectable”: False, “hideable”: True},

        # if i == "S_NO" or i == "SYMBOL" or i == "DATE" or i == "DELIV_PER" or i == "DELIV_QTY" or i == "TPrice_Change" or i == "NPrice_Change" or i == "LOW_PRICE" or i == "OPEN_PRICE" or i == "CLOSE_PRICE" or i == "HIGH_PRICE" or i == "TTL_TRD_QNTY" or i == "NO_OF_TRADES" or i == "TURNOVER_LACS"
        # else {"name": i, "id": i, "deletable": False, "selectable": False}
        # for i in df4.columns 
       
        
    ],
    data=df4.to_dict('records'),  # the contents of the table
    editable=False,              # allow editing of data inside all cells
    filter_action="native",     # allow filtering of data by user ('native') or not ('none')
    sort_action="native",       # enables data to be sorted per-column by user or not ('none')
    sort_mode="single",         # sort across 'multi' or 'single' columns
    column_selectable="single",  # allow users to select 'multi' or 'single' columns
    row_selectable="single",     # allow users to select 'multi' or 'single' rows
    row_deletable=False,         # choose if user can delete a row (True) or not (False)
    selected_columns=[],        # ids of columns that user selects
    selected_rows=[],           # indices of rows that user selects
    page_action="native",       # all data is passed to the table up-front or not ('none')
    page_current=0,             # page number that user is on
    page_size=31,                # number of rows visible per page
    style_cell={                # ensure adequate header width when text is shorter than cell's text
        'minWidth': 'auto', 'maxWidth': 'auto', 'width': 'auto', 'whitespace':'normal','fontSize':16, 'font-family':'sans-serif'#, 'fontWeight': 'bold'
    },
    style_table={'height': '600px', 'overflowY': 'scroll','width':'2250px','overflowX': 'auto'}, #auto or scroll
    style_cell_conditional=(
        [ {  
            'if': {'column_id': c},
            'textAlign': 'center'  # align text columns to left. By default they are aligned to right
        } for c in df4.columns
        ] +
        [{'if': {'column_id': 'SYMBOL'},
            'width': '200px',}]
         +
        [{'if': {'column_id': 'DATE'},
            'width': '100px',  }]
         +
        [{'if': {'column_id': 'DELIV_PER'},
            'width': '100px',  }]  
        

        ),  
            
    style_data={                # overflow cells' content into multiple lines
        'whiteSpace': 'normal',
        'height': 'auto'
                },
    
    fixed_rows={ 'headers': True, 'data': 2 },
    style_data_conditional=([
        {
        'if': {'row_index': 'odd'},
        'backgroundColor': 'rgb(220, 220, 220)',
        }]+
        [
    {
        'if': {
            'filter_query': '{DATE} contains "NA"'
        },
        'backgroundColor': '#0074D9',
        'color': 'white'
    }
]+
        [
    {
        'if': {
            'column_id': 'DELIV_PER',

            # since using .format, escape { with {{
            'filter_query': '{{DELIV_PER}} = {}'.format(df4['DELIV_PER'].max())
        },
        'backgroundColor': '#85144b',
        'color': 'white'
    },
]
        

),
    
     style_header={            
    'border': 'thin lightgrey solid',
    'backgroundColor': 'Aqua',
    'fontWeight': 'bold'
                },),

#============================================================================================================================================
html.H1(id=‘stockheadingontable2’, children = ‘FUTURES OPEN INTEREST BUILDUP OF CURRENT MONTH’,
style = {
‘textAlign’ : ‘center’,
‘color’ : ‘#456FBV’ ,
‘marginBottom’: ‘0.05em’,
‘background’ :’#ffaa80
},),
#============================================================================================================================================

#============================================================================================================================================
@app.callback(
dash.dependencies.Output(‘stocks’, ‘options’),
dash.dependencies.Input(‘radio’, ‘value’))
def dropdown_options(listvalues):
return [{‘label’: c, ‘value’: c} for c in consdf[listvalues]]
#============================================================================================================================================
@app.callback(
dash.dependencies.Output(“graph”, “figure”),

dash.dependencies.Output(“graph”, “figure”)],

dash.dependencies.Input("stocks", "value"))

def display_candlestick(value):
print(value)
df=sn(value,87)
df=df.sort_values(by=‘S_NO’,ascending=True,ignore_index=True)
startdt,enddt = [df.iat[0,2],df.iat[-1,2]]
ddf1=df.set_index(‘DATE’) # SETS DATE AS INDEX
ddf1.index = pd.to_datetime(ddf1.index) # CONVERTS INDEX INTO DATE TIME OBJECT
missingdate=pd.date_range(start=startdt, end=enddt).difference(ddf1.index)
missingdate=missingdate.tolist()
for i in range(0,len(missingdate)):
missingdate[i]=missingdate[i].strftime(’%Y-%m-%d’)
df[‘9ema’]=df.CLOSE_PRICE.ewm(span=9, adjust=False).mean().round(2)
df[‘20ema’]=df.CLOSE_PRICE.ewm(span=20, adjust=False).mean().round(2)
# df[‘50sma’]=df.CLOSE_PRICE.rolling(window=50).mean().round(2)
# df[‘100sma’]=df.CLOSE_PRICE.rolling(window=100).mean().round(2)
# df[‘200sma’]=df.CLOSE_PRICE.rolling(window=200).mean().round(2)
df[‘20volsma’]=df.TTL_TRD_QNTY.rolling(window=20).mean().round(2) # moving average on volume
# print(df)
df=df.drop(columns=[‘SYMBOL’,‘S_NO’, ‘DELIV_PER’, ‘DELIV_QTY’,‘NPrice_Change’,‘NO_OF_TRADES’, ‘TURNOVER_LACS’])
print("\n\n\n\nDF after dropping column",df)
fig = make_subplots(rows=2, cols=1, shared_yaxes=(True),vertical_spacing=0.03,row_heights=(1.5,0.5))
fig.add_trace(go.Candlestick(
x=df[‘DATE’],
open=df[‘OPEN_PRICE’],
high=df[‘HIGH_PRICE’],
low=df[‘LOW_PRICE’],
close=df[‘CLOSE_PRICE’]), row=1,col=1)
print(“step1\n”)
fig.update_layout(height=750) # Sets the height of whole figure
df[“Color”] = np.where(df[“TPrice_Change”]<0, ‘OrangeRed’, ‘Lime’)
fig.add_trace(go.Bar( x=df[‘DATE’], y=df[‘TTL_TRD_QNTY’],marker_color=df[‘Color’]), row=2,col=1)
fig.add_trace(go.Scatter( x=df[‘DATE’], y=df[‘9ema’],mode=“lines”,name=“9EMA”,line=dict(color=‘Lime’, width=2)), row=1,col=1,)
fig.add_trace(go.Scatter( x=df[‘DATE’], y=df[‘20ema’],mode=“lines”,name=“20EMA”,line=dict(color=‘OrangeRed’, width=2)), row=1,col=1,)
fig.add_trace(go.Scatter( x=df[‘DATE’], y=df[‘20volsma’],mode=“lines”,name=“Vol.Avg”,line=dict(color=‘royalblue’, width=2)), row=2,col=1,)# mode=‘lines’, name=“vol average”)
# fig.update_traces(mode=“lines”)
# fig.add_trace(go.Scatter( x=df[‘DATE’], y=df[‘50sma’]), row=1,col=1,)
# fig.add_trace(go.Scatter( x=df[‘DATE’], y=df[‘100sma’]), row=1,col=1,)
# fig.add_trace(go.Scatter( x=df[‘DATE’], y=df[‘200sma’]), row=1,col=1,)

fig.update_xaxes(
rangebreaks=[
  
    dict(values=missingdate)
   
    # dict(bounds=["fri", "mon"]), #hide weekends
    # dict(values=["2021-10-09", "2021-10-10","2021-10-11"])  # hide Christmas and New Year's
])
 
fig.update_yaxes(side="right")
fig.update_layout(xaxis_rangeslider_visible=False)
# plot(fig)
print("Step2\n")
return fig

#============================================================================================================================================
@app.callback(
dash.dependencies.Output(“STOCK_LAST_30_DAYS_DATA”, “data”),

dash.dependencies.Output(“graph”, “figure”)],

dash.dependencies.Input("stocks", "value"))

def display_table(value):
df4=sn(value,30)
df4[‘DATE’]=df4[‘DATE’].astype(‘datetime64[ns]’)
df4[‘DATE’]=df4[‘DATE’].dt.strftime(’%d-%b-%y’)
df4[‘TURNOVER_LACS’]= df4[‘TURNOVER_LACS’].round(0)
df4[‘DELIV_PER’]= df4[‘DELIV_PER’].round(0)
df4[‘TPrice_Change’]= df4[‘TPrice_Change’].round(1)
df4[‘NPrice_Change’]= df4[‘TPrice_Change’].round(1)
df4[‘LOW_PRICE’]= df4[‘LOW_PRICE’].round(1)
df4[‘OPEN_PRICE’]= df4[‘OPEN_PRICE’].round(1)
df4[‘CLOSE_PRICE’]= df4[‘CLOSE_PRICE’].round(1)
df4[‘HIGH_PRICE’]= df4[‘HIGH_PRICE’].round(1)
# d1=round(df4.DELIV_PER.mean(),0)
d1=round((df4.DELIV_QTY.sum()*100)/(df4.TTL_TRD_QNTY.sum()),0)
d11=round(df4.DELIV_QTY.mean(),0)
d2=round(df4.TTL_TRD_QNTY.mean(),0)
d3=round(df4.NO_OF_TRADES.mean(),0)
d4=round(df4.TURNOVER_LACS.mean(),0)
data ={
‘S_NO’:‘NA’,
‘SYMBOL’ : ‘NA’,
‘DATE’:‘NA’,
‘DELIV_PER’ : d1,
‘DELIV_QTY’ : d11,
‘TPrice_Change’: ‘NA’,
‘NPrice_Change’: ‘NA’,
‘LOW_PRICE’: ‘NA’,
‘OPEN_PRICE’: ‘NA’,
‘CLOSE_PRICE’: ‘NA’,
‘HIGH_PRICE’: ‘NA’,
‘TTL_TRD_QNTY’:d2,
‘NO_OF_TRADES’:d3,
‘TURNOVER_LACS’:d4,
}
maxdelivper=str(df4[‘DELIV_PER’].max())
print(maxdelivper)
type(maxdelivper)
df11=pd.DataFrame(data,index=[31])
df4=pd.concat([df11,df4])
# df4
print(“table is retrievable1”)
# df4.info()
data=df4.to_dict(‘records’)
# data
print(“table is retrievable2”)
return data
#============================================================================================================================================
@app.callback(
[dash.dependencies.Output(“charttitle”, “children”),
dash.dependencies.Output(“stock_sector_details1”, “children”),
dash.dependencies.Output(“stockheadingontable”, “children”),
dash.dependencies.Output(“stock_sector_details2”, “children”),],

dash.dependencies.Output(“graph”, “figure”)],

[dash.dependencies.Input("stocks", "value")])

def display_table(value):
value1=value
dfsec=dfsector.loc[(dfsector[‘SYMBOL’] == value1)]
children=value
children1=" (" + dfsec.iat[0,1]+"/ “+” /" + dfsec.iat[0,2]+"/ “+” /" + dfsec.iat[0,3]+ “/ “+” /” + dfsec.iat[0,4]+") "
return children,children1, children,children1
#============================================================================================================================================

@app.callback(
dash.dependencies.Output(“STOCK_LAST_30_DAYS_DATA”, “style_data_conditional”),
dash.dependencies.Input(“stocks”, “value”))
def style_data_conditional1(value):
# print(“This is working”)
return [
{
‘if’: {
‘column_id’: ‘DELIV_PER’,

            # since using .format, escape { with {{
            'filter_query': '{{DELIV_PER}} = {}'.format(df4['DELIV_PER'].max())
        },
        'backgroundColor': '#85144b',
        'color': 'white'
        },
]

if name == ‘main’:
app.run_server()

Sorry, it is impossible to read your code as the python comments are interpreted as markdown headings. I am also confused by the fact that your callback to update the table style does not use value at all…

You should probably update the “data” and “style_data_conditional” in the same callback, triggered by updates in the dropdown.

Sorry for inconvenience. Probably I am unable to explain my problem properly. Actually in my code I have 1. A radio button, 2. A dropdown and 3. A table in sequence . The user first clicks on the radio button. Based on the values of radio button, values of dropdown are populated. Now based on the selected value of dropdown, a table is generated. In the beginning when program runs, I have put a table as default value (default table). Now every time user selects a value from dropdown, the table values are modified through callback. In the callback function I have returned the “data”. Hence the columns and conditional formatting remains same as the default values, but the data inside the table modifies every time the user selects from dropdown. I have applied “style_data_conditional” in the dafault table to highlight the column having highest values. But unfortunately when the values of table are modified, the “style_data_conditional” is not applied to modified table.

Basically my problem is that I want “style_data_conditional” to be applied on modified values of table. If you can give an example how to return “style_data_conditional” through callback so that when the table values are modified, they also get formatted . It would be great help for me.

Thanku very much for your previous efforts and in anticipation. You are a great tutor.

Basically my problem is that I want “style_data_conditional” to be applied on modified values of table.

Ok, but if the data is modified, then the maximum will in principle be as well…

Here’s a minimal example:

from dash import Dash, dash_table, html, dcc, Output, Input
import pandas as pd
import plotly.express as px

app = Dash(__name__)

df = px.data.iris()

app.layout = html.Div(
    [
        dcc.Dropdown(
            id="dropdown",
            options=[{"label": i, "value": i} for i in df.species.unique()],
        ),
        dash_table.DataTable(
            id="table",
            columns=[{"name": i, "id": i} for i in df.columns],
        )
    ]
)

# Copied from my previous post...
def style_table_by_max_value(df):
    if 'id' in df:
        numeric_columns = df.select_dtypes('number').drop(['id'], axis=1)
    else:
        numeric_columns = df.select_dtypes('number')
    max_across_numeric_columns = numeric_columns.max()
    styles = []
    for col, val in max_across_numeric_columns.items():
        styles.append({
            'if': {
                'filter_query': f"{{{col}}} = {val}",   
                'column_id': col
            },
            'backgroundColor': '#39CCCC',
            'color': 'white'
        })
    return styles

@app.callback(
    Output("table", "data"),
    Output("table", "style_data_conditional"),
    Input("dropdown", "value")
)
def update_table(value):
    if value is None:
        return None, None
    
    # filter by selection
    df_ = df[df.species == value]

    # highlight max per numeric row
    new_style = style_table_by_max_value(df_)

    return df_.to_dict("records"), new_style

if __name__ == "__main__":
    app.run_server(debug=True)

THANKU SIR.
IT WORKED FOR ME. YOUR EFFORTS ARE REALLY APPRECIABLE.
I HAVE DONE IT LITTLE DIFFERENTLY. I RETURNED THE COMPLETE TABLE FROM CALLBACK.
ONE MORE QUERRY I HAVE . I WANT TO PUBLISH MY DASH WEBSITE FOR PUBLIC. ALSO MY CODE DERIVES MANY VALUES FROM MY LOCAL MYSQL SERVER. I TRIED TO DO THIS USING HEROKU, BUT IT FAILED. CAN YOU HELP.

Please make sure to post a new thread regarding the Heroku deployment. I will be happy to help if I can.