File size: 5,781 Bytes
b9ea93b
2ba9451
 
 
 
 
d11e92b
2ba9451
 
a979d91
2ba9451
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6109d73
2ba9451
d9b2134
 
2ba9451
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
from . import nsepythonmodified as ns
import pandas as pd
import re
from datetime import datetime as dt

# persist helpers (HF only)
from .persist import exists, load, save


def build_preopen_html(key):
    """
    Build full Pre-Open HTML
    - Daily TTL (via persist.py)
    - HTML only cache
    """

    # ================= CACHE (TTL via persist) =================
    cache_name = f"DAILY_PREOPEN_{key.upper()}"

    if exists(cache_name, "html"):
        cached_html = load(cache_name, "html")
        if isinstance(cached_html, str):
            return cached_html

    # ================= FETCH DATA =================
    p = ns.nse_preopen(key)

    data_df = p["data"]
    rem_df  = p["rem"]

    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()

    # ================= REMOVE PATTERN COLUMNS =================
    pattern_remove = re.compile(r"^(price_|buyQty_|sellQty_|iep_)\d+$")

    def remove_pattern_cols(df):
        if df is None or df.empty:
            return df
        return df[[c for c in df.columns if not pattern_remove.match(c)]]

    main_df  = remove_pattern_cols(main_df)
    const_df = remove_pattern_cols(const_df)
    rem_df   = remove_pattern_cols(rem_df)

    # ================= TABLE COLOR HELPER =================
    def df_to_html_color(df, metric_col=None):
        if df is None or df.empty:
            return "<i>No data</i>"

        df_html = df.copy()
        top_up, top_down = [], []

        if metric_col and metric_col in df_html.columns:
            col_num = pd.to_numeric(df_html[metric_col], errors="coerce").dropna()
            top_up = col_num.nlargest(3).index.tolist()
            top_down = col_num.nsmallest(3).index.tolist()

        for idx, row in df_html.iterrows():
            for col in df_html.columns:
                val = row[col]
                cls = ""
                if isinstance(val, (int, float)):
                    val_fmt = f"{val:.2f}"
                    if val > 0:
                        cls = "numeric-positive"
                    elif val < 0:
                        cls = "numeric-negative"
                    if metric_col and col == metric_col:
                        if idx in top_up:
                            cls += " top-up"
                        elif idx in top_down:
                            cls += " top-down"
                    df_html.at[idx, col] = f'<span class="{cls.strip()}">{val_fmt}</span>'
                else:
                    df_html.at[idx, col] = str(val)

        return df_html.to_html(index=False, escape=False, classes="compact-table")

    # ================= MINI INFO CARDS =================
    def build_info_cards(rem_df, main_df):
        combined = pd.concat([rem_df, main_df], axis=1)
        combined = combined.loc[:, ~combined.columns.duplicated()]
        combined = remove_pattern_cols(combined)

        html = '<div class="mini-card-container">'
        for col in combined.columns:
            val = combined.at[0, col] if not combined.empty else ""
            html += f"""
            <div class="mini-card">
                <div class="card-key">{col}</div>
                <div class="card-val">{val}</div>
            </div>
            """
        html += '</div>'
        return html

    info_cards_html = build_info_cards(rem_df, main_df)

    # ================= CONSTITUENTS TABLE =================
    cons_html = df_to_html_color(const_df)

    # ================= METRIC TABLES =================
    metric_cols_allowed = [
        "pChange",
        "totalTurnover",
        "marketCap",
        "totalTradedVolume"
    ]

    metric_tables = ""
    for col in metric_cols_allowed:
        if col in const_df.columns:
            df_m = const_df.copy()
            df_m[col] = pd.to_numeric(df_m[col], errors="coerce")
            df_m = df_m.sort_values(col, ascending=False)

            show_cols = ["symbol", col] if "symbol" in df_m.columns else [col]
            metric_tables += f"""
            <div class="small-table">
                <div class="st-title">{col}</div>
                <div class="st-body">
                    {df_to_html_color(df_m[show_cols], metric_col=col)}
                </div>
            </div>
            """

    # ================= FINAL HTML =================
    html_out = f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body {{ font-family: Arial; margin: 12px; background: #f5f5f5; font-size: 14px; }}
h2, h3 {{ margin: 10px 0; }}
table {{ border-collapse: collapse; width: 100%; }}
th, td {{ border: 1px solid #bbb; padding: 6px; font-size: 13px; }}
th {{ background: #333; color: #fff; }}
.numeric-positive {{ color: green; font-weight: bold; }}
.numeric-negative {{ color: red; font-weight: bold; }}
.top-up {{ background: #b6f2b6; }}
.top-down {{ background: #f2b6b6; }}
.grid {{ display: grid; grid-template-columns: repeat(5, 1fr); gap: 12px; }}
.small-table {{ background: #fff; padding: 8px; border-radius: 6px; border: 1px solid #ddd; }}
.st-title {{ text-align: center; font-weight: bold; background: #222; color: #fff; padding: 6px; }}
.st-body {{ max-height: 300px; overflow-y: auto; }}
.mini-card-container {{ display: flex; flex-wrap: wrap; gap: 10px; }}
.mini-card {{ background: #fff; padding: 8px 10px; border-radius: 6px; border: 1px solid #ddd; min-width: 120px; }}
.card-key {{ font-weight: bold; }}
</style>
</head>
<body>

<h2>Pre-Open Market — {key}</h2>

<h3>Info</h3>
{info_cards_html}

<h3>Constituents</h3>
{cons_html}

<h3>Key Metrics</h3>
<div class="grid">
{metric_tables}
</div>

</body>
</html>
"""

    # ================= SAVE (HTML ONLY) =================
    save(cache_name, html_out, "html")

    return html_out