File size: 11,593 Bytes
e03d20d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import gradio as gr
import os
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
import torch
import requests
import json
from datetime import datetime

class FinanceAgent:
    def __init__(self):
        """Initialize the Finance Agent with a language model"""
        try:
            # Use a lightweight model that works well for text generation
            model_name = "microsoft/DialoGPT-medium"
            self.tokenizer = AutoTokenizer.from_pretrained(model_name)
            self.model = AutoModelForCausalLM.from_pretrained(model_name)
            
            # Add padding token if it doesn't exist
            if self.tokenizer.pad_token is None:
                self.tokenizer.pad_token = self.tokenizer.eos_token
                
            self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
            self.model.to(self.device)
            
        except Exception as e:
            print(f"Error initializing model: {e}")
            self.model = None
            self.tokenizer = None
    
    def get_finance_knowledge_base(self):
        """Finance knowledge base for common topics"""
        return {
            "stocks": {
                "definition": "Stocks represent ownership shares in a company",
                "key_points": [
                    "Stock prices fluctuate based on supply and demand",
                    "Dividends provide regular income to shareholders",
                    "Growth stocks focus on capital appreciation",
                    "Value stocks are typically undervalued by the market",
                    "Diversification reduces investment risk"
                ]
            },
            "bonds": {
                "definition": "Bonds are debt securities issued by corporations or governments",
                "key_points": [
                    "Bonds pay fixed interest over time",
                    "Government bonds are generally safer than corporate bonds",
                    "Bond prices move inversely to interest rates",
                    "Credit rating affects bond yields",
                    "Bonds provide portfolio stability"
                ]
            },
            "cryptocurrency": {
                "definition": "Digital currencies secured by cryptography",
                "key_points": [
                    "Bitcoin was the first cryptocurrency",
                    "Blockchain technology ensures security",
                    "High volatility characterizes crypto markets",
                    "Regulatory uncertainty affects prices",
                    "Limited supply drives scarcity value"
                ]
            },
            "investing": {
                "definition": "Allocating money to generate returns over time",
                "key_points": [
                    "Start early to benefit from compound interest",
                    "Diversify across asset classes",
                    "Consider risk tolerance and time horizon",
                    "Regular investing through dollar-cost averaging",
                    "Rebalance portfolio periodically"
                ]
            },
            "retirement": {
                "definition": "Planning for financial security after working years",
                "key_points": [
                    "401(k) plans offer tax advantages",
                    "IRA accounts provide additional savings options",
                    "Social Security provides base income",
                    "Healthcare costs increase in retirement",
                    "Estate planning protects beneficiaries"
                ]
            },
            "budgeting": {
                "definition": "Planning and controlling personal expenses",
                "key_points": [
                    "Track income and expenses regularly",
                    "Follow the 50/30/20 rule for allocation",
                    "Build an emergency fund",
                    "Automate savings and bill payments",
                    "Review and adjust budget monthly"
                ]
            }
        }
    
    def generate_finance_response(self, user_input):
        """Generate a comprehensive finance response"""
        user_input_lower = user_input.lower()
        knowledge_base = self.get_finance_knowledge_base()
        
        # Find relevant topics
        relevant_topics = []
        for topic, info in knowledge_base.items():
            if topic in user_input_lower or any(keyword in user_input_lower for keyword in [topic]):
                relevant_topics.append((topic, info))
        
        # Generate response
        if relevant_topics:
            response = f"## Finance Topic: {user_input}\n\n"
            
            for topic, info in relevant_topics:
                response += f"### {topic.title()}\n"
                response += f"**Definition:** {info['definition']}\n\n"
                response += "**Key Points:**\n"
                for point in info['key_points']:
                    response += f"• {point}\n"
                response += "\n"
        else:
            # General finance advice
            response = f"## Finance Topic: {user_input}\n\n"
            response += self.generate_general_advice(user_input)
        
        # Add disclaimer
        response += "\n---\n"
        response += "*Disclaimer: This information is for educational purposes only and should not be considered as financial advice. Please consult with a qualified financial advisor for personalized guidance.*"
        
        return response
    
    def generate_general_advice(self, topic):
        """Generate general financial advice for unknown topics"""
        general_tips = [
            "Consider your financial goals and risk tolerance",
            "Diversification is key to managing investment risk",
            "Start with fundamental analysis before making decisions",
            "Keep informed about market trends and economic indicators",
            "Consider consulting with financial professionals",
            "Maintain an emergency fund for unexpected expenses",
            "Regular review and adjustment of financial strategies is important"
        ]
        
        response = f"Here's some general guidance regarding '{topic}':\n\n"
        response += "**General Financial Principles:**\n"
        for tip in general_tips[:5]:  # Show first 5 tips
            response += f"• {tip}\n"
        
        response += f"\n**Specific to '{topic}':**\n"
        response += f"• Research thoroughly before making any financial decisions related to {topic}\n"
        response += f"• Understand the risks and potential returns associated with {topic}\n"
        response += f"• Consider how {topic} fits into your overall financial portfolio\n"
        
        return response

# Initialize the finance agent
finance_agent = FinanceAgent()

def process_finance_query(user_input, history):
    """Process user input and return finance advice"""
    if not user_input.strip():
        return "Please enter a finance topic or question.", history
    
    try:
        # Generate response
        response = finance_agent.generate_finance_response(user_input)
        
        # Update history
        history.append([user_input, response])
        
        return "", history
        
    except Exception as e:
        error_response = f"I apologize, but I encountered an error processing your request: {str(e)}\n\nPlease try rephrasing your question."
        history.append([user_input, error_response])
        return "", history

def clear_conversation():
    """Clear the conversation history"""
    return [], ""

# Create Gradio interface
with gr.Blocks(
    theme=gr.themes.Soft(),
    title="Finance Agent",
    css="""
    .container {
        max-width: 800px;
        margin: 0 auto;
    }
    .header {
        text-align: center;
        padding: 20px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 10px;
        margin-bottom: 20px;
    }
    """
) as demo:
    
    gr.HTML("""
    <div class="header">
        <h1>🏦 Finance Agent</h1>
        <p>Your AI-powered financial advisor for quick insights and guidance</p>
    </div>
    """)
    
    with gr.Row():
        with gr.Column(scale=1):
            gr.HTML("""
            <div style="background: #f8f9fa; padding: 15px; border-radius: 10px; margin-bottom: 15px;">
                <h3>💡 How to Use:</h3>
                <ul>
                    <li>Enter any finance topic (stocks, bonds, investing, etc.)</li>
                    <li>Ask questions about budgeting, retirement planning</li>
                    <li>Get quick insights on cryptocurrency, trading</li>
                    <li>Learn about financial planning strategies</li>
                </ul>
            </div>
            """)
            
            gr.HTML("""
            <div style="background: #e8f5e8; padding: 15px; border-radius: 10px;">
                <h3>📈 Popular Topics:</h3>
                <p><strong>Investing:</strong> Stocks, Bonds, ETFs</p>
                <p><strong>Planning:</strong> Retirement, Budgeting</p>
                <p><strong>Trading:</strong> Cryptocurrency, Options</p>
                <p><strong>Banking:</strong> Savings, Loans, Credit</p>
            </div>
            """)
    
    with gr.Column(scale=2):
        chatbot = gr.Chatbot(
            height=500,
            show_label=False,
            container=True,
            bubble_full_width=False
        )
        
        with gr.Row():
            user_input = gr.Textbox(
                placeholder="Enter your finance topic or question (e.g., 'stocks', 'retirement planning', 'cryptocurrency')",
                show_label=False,
                container=False,
                scale=4
            )
            submit_btn = gr.Button("Ask Agent", variant="primary", scale=1)
        
        with gr.Row():
            clear_btn = gr.Button("Clear Chat", variant="secondary")
            gr.HTML("<div style='flex: 1;'></div>")  # Spacer
    
    # Example questions
    gr.Examples(
        examples=[
            ["What are stocks and how do they work?"],
            ["How should I start investing as a beginner?"],
            ["Explain cryptocurrency basics"],
            ["What's the best budgeting strategy?"],
            ["How to plan for retirement?"],
            ["What are the differences between stocks and bonds?"]
        ],
        inputs=user_input,
        label="Example Questions"
    )
    
    # Event handlers
    submit_btn.click(
        process_finance_query,
        inputs=[user_input, chatbot],
        outputs=[user_input, chatbot]
    )
    
    user_input.submit(
        process_finance_query,
        inputs=[user_input, chatbot],
        outputs=[user_input, chatbot]
    )
    
    clear_btn.click(
        clear_conversation,
        outputs=[chatbot, user_input]
    )
    
    gr.HTML("""
    <div style="text-align: center; margin-top: 20px; padding: 15px; background: #f1f3f4; border-radius: 10px;">
        <p><strong>⚠️ Important Disclaimer:</strong> This AI agent provides educational information only. 
        Always consult qualified financial advisors for personalized advice.</p>
        <p>Built with ❤️ using Gradio and Hugging Face</p>
    </div>
    """)

# Launch configuration for Hugging Face Spaces
if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False
    )