Subham9126 commited on
Commit
d74ca88
·
verified ·
1 Parent(s): 15f0a56

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +223 -40
app.py CHANGED
@@ -1,42 +1,225 @@
 
 
 
 
 
 
 
1
  import gradio as gr
2
- from sentence_transformers import SentenceTransformer, util
3
- import torch
4
-
5
- # Load the SentenceTransformer model
6
- model = SentenceTransformer('all-MiniLM-L6-v2')
7
-
8
- def find_relevant_words(query, data, top_k):
9
- # Convert data string to list
10
- word_list = [word.strip() for word in data.split(',')]
11
-
12
- # Create embeddings
13
- query_embedding = model.encode(query, convert_to_tensor=True)
14
- word_embeddings = model.encode(word_list, convert_to_tensor=True)
15
-
16
- # Compute cosine similarities
17
- cos_scores = util.cos_sim(query_embedding, word_embeddings)[0]
18
-
19
- # Get top-k results
20
- top_results = torch.topk(cos_scores, k=min(top_k, len(word_list)))
21
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  results = []
23
- for score, idx in zip(top_results.values, top_results.indices):
24
- results.append(f"{word_list[idx]} (Score: {score:.4f})")
25
-
26
- return "\n".join(results)
27
-
28
- # Create Gradio interface
29
- iface = gr.Interface(
30
- fn=find_relevant_words,
31
- inputs=[
32
- gr.Textbox(label="Query"),
33
- gr.Textbox(label="Data (comma-separated words)"),
34
- gr.Slider(minimum=1, maximum=20, step=1, label="Top K", value=5)
35
- ],
36
- outputs=gr.Textbox(label="Results"),
37
- title="Semantic Word Relevance Finder",
38
- description="Enter a query and a list of words to find the most semantically relevant words."
39
- )
40
-
41
- # Launch the app
42
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------ Imports ------------------
2
+ import pandas as pd
3
+ import numpy as np
4
+ import pytz
5
+ import json
6
+ import random
7
+ from datetime import datetime
8
  import gradio as gr
9
+ from apscheduler.schedulers.background import BackgroundScheduler
10
+ from gradio_client import Client
11
+ from talib import abstract
12
+
13
+ # ------------------ Configuration ------------------
14
+ CSV_FILE = "daily_indicators.csv"
15
+ PREDEFINED_SYMBOLS = ["RELIANCE", "TCS", "INFY", "HDFCBANK", "ICICIBANK"]
16
+ PREDEFINED_START = "2024-01-01"
17
+ INTERVAL = 1440 # Daily interval
18
+ CLIENT = Client("Subham9126/IME", hf_token=HF_TOKEN)
19
+ MASTER_MAPPING = {'open': 'open', 'high': 'high', 'low': 'low', 'close': 'close', 'volume': 'volume'}
20
+
21
+ # ------------------ Data Fetch ------------------
22
+ def fetch_data():
23
+ """Fetch historical OHLCV data from Hugging Face API for predefined symbols."""
24
+ hist_data = CLIENT.predict(
25
+ ticker_input=json.dumps(PREDEFINED_SYMBOLS),
26
+ start_date=PREDEFINED_START,
27
+ end_date=datetime.now(pytz.timezone("Asia/Kolkata")).strftime("%Y-%m-%d"),
28
+ interval=INTERVAL,
29
+ batch_size=50,
30
+ batch_delay=0.5,
31
+ max_concurrent=50,
32
+ api_name="/execute_stock_request"
33
+ )
34
+ return hist_data
35
+
36
+ # ------------------ JSON to DataFrame ------------------
37
+ def candles_json_to_df(json_data):
38
+ """Convert Groww-like JSON to a pandas DataFrame"""
39
+ records = []
40
+ ist_timezone = pytz.timezone('Asia/Kolkata')
41
+
42
+ for ticker_entry in json_data.get("data", []):
43
+ symbol = ticker_entry.get("ticker")
44
+ candles = ticker_entry.get("data", {}).get("candles", [])
45
+ for candle in candles:
46
+ if isinstance(candle, list) and len(candle) >= 6:
47
+ unix = candle[0]
48
+ utc_datetime = datetime.utcfromtimestamp(unix)
49
+ ist_datetime = utc_datetime.replace(tzinfo=pytz.utc).astimezone(ist_timezone)
50
+ records.append({
51
+ "symbol": symbol,
52
+ "unix": unix,
53
+ "datetime": ist_datetime.strftime('%Y-%m-%d %H:%M:%S'),
54
+ "open": candle[1],
55
+ "high": candle[2],
56
+ "low": candle[3],
57
+ "close": candle[4],
58
+ "volume": candle[5],
59
+ })
60
+ return pd.DataFrame(records)
61
+
62
+ # ------------------ TA-Lib Indicator ------------------
63
+ def talib_indicator(name, df, **kwargs):
64
+ """Run any TA-Lib indicator with auto column mapping"""
65
+ func = abstract.Function(name)
66
+ needed_inputs = {k: MASTER_MAPPING[k] for k in func.input_names if k in MASTER_MAPPING}
67
+ func.input_names = needed_inputs
68
+ return func(df, **kwargs)
69
+
70
+ # ------------------ Multi-symbol TA-Lib ------------------
71
+ def calculate_multi_symbol_indicators(df, indicators=None):
72
+ """Calculate TA-Lib indicators for multiple symbols"""
73
+ df = df.drop_duplicates(subset=['symbol', 'unix']).sort_values(['symbol','unix']).reset_index(drop=True)
74
+ indicators = indicators or ['SMA', 'MACD', 'RSI', 'ADX']
75
+ processed_symbols = []
76
+
77
+ for symbol, group_df in df.groupby('symbol'):
78
+ df_copy = group_df.copy().reset_index(drop=True)
79
+ for col in ['open','high','low','close','volume']:
80
+ df_copy[col] = df_copy[col].astype(float)
81
+ ta_df = df_copy[['open','high','low','close','volume']]
82
+ indicator_columns = {}
83
+
84
+ for indicator in indicators:
85
+ try:
86
+ result = talib_indicator(indicator, ta_df)
87
+ if isinstance(result, (pd.Series, np.ndarray)):
88
+ indicator_columns[indicator] = result
89
+ elif isinstance(result, tuple):
90
+ for i, val in enumerate(result):
91
+ indicator_columns[f"{indicator}_{i}"] = val
92
+ except Exception as e:
93
+ print(f"[WARNING] Failed {indicator} for {symbol}: {e}")
94
+ continue
95
+
96
+ for col_name, col_data in indicator_columns.items():
97
+ df_copy[col_name] = col_data
98
+
99
+ processed_symbols.append(df_copy)
100
+
101
+ return pd.concat(processed_symbols, ignore_index=True)
102
+
103
+ # ------------------ Indicator Mapping ------------------
104
+ def create_indicator_mapping(columns):
105
+ mapping = {}
106
+ skip_cols = {'symbol','unix','datetime','open','high','low','close','volume'}
107
+ indicator_cols = [c for c in columns if c not in skip_cols]
108
+ from collections import defaultdict
109
+ temp_map = defaultdict(list)
110
+
111
+ for col in indicator_cols:
112
+ if "_" in col:
113
+ prefix = col.split("_")[0]
114
+ temp_map[prefix].append(col)
115
+ else:
116
+ mapping[col] = [col]
117
+
118
+ for key, values in temp_map.items():
119
+ mapping[key] = values
120
+ return mapping
121
+
122
+ # ------------------ Query Indicators ------------------
123
+ def query_indicators(df, tickers, indicators, date=None, start=None, end=None, mapping=None):
124
+ """Return JSON-formatted indicator results"""
125
+ if isinstance(tickers, str):
126
+ tickers = [t.strip() for t in tickers.split(",")]
127
+ if isinstance(indicators, str):
128
+ indicators = [i.strip() for i in indicators.split(",")]
129
+ mapping = mapping or create_indicator_mapping(df.columns.tolist())
130
+
131
+ df['datetime'] = pd.to_datetime(df['datetime'])
132
+ df_filtered = df[df['symbol'].isin(tickers)]
133
+
134
+ if date:
135
+ df_filtered = df_filtered[df_filtered['datetime'].dt.strftime("%Y-%m-%d") == date]
136
+ else:
137
+ start = start or PREDEFINED_START
138
+ end = end or datetime.now(pytz.timezone("Asia/Kolkata")).strftime("%Y-%m-%d")
139
+ df_filtered = df_filtered[(df_filtered['datetime'].dt.strftime("%Y-%m-%d") >= start) &
140
+ (df_filtered['datetime'].dt.strftime("%Y-%m-%d") <= end)]
141
+
142
  results = []
143
+ for ticker in tickers:
144
+ df_ticker = df_filtered[df_filtered['symbol']==ticker]
145
+ for indicator in indicators:
146
+ cols = mapping.get(indicator, [])
147
+ for _, row in df_ticker.iterrows():
148
+ results.append({
149
+ "ticker": ticker,
150
+ "date": row['datetime'].strftime("%Y-%m-%d %H:%M:%S"),
151
+ "indicator": indicator,
152
+ "values": {col.replace(f"{indicator}_","") if len(cols)>1 else "value": row[col] for col in cols}
153
+ })
154
+ return results
155
+
156
+ # ------------------ Daily CSV Refresh ------------------
157
+ def fetch_and_store_csv():
158
+ raw_data = fetch_data()
159
+ df = candles_json_to_df(raw_data)
160
+ df_indicators = calculate_multi_symbol_indicators(df)
161
+ df_indicators.to_csv(CSV_FILE, index=False)
162
+ global indicator_mapping
163
+ indicator_mapping = create_indicator_mapping(df_indicators.columns.tolist())
164
+ print(f"[INFO] CSV refreshed at {datetime.now()}")
165
+
166
+ def schedule_daily_update():
167
+ ist = pytz.timezone("Asia/Kolkata")
168
+ scheduler = BackgroundScheduler(timezone=ist)
169
+ random_minute = random.randint(0, 30)
170
+ scheduler.add_job(fetch_and_store_csv, 'cron', hour=16, minute=random_minute)
171
+ scheduler.start()
172
+ print(f"[INFO] Scheduled daily CSV update at 16:{random_minute:02d} IST")
173
+
174
+ # ------------------ Gradio Functions ------------------
175
+ def gradio_query(tickers, indicators, date=None, start=None, end=None):
176
+ df = pd.read_csv(CSV_FILE)
177
+ return json.dumps(query_indicators(df, tickers, indicators, date, start, end, indicator_mapping), indent=2)
178
+
179
+ def view_last_csv():
180
+ try:
181
+ df = pd.read_csv(CSV_FILE)
182
+ return df.tail(20).to_string()
183
+ except FileNotFoundError:
184
+ return "[ERROR] CSV file not found!"
185
+
186
+ def manual_refresh_csv():
187
+ fetch_and_store_csv()
188
+ return f"[INFO] CSV refreshed manually at {datetime.now()}"
189
+
190
+ # ------------------ Initialize ------------------
191
+ fetch_and_store_csv() # Initial CSV
192
+ schedule_daily_update() # Start scheduler
193
+
194
+ # ------------------ Gradio UI ------------------
195
+ with gr.Blocks() as app:
196
+ gr.Markdown("## TA-Lib Indicators Dashboard")
197
+
198
+ with gr.Row():
199
+ tickers_input = gr.Textbox(label="Tickers (comma-separated)", value="RELIANCE,INFY")
200
+ indicators_input = gr.Textbox(label="Indicators (comma-separated)", value="SMA,MACD")
201
+
202
+ with gr.Row():
203
+ date_input = gr.Textbox(label="Date (optional YYYY-MM-DD)", value="")
204
+ start_input = gr.Textbox(label="Start Date (optional YYYY-MM-DD)", value="")
205
+ end_input = gr.Textbox(label="End Date (optional YYYY-MM-DD)", value="")
206
+
207
+ output_json = gr.Code(label="Output JSON", language="json")
208
+ run_button = gr.Button("Get Indicators")
209
+ run_button.click(
210
+ gradio_query,
211
+ inputs=[tickers_input, indicators_input, date_input, start_input, end_input],
212
+ outputs=output_json
213
+ )
214
+
215
+ gr.Markdown("### Debug / Manual Controls")
216
+ with gr.Row():
217
+ view_csv_btn = gr.Button("View Last CSV (Tail 20 rows)")
218
+ csv_view_output = gr.Textbox(label="Last CSV Preview", lines=20)
219
+ view_csv_btn.click(view_last_csv, outputs=csv_view_output)
220
+
221
+ manual_refresh_btn = gr.Button("Manual Refresh CSV")
222
+ refresh_output = gr.Textbox(label="Manual Refresh Status")
223
+ manual_refresh_btn.click(manual_refresh_csv, outputs=refresh_output)
224
+
225
+ app.launch()