Spaces:
Sleeping
Sleeping
File size: 10,359 Bytes
c30d6e8 | 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 | 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() |