from nsepython import * import pandas as pd def build_preopen_html(key="NIFTY"): # Fetch pre-open data p = nsefetch("https://www.nseindia.com/api/market-data-pre-open?key=" + key) data_df = df_from_data(p.pop("data")) rem_df = df_from_data([p]) main_df = data_df.iloc[[0]] if not data_df.empty else pd.DataFrame() const_df = data_df.iloc[1:] if len(data_df) > 1 else pd.DataFrame() # ================= HELPER FUNCTION ================= def df_to_html_color(df, metric_col=None): df_html = df.copy() top3_up = [] top3_down = [] if metric_col and metric_col in df_html.columns and pd.api.types.is_numeric_dtype(df_html[metric_col]): col_numeric = df_html[metric_col].dropna() top3_up = col_numeric.nlargest(3).index.tolist() top3_down = col_numeric.nsmallest(3).index.tolist() for idx, row in df_html.iterrows(): for col in df_html.columns: val = row[col] style = "" if pd.api.types.is_numeric_dtype(type(val)) or isinstance(val, (int, float)): val_fmt = f"{val:.2f}" if val > 0: style = "numeric-positive" elif val < 0: style = "numeric-negative" if metric_col and col == metric_col: if idx in top3_up: style += " top-up" elif idx in top3_down: style += " top-down" df_html.at[idx, col] = f'{val_fmt}' else: df_html.at[idx, col] = str(val) return df_html.to_html(index=False, escape=False, classes="compact-table") # ================= MERGE INFO + MAIN INTO MINI-CARDS ================= def merge_info_main_cards(rem_df, main_df): combined = pd.concat([rem_df, main_df], axis=1) combined = combined.loc[:, ~combined.columns.duplicated()] cards_html = '