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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import groq
|
| 3 |
+
import os
|
| 4 |
+
import json
|
| 5 |
+
from typing import Dict, List
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
from dotenv import load_dotenv
|
| 9 |
+
|
| 10 |
+
# Load environment variables
|
| 11 |
+
load_dotenv()
|
| 12 |
+
|
| 13 |
+
class FinanceAIAgent:
|
| 14 |
+
def __init__(self, api_key: str):
|
| 15 |
+
self.client = groq.Client(api_key=api_key)
|
| 16 |
+
self.model = "llama-3.3-70b-versatile"
|
| 17 |
+
self.conversation_history = []
|
| 18 |
+
|
| 19 |
+
def generate_response(self, prompt: str, context: str = "") -> str:
|
| 20 |
+
# Combine context and prompt
|
| 21 |
+
full_prompt = f"{context}\n\nUser: {prompt}\nAssistant:"
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
chat_completion = self.client.chat.completions.create(
|
| 25 |
+
model=self.model,
|
| 26 |
+
messages=[{"role": "user", "content": full_prompt}],
|
| 27 |
+
temperature=0.7,
|
| 28 |
+
max_tokens=1000
|
| 29 |
+
)
|
| 30 |
+
return chat_completion.choices[0].message.content
|
| 31 |
+
except Exception as e:
|
| 32 |
+
return f"Error generating response: {str(e)}"
|
| 33 |
+
|
| 34 |
+
def analyze_portfolio(self, portfolio_data: str) -> str:
|
| 35 |
+
prompt = f"""Analyze the following investment portfolio and provide insights:
|
| 36 |
+
{portfolio_data}
|
| 37 |
+
Include:
|
| 38 |
+
1. Risk assessment
|
| 39 |
+
2. Diversification analysis
|
| 40 |
+
3. Recommendations for rebalancing
|
| 41 |
+
4. Potential areas of concern"""
|
| 42 |
+
return self.generate_response(prompt)
|
| 43 |
+
|
| 44 |
+
def financial_planning(self, income: float, expenses: List[Dict], goals: List[str]) -> str:
|
| 45 |
+
prompt = f"""Create a financial plan based on:
|
| 46 |
+
Income: ${income}
|
| 47 |
+
Monthly Expenses: {json.dumps(expenses, indent=2)}
|
| 48 |
+
Financial Goals: {json.dumps(goals, indent=2)}
|
| 49 |
+
|
| 50 |
+
Provide:
|
| 51 |
+
1. Budget breakdown
|
| 52 |
+
2. Savings recommendations
|
| 53 |
+
3. Investment strategies
|
| 54 |
+
4. Timeline for achieving goals"""
|
| 55 |
+
return self.generate_response(prompt)
|
| 56 |
+
|
| 57 |
+
def market_analysis(self, ticker: str, timeframe: str) -> str:
|
| 58 |
+
prompt = f"""Provide a detailed market analysis for {ticker} over {timeframe} timeframe.
|
| 59 |
+
Include:
|
| 60 |
+
1. Technical analysis perspectives
|
| 61 |
+
2. Fundamental factors
|
| 62 |
+
3. Market sentiment
|
| 63 |
+
4. Risk factors
|
| 64 |
+
5. Potential catalysts"""
|
| 65 |
+
return self.generate_response(prompt)
|
| 66 |
+
|
| 67 |
+
def create_finance_ai_interface():
|
| 68 |
+
agent = FinanceAIAgent(api_key=os.getenv("GROQ_API_KEY"))
|
| 69 |
+
|
| 70 |
+
with gr.Blocks(title="Finance AI Assistant") as interface:
|
| 71 |
+
gr.Markdown("# Finance AI Assistant")
|
| 72 |
+
|
| 73 |
+
with gr.Tab("Portfolio Analysis"):
|
| 74 |
+
portfolio_input = gr.Textbox(
|
| 75 |
+
label="Enter portfolio details (ticker symbols and allocations)",
|
| 76 |
+
placeholder="AAPL: 25%, MSFT: 25%, GOOGL: 25%, AMZN: 25%"
|
| 77 |
+
)
|
| 78 |
+
portfolio_button = gr.Button("Analyze Portfolio")
|
| 79 |
+
portfolio_output = gr.Textbox(label="Analysis Results")
|
| 80 |
+
|
| 81 |
+
portfolio_button.click(
|
| 82 |
+
fn=agent.analyze_portfolio,
|
| 83 |
+
inputs=[portfolio_input],
|
| 84 |
+
outputs=portfolio_output
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
with gr.Tab("Financial Planning"):
|
| 88 |
+
with gr.Row():
|
| 89 |
+
income_input = gr.Number(label="Monthly Income ($)")
|
| 90 |
+
|
| 91 |
+
with gr.Row():
|
| 92 |
+
expenses_input = gr.Dataframe(
|
| 93 |
+
headers=["Category", "Amount"],
|
| 94 |
+
datatype=["str", "number"],
|
| 95 |
+
label="Monthly Expenses"
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
goals_input = gr.Textbox(
|
| 99 |
+
label="Financial Goals (one per line)",
|
| 100 |
+
placeholder="1. Save for retirement\n2. Buy a house\n3. Start a business"
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
planning_button = gr.Button("Generate Financial Plan")
|
| 104 |
+
planning_output = gr.Textbox(label="Financial Plan")
|
| 105 |
+
|
| 106 |
+
def process_financial_plan(income, expenses_df, goals):
|
| 107 |
+
expenses = expenses_df.to_dict('records')
|
| 108 |
+
goals_list = [g.strip() for g in goals.split('\n') if g.strip()]
|
| 109 |
+
return agent.financial_planning(income, expenses, goals_list)
|
| 110 |
+
|
| 111 |
+
planning_button.click(
|
| 112 |
+
fn=process_financial_plan,
|
| 113 |
+
inputs=[income_input, expenses_input, goals_input],
|
| 114 |
+
outputs=planning_output
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
with gr.Tab("Market Analysis"):
|
| 118 |
+
with gr.Row():
|
| 119 |
+
ticker_input = gr.Textbox(label="Stock Ticker")
|
| 120 |
+
timeframe_input = gr.Dropdown(
|
| 121 |
+
choices=["1 day", "1 week", "1 month", "3 months", "1 year"],
|
| 122 |
+
label="Timeframe"
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
market_button = gr.Button("Analyze Market")
|
| 126 |
+
market_output = gr.Textbox(label="Market Analysis")
|
| 127 |
+
|
| 128 |
+
market_button.click(
|
| 129 |
+
fn=agent.market_analysis,
|
| 130 |
+
inputs=[ticker_input, timeframe_input],
|
| 131 |
+
outputs=market_output
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
with gr.Tab("AI Chat"):
|
| 135 |
+
chatbot = gr.Chatbot()
|
| 136 |
+
msg = gr.Textbox(label="Ask anything about finance")
|
| 137 |
+
clear = gr.Button("Clear")
|
| 138 |
+
|
| 139 |
+
def respond(message, history):
|
| 140 |
+
history.append((message, agent.generate_response(message)))
|
| 141 |
+
return "", history
|
| 142 |
+
|
| 143 |
+
msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
| 144 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
| 145 |
+
|
| 146 |
+
return interface
|
| 147 |
+
|
| 148 |
+
# Launch the interface
|
| 149 |
+
if __name__ == "__main__":
|
| 150 |
+
interface = create_finance_ai_interface()
|
| 151 |
+
interface.launch()
|
| 152 |
+
|
| 153 |
+
# import gradio as gr
|
| 154 |
+
# import groq
|
| 155 |
+
# import pandas as pd
|
| 156 |
+
# from datetime import datetime
|
| 157 |
+
# import plotly.express as px
|
| 158 |
+
# import json
|
| 159 |
+
# import os
|
| 160 |
+
# from typing import List, Dict
|
| 161 |
+
# from dotenv import load_dotenv
|
| 162 |
+
|
| 163 |
+
# # Load environment variables
|
| 164 |
+
# load_dotenv()
|
| 165 |
+
|
| 166 |
+
# # Initialize Groq client
|
| 167 |
+
# client = groq.Groq(api_key=os.environ["GROQ_API_KEY"])
|
| 168 |
+
|
| 169 |
+
# class FinanceAgent:
|
| 170 |
+
# def __init__(self):
|
| 171 |
+
# self.transactions = []
|
| 172 |
+
# self.budgets = {}
|
| 173 |
+
# self.goals = []
|
| 174 |
+
|
| 175 |
+
# def get_ai_advice(self, query: str) -> str:
|
| 176 |
+
# """Get financial advice from LLaMA model via Groq"""
|
| 177 |
+
# chat_completion = client.chat.completions.create(
|
| 178 |
+
# messages=[{
|
| 179 |
+
# "role": "system",
|
| 180 |
+
# "content": "You are a financial advisor. Provide clear, actionable advice."
|
| 181 |
+
# }, {
|
| 182 |
+
# "role": "user",
|
| 183 |
+
# "content": query
|
| 184 |
+
# }],
|
| 185 |
+
# model="llama-3.3-70b-versatile",
|
| 186 |
+
# temperature=0.7,
|
| 187 |
+
# )
|
| 188 |
+
# return chat_completion.choices[0].message.content
|
| 189 |
+
|
| 190 |
+
# def add_transaction(self, amount: float, category: str, description: str) -> Dict:
|
| 191 |
+
# """Add a new transaction"""
|
| 192 |
+
# transaction = {
|
| 193 |
+
# "date": datetime.now().strftime("%Y-%m-%d"),
|
| 194 |
+
# "amount": amount,
|
| 195 |
+
# "category": category,
|
| 196 |
+
# "description": description
|
| 197 |
+
# }
|
| 198 |
+
# self.transactions.append(transaction)
|
| 199 |
+
# return {"status": "success", "message": "Transaction added successfully"}
|
| 200 |
+
|
| 201 |
+
# def set_budget(self, category: str, amount: float) -> Dict:
|
| 202 |
+
# """Set a budget for a category"""
|
| 203 |
+
# self.budgets[category] = amount
|
| 204 |
+
# return {"status": "success", "message": f"Budget set for {category}"}
|
| 205 |
+
|
| 206 |
+
# def get_spending_analysis(self) -> Dict:
|
| 207 |
+
# """Analyze spending patterns"""
|
| 208 |
+
# df = pd.DataFrame(self.transactions)
|
| 209 |
+
# if df.empty:
|
| 210 |
+
# return {"status": "error", "message": "No transactions found"}
|
| 211 |
+
|
| 212 |
+
# spending_by_category = df.groupby('category')['amount'].sum().to_dict()
|
| 213 |
+
# return {
|
| 214 |
+
# "status": "success",
|
| 215 |
+
# "spending": spending_by_category,
|
| 216 |
+
# "total": sum(spending_by_category.values())
|
| 217 |
+
# }
|
| 218 |
+
|
| 219 |
+
# def create_interface():
|
| 220 |
+
# agent = FinanceAgent()
|
| 221 |
+
|
| 222 |
+
# with gr.Blocks(title="Personal Finance Assistant") as interface:
|
| 223 |
+
# gr.Markdown("# Personal Finance Assistant")
|
| 224 |
+
|
| 225 |
+
# with gr.Tab("Transactions"):
|
| 226 |
+
# with gr.Row():
|
| 227 |
+
# amount_input = gr.Number(label="Amount")
|
| 228 |
+
# category_input = gr.Dropdown(
|
| 229 |
+
# choices=["Groceries", "Utilities", "Entertainment", "Transportation", "Other"],
|
| 230 |
+
# label="Category"
|
| 231 |
+
# )
|
| 232 |
+
# description_input = gr.Textbox(label="Description")
|
| 233 |
+
# add_btn = gr.Button("Add Transaction")
|
| 234 |
+
# transaction_output = gr.JSON(label="Result")
|
| 235 |
+
|
| 236 |
+
# add_btn.click(
|
| 237 |
+
# fn=agent.add_transaction,
|
| 238 |
+
# inputs=[amount_input, category_input, description_input],
|
| 239 |
+
# outputs=transaction_output
|
| 240 |
+
# )
|
| 241 |
+
|
| 242 |
+
# with gr.Tab("Budgeting"):
|
| 243 |
+
# with gr.Row():
|
| 244 |
+
# budget_category = gr.Dropdown(
|
| 245 |
+
# choices=["Groceries", "Utilities", "Entertainment", "Transportation", "Other"],
|
| 246 |
+
# label="Category"
|
| 247 |
+
# )
|
| 248 |
+
# budget_amount = gr.Number(label="Budget Amount")
|
| 249 |
+
# set_budget_btn = gr.Button("Set Budget")
|
| 250 |
+
# budget_output = gr.JSON(label="Result")
|
| 251 |
+
|
| 252 |
+
# set_budget_btn.click(
|
| 253 |
+
# fn=agent.set_budget,
|
| 254 |
+
# inputs=[budget_category, budget_amount],
|
| 255 |
+
# outputs=budget_output
|
| 256 |
+
# )
|
| 257 |
+
|
| 258 |
+
# with gr.Tab("Analysis"):
|
| 259 |
+
# analyze_btn = gr.Button("Analyze Spending")
|
| 260 |
+
# spending_output = gr.JSON(label="Spending Analysis")
|
| 261 |
+
|
| 262 |
+
# analyze_btn.click(
|
| 263 |
+
# fn=agent.get_spending_analysis,
|
| 264 |
+
# outputs=spending_output
|
| 265 |
+
# )
|
| 266 |
+
|
| 267 |
+
# with gr.Tab("AI Advisor"):
|
| 268 |
+
# query_input = gr.Textbox(label="Ask for financial advice")
|
| 269 |
+
# advice_btn = gr.Button("Get Advice")
|
| 270 |
+
# advice_output = gr.Textbox(label="AI Advice")
|
| 271 |
+
|
| 272 |
+
# advice_btn.click(
|
| 273 |
+
# fn=agent.get_ai_advice,
|
| 274 |
+
# inputs=query_input,
|
| 275 |
+
# outputs=advice_output
|
| 276 |
+
# )
|
| 277 |
+
|
| 278 |
+
# return interface
|
| 279 |
+
|
| 280 |
+
# if __name__ == "__main__":
|
| 281 |
+
# interface = create_interface()
|
| 282 |
+
# interface.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
streamlit
|
| 2 |
+
gradio
|
| 3 |
+
phi
|
| 4 |
+
groq
|
| 5 |
+
pandas
|
| 6 |
+
python-dotenv
|
| 7 |
+
yfinance
|
| 8 |
+
datetime
|