Akshayram1 commited on
Commit
072a7e8
·
verified ·
1 Parent(s): a6fd225

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -75
app.py CHANGED
@@ -3,6 +3,7 @@ import firebase_admin
3
  from firebase_admin import credentials, db
4
  import pandas as pd
5
  import plotly.express as px
 
6
  from datetime import datetime
7
 
8
  # Initialize Firebase Realtime Database
@@ -26,10 +27,30 @@ def fetch_usernames():
26
  st.error(f"Error fetching usernames: {str(e)}")
27
  return []
28
 
29
- def fetch_user_transactions(username, selected_month):
30
- """Fetch financial messages for a specific user and month from Firebase"""
31
  try:
32
- ref = db.reference(f'financialMessages/{username}/{selected_month}')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  transactions = ref.get()
34
 
35
  if not transactions:
@@ -52,53 +73,7 @@ def fetch_user_transactions(username, selected_month):
52
  st.error(f"Error fetching data: {str(e)}")
53
  return []
54
 
55
- def create_transaction_distribution_chart(df):
56
- """Create an enhanced transaction distribution visualization"""
57
- # Calculate transaction type counts and amounts
58
- type_summary = df.groupby('Transaction Type').agg({
59
- 'Transaction ID': 'count',
60
- 'Amount': 'sum'
61
- }).reset_index()
62
-
63
- type_summary.columns = ['Transaction Type', 'Count', 'Total Amount']
64
-
65
- # Create pie chart for transaction counts
66
- fig_count = px.pie(
67
- type_summary,
68
- values='Count',
69
- names='Transaction Type',
70
- title='Transaction Distribution by Count',
71
- color='Transaction Type',
72
- color_discrete_map={'credited': '#00CC96', 'debited': '#EF553B'},
73
- hole=0.4
74
- )
75
-
76
- # Create pie chart for transaction amounts
77
- fig_amount = px.pie(
78
- type_summary,
79
- values='Total Amount',
80
- names='Transaction Type',
81
- title='Transaction Distribution by Amount',
82
- color='Transaction Type',
83
- color_discrete_map={'credited': '#00CC96', 'debited': '#EF553B'},
84
- hole=0.4
85
- )
86
-
87
- # Update layout for better appearance
88
- for fig in [fig_count, fig_amount]:
89
- fig.update_traces(
90
- textposition='inside',
91
- textinfo='percent+label',
92
- pull=[0.1, 0.1],
93
- marker=dict(line=dict(color='#FFFFFF', width=2))
94
- )
95
- fig.update_layout(
96
- showlegend=True,
97
- legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
98
- height=400
99
- )
100
-
101
- return fig_count, fig_amount
102
 
103
  def main():
104
  st.set_page_config(page_title="Financial Transactions Dashboard", layout="wide")
@@ -117,13 +92,21 @@ def main():
117
  options=usernames if usernames else ["No users found"]
118
  )
119
 
120
- # Month selection
121
- months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
122
- selected_month = st.sidebar.selectbox("Select Month", options=months)
123
-
124
  if username and username != "No users found":
 
 
 
 
 
 
 
 
 
 
 
125
  # Fetch data
126
- data = fetch_user_transactions(username, selected_month)
127
 
128
  if data:
129
  df = pd.DataFrame(data)
@@ -153,6 +136,7 @@ def main():
153
  masked_df = df[df['Transaction Date'].isin(selected_dates)]
154
 
155
  # Dashboard metrics
 
156
  col1, col2, col3 = st.columns(3)
157
 
158
  with col1:
@@ -166,7 +150,27 @@ def main():
166
  total_credited = masked_df[masked_df['Transaction Type'] == 'credited']['Amount'].sum()
167
  st.metric("Total Credited", f"₹ {total_credited:,.2f}")
168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  # Transactions table
 
170
  st.subheader("Recent Transactions")
171
  st.dataframe(
172
  masked_df,
@@ -179,35 +183,17 @@ def main():
179
  hide_index=True
180
  )
181
 
182
- # Create transaction distribution visualizations
183
- fig_count, fig_amount = create_transaction_distribution_chart(masked_df)
184
-
185
- # Display visualizations in columns
186
- st.subheader("Transaction Distribution Analysis")
187
- col1, col2 = st.columns(2)
188
-
189
- with col1:
190
- st.plotly_chart(fig_count, use_container_width=True)
191
-
192
- with col2:
193
- st.plotly_chart(fig_amount, use_container_width=True)
194
-
195
- # Daily transactions chart
196
- st.subheader("Daily Transaction Amounts")
197
- daily_amounts = masked_df.groupby('Transaction Date')['Amount'].sum()
198
- st.line_chart(daily_amounts)
199
-
200
  # Download button
201
  if st.button("Download Transactions"):
202
  csv = masked_df.to_csv(index=False)
203
  st.download_button(
204
  label="Download CSV",
205
  data=csv,
206
- file_name=f"{username}_{selected_month}_transactions.csv",
207
  mime="text/csv"
208
  )
209
  else:
210
- st.warning(f"No transactions found for user: {username} in {selected_month}")
211
 
212
  if __name__ == "__main__":
213
  main()
 
3
  from firebase_admin import credentials, db
4
  import pandas as pd
5
  import plotly.express as px
6
+ import plotly.graph_objects as go
7
  from datetime import datetime
8
 
9
  # Initialize Firebase Realtime Database
 
27
  st.error(f"Error fetching usernames: {str(e)}")
28
  return []
29
 
30
+ def fetch_available_years(username):
31
+ """Fetch available years for a specific user"""
32
  try:
33
+ ref = db.reference(f'financialMessages/{username}')
34
+ data = ref.get()
35
+ if data:
36
+ # Extract years from the data structure
37
+ years = set()
38
+ for key in data.keys():
39
+ # Assuming the structure includes year information
40
+ if isinstance(data[key], dict):
41
+ years.add(key.split('_')[0] if '_' in key else '2024') # Default to 2024 if no year specified
42
+ return sorted(list(years))
43
+ return ['2024'] # Default year if no data found
44
+ except Exception as e:
45
+ st.error(f"Error fetching years: {str(e)}")
46
+ return ['2024']
47
+
48
+ def fetch_user_transactions(username, selected_year, selected_month):
49
+ """Fetch financial messages for a specific user, year, and month from Firebase"""
50
+ try:
51
+ # Construct the path with year and month
52
+ path = f"{selected_month}_{selected_year}" if selected_year != "2024" else selected_month
53
+ ref = db.reference(f'financialMessages/{username}/{path}')
54
  transactions = ref.get()
55
 
56
  if not transactions:
 
73
  st.error(f"Error fetching data: {str(e)}")
74
  return []
75
 
76
+ # [Previous visualization functions remain the same]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
  def main():
79
  st.set_page_config(page_title="Financial Transactions Dashboard", layout="wide")
 
92
  options=usernames if usernames else ["No users found"]
93
  )
94
 
95
+ # Year selection
 
 
 
96
  if username and username != "No users found":
97
+ available_years = fetch_available_years(username)
98
+ selected_year = st.sidebar.selectbox(
99
+ "Select Year",
100
+ options=available_years,
101
+ index=len(available_years)-1 # Default to latest year
102
+ )
103
+
104
+ # Month selection
105
+ months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
106
+ selected_month = st.sidebar.selectbox("Select Month", options=months)
107
+
108
  # Fetch data
109
+ data = fetch_user_transactions(username, selected_year, selected_month)
110
 
111
  if data:
112
  df = pd.DataFrame(data)
 
136
  masked_df = df[df['Transaction Date'].isin(selected_dates)]
137
 
138
  # Dashboard metrics
139
+ st.subheader("Transaction Summary")
140
  col1, col2, col3 = st.columns(3)
141
 
142
  with col1:
 
150
  total_credited = masked_df[masked_df['Transaction Type'] == 'credited']['Amount'].sum()
151
  st.metric("Total Credited", f"₹ {total_credited:,.2f}")
152
 
153
+ # Visualizations Section
154
+ st.markdown("---")
155
+ st.subheader(f"Transaction Analysis - {selected_month} {selected_year}")
156
+
157
+ # Create three columns for visualizations
158
+ col1, col2, col3 = st.columns(3)
159
+
160
+ with col1:
161
+ trend_fig = create_trend_chart(masked_df)
162
+ st.plotly_chart(trend_fig, use_container_width=True)
163
+
164
+ with col2:
165
+ dist_fig = create_distribution_chart(masked_df)
166
+ st.plotly_chart(dist_fig, use_container_width=True)
167
+
168
+ with col3:
169
+ comp_fig = create_daily_comparison(masked_df)
170
+ st.plotly_chart(comp_fig, use_container_width=True)
171
+
172
  # Transactions table
173
+ st.markdown("---")
174
  st.subheader("Recent Transactions")
175
  st.dataframe(
176
  masked_df,
 
183
  hide_index=True
184
  )
185
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  # Download button
187
  if st.button("Download Transactions"):
188
  csv = masked_df.to_csv(index=False)
189
  st.download_button(
190
  label="Download CSV",
191
  data=csv,
192
+ file_name=f"{username}_{selected_year}_{selected_month}_transactions.csv",
193
  mime="text/csv"
194
  )
195
  else:
196
+ st.warning(f"No transactions found for user: {username} in {selected_month} {selected_year}")
197
 
198
  if __name__ == "__main__":
199
  main()