Akshayram1 commited on
Commit
a0a9810
·
verified ·
1 Parent(s): 7ade7b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -121
app.py CHANGED
@@ -3,123 +3,102 @@ import firebase_admin
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
- # [Previous initialization code remains the same until the main() function]
 
 
 
 
 
 
 
10
 
11
- def create_trend_chart(df):
12
- """Create a line chart showing transaction trends"""
13
- # Group by date and transaction type
14
- daily_trends = df.pivot_table(
15
- index='Transaction Date',
16
- columns='Transaction Type',
17
- values='Amount',
18
- aggfunc='sum'
19
- ).fillna(0)
20
-
21
- fig = go.Figure()
22
-
23
- if 'credited' in daily_trends.columns:
24
- fig.add_trace(go.Scatter(
25
- x=daily_trends.index,
26
- y=daily_trends['credited'],
27
- name='Credited',
28
- line=dict(color='#00CC96', width=3),
29
- fill='tonexty'
30
- ))
31
-
32
- if 'debited' in daily_trends.columns:
33
- fig.add_trace(go.Scatter(
34
- x=daily_trends.index,
35
- y=daily_trends['debited'],
36
- name='Debited',
37
- line=dict(color='#EF553B', width=3),
38
- fill='tonexty'
39
- ))
40
-
41
- fig.update_layout(
42
- title='Daily Transaction Trends',
43
- xaxis_title='Date',
44
- yaxis_title='Amount (₹)',
45
- hovermode='x unified',
46
- showlegend=True,
47
- legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
48
- height=400
49
- )
50
-
51
- return fig
52
 
53
- def create_distribution_chart(df):
54
- """Create a pie chart for transaction distribution"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  type_summary = df.groupby('Transaction Type').agg({
 
56
  'Amount': 'sum'
57
  }).reset_index()
58
 
59
- fig = px.pie(
 
 
 
60
  type_summary,
61
- values='Amount',
62
  names='Transaction Type',
63
- title='Transaction Amount Distribution',
64
  color='Transaction Type',
65
  color_discrete_map={'credited': '#00CC96', 'debited': '#EF553B'},
66
  hole=0.4
67
  )
68
 
69
- fig.update_traces(
70
- textposition='inside',
71
- textinfo='percent+value',
72
- pull=[0.1, 0.1],
73
- marker=dict(line=dict(color='#FFFFFF', width=2))
74
- )
75
-
76
- fig.update_layout(
77
- showlegend=True,
78
- legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
79
- height=400
80
- )
81
-
82
- return fig
83
-
84
- def create_daily_comparison(df):
85
- """Create a bar chart comparing daily credited vs debited amounts"""
86
- daily_comparison = df.pivot_table(
87
- index='Transaction Date',
88
- columns='Transaction Type',
89
- values='Amount',
90
- aggfunc='sum'
91
- ).fillna(0)
92
-
93
- fig = go.Figure()
94
-
95
- if 'credited' in daily_comparison.columns:
96
- fig.add_trace(go.Bar(
97
- name='Credited',
98
- x=daily_comparison.index,
99
- y=daily_comparison['credited'],
100
- marker_color='#00CC96'
101
- ))
102
-
103
- if 'debited' in daily_comparison.columns:
104
- fig.add_trace(go.Bar(
105
- name='Debited',
106
- x=daily_comparison.index,
107
- y=daily_comparison['debited'],
108
- marker_color='#EF553B'
109
- ))
110
-
111
- fig.update_layout(
112
- title='Daily Transaction Comparison',
113
- xaxis_title='Date',
114
- yaxis_title='Amount (₹)',
115
- barmode='group',
116
- hovermode='x unified',
117
- showlegend=True,
118
- legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
119
- height=400
120
  )
121
 
122
- return fig
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
 
124
  def main():
125
  st.set_page_config(page_title="Financial Transactions Dashboard", layout="wide")
@@ -174,7 +153,6 @@ def main():
174
  masked_df = df[df['Transaction Date'].isin(selected_dates)]
175
 
176
  # Dashboard metrics
177
- st.subheader("Transaction Summary")
178
  col1, col2, col3 = st.columns(3)
179
 
180
  with col1:
@@ -188,27 +166,7 @@ def main():
188
  total_credited = masked_df[masked_df['Transaction Type'] == 'credited']['Amount'].sum()
189
  st.metric("Total Credited", f"₹ {total_credited:,.2f}")
190
 
191
- # Visualizations Section
192
- st.markdown("---")
193
- st.subheader("Transaction Analysis")
194
-
195
- # Create three columns for visualizations
196
- col1, col2, col3 = st.columns(3)
197
-
198
- with col1:
199
- trend_fig = create_trend_chart(masked_df)
200
- st.plotly_chart(trend_fig, use_container_width=True)
201
-
202
- with col2:
203
- dist_fig = create_distribution_chart(masked_df)
204
- st.plotly_chart(dist_fig, use_container_width=True)
205
-
206
- with col3:
207
- comp_fig = create_daily_comparison(masked_df)
208
- st.plotly_chart(comp_fig, use_container_width=True)
209
-
210
  # Transactions table
211
- st.markdown("---")
212
  st.subheader("Recent Transactions")
213
  st.dataframe(
214
  masked_df,
@@ -221,6 +179,24 @@ def main():
221
  hide_index=True
222
  )
223
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
  # Download button
225
  if st.button("Download Transactions"):
226
  csv = masked_df.to_csv(index=False)
 
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
9
+ try:
10
+ app = firebase_admin.get_app()
11
+ except ValueError:
12
+ cred = credentials.Certificate("serviceAccountKey.json")
13
+ app = firebase_admin.initialize_app(cred, {
14
+ 'databaseURL': 'https://transacapp-22b6e-default-rtdb.firebaseio.com/'
15
+ })
16
 
17
+ def fetch_usernames():
18
+ """Fetch list of all usernames from Firebase"""
19
+ try:
20
+ ref = db.reference('financialMessages')
21
+ users = ref.get()
22
+ if users:
23
+ return list(users.keys())
24
+ return []
25
+ except Exception as e:
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:
36
+ return []
37
+
38
+ messages = []
39
+ for transaction_id, data in transactions.items():
40
+ if isinstance(data, dict):
41
+ messages.append({
42
+ 'Transaction ID': transaction_id,
43
+ 'Account Number': data.get('accountNumber', ''),
44
+ 'Amount': float(data.get('amount', 0)),
45
+ 'Reference No': data.get('referenceNo', ''),
46
+ 'Transaction Date': data.get('transactionDate', ''),
47
+ 'Transaction Type': data.get('transactionType', '')
48
+ })
49
+
50
+ return messages
51
+ except Exception as e:
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")
 
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
  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
  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)