File size: 8,276 Bytes
d967fbb 91417fc d967fbb 91417fc d967fbb 91417fc d967fbb 91417fc d967fbb 91417fc d967fbb 1f2ca66 d967fbb 91417fc 1f2ca66 91417fc d967fbb 91417fc d967fbb 91417fc d967fbb 91417fc d967fbb 91417fc d967fbb 91417fc d967fbb 91417fc d967fbb 91417fc d967fbb 91417fc d967fbb 91417fc d967fbb 91417fc d967fbb 91417fc d967fbb 91417fc d967fbb | 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 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | import streamlit as st
import firebase_admin
from firebase_admin import credentials, db
import pandas as pd
import plotly.express as px
from datetime import datetime
# Initialize Firebase Realtime Database
try:
app = firebase_admin.get_app()
except ValueError:
cred = credentials.Certificate("serviceAccountKey.json")
app = firebase_admin.initialize_app(cred, {
'databaseURL': 'https://transacapp-22b6e-default-rtdb.firebaseio.com/'
})
def fetch_usernames():
"""Fetch list of all usernames from Firebase"""
try:
ref = db.reference('financialMessages')
users = ref.get()
if users:
return list(users.keys())
return []
except Exception as e:
st.error(f"Error fetching usernames: {str(e)}")
return []
def fetch_user_transactions(username, selected_month):
"""Fetch financial messages for a specific user and month from Firebase"""
try:
ref = db.reference(f'financialMessages/{username}/{selected_month}')
transactions = ref.get()
if not transactions:
return []
messages = []
for transaction_id, data in transactions.items():
if isinstance(data, dict):
messages.append({
'Person Name': data.get('personName', ''),
'Account Number': data.get('accountNumber', ''),
'Amount': float(data.get('amount', 0)),
'Reference No': data.get('referenceNo', ''),
'Transaction Date': data.get('transactionDate', ''),
'Transaction Type': data.get('transactionType', '')
})
return messages
except Exception as e:
st.error(f"Error fetching data: {str(e)}")
return []
def create_transaction_distribution_chart(df):
"""Create an enhanced transaction distribution visualization with multiple chart types"""
# Calculate transaction type summaries
type_summary = df.groupby('Transaction Type').agg({
'Person Name': 'count',
'Amount': ['sum', 'mean', 'min', 'max']
}).round(2)
type_summary.columns = ['Count', 'Total Amount', 'Average Amount', 'Min Amount', 'Max Amount']
type_summary = type_summary.reset_index()
# Create bar chart comparing transaction counts and amounts
fig_comparison = px.bar(
type_summary,
x='Transaction Type',
y=['Count', 'Total Amount'],
barmode='group',
title='Transaction Comparison by Type',
labels={'value': 'Value', 'variable': 'Metric'},
color_discrete_sequence=['#4C78A8', '#72B7B2'],
template='plotly_white'
)
fig_comparison.update_layout(
xaxis_title="Transaction Type",
yaxis_title="Value",
legend_title="Metric",
height=400,
showlegend=True,
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
)
)
# Create detailed metrics visualization
fig_metrics = px.bar(
type_summary.melt(
id_vars=['Transaction Type'],
value_vars=['Average Amount', 'Min Amount', 'Max Amount']
),
x='Transaction Type',
y='value',
color='variable',
barmode='group',
title='Transaction Amount Metrics by Type',
labels={'value': 'Amount (₹)', 'variable': 'Metric'},
color_discrete_sequence=['#FF9DA7', '#9C755F', '#BAB0AC'],
template='plotly_white'
)
fig_metrics.update_layout(
xaxis_title="Transaction Type",
yaxis_title="Amount (₹)",
height=400,
showlegend=True,
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
)
)
# Add hover information
for fig in [fig_comparison, fig_metrics]:
fig.update_traces(
hovertemplate="<br>".join([
"Transaction Type: %{x}",
"Value: %{y:,.2f}",
"<extra></extra>"
])
)
return fig_comparison, fig_metrics
def main():
st.set_page_config(page_title="Financial Transactions Dashboard", layout="wide")
# Header
st.title("Financial Transactions Dashboard")
st.markdown("---")
# Sidebar filters
st.sidebar.header("Filters")
# Username dropdown
usernames = fetch_usernames()
username = st.sidebar.selectbox(
"Select Username",
options=usernames if usernames else ["No users found"]
)
# Month selection
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
selected_month = st.sidebar.selectbox("Select Month", options=months)
if username and username != "No users found":
# Fetch data
data = fetch_user_transactions(username, selected_month)
if data:
df = pd.DataFrame(data)
df['Amount'] = pd.to_numeric(df['Amount'])
# Transaction type dropdown
transaction_type = st.sidebar.selectbox(
"Select Transaction Type",
options=["All", "debited", "credited"]
)
# Date filter
dates = df['Transaction Date'].unique()
selected_dates = st.sidebar.multiselect(
"Select Dates",
options=dates,
default=dates
)
# Apply filters
if transaction_type != "All":
masked_df = df[
(df['Transaction Type'] == transaction_type) &
(df['Transaction Date'].isin(selected_dates))
]
else:
masked_df = df[df['Transaction Date'].isin(selected_dates)]
# Dashboard metrics
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Total Transactions", len(masked_df))
with col2:
total_debited = masked_df[masked_df['Transaction Type'] == 'debited']['Amount'].sum()
st.metric("Total Debited", f"₹ {total_debited:,.2f}")
with col3:
total_credited = masked_df[masked_df['Transaction Type'] == 'credited']['Amount'].sum()
st.metric("Total Credited", f"₹ {total_credited:,.2f}")
# Transactions table
st.subheader("Recent Transactions")
st.dataframe(
masked_df,
column_config={
"Amount": st.column_config.NumberColumn(
"Amount",
format="₹ %.2f"
)
},
hide_index=True
)
# Create transaction distribution visualizations
fig_count, fig_amount = create_transaction_distribution_chart(masked_df)
# Display visualizations in columns
st.subheader("Transaction Distribution Analysis")
col1, col2 = st.columns(2)
with col1:
st.plotly_chart(fig_count, use_container_width=True)
with col2:
st.plotly_chart(fig_amount, use_container_width=True)
# Daily transactions chart
st.subheader("Daily Transaction Amounts")
daily_amounts = masked_df.groupby('Transaction Date')['Amount'].sum()
st.line_chart(daily_amounts)
# Download button
if st.button("Download Transactions"):
csv = masked_df.to_csv(index=False)
st.download_button(
label="Download CSV",
data=csv,
file_name=f"{username}_{selected_month}_transactions.csv",
mime="text/csv"
)
else:
st.warning(f"No transactions found for user: {username} in {selected_month}")
if __name__ == "__main__":
main() |