import gradio as gr import groq import os import json from typing import Dict, List import pandas as pd from datetime import datetime from dotenv import load_dotenv # Load environment variables load_dotenv() class FinanceAIAgent: def __init__(self, api_key: str): self.client = groq.Client(api_key=api_key) self.model = "llama-3.3-70b-versatile" self.conversation_history = [] def generate_response(self, prompt: str, context: str = "") -> str: # Combine context and prompt full_prompt = f"{context}\n\nUser: {prompt}\nAssistant:" try: chat_completion = self.client.chat.completions.create( model=self.model, messages=[{"role": "user", "content": full_prompt}], temperature=0.7, max_tokens=1000 ) return chat_completion.choices[0].message.content except Exception as e: return f"Error generating response: {str(e)}" def analyze_portfolio(self, portfolio_data: str) -> str: prompt = f"""Analyze the following investment portfolio and provide insights: {portfolio_data} Include: 1. Risk assessment 2. Diversification analysis 3. Recommendations for rebalancing 4. Potential areas of concern""" return self.generate_response(prompt) def financial_planning(self, income: float, expenses: List[Dict], goals: List[str]) -> str: prompt = f"""Create a financial plan based on: Income: ${income} Monthly Expenses: {json.dumps(expenses, indent=2)} Financial Goals: {json.dumps(goals, indent=2)} Provide: 1. Budget breakdown 2. Savings recommendations 3. Investment strategies 4. Timeline for achieving goals""" return self.generate_response(prompt) def market_analysis(self, ticker: str, timeframe: str) -> str: prompt = f"""Provide a detailed market analysis for {ticker} over {timeframe} timeframe. Include: 1. Technical analysis perspectives 2. Fundamental factors 3. Market sentiment 4. Risk factors 5. Potential catalysts""" return self.generate_response(prompt) def create_finance_ai_interface(): agent = FinanceAIAgent(api_key=os.getenv("GROQ_API_KEY")) with gr.Blocks(title="Finance AI Assistant") as interface: gr.Markdown("# Finance AI Assistant") with gr.Tab("Portfolio Analysis"): portfolio_input = gr.Textbox( label="Enter portfolio details (ticker symbols and allocations)", placeholder="AAPL: 25%, MSFT: 25%, GOOGL: 25%, AMZN: 25%" ) portfolio_button = gr.Button("Analyze Portfolio") portfolio_output = gr.Textbox(label="Analysis Results") portfolio_button.click( fn=agent.analyze_portfolio, inputs=[portfolio_input], outputs=portfolio_output ) with gr.Tab("Financial Planning"): with gr.Row(): income_input = gr.Number(label="Monthly Income ($)") with gr.Row(): expenses_input = gr.Dataframe( headers=["Category", "Amount"], datatype=["str", "number"], label="Monthly Expenses" ) goals_input = gr.Textbox( label="Financial Goals (one per line)", placeholder="1. Save for retirement\n2. Buy a house\n3. Start a business" ) planning_button = gr.Button("Generate Financial Plan") planning_output = gr.Textbox(label="Financial Plan") def process_financial_plan(income, expenses_df, goals): expenses = expenses_df.to_dict('records') goals_list = [g.strip() for g in goals.split('\n') if g.strip()] return agent.financial_planning(income, expenses, goals_list) planning_button.click( fn=process_financial_plan, inputs=[income_input, expenses_input, goals_input], outputs=planning_output ) with gr.Tab("Market Analysis"): with gr.Row(): ticker_input = gr.Textbox(label="Stock Ticker") timeframe_input = gr.Dropdown( choices=["1 day", "1 week", "1 month", "3 months", "1 year"], label="Timeframe" ) market_button = gr.Button("Analyze Market") market_output = gr.Textbox(label="Market Analysis") market_button.click( fn=agent.market_analysis, inputs=[ticker_input, timeframe_input], outputs=market_output ) with gr.Tab("AI Chat"): chatbot = gr.Chatbot() msg = gr.Textbox(label="Ask anything about finance") clear = gr.Button("Clear") def respond(message, history): history.append((message, agent.generate_response(message))) return "", history msg.submit(respond, [msg, chatbot], [msg, chatbot]) clear.click(lambda: None, None, chatbot, queue=False) return interface # Launch the interface if __name__ == "__main__": interface = create_finance_ai_interface() interface.launch() # import gradio as gr # import groq # import pandas as pd # from datetime import datetime # import plotly.express as px # import json # import os # from typing import List, Dict # from dotenv import load_dotenv # # Load environment variables # load_dotenv() # # Initialize Groq client # client = groq.Groq(api_key=os.environ["GROQ_API_KEY"]) # class FinanceAgent: # def __init__(self): # self.transactions = [] # self.budgets = {} # self.goals = [] # def get_ai_advice(self, query: str) -> str: # """Get financial advice from LLaMA model via Groq""" # chat_completion = client.chat.completions.create( # messages=[{ # "role": "system", # "content": "You are a financial advisor. Provide clear, actionable advice." # }, { # "role": "user", # "content": query # }], # model="llama-3.3-70b-versatile", # temperature=0.7, # ) # return chat_completion.choices[0].message.content # def add_transaction(self, amount: float, category: str, description: str) -> Dict: # """Add a new transaction""" # transaction = { # "date": datetime.now().strftime("%Y-%m-%d"), # "amount": amount, # "category": category, # "description": description # } # self.transactions.append(transaction) # return {"status": "success", "message": "Transaction added successfully"} # def set_budget(self, category: str, amount: float) -> Dict: # """Set a budget for a category""" # self.budgets[category] = amount # return {"status": "success", "message": f"Budget set for {category}"} # def get_spending_analysis(self) -> Dict: # """Analyze spending patterns""" # df = pd.DataFrame(self.transactions) # if df.empty: # return {"status": "error", "message": "No transactions found"} # spending_by_category = df.groupby('category')['amount'].sum().to_dict() # return { # "status": "success", # "spending": spending_by_category, # "total": sum(spending_by_category.values()) # } # def create_interface(): # agent = FinanceAgent() # with gr.Blocks(title="Personal Finance Assistant") as interface: # gr.Markdown("# Personal Finance Assistant") # with gr.Tab("Transactions"): # with gr.Row(): # amount_input = gr.Number(label="Amount") # category_input = gr.Dropdown( # choices=["Groceries", "Utilities", "Entertainment", "Transportation", "Other"], # label="Category" # ) # description_input = gr.Textbox(label="Description") # add_btn = gr.Button("Add Transaction") # transaction_output = gr.JSON(label="Result") # add_btn.click( # fn=agent.add_transaction, # inputs=[amount_input, category_input, description_input], # outputs=transaction_output # ) # with gr.Tab("Budgeting"): # with gr.Row(): # budget_category = gr.Dropdown( # choices=["Groceries", "Utilities", "Entertainment", "Transportation", "Other"], # label="Category" # ) # budget_amount = gr.Number(label="Budget Amount") # set_budget_btn = gr.Button("Set Budget") # budget_output = gr.JSON(label="Result") # set_budget_btn.click( # fn=agent.set_budget, # inputs=[budget_category, budget_amount], # outputs=budget_output # ) # with gr.Tab("Analysis"): # analyze_btn = gr.Button("Analyze Spending") # spending_output = gr.JSON(label="Spending Analysis") # analyze_btn.click( # fn=agent.get_spending_analysis, # outputs=spending_output # ) # with gr.Tab("AI Advisor"): # query_input = gr.Textbox(label="Ask for financial advice") # advice_btn = gr.Button("Get Advice") # advice_output = gr.Textbox(label="AI Advice") # advice_btn.click( # fn=agent.get_ai_advice, # inputs=query_input, # outputs=advice_output # ) # return interface # if __name__ == "__main__": # interface = create_interface() # interface.launch()