stock / app.py
seawolf2357's picture
Update app.py
7878351 verified
raw
history blame contribute delete
No virus
6.33 kB
import discord
import logging
import os
import asyncio
import subprocess
from huggingface_hub import InferenceClient
from yahooquery import Ticker
from datetime import datetime
# ๋กœ๊น… ์„ค์ •
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s:%(levelname)s:%(name)s: %(message)s', handlers=[logging.StreamHandler()])
# ์ธํ…ํŠธ ์„ค์ •
intents = discord.Intents.default()
intents.message_content = True
intents.messages = True
intents.guilds = True
intents.guild_messages = True
# ์ถ”๋ก  API ํด๋ผ์ด์–ธํŠธ ์„ค์ •
hf_client = InferenceClient("CohereForAI/c4ai-command-r-plus", token=os.getenv("HF_TOKEN"))
# ํŠน์ • ์ฑ„๋„ ID
SPECIFIC_CHANNEL_ID = int(os.getenv("DISCORD_CHANNEL_ID"))
# ๋Œ€ํ™” ํžˆ์Šคํ† ๋ฆฌ๋ฅผ ์ €์žฅํ•  ์ „์—ญ ๋ณ€์ˆ˜
conversation_history = []
class MyClient(discord.Client):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.is_processing = False
async def on_ready(self):
logging.info(f'{self.user}๋กœ ๋กœ๊ทธ์ธ๋˜์—ˆ์Šต๋‹ˆ๋‹ค!')
subprocess.Popen(["python", "web.py"])
logging.info("web.py ์„œ๋ฒ„๊ฐ€ ์‹œ์ž‘๋˜์—ˆ์Šต๋‹ˆ๋‹ค.")
async def on_message(self, message):
if message.author == self.user:
return
if not self.is_message_in_specific_channel(message):
return
if self.is_processing:
return
self.is_processing = True
try:
response = await handle_message(message)
await message.channel.send(response)
finally:
self.is_processing = False
def is_message_in_specific_channel(self, message):
return message.channel.id == SPECIFIC_CHANNEL_ID or (
isinstance(message.channel, discord.Thread) and message.channel.parent_id == SPECIFIC_CHANNEL_ID
)
async def handle_message(message):
user_input = message.content
user_mention = message.author.mention
# ํ‹ฐ์ปค๋ฅผ ์ œ๊ณตํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ
if not user_input.startswith("!t "):
ticker = await find_ticker(user_input)
if ticker:
return f"{user_mention}, ์ข…๋ชฉ๋ช…์„ ์ฐพ์•˜์Šต๋‹ˆ๋‹ค: {ticker}. ํ‹ฐ์ปค ์ •๋ณด๋ฅผ ์›ํ•˜๋ฉด '!t {ticker}'๋ผ๊ณ  ์ž…๋ ฅํ•˜์„ธ์š”."
else:
return f"{user_mention}, ์ข…๋ชฉ๋ช…์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ์˜ฌ๋ฐ”๋ฅธ ์ข…๋ชฉ๋ช…์„ ์ž…๋ ฅํ•˜์„ธ์š”."
# ํ‹ฐ์ปค๋ฅผ ์ œ๊ณตํ•œ ๊ฒฝ์šฐ
ticker = user_input[3:].strip().upper()
return await handle_ticker(ticker, user_mention)
async def handle_ticker(ticker, user_mention):
global conversation_history # ์ „์—ญ ๋ณ€์ˆ˜ ์‚ฌ์šฉ์„ ๋ช…์‹œ
conversation_history.append({"role": "user", "content": ticker})
logging.debug(f'Conversation history updated: {conversation_history}')
company_info, charts, news_summary, prediction = await get_stock_info(ticker)
conversation_history.append({"role": "assistant", "content": prediction})
if len(conversation_history) > 20:
conversation_history.pop(0)
return f"""
**ํšŒ์‚ฌ ์ •๋ณด:**
ํšŒ์‚ฌ ์ด๋ฆ„: {company_info.get('longName', 'N/A')}
ํ‹ฐ์ปค: {ticker}
์‚ฐ์—…: {company_info.get('industry', 'N/A')}
์„นํ„ฐ: {company_info.get('sector', 'N/A')}
์‹œ๊ฐ€ ์ด์•ก: {company_info.get('marketCap', 'N/A')}
ํ˜„์žฌ๊ฐ€: {company_info.get('currentPrice', 'N/A')}
๋ฐ์ดํ„ฐ ์—…๋ฐ์ดํŠธ: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
**์ตœ๊ทผ 1์ผ ์ฐจํŠธ:**
{charts['1d']}
**์ตœ๊ทผ 1์ฃผ ์ฐจํŠธ:**
{charts['1w']}
**์ตœ๊ทผ 1๊ฐœ์›” ์ฐจํŠธ:**
{charts['1m']}
**์ตœ๊ทผ 1๋…„ ์ฐจํŠธ:**
{charts['1y']}
**์ตœ๊ทผ 10๋…„ ์ฐจํŠธ:**
{charts['10y']}
**์ตœ์‹  ๋‰ด์Šค:**
{news_summary}
**ํ–ฅํ›„ 1์ฃผ์ผ๊ฐ„ ์‹œ์„ธ ์˜ˆ์ธก:**
{prediction}
"""
async def find_ticker(query):
tickers = Ticker(query)
for ticker in tickers.symbols:
return ticker
return None
async def get_stock_info(ticker):
tickers = Ticker(ticker)
summary = tickers.summary_detail[ticker]
price = summary.get("previousClose", "N/A")
company_info = {
'longName': tickers.asset_profile[ticker].get('longName', 'N/A'),
'industry': tickers.asset_profile[ticker].get('industry', 'N/A'),
'sector': tickers.asset_profile[ticker].get('sector', 'N/A'),
'marketCap': summary.get('marketCap', 'N/A'),
'currentPrice': price,
}
charts = {
'1d': get_chart_summary(tickers.history(period="1d", interval="1d")),
'1w': get_chart_summary(tickers.history(period="5d", interval="1d")),
'1m': get_chart_summary(tickers.history(period="1mo", interval="1d")),
'1y': get_chart_summary(tickers.history(period="1y", interval="1d")),
'10y': get_chart_summary(tickers.history(period="10y", interval="1d")),
}
news_summary = get_news_summary(tickers.news())
prediction = await predict_stock(ticker)
return company_info, charts, news_summary, prediction
def get_chart_summary(history):
if history.empty:
return "๋ฐ์ดํ„ฐ ์—†์Œ"
avg_price = history['close'].mean()
max_price = history['close'].max()
min_price = history['close'].min()
return f"ํ‰๊ท ๊ฐ€: {avg_price:.2f}, ์ตœ๊ณ ๊ฐ€: {max_price:.2f}, ์ตœ์ €๊ฐ€: {min_price:.2f}"
def get_news_summary(news):
if not news:
return "๋‰ด์Šค ์š”์•ฝ์„ ๊ฐ€์ ธ์˜ค๋Š” ๋ฐ ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค."
news_summary = ""
for article in news[:5]:
news_summary += f"- {article['title']}: {article['summary']}\n"
return news_summary.strip()
async def predict_stock(ticker):
messages = [{"role": "system", "content": f"์‚ฌ์šฉ์ž๊ฐ€ ํ‹ฐ์ปค '{ticker}'์— ๋Œ€ํ•ด ์•Œ๊ณ  ์‹ถ์–ดํ•ฉ๋‹ˆ๋‹ค."}] + conversation_history
logging.debug(f'๋ชจ๋ธ์— ๋ณด๋‚ผ ๋ฉ”์‹œ์ง€: {messages}')
loop = asyncio.get_event_loop()
response = await loop.run_in_executor(None, lambda: hf_client.chat_completion(
messages, max_tokens=1000, stream=True, temperature=0.7, top_p=0.85))
full_response = []
for part in response:
if part.choices and part.choices[0].delta and part.choices[0].delta.content:
full_response.append(part.choices[0].delta.content)
return ''.join(full_response).strip()
if __name__ == "__main__":
discord_token = os.getenv('DISCORD_TOKEN')
discord_client = MyClient(intents=intents)
discord_client.run(discord_token)