Spaces:
Runtime error

etf_bot_hf / app.py
SHIMCH's picture
Upload folder using huggingface_hub
1cd5164 verified
Raw History Blame Contribute Delete
15.3 kB
from enum import Enum
from typing import List, TypedDict, Annotated
from pydantic import BaseModel, Field
from decimal import Decimal
import ast
import re
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.messages import HumanMessage, AIMessage
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_community.tools import QuerySQLDatabaseTool
from langchain_community.utilities import SQLDatabase
# from langchain_ollama import OllamaEmbeddings
from langchain.agents.agent_toolkits import create_retriever_tool
from langgraph.graph import START, StateGraph
import gradio as gr
##################################################################
# ํ™˜๊ฒฝ ์„ค์ • / ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์—ฐ๊ฒฐ
##################################################################
from dotenv import load_dotenv
load_dotenv()
db = SQLDatabase.from_uri("sqlite:///etf_database_ref.db")
##################################################################
# ๊ณ ์œ ๋ช…์‚ฌ DB ๊ฒ€์ƒ‰
##################################################################
def query_as_list(db, query):
res = db.run(query)
res = [el for sub in ast.literal_eval(res) for el in sub if el]
res = [re.sub(r"\b\d+\b", "", string).strip() for string in res]
return list(set(res))
etfs = query_as_list(db, "SELECT ์ข…๋ชฉ๋ช… FROM ETFs")
fund_managers = query_as_list(db, "SELECT ์šด์šฉ์‚ฌ FROM ETFs")
underlying_assets = query_as_list(db, "SELECT ๊ธฐ์ดˆ์ž์‚ฐ FROM ETFsInfo")
# ์ž„๋ฒ ๋”ฉ ๋ชจ๋ธ ์ƒ์„ฑ
embeddings = OpenAIEmbeddings(model="text-embedding-3-large")
# ์ž„๋ฒ ๋”ฉ ๋ฒกํ„ฐ ์ €์žฅ์†Œ ์ƒ์„ฑ
vector_store = InMemoryVectorStore(embeddings)
# ETF ์ข…๋ชฉ๋ช…๊ณผ ์šด์šฉ์‚ฌ๋ฅผ ์ž„๋ฒ ๋”ฉ ๋ฒกํ„ฐ๋กœ ๋ณ€ํ™˜
_ = vector_store.add_texts(etfs + fund_managers + underlying_assets)
retriever = vector_store.as_retriever(search_kwargs={"k": 10})
# ๊ฒ€์ƒ‰ ํ”„๋กฌํ”„ํŠธ ์ƒ์„ฑ
description = (
"Use to look up values to filter on. Input is an approximate spelling "
"of the proper noun, output is valid proper nouns. Use the noun most "
"similar to the search."
)
# ๊ฒ€์ƒ‰ ๋„๊ตฌ ์ƒ์„ฑ
entity_retriever_tool = create_retriever_tool(
retriever,
name="search_proper_nouns",
description=description,
)
##################################################################
# ์ƒํƒœ ์ •๋ณด ํƒ€์ž… ์ •์˜
##################################################################
class State(TypedDict):
question: str # ์‚ฌ์šฉ์ž ์ž…๋ ฅ ์งˆ๋ฌธ
user_profile: dict # ์‚ฌ์šฉ์ž ํ”„๋กœํ•„ ์ •๋ณด
query: str # ์ƒ์„ฑ๋œ SQL ์ฟผ๋ฆฌ
candidates: list # ํ›„๋ณด ETF ๋ชฉ๋ก
rankings: list # ์ˆœ์œ„๊ฐ€ ๋งค๊ฒจ์ง„ ETF ๋ชฉ๋ก
explanation: str # ์ถ”์ฒœ ์ด์œ  ์„ค๋ช…
final_answer: str # ์ตœ์ข… ์ถ”์ฒœ ๋‹ต๋ณ€
##################################################################
# ์‚ฌ์šฉ์ž ํ”„๋กœํ•„ ๋ถ„์„
##################################################################
class RiskTolerance(str, Enum):
CONSERVATIVE = "conservative"
MODERATE = "moderate"
AGGRESSIVE = "aggressive"
class InvestmentHorizon(str, Enum):
SHORT = "short"
MEDIUM = "medium"
LONG = "long"
class InvestmentProfile(BaseModel):
risk_tolerance: RiskTolerance = Field(
description="ํˆฌ์ž์ž์˜ ์œ„ํ—˜ ์„ฑํ–ฅ (conservative/moderate/aggressive)"
)
investment_horizon: InvestmentHorizon = Field(
description="ํˆฌ์ž ๊ธฐ๊ฐ„ (short/medium/long)"
)
investment_goal: str = Field(
description="ํˆฌ์ž์˜ ์ฃผ์š” ๋ชฉ์  ์„ค๋ช…"
)
preferred_sectors: List[str] = Field(
description="์„ ํ˜ธํ•˜๋Š” ํˆฌ์ž ์„นํ„ฐ ๋ชฉ๋ก"
)
excluded_sectors: List[str] = Field(
description="ํˆฌ์ž๋ฅผ ์›ํ•˜์ง€ ์•Š๋Š” ์„นํ„ฐ ๋ชฉ๋ก"
)
monthly_investment: int = Field(
description="์›” ํˆฌ์ž ๊ฐ€๋Šฅ ๊ธˆ์•ก (์›)"
)
# ์‚ฌ์šฉ์ž ํ”„๋กœํ•„ ๋ถ„์„ ํ”„๋กฌํ”„ํŠธ
PROFILE_TEMPLATE= """
์‚ฌ์šฉ์ž์˜ ์งˆ๋ฌธ์„ ๋ถ„์„ํ•˜์—ฌ ํˆฌ์ž ํ”„๋กœํ•„์„ ์ƒ์„ฑํ•ด์ฃผ์„ธ์š”.
์‚ฌ์šฉ์ž ์งˆ๋ฌธ: {question}
"""
profile_prompt = ChatPromptTemplate.from_template(PROFILE_TEMPLATE)
# ์‚ฌ์šฉ์ž ํ”„๋กœํ•„ ๋ถ„์„ ๋ชจ๋ธ ์ƒ์„ฑ
llm = ChatOpenAI(model="gpt-4.1-mini")
profile_llm = llm.with_structured_output(InvestmentProfile)
# ์‚ฌ์šฉ์ž ํ”„๋กœํ•„ ๋ถ„์„ ํ•จ์ˆ˜
def analyze_profile(state: State) -> dict:
"""์‚ฌ์šฉ์ž ์งˆ๋ฌธ์„ ๋ถ„์„ํ•˜์—ฌ ํˆฌ์ž ํ”„๋กœํ•„ ์ƒ์„ฑ"""
prompt = profile_prompt.invoke({"question": state["question"]})
response = profile_llm.invoke(prompt)
return {"user_profile": dict(response)}
##################################################################
# SQL ์ฟผ๋ฆฌ ์ƒ์„ฑ
##################################################################
# SQL Query Generation Template
QUERY_TEMPLATE = """
Given an input question and investment profile, create a syntactically correct {dialect} query to run. Unless specified, limit your query to at most {top_k} results. Order the results by most relevant columns based on the investment profile.
Never query for all columns from a specific table, only ask for relevant columns given the question and investment criteria.
Pay attention to use only the column names you can see in the schema description. Be careful to not query for columns that do not exist. Also, pay attention to which column is in which table.
Available tables:
{table_info}
Entity relationships:
{entity_info}
- Use exact matches when comparing entity names
- Check for historical name variations if available
- Apply case-sensitive matching for official names
- Handle both Korean and English entity names when present
Investment Profile:
{user_profile}
Question: {input}
Important:
1. Use only existing columns
2. Query only necessary columns (no SELECT *)
3. Follow correct table relationships
4. Consider performance and indexing
"""
# SQL Query Generation Prompt Template
query_prompt_template = ChatPromptTemplate.from_template(QUERY_TEMPLATE)
# SQL Query Output
class QueryOutput(TypedDict):
"""Generated SQL query."""
query: Annotated[str, ..., "Syntactically valid SQL query."]
explanation: Annotated[str, ..., "Query explanation and selection criteria (in ํ•œ๊ตญ์–ด)"]
def write_query(state: State):
"""Generate SQL query to fetch information."""
prompt = query_prompt_template.invoke(
{
"dialect": db.dialect,
"top_k": 10,
"table_info": db.get_table_info(),
"input": state["question"],
"entity_info": entity_retriever_tool.invoke(state["question"]),
"user_profile": state["user_profile"],
}
)
structured_llm = llm.with_structured_output(QueryOutput)
result = structured_llm.invoke(prompt)
return {"query": result["query"], "explanation": result["explanation"]}
##################################################################
# ํ›„๋ณด ETF ๊ฒ€์ƒ‰
##################################################################
def execute_query(state: State) -> dict:
"""SQL ์ฟผ๋ฆฌ ์‹คํ–‰ํ•˜์—ฌ ํ›„๋ณด ETF ๊ฒ€์ƒ‰"""
execute_query_tool = QuerySQLDatabaseTool(db=db)
results = execute_query_tool.invoke(state["query"])
return {"candidates": results}
##################################################################
# ETF ์ˆœ์œ„ ๋งค๊ธฐ๊ธฐ
##################################################################
RANKING_TEMPLATE = """
Rank the following ETF candidates based on the user's investment profile and return the top 3(three) ETFs.
Consider these factors when ranking:
1. ์ˆ˜์ต๋ฅ 
2. ๋ณ€๋™์„ฑ
3. ์ˆœ์ž์‚ฐ์ด์•ก
4. ๋ณ€๋™์„ฑ
5. User Profile matching score
User Profile:
{user_profile}
Candidate ETFs:
{candidates}
"""
# ETF Ranking Prompt Template
ranking_prompt = ChatPromptTemplate.from_template(RANKING_TEMPLATE)
# ETF Ranking Output
class ETFRanking(TypedDict):
"""Individual ETF ranking result"""
rank: Annotated[int, ..., "Ranking position (1-5)"]
etf_code: Annotated[str, ..., "ETF ์ข…๋ชฉ์ฝ”๋“œ (6-digit)"]
etf_name: Annotated[str, ..., "ETF ์ข…๋ชฉ๋ช…"]
score: Annotated[float, ..., "Composite score (0-100)"]
ranking_reason: Annotated[str, ..., "Explanation for the ranking (in ํ•œ๊ตญ์–ด)"]
class ETFRankingResult(TypedDict):
"""Ranked ETFs"""
rankings: List[ETFRanking]
# ETF Ranking Function
def rank_etfs(state: State) -> dict:
"""Rank ETF candidates based on user's investment profile"""
prompt = ranking_prompt.invoke(
{
"user_profile": state["user_profile"],
"candidates": state["candidates"],
}
)
structured_llm = llm.with_structured_output(ETFRankingResult)
results = structured_llm.invoke(prompt)
return {"rankings": results}
##################################################################
# ์ถ”์ฒœ ์ด์œ  ์„ค๋ช…
##################################################################
EXPLANATION_TEMPLATE = """
Please provide a comprehensive explanation for the recommended ETFs based on the user's investment profile.
[GUIDELINES]
1. ETF Characteristics
- Investment strategy and approach
- Historical performance overview
- Fee structure and efficiency
- Underlying assets and diversification
2. Profile Fit Analysis
- Alignment with risk tolerance
- Match with investment horizon
- Sector preference compatibility
- Investment goal contribution
3. Portfolio Construction
- Recommended allocation percentages
- Diversification benefits
- Rebalancing considerations
- Implementation strategy
4. Risk Considerations
- Market risk factors
- Specific ETF risks
- Economic scenario impacts
- Monitoring requirements
--------------------------------------------
[User Profile]
{user_profile}
[Selected ETFs]
{rankings}
"""
# ์ถ”์ฒœ ์„ค๋ช… ํ”„๋กฌํ”„ํŠธ
explanation_prompt = ChatPromptTemplate.from_template(EXPLANATION_TEMPLATE)
# ์ถ”์ฒœ ์„ค๋ช… ์ถœ๋ ฅ ์Šคํ‚ค๋งˆ
class ETFRecommendation(BaseModel):
"""Individual ETF recommendation details"""
etf_code: str = Field(..., description="ETF ์ข…๋ชฉ์ฝ”๋“œ (6-digit)")
etf_name: str = Field(..., description="ETF ์ข…๋ชฉ๋ช…")
allocation: Decimal = Field(..., description="Recommended allocation % (0-100)")
description: str = Field(..., description="ETF description and investment strategy (in ํ•œ๊ตญ์–ด)")
key_points: List[str] = Field(..., description="Key investment points (in ํ•œ๊ตญ์–ด)")
risks: List[str] = Field(..., description="Risk factors to consider (in ํ•œ๊ตญ์–ด)")
class RecommendationExplanation(BaseModel):
"""ETF recommendation explanation with markdown formatting"""
overview: str = Field(..., description="Overall strategy explanation (in ํ•œ๊ตญ์–ด)")
recommendations: List[ETFRecommendation] = Field(..., description="ETF details")
considerations: List[str] = Field(..., description="Important considerations (in ํ•œ๊ตญ์–ด)")
# ๋งˆํฌ๋‹ค์šด ํฌ๋งท์œผ๋กœ ์ถœ๋ ฅ
def to_markdown(self) -> str:
"""Convert explanation to markdown format"""
markdown = [
"# ETF ํฌํŠธํด๋ฆฌ์˜ค ์ถ”์ฒœ",
"",
"## ํˆฌ์ž ์ „๋žต ๊ฐœ์š”",
self.overview,
"",
"## ์ถ”์ฒœ ETF ํฌํŠธํด๋ฆฌ์˜ค",
""
]
# ํฌํŠธํด๋ฆฌ์˜ค ๊ตฌ์„ฑ ๋น„์œจ
markdown.extend([
"| ETF | ์ข…๋ชฉ์ฝ”๋“œ | ์ถ”์ฒœ๋น„์ค‘ |",
"|-----|----------|----------|"
])
for rec in self.recommendations:
markdown.append(
f"| {rec.etf_name} | {rec.etf_code} | {rec.allocation}% |"
)
# ETF ์ƒ์„ธ ์„ค๋ช…
markdown.append("\n## ETF ์ƒ์„ธ ์„ค๋ช…\n")
for rec in self.recommendations:
markdown.extend([
f"### {rec.etf_name} ({rec.etf_code})",
rec.description,
"",
"**์ฃผ์š” ํˆฌ์ž ํฌ์ธํŠธ:**",
"".join([f"\n* {point}" for point in rec.key_points]),
"",
"**ํˆฌ์ž ์œ„ํ—˜:**",
"".join([f"\n* {risk}" for risk in rec.risks]),
""
])
# ํˆฌ์ž ๋ฆฌ์Šคํฌ ๊ณ ๋ ค์‚ฌํ•ญ
markdown.extend([
"## ํˆฌ์ž ์‹œ ๊ณ ๋ ค์‚ฌํ•ญ",
"".join([f"\n* {item}" for item in self.considerations]),
""
])
return "\n".join(markdown)
# ์ถ”์ฒœ ์„ค๋ช… ์ƒ์„ฑ ํ•จ์ˆ˜
def generate_explanation(state: dict) -> dict:
"""Generate structured ETF recommendation explanation"""
# ํ”„๋กฌํ”„ํŠธ ์ƒ์„ฑ
prompt = explanation_prompt.invoke({
"rankings": state["rankings"],
"user_profile": state["user_profile"]
})
# ๊ตฌ์กฐํ™”๋œ ์ถœ๋ ฅ ์ƒ์„ฑ
structured_llm = llm.with_structured_output(RecommendationExplanation)
response = structured_llm.invoke(prompt)
return {"final_answer": {
"explanation": response.model_dump(),
"markdown": response.to_markdown()
}}
##################################################################
# ETF ์ถ”์ฒœ ๋ด‡ - ์ƒํƒœ ๊ทธ๋ž˜ํ”„ ์ƒ์„ฑ
##################################################################
# ์ƒํƒœ ๊ทธ๋ž˜ํ”„ ์ƒ์„ฑ
graph_builder = StateGraph(State).add_sequence(
[analyze_profile, write_query, execute_query, rank_etfs, generate_explanation]
)
graph_builder.add_edge(START, "analyze_profile")
graph = graph_builder.compile()
##################################################################
# ETF ์ถ”์ฒœ ๋ด‡ - ๋ฉ”์ธ ํ•จ์ˆ˜
##################################################################
def process_message(message: str) -> str:
try:
etf_recommendation = graph.invoke(
{"question": message}
)
return etf_recommendation["final_answer"]["markdown"]
except Exception as e:
return f"""
# ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค
์ฃ„์†กํ•ฉ๋‹ˆ๋‹ค. ์š”์ฒญ์„ ์ฒ˜๋ฆฌํ•˜๋Š” ์ค‘์— ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค.
์˜ค๋ฅ˜ ๋‚ด์šฉ: {str(e)}
๋‹ค์‹œ ์‹œ๋„ํ•ด์ฃผ์‹œ๊ฑฐ๋‚˜, ์งˆ๋ฌธ์„ ๋‹ค๋ฅธ ๋ฐฉ์‹์œผ๋กœ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.
"""
def answer_invoke(message: str, history: List) -> str:
return process_message(message) # ๋ฉ”์‹œ์ง€ ์ฒ˜๋ฆฌ ํ•จ์ˆ˜ ํ˜ธ์ถœ - ๋Œ€ํ™” ์ด๋ ฅ ๋ฏธ์‚ฌ์šฉ
# Create Gradio interface
demo = gr.ChatInterface(
fn=answer_invoke,
title="๋งž์ถคํ˜• ETF ์ถ”์ฒœ ์–ด์‹œ์Šคํ„ดํŠธ",
description="""
ํˆฌ์ž ์„ฑํ–ฅ๊ณผ ๋ชฉํ‘œ์— ๋งž๋Š” ETF๋ฅผ ์ถ”์ฒœํ•ด๋“œ๋ฆฝ๋‹ˆ๋‹ค.
๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ •๋ณด๋ฅผ ํฌํ•จํ•˜์—ฌ ์งˆ๋ฌธํ•ด์ฃผ์„ธ์š”:
- ํˆฌ์ž ๋ชฉ์ 
- ํˆฌ์ž ๊ธฐ๊ฐ„
- ์œ„ํ—˜ ์„ฑํ–ฅ
- ์„ ํ˜ธ/์ œ์™ธ ์„นํ„ฐ
- ์›” ํˆฌ์ž ๊ฐ€๋Šฅ ๊ธˆ์•ก
์˜ˆ์‹œ) "์›” 100๋งŒ์› ์ •๋„๋ฅผ 3๋…„ ์ด์ƒ ์žฅ๊ธฐ ํˆฌ์žํ•˜๊ณ  ์‹ถ๊ณ , IT์™€ ํ—ฌ์Šค์ผ€์–ด ์„นํ„ฐ๋ฅผ ์„ ํ˜ธํ•ฉ๋‹ˆ๋‹ค.
๋ณด์ˆ˜์ ์ธ ํˆฌ์ž๋ฅผ ์„ ํ˜ธํ•˜๋ฉฐ, ๋‹ด๋ฐฐ ๊ด€๋ จ ๊ธฐ์—…์€ ์ œ์™ธํ•˜๊ณ  ์‹ถ์Šต๋‹ˆ๋‹ค."
""",
examples=[
"""20๋Œ€ ํ›„๋ฐ˜์˜ ๋Œ€ํ•™์ƒ์ž…๋‹ˆ๋‹ค.
์›” 50๋งŒ์› ์ •๋„๋ฅผ 1๋…„ ์ด์ƒ ์žฅ๊ธฐ ํˆฌ์žํ•˜๊ณ  ์‹ถ๊ณ ,
ํ™˜์œจ๊ณผ ๊ธˆ๋ฆฌ์— ๊ด€์‹ฌ์ด ์žˆ์Šต๋‹ˆ๋‹ค.
๊ณ ์œ„ํ—˜ ๊ณ ์ˆ˜์ต์„ ์ถ”๊ตฌํ•˜๋ฉฐ, ESG ์š”์†Œ๋„ ๊ณ ๋ คํ•˜๊ณ  ์‹ถ์Šต๋‹ˆ๋‹ค.
์ ํ•ฉํ•œ ETF๋ฅผ ์ถ”์ฒœํ•ด์ฃผ์„ธ์š”."""
],
type="messages",
)
# ์ธํ„ฐํŽ˜์ด์Šค ์‹คํ–‰
if __name__ == "__main__":
demo.launch()
s