File size: 6,357 Bytes
5bdd16f
 
18fb305
 
 
 
 
1add288
18fb305
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import openai

# Add your OpenAI API key here
openai.api_key = st.secrets["OPEN_AI_KEY"]

st.title("Transaction Analysis")

# Load the data
df_converted = pd.read_csv('payments_optimized.csv')

# Convert CreatedDate to datetime
df_converted['CreatedDate'] = pd.to_datetime(df_converted['CreatedDate'])

# Function to analyze transaction data
def analyze_transaction_data(df):
    summary = {
        "total_transactions": len(df),
        "total_amount": df['Amount'].sum(),
        "average_amount": df['Amount'].mean(),
        "max_amount": df['Amount'].max(),
        "min_amount": df['Amount'].min(),
        "median_amount": df['Amount'].median(),
        "transaction_trend": df.groupby(df['CreatedDate'].dt.to_period("M"))['Amount'].sum().tolist()
    }
    return summary

# Function to get response from ChatGPT
def get_chatgpt_response(prompt):
    response = openai.ChatCompletion.create(
        model="gpt-4o",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": prompt}
        ],
        max_tokens=500
    )
    return response.choices[0].message['content'].strip()

# Function to send report to ChatGPT
def send_report(plot_title, data):
    summary = analyze_transaction_data(data)
    prompt = f"""
    Transaction Data Insights:
    1. Total Transactions: {summary['total_transactions']}
    2. Total Amount Transacted: ${summary['total_amount']:.2f}
    3. Average Transaction Amount: ${summary['average_amount']:.2f}
    4. Maximum Transaction Amount: ${summary['max_amount']:.2f}
    5. Minimum Transaction Amount: ${summary['min_amount']:.2f}
    6. Median Transaction Amount: ${summary['median_amount']:.2f}

    Provide strategic ideas based on this data.
    """
    response = get_chatgpt_response(prompt)
    st.session_state['chat_with_gpt'] = f"Report for {plot_title} sent to ChatGPT. Data Summary: {summary}\n\nChatGPT Response: {response}"
    st.experimental_rerun()

# Plotting Transaction Amounts over Time with clickable dots
st.subheader('Transaction Amounts Over Time')
fig = px.scatter(
    df_converted,
    x='CreatedDate',
    y='Amount',
    custom_data=['CustomerName', 'PaymentMethod', 'Store', 'InvoiceType', 'TransactionType'],
    title='Transaction Amounts Over Time'
)

fig.update_traces(
    marker=dict(size=10),
    selector=dict(mode='markers'),
    hovertemplate=(
        'Date: %{x}<br>'
        'Amount: $%{y}<br>'
        'Customer: %{customdata[0]}<br>'
        'Payment Method: %{customdata[1]}<br>'
        'Store: %{customdata[2]}<br>'
        'Invoice Type: %{customdata[3]}<br>'
        'Transaction Type: %{customdata[4]}<br>'
    )
)

# Convert Plotly figure to a FigureWidget
fig_widget = go.FigureWidget(fig)

# Function to display click data
def display_click_data(trace, points, state):
    if points.point_inds:
        point = points.point_inds[0]
        selected_data = df_converted.iloc[point]
        st.session_state['selected_point'] = selected_data.to_dict()
        st.experimental_rerun()

# Add click event handler
fig_widget.data[0].on_click(display_click_data)

# Display the plot
st.plotly_chart(fig_widget)

# Display details when a point is clicked
if 'selected_point' in st.session_state:
    st.write('Details for selected transaction:')
    st.write(st.session_state['selected_point'])

# Button to send report to ChatGPT
if st.button("Executive Report - Transaction Amounts Over Time"):
    send_report("Transaction Amounts Over Time", df_converted[
        ['CreatedDate', 'Amount', 'CustomerName', 'PaymentMethod', 'Store', 'InvoiceType', 'TransactionType']]
    )

# Plotting Payment Method Preferences
st.subheader('Payment Method Preferences')
payment_method_counts_converted = df_converted['PaymentMethod'].value_counts().reset_index()
payment_method_counts_converted.columns = ['PaymentMethod', 'Count']
fig = px.bar(payment_method_counts_converted, x='PaymentMethod', y='Count', title='Payment Method Preferences')
fig.update_layout(xaxis_title='Payment Method', yaxis_title='Number of Transactions')
st.plotly_chart(fig)

# Button to send report to ChatGPT
if st.button("Executive Report - Payment Method Preferences"):
    send_report("Payment Method Preferences", payment_method_counts_converted)

# Calculate the total amount of payments for the most frequent customers
top_customers = df_converted['CustomerName'].value_counts().index[:10]
total_amounts = df_converted[df_converted['CustomerName'].isin(top_customers)].groupby('CustomerName', observed=True)[
    'Amount'].sum().reset_index()

# Plot the total payment amounts for the most frequent customers
st.subheader('Total Payment Amounts for Most Frequent Customers')
fig = px.bar(total_amounts, x='CustomerName', y='Amount', title='Total Payment Amounts for Most Frequent Customers')
fig.update_layout(xaxis_title='Customer Name', yaxis_title='Total Transaction Amount ($)', yaxis_tickprefix='$')
st.plotly_chart(fig)

# Button to send report to ChatGPT
if st.button("Executive Report - Total Payment Amounts for Most Frequent Customers"):
    send_report("Total Payment Amounts for Most Frequent Customers", total_amounts)

# Simulated chat with ChatGPT
if 'chat_with_gpt' in st.session_state:
    st.subheader("Chat with ChatGPT")
    st.write(st.session_state['chat_with_gpt'])
    user_input = st.text_input("Your question for ChatGPT:", key="chat_input")
    if st.button("Send"):
        if user_input:
            summary = analyze_transaction_data(df_converted)
            prompt = f"""
            Transaction Data Insights:
            1. Total Transactions: {summary['total_transactions']}
            2. Total Amount Transacted: ${summary['total_amount']:.2f}
            3. Average Transaction Amount: ${summary['average_amount']:.2f}
            4. Maximum Transaction Amount: ${summary['max_amount']:.2f}
            5. Minimum Transaction Amount: ${summary['min_amount']:.2f}
            6. Median Transaction Amount: ${summary['median_amount']:.2f}

            User Question: {user_input}
            """
            response = get_chatgpt_response(prompt)
            st.write(f"ChatGPT Response: {response}")
        else:
            st.write("Please enter a question for ChatGPT.")