Srish117 commited on
Commit
d376f4f
·
verified ·
1 Parent(s): 1589955

Added Generate All FUNC and Interactive Graphs

Browse files
Files changed (1) hide show
  1. app.py +375 -77
app.py CHANGED
@@ -86,41 +86,210 @@
86
  # st.markdown("<br><hr><center><p style='color: grey;'>© 2024 All Rights Reserved</p></center><br>", unsafe_allow_html=True)
87
 
88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  import streamlit as st
90
  import requests
91
  import pandas as pd
92
  import pymongo
93
  import datetime
 
94
  from pymongo import MongoClient
95
- import matplotlib.pyplot as plt
96
- import os
97
  import ssl
98
- import pytz # Importing pytz for timezone handling
99
-
100
-
101
-
102
- # Fetch the secret key from environment variables
103
- Mongo_ip = os.getenv("Mongo_IP")
104
 
105
  # Setting up IST timezone
106
  ist_timezone = pytz.timezone("Asia/Kolkata")
 
107
 
108
  # Connect to MongoDB
 
 
109
  client = MongoClient(
110
- Mongo_ip,
111
  ssl=True,
112
  ssl_cert_reqs=ssl.CERT_NONE # Bypass SSL certificate verification
113
  )
114
  db = client.GoldRates
115
  collection = db['GoldRates']
116
-
 
 
 
 
117
  # Backend functions
118
  def jina(url):
119
  base_url = "https://r.jina.ai/"
120
- url = base_url + url
121
- response = requests.get(url)
122
  return response.text
123
-
124
  def price_cities(url):
125
  text = jina(url)
126
  pos1 = text.find('**')
@@ -140,10 +309,8 @@ def price_cities(url):
140
 
141
  return value_24k, value_22k, value_18k
142
 
143
- # Helper function to insert data only once per day (no time constraint)
144
  def insert_data_if_not_exists(city, date, value_24k, value_22k, value_18k):
145
- query = {"Date": date, "Place": city}
146
- if not collection.find_one(query):
147
  document = {
148
  "Date": date,
149
  "Place": city,
@@ -153,21 +320,17 @@ def insert_data_if_not_exists(city, date, value_24k, value_22k, value_18k):
153
  }
154
  collection.insert_one(document)
155
 
156
- # Function to fetch weekly data for chart
157
  def fetch_weekly_data(city):
158
  today = datetime.datetime.now(ist_timezone)
159
  start_date = today - datetime.timedelta(days=7)
160
- query = {"Place": city, "Date": {"$gte": start_date.strftime("%Y-%m-%d")}}
161
- return list(collection.find(query).sort("Date", -1))
162
 
163
- # Function to check if it's the first run of the day after 12:30 PM IST
164
  def is_first_run_after_1230():
165
  today = datetime.datetime.now(ist_timezone)
166
  time_check = today.replace(hour=12, minute=30, second=0, microsecond=0)
167
  date_check = today.strftime("%Y-%m-%d")
168
  return today >= time_check and not collection.find_one({"Date": date_check})
169
 
170
- # Fetch and save rates for all cities
171
  def fetch_and_save_all_cities():
172
  date_today = datetime.datetime.now(ist_timezone).strftime("%Y-%m-%d")
173
  for city in cities:
@@ -178,41 +341,34 @@ def fetch_and_save_all_cities():
178
  except Exception as e:
179
  st.error(f"Could not fetch the gold rates for {city}. {e}")
180
 
181
- # List of cities
182
- cities = ['Hyderabad', 'Ahmedabad', 'Ayodhya', 'Bangalore', 'Bhubaneswar', 'Chandigarh', 'Chennai',
183
- 'Coimbatore', 'Delhi', 'Jaipur', 'Kerala', 'Kolkata', 'Lucknow',
184
- 'Madurai', 'Mangalore', 'Mumbai', 'Mysore', 'Nagpur', 'Nashik', 'Patna',
185
- 'Pune', 'Rajkot', 'Salem', 'Surat', 'Trichy', 'Vadodara', 'Vijayawada', 'Visakhapatnam']
186
-
187
- # Main UI
188
- st.title('Gold Rates in Indian Cities')
189
- st.subheader('Select a city to view the current gold rates and a weekly trend.')
190
- st.sidebar.title("About the Project")
191
- st.sidebar.write("This project fetches current gold rates for 24K, 22K, and 18K gold from GoodReturns for 28 Indian states. The rates for 1g, 8g, and 10g are displayed.")
192
- st.sidebar.write("**Developed by:**")
193
- st.sidebar.write("[Srish Rachamalla](https://www.linkedin.com/in/srishrachamalla/)")
194
- st.sidebar.write("[Sai Teja Pallerla](https://www.linkedin.com/in/saiteja-pallerla-668734225/)")
195
-
196
- # Dropdown for city selection
197
- selected_city = st.selectbox('Select a City', cities)
198
 
199
- # Generate button
200
- if st.button("Generate Gold Rates"):
201
- # If it's the first time after 12:30 PM, fetch and save rates for all cities
202
- if is_first_run_after_1230():
203
- fetch_and_save_all_cities()
204
- st.success("Gold rates for all cities have been fetched and saved.")
205
 
206
- # Fetch and display gold rates for the selected city
207
- if selected_city:
208
- date_today = datetime.datetime.now(ist_timezone).strftime("%Y-%m-%d")
209
- city_url = f"https://www.goodreturns.in/gold-rates/{selected_city}.html"
210
 
 
 
 
211
  try:
212
  value_24k, value_22k, value_18k = price_cities(city_url)
213
- insert_data_if_not_exists(selected_city, date_today, value_24k, value_22k, value_18k)
 
214
 
215
- # Prepare data for current rates
216
  current_data = {
217
  'Gold Purity': ['24K', '22K', '18K'],
218
  '1g Price (₹)': [float(value_24k.replace(',', '')), float(value_22k.replace(',', '')), float(value_18k.replace(',', ''))],
@@ -222,36 +378,178 @@ if st.button("Generate Gold Rates"):
222
 
223
  # Display current data
224
  df = pd.DataFrame(current_data)
225
- st.write(f"Gold rates in {selected_city} as of {date_today}:")
226
- st.dataframe(df.style.format(precision=2).set_properties(**{
 
 
227
  'background-color': 'black',
228
  'color': 'white',
229
- 'border-color': 'gray'
230
- }))
231
-
232
- # Weekly trend data
233
- weekly_data = fetch_weekly_data(selected_city)
234
- if weekly_data:
235
- dates = [doc["Date"] for doc in weekly_data]
236
- rates_24k = [doc["GoldRate_24k"] for doc in weekly_data]
237
- rates_22k = [doc["GoldRate_22k"] for doc in weekly_data]
238
- rates_18k = [doc["GoldRate_18k"] for doc in weekly_data]
239
-
240
- # Plot weekly trends
241
- plt.figure(figsize=(10, 5))
242
- plt.plot(dates, rates_24k, label="24K Gold", color="gold", marker='o')
243
- plt.plot(dates, rates_22k, label="22K Gold", color="red", marker='o')
244
- plt.plot(dates, rates_18k, label="18K Gold", color="brown", marker='o')
245
- plt.title(f"Gold Rates Trend in {selected_city} (Past Week)")
246
- plt.xlabel("Date")
247
- plt.ylabel("Price (₹)")
248
- plt.legend()
249
- plt.xticks(rotation=45)
250
- st.pyplot(plt)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
 
252
  except Exception as e:
253
- st.error(f"Could not fetch the gold rates. Please try again. {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
 
255
- # Footer
256
- st.markdown("<br><hr><center><p style='color: grey;'>© 2024 All Rights Reserved</p></center><br>", unsafe_allow_html=True)
257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  # st.markdown("<br><hr><center><p style='color: grey;'>© 2024 All Rights Reserved</p></center><br>", unsafe_allow_html=True)
87
 
88
 
89
+ # import streamlit as st
90
+ # import requests
91
+ # import pandas as pd
92
+ # import pymongo
93
+ # import datetime
94
+ # from pymongo import MongoClient
95
+ # import matplotlib.pyplot as plt
96
+ # import os
97
+ # import ssl
98
+ # import pytz # Importing pytz for timezone handling
99
+
100
+
101
+
102
+ # # Fetch the secret key from environment variables
103
+ # Mongo_ip = os.getenv("Mongo_IP")
104
+
105
+ # # Setting up IST timezone
106
+ # ist_timezone = pytz.timezone("Asia/Kolkata")
107
+
108
+ # # Connect to MongoDB
109
+ # client = MongoClient(
110
+ # Mongo_ip,
111
+ # ssl=True,
112
+ # ssl_cert_reqs=ssl.CERT_NONE # Bypass SSL certificate verification
113
+ # )
114
+ # db = client.GoldRates
115
+ # collection = db['GoldRates']
116
+
117
+ # # Backend functions
118
+ # def jina(url):
119
+ # base_url = "https://r.jina.ai/"
120
+ # url = base_url + url
121
+ # response = requests.get(url)
122
+ # return response.text
123
+
124
+ # def price_cities(url):
125
+ # text = jina(url)
126
+ # pos1 = text.find('**')
127
+ # new = text[:pos1]
128
+
129
+ # twentytwok = new[int(new.find('22K')):int(new.find('24K'))]
130
+ # value_22k = twentytwok[int(twentytwok.find('\n\n') + 1): int(twentytwok.find('\n\n+'))][3:]
131
+ # value_22k = value_22k.split('\n')[0]
132
+
133
+ # twentyfourk = new[int(new.find('24K')):int(new.find('18K'))]
134
+ # value_24k = twentyfourk[int(twentyfourk.find('\n\n') + 1): int(twentyfourk.find('\n\n+'))][3:]
135
+ # value_24k = value_24k.split('\n')[0]
136
+
137
+ # eighteenk = new[int(new.find('18K')):]
138
+ # value_18k = eighteenk[int(eighteenk.find('\n\n') + 1): int(eighteenk.find('\n\n+'))][3:]
139
+ # value_18k = value_18k.split('\n')[0]
140
+
141
+ # return value_24k, value_22k, value_18k
142
+
143
+ # # Helper function to insert data only once per day (no time constraint)
144
+ # def insert_data_if_not_exists(city, date, value_24k, value_22k, value_18k):
145
+ # query = {"Date": date, "Place": city}
146
+ # if not collection.find_one(query):
147
+ # document = {
148
+ # "Date": date,
149
+ # "Place": city,
150
+ # "GoldRate_24k": float(value_24k.replace(',', '')),
151
+ # "GoldRate_22k": float(value_22k.replace(',', '')),
152
+ # "GoldRate_18k": float(value_18k.replace(',', ''))
153
+ # }
154
+ # collection.insert_one(document)
155
+
156
+ # # Function to fetch weekly data for chart
157
+ # def fetch_weekly_data(city):
158
+ # today = datetime.datetime.now(ist_timezone)
159
+ # start_date = today - datetime.timedelta(days=7)
160
+ # query = {"Place": city, "Date": {"$gte": start_date.strftime("%Y-%m-%d")}}
161
+ # return list(collection.find(query).sort("Date", -1))
162
+
163
+ # # Function to check if it's the first run of the day after 12:30 PM IST
164
+ # def is_first_run_after_1230():
165
+ # today = datetime.datetime.now(ist_timezone)
166
+ # time_check = today.replace(hour=12, minute=30, second=0, microsecond=0)
167
+ # date_check = today.strftime("%Y-%m-%d")
168
+ # return today >= time_check and not collection.find_one({"Date": date_check})
169
+
170
+ # # Fetch and save rates for all cities
171
+ # def fetch_and_save_all_cities():
172
+ # date_today = datetime.datetime.now(ist_timezone).strftime("%Y-%m-%d")
173
+ # for city in cities:
174
+ # city_url = f"https://www.goodreturns.in/gold-rates/{city}.html"
175
+ # try:
176
+ # value_24k, value_22k, value_18k = price_cities(city_url)
177
+ # insert_data_if_not_exists(city, date_today, value_24k, value_22k, value_18k)
178
+ # except Exception as e:
179
+ # st.error(f"Could not fetch the gold rates for {city}. {e}")
180
+
181
+ # # List of cities
182
+ # cities = ['Hyderabad', 'Ahmedabad', 'Ayodhya', 'Bangalore', 'Bhubaneswar', 'Chandigarh', 'Chennai',
183
+ # 'Coimbatore', 'Delhi', 'Jaipur', 'Kerala', 'Kolkata', 'Lucknow',
184
+ # 'Madurai', 'Mangalore', 'Mumbai', 'Mysore', 'Nagpur', 'Nashik', 'Patna',
185
+ # 'Pune', 'Rajkot', 'Salem', 'Surat', 'Trichy', 'Vadodara', 'Vijayawada', 'Visakhapatnam']
186
+
187
+ # # Main UI
188
+ # st.title('Gold Rates in Indian Cities')
189
+ # st.subheader('Select a city to view the current gold rates and a weekly trend.')
190
+ # st.sidebar.title("About the Project")
191
+ # st.sidebar.write("This project fetches current gold rates for 24K, 22K, and 18K gold from GoodReturns for 28 Indian states. The rates for 1g, 8g, and 10g are displayed.")
192
+ # st.sidebar.write("**Developed by:**")
193
+ # st.sidebar.write("[Srish Rachamalla](https://www.linkedin.com/in/srishrachamalla/)")
194
+ # st.sidebar.write("[Sai Teja Pallerla](https://www.linkedin.com/in/saiteja-pallerla-668734225/)")
195
+
196
+ # # Dropdown for city selection
197
+ # selected_city = st.selectbox('Select a City', cities)
198
+
199
+ # # Generate button
200
+ # if st.button("Generate Gold Rates"):
201
+ # # If it's the first time after 12:30 PM, fetch and save rates for all cities
202
+ # if is_first_run_after_1230():
203
+ # fetch_and_save_all_cities()
204
+ # st.success("Gold rates for all cities have been fetched and saved.")
205
+
206
+ # # Fetch and display gold rates for the selected city
207
+ # if selected_city:
208
+ # date_today = datetime.datetime.now(ist_timezone).strftime("%Y-%m-%d")
209
+ # city_url = f"https://www.goodreturns.in/gold-rates/{selected_city}.html"
210
+
211
+ # try:
212
+ # value_24k, value_22k, value_18k = price_cities(city_url)
213
+ # insert_data_if_not_exists(selected_city, date_today, value_24k, value_22k, value_18k)
214
+
215
+ # # Prepare data for current rates
216
+ # current_data = {
217
+ # 'Gold Purity': ['24K', '22K', '18K'],
218
+ # '1g Price (₹)': [float(value_24k.replace(',', '')), float(value_22k.replace(',', '')), float(value_18k.replace(',', ''))],
219
+ # '8g Price (₹)': [float(value_24k.replace(',', '')) * 8, float(value_22k.replace(',', '')) * 8, float(value_18k.replace(',', '')) * 8],
220
+ # '10g Price (₹)': [float(value_24k.replace(',', '')) * 10, float(value_22k.replace(',', '')) * 10, float(value_18k.replace(',', '')) * 10]
221
+ # }
222
+
223
+ # # Display current data
224
+ # df = pd.DataFrame(current_data)
225
+ # st.write(f"Gold rates in {selected_city} as of {date_today}:")
226
+ # st.dataframe(df.style.format(precision=2).set_properties(**{
227
+ # 'background-color': 'black',
228
+ # 'color': 'white',
229
+ # 'border-color': 'gray'
230
+ # }))
231
+
232
+ # # Weekly trend data
233
+ # weekly_data = fetch_weekly_data(selected_city)
234
+ # if weekly_data:
235
+ # dates = [doc["Date"] for doc in weekly_data]
236
+ # rates_24k = [doc["GoldRate_24k"] for doc in weekly_data]
237
+ # rates_22k = [doc["GoldRate_22k"] for doc in weekly_data]
238
+ # rates_18k = [doc["GoldRate_18k"] for doc in weekly_data]
239
+
240
+ # # Plot weekly trends
241
+ # plt.figure(figsize=(10, 5))
242
+ # plt.plot(dates, rates_24k, label="24K Gold", color="gold", marker='o')
243
+ # plt.plot(dates, rates_22k, label="22K Gold", color="red", marker='o')
244
+ # plt.plot(dates, rates_18k, label="18K Gold", color="brown", marker='o')
245
+ # plt.title(f"Gold Rates Trend in {selected_city} (Past Week)")
246
+ # plt.xlabel("Date")
247
+ # plt.ylabel("Price (₹)")
248
+ # plt.legend()
249
+ # plt.xticks(rotation=45)
250
+ # st.pyplot(plt)
251
+
252
+ # except Exception as e:
253
+ # st.error(f"Could not fetch the gold rates. Please try again. {e}")
254
+
255
+ # # Footer
256
+ # st.markdown("<br><hr><center><p style='color: grey;'>© 2024 All Rights Reserved</p></center><br>", unsafe_allow_html=True)
257
+
258
  import streamlit as st
259
  import requests
260
  import pandas as pd
261
  import pymongo
262
  import datetime
263
+ import pytz
264
  from pymongo import MongoClient
265
+ import plotly.graph_objs as go
266
+ from plotly.subplots import make_subplots
267
  import ssl
 
 
 
 
 
 
268
 
269
  # Setting up IST timezone
270
  ist_timezone = pytz.timezone("Asia/Kolkata")
271
+ Mongo_ip = os.getenv("Mongo_IP")
272
 
273
  # Connect to MongoDB
274
+ MONGO_URI = Mongo_ip
275
+ # client = MongoClient(MONGO_URI, ssl=True, ssl_cert_reqs=ssl.CERT_NONE)
276
  client = MongoClient(
277
+ MONGO_URI,
278
  ssl=True,
279
  ssl_cert_reqs=ssl.CERT_NONE # Bypass SSL certificate verification
280
  )
281
  db = client.GoldRates
282
  collection = db['GoldRates']
283
+ # List of cities
284
+ cities = ['Hyderabad', 'Ahmedabad', 'Ayodhya', 'Bangalore', 'Bhubaneswar', 'Chandigarh', 'Chennai',
285
+ 'Coimbatore', 'Delhi', 'Jaipur', 'Kerala', 'Kolkata', 'Lucknow',
286
+ 'Madurai', 'Mangalore', 'Mumbai', 'Mysore', 'Nagpur', 'Nashik', 'Patna',
287
+ 'Pune', 'Rajkot', 'Salem', 'Surat', 'Trichy', 'Vadodara', 'Vijayawada', 'Visakhapatnam']
288
  # Backend functions
289
  def jina(url):
290
  base_url = "https://r.jina.ai/"
291
+ response = requests.get(base_url + url)
 
292
  return response.text
 
293
  def price_cities(url):
294
  text = jina(url)
295
  pos1 = text.find('**')
 
309
 
310
  return value_24k, value_22k, value_18k
311
 
 
312
  def insert_data_if_not_exists(city, date, value_24k, value_22k, value_18k):
313
+ if not collection.find_one({"Date": date, "Place": city}):
 
314
  document = {
315
  "Date": date,
316
  "Place": city,
 
320
  }
321
  collection.insert_one(document)
322
 
 
323
  def fetch_weekly_data(city):
324
  today = datetime.datetime.now(ist_timezone)
325
  start_date = today - datetime.timedelta(days=7)
326
+ return list(collection.find({"Place": city, "Date": {"$gte": start_date.strftime("%Y-%m-%d")}}).sort("Date", -1))
 
327
 
 
328
  def is_first_run_after_1230():
329
  today = datetime.datetime.now(ist_timezone)
330
  time_check = today.replace(hour=12, minute=30, second=0, microsecond=0)
331
  date_check = today.strftime("%Y-%m-%d")
332
  return today >= time_check and not collection.find_one({"Date": date_check})
333
 
 
334
  def fetch_and_save_all_cities():
335
  date_today = datetime.datetime.now(ist_timezone).strftime("%Y-%m-%d")
336
  for city in cities:
 
341
  except Exception as e:
342
  st.error(f"Could not fetch the gold rates for {city}. {e}")
343
 
344
+ # Get last Friday's date
345
+ def get_last_friday():
346
+ today = datetime.datetime.now(ist_timezone)
347
+ last_friday = today - datetime.timedelta(days=(today.weekday() - 4) % 7)
348
+ return last_friday.strftime("%Y-%m-%d")
349
+ def fetch_historical_data(city, days=365): # Default to the past year
350
+ end_date = datetime.datetime.now(ist_timezone)
351
+ start_date = end_date - datetime.timedelta(days=days)
352
+ return list(collection.find({"Place": city, "Date": {"$gte": start_date.strftime("%Y-%m-%d"), "$lte": end_date.strftime("%Y-%m-%d")}}).sort("Date", 1))
353
+ def display_city_gold_rates(city):
354
+ today = datetime.datetime.now(ist_timezone)
355
+ date_to_fetch = today.strftime("%Y-%m-%d")
 
 
 
 
 
356
 
357
+ if today.weekday() >= 5: # Weekend
358
+ st.info("Today is a weekend. Showing last available data.")
 
 
 
 
359
 
360
+ # Attempt to retrieve document for today's date
361
+ doc = collection.find_one({"Date": date_to_fetch, "Place": city})
 
 
362
 
363
+ if not doc:
364
+ st.warning(f"No data found for {city} on {date_to_fetch}. Scraping for latest data...")
365
+ city_url = f"https://www.goodreturns.in/gold-rates/{city}.html"
366
  try:
367
  value_24k, value_22k, value_18k = price_cities(city_url)
368
+ insert_data_if_not_exists(city, date_to_fetch, value_24k, value_22k, value_18k)
369
+ st.success(f"Fetched latest gold rates for {city}.")
370
 
371
+ # Prepare current rates table with newly scraped data
372
  current_data = {
373
  'Gold Purity': ['24K', '22K', '18K'],
374
  '1g Price (₹)': [float(value_24k.replace(',', '')), float(value_22k.replace(',', '')), float(value_18k.replace(',', ''))],
 
378
 
379
  # Display current data
380
  df = pd.DataFrame(current_data)
381
+ # st.dataframe(df)
382
+
383
+ # Create a styled dataframe for Streamlit
384
+ styled_df = df.style.format(precision=2).set_properties(**{
385
  'background-color': 'black',
386
  'color': 'white',
387
+ 'border-color': 'gray',
388
+ 'font-size': '16px',
389
+ 'text-align': 'center'
390
+ }).set_table_attributes('style="width: 80%; margin: auto;"') # Center the table
391
+
392
+ st.dataframe(styled_df)
393
+
394
+ # Fetch historical data
395
+ historical_data = fetch_historical_data(city)
396
+
397
+ if historical_data:
398
+ dates = [doc["Date"] for doc in historical_data]
399
+ rates_24k = [doc["GoldRate_24k"] for doc in historical_data]
400
+ rates_22k = [doc["GoldRate_22k"] for doc in historical_data]
401
+ rates_18k = [doc["GoldRate_18k"] for doc in historical_data]
402
+
403
+ # Create an interactive Plotly line chart for the historical data
404
+ fig = make_subplots(specs=[[{"secondary_y": False}]])
405
+
406
+ # Add 24K data trace
407
+ fig.add_trace(
408
+ go.Scatter(x=dates, y=rates_24k, mode='lines+markers', name="24K Gold",
409
+ line=dict(color="gold"), marker=dict(size=8)),
410
+ secondary_y=False,
411
+ )
412
+
413
+ # Add 22K data trace
414
+ fig.add_trace(
415
+ go.Scatter(x=dates, y=rates_22k, mode='lines+markers', name="22K Gold",
416
+ line=dict(color="red"), marker=dict(size=8)),
417
+ secondary_y=False,
418
+ )
419
+
420
+ # Add 18K data trace
421
+ fig.add_trace(
422
+ go.Scatter(x=dates, y=rates_18k, mode='lines+markers', name="18K Gold",
423
+ line=dict(color="brown"), marker=dict(size=8)),
424
+ secondary_y=False,
425
+ )
426
+
427
+ # Set chart titles and layout
428
+ fig.update_layout(
429
+ title_text=f"Gold Rates Trend in {city} (Historical Data)",
430
+ xaxis_title="Date",
431
+ yaxis_title="Price (₹)",
432
+ hovermode="x unified",
433
+ template="plotly_dark"
434
+ )
435
+
436
+ # Display the interactive chart in Streamlit
437
+ st.plotly_chart(fig, use_container_width=True)
438
+ else:
439
+ st.warning(f"No historical data found for {city}.")
440
 
441
  except Exception as e:
442
+ st.error(f"Could not fetch the gold rates for {city}. {e}")
443
+ return
444
+ # else:
445
+ # st.success(f"Gold Rates for {city} on {date_to_fetch}")
446
+ # Prepare current rates table
447
+ if doc:
448
+ st.success(f"Gold Rates for {city} on {date_to_fetch}")
449
+
450
+ # Prepare data for current rates
451
+ current_data = {
452
+ 'Gold Purity': ['24K', '22K', '18K'],
453
+ '1g Price (₹)': [doc["GoldRate_24k"], doc["GoldRate_22k"], doc["GoldRate_18k"]],
454
+ '8g Price (₹)': [doc["GoldRate_24k"] * 8, doc["GoldRate_22k"] * 8, doc["GoldRate_18k"] * 8],
455
+ '10g Price (₹)': [doc["GoldRate_24k"] * 10, doc["GoldRate_22k"] * 10, doc["GoldRate_18k"] * 10]
456
+ }
457
+
458
+ # Display current data as a stylish table
459
+ df = pd.DataFrame(current_data)
460
+
461
+ # Create a styled dataframe for Streamlit
462
+ styled_df = df.style.format(precision=2).set_properties(**{
463
+ 'background-color': 'black',
464
+ 'color': 'white',
465
+ 'border-color': 'gray',
466
+ 'font-size': '16px',
467
+ 'text-align': 'center'
468
+ }).set_table_attributes('style="width: 80%; margin: auto;"') # Center the table
469
+
470
+ st.dataframe(styled_df)
471
+
472
+ # Fetch historical data
473
+ historical_data = fetch_historical_data(city)
474
+
475
+ if historical_data:
476
+ dates = [doc["Date"] for doc in historical_data]
477
+ rates_24k = [doc["GoldRate_24k"] for doc in historical_data]
478
+ rates_22k = [doc["GoldRate_22k"] for doc in historical_data]
479
+ rates_18k = [doc["GoldRate_18k"] for doc in historical_data]
480
+
481
+ # Create an interactive Plotly line chart for the historical data
482
+ fig = make_subplots(specs=[[{"secondary_y": False}]])
483
+
484
+ # Add 24K data trace
485
+ fig.add_trace(
486
+ go.Scatter(x=dates, y=rates_24k, mode='lines+markers', name="24K Gold",
487
+ line=dict(color="gold"), marker=dict(size=8)),
488
+ secondary_y=False,
489
+ )
490
+
491
+ # Add 22K data trace
492
+ fig.add_trace(
493
+ go.Scatter(x=dates, y=rates_22k, mode='lines+markers', name="22K Gold",
494
+ line=dict(color="red"), marker=dict(size=8)),
495
+ secondary_y=False,
496
+ )
497
+
498
+ # Add 18K data trace
499
+ fig.add_trace(
500
+ go.Scatter(x=dates, y=rates_18k, mode='lines+markers', name="18K Gold",
501
+ line=dict(color="brown"), marker=dict(size=8)),
502
+ secondary_y=False,
503
+ )
504
+
505
+ # Set chart titles and layout
506
+ fig.update_layout(
507
+ title_text=f"Gold Rates Trend in {city} (Historical Data)",
508
+ xaxis_title="Date",
509
+ yaxis_title="Price (₹)",
510
+ hovermode="x unified",
511
+ template="plotly_dark"
512
+ )
513
+
514
+ # Display the interactive chart in Streamlit
515
+ st.plotly_chart(fig, use_container_width=True)
516
+ else:
517
+ st.warning(f"No historical data found for {city}.")
518
+ # else:
519
+ # st.warning(f"No data found for {city} on {date_to_fetch}.")
520
+ # Main UI
521
+ st.title('Gold Rates in Indian Cities')
522
+ st.subheader('Select a city to view the current gold rates and a weekly trend.')
523
+ st.sidebar.title("About the Project")
524
+ st.sidebar.write("This project fetches current gold rates for 24K, 22K, and 18K gold from GoodReturns for 28 Indian states. The rates for 1g, 8g, and 10g are displayed.")
525
+ st.sidebar.write("**Developed by:**")
526
+ st.sidebar.write("[Srish Rachamalla](https://www.linkedin.com/in/srishrachamalla/)")
527
+ st.sidebar.write("[Sai Teja Pallerla](https://www.linkedin.com/in/saiteja-pallerla-668734225/)")
528
 
529
+ selected_city = st.selectbox('Select a City', cities)
 
530
 
531
+ if st.button("Generate Gold Rates for Selected City"):
532
+ if is_first_run_after_1230() and datetime.datetime.now(ist_timezone).weekday() not in [5, 6]:
533
+ fetch_and_save_all_cities()
534
+ st.success("Gold rates for all cities have been fetched and saved.")
535
+ if selected_city:
536
+ display_city_gold_rates(selected_city)
537
+
538
+ if st.button("Generate All Gold Rates"):
539
+ current_time = datetime.datetime.now(ist_timezone).time()
540
+ if current_time >= datetime.time(13, 0) and datetime.datetime.now(ist_timezone).weekday() not in [5, 6]:
541
+ for city in cities:
542
+ if not collection.find_one({"Date": datetime.datetime.now(ist_timezone).strftime("%Y-%m-%d"), "Place": city}):
543
+ city_url = f"https://www.goodreturns.in/gold-rates/{city}.html"
544
+ try:
545
+ value_24k, value_22k, value_18k = price_cities(city_url)
546
+ insert_data_if_not_exists(city, datetime.datetime.now(ist_timezone).strftime("%Y-%m-%d"), value_24k, value_22k, value_18k)
547
+ st.success(f"Gold rates for {city} saved successfully.")
548
+ except Exception as e:
549
+ st.error(f"Could not fetch the gold rates for {city}. {e}")
550
+ st.success("Gold rates for all cities have been fetched and saved.")
551
+ else:
552
+ st.warning("Gold rates can only be saved to the database after 1 PM on weekdays.")
553
+ for city in cities:
554
+ st.subheader(f"Gold Rates in {city} as of {datetime.datetime.now(ist_timezone).strftime('%Y-%m-%d')}")
555
+ display_city_gold_rates(city)