Llama3.2:3B 모델에게 특정 주식의 데이터를 던져주고 해당 주식을 팔 것인지 (SELL), 살 것인지 (BUY), 그냥 들고 있을 것인지 (HOLD) 판단하게 하고, 그 이유를 물어보려고 한다.
주식 데이터 수집은 KRX에서 한국의 주식 데이터를 스크래핑하는 파이썬 모듈인 pykrx를 이용한다. 특정 주식의 시가(open), 고가(high), 저가(low), 종가(close), 거래량(volume), 거래대금, 등락률은 pykrx의 get_market_ohlcv 함수를 이용하여 얻을 수 있다. get_market_ohlcv 함수는 시작일/종료일/티커 세 개의 파라미터를 입력받아 OHLCV를 일자별로 정렬하여 DataFrame으로 반환한다.
다음은 2025년1월1일 부터 2025년 2월 15일 현재까지 삼성전자 주식의 시가와 종가 및 거래량을 날짜별로 나타낸 그래프다.
디음은 위 그래프를 그리는 코드다. 여기서 005930은 삼성전자의 티커이다.
from pykrx import stock
from datetime import datetime
import matplotlib.pyplot as plt
# ohlcv
end_date = datetime.today()
end_date = end_date.strftime('%Y%m%d')
start_date = "20250101"
df_ss = stock.get_market_ohlcv(start_date, end_date, "005930")
dates_ss = df_ss.index
# plotting
fig, ax1 = plt.subplots(2, 1, figsize=(14, 10))
# subplot 1
ax1[0].plot(dates_ss, df_ss['시가'], color='green', label='시가')
ax1[0].plot(dates_ss, df_ss['종가'], color='red', label='종가')
ax1[0].set_xlabel('Date')
ax1[0].set_ylabel('Price')
ax1[0].set_title(stock.get_market_ticker_name("005930") + " 주가")
ax1[0].legend()
ax1[0].grid()
# subplot 2
ax1[1].bar(dates_ss, df_ss['거래량'], color='blue', alpha=0.5, label='거래량')
ax1[1].set_xlabel('Date')
ax1[1].set_ylabel('Volume')
ax1[1].set_title(stock.get_market_ticker_name("005930") + " 거래량")
ax1[1].legend()
ax1[1].grid()
#
plt.tight_layout()
plt.show()
이제 Llama3.2:3B 모델에게 삼성전자 주식의 OHLCV데이터를 주고 해당 주식의 매매 여부를 묻고자 한다. 다음은 그 코드다. LLM에게 질의 응답하는 방법에 관한 게시글(https://pasus.tistory.com/370)을 참고하면 쉽게 이해할 수 있을 것이다.
from pykrx import stock
from openai import OpenAI
from datetime import datetime
import json
llama_client = OpenAI(
base_url = 'http://localhost:11434/v1',
api_key='ollama',
)
def llama_trading(start_date, end_date, ticker):
# 1. getting OHLCV data
df = stock.get_market_ohlcv(start_date, end_date, ticker)
# 2. getting Llama3.2 decision
response = llama_client.chat.completions.create(
model="llama3.2:3b",
#model = 'deepseek-r1:8b',
messages=[
{
"role": "system",
"content": [
{
"type": "text",
"text": """You are an expert in stock trading. Tell me whether to buy, sell,
or hold at the moment based on the chart data provided.
Response in JSON format.
Response Example:
{"decision": "buy", "reason": "explain why"}
{"decision": "sell", "reason": "explain why"}
{"decision": "hold", "reason": "explain why"}
No other text or formatting is allowed.
If you have any explanation, put it under "reason". """
}
]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": df.to_json()
}
]
}
],
response_format={
"type": "json_object"
}
)
result = response.choices[0].message.content
result = json.loads(result)
print("----- Decision: ", result["decision"].upper(), "-----")
print(f"***** Reason: {result['reason']} *****")
def main():
end_date = datetime.today()
end_date = end_date.strftime('%Y%m%d')
start_date = "20250101"
samsung_ticker = "005930"
llama_trading(start_date, end_date, samsung_ticker)
if __name__=="__main__":
main()
2025년1월1일 부터 2025년 2월 15일 현재까지의 삼성전자 데이터를 주고 매매 판단을 물었더니 다음과 같은 답변을 하였다.
----- Decision: BUY -----
***** Reason: The price has risen significantly in the last few days, indicating a trend upwards. The charts also show strong support at certain key levels, making it a good buying opportunity. *****
상승 추세이니 사라고 한다. 다음은 똑 같은 데이터로 GPT-4o 에게 매매 판단을 물은 것이다. 답변은 다음과 같았다.
----- GPT4 Decision: HOLD -----
***** Reason: The stock price shows a recent recovery from lows at the beginning of the month after a sharp decline. However, it has not yet established a clear upward trend and the current volatility and varying trading volumes suggest uncertainty in the market. Further monitoring is needed to confirm a continued upward trend before action. *****
GPT는 홀드하라고 한다. 이유를 읽어보면 GPT-4o가 더 설득력이 있는 것 같다. Llama3.2 는 무료이고, GPT-4o 는 유료임을 고려하자.
혹시나 해서 deepseek-r1:8B 에게도 물어보았다. 답변은 다음과 같았다.
----- Decision: BUY -----
***** Reason: The stock has shown a recent uptrend in its trading sessions. The last seven days indicate a consistent increase in price, with each data point reflecting higher values than the previous one. This upward movement suggests that the market is perceiving positive news or improving fundamentals about the company. Additionally, comparing this trend to earlier periods shows that the current upward trend is stronger and sustained compared to past fluctuations. There appears to be increasing investor confidence, which often leads to continued growth in stock prices. Therefore, based on these indicators, it is advisable to consider purchasing the stock as part of a strategic investment decision. *****
설명이 나름 괜찮은 것 같다.
과연 월요일 삼성전자 주가의 향방은?
OHLCV 데이터 외에 주가에 영향을 미칠 수 있는 다른 정보를 더 준다면 ? 종목까지 선정하게 한다면 ?
'AI 딥러닝 > DLA' 카테고리의 다른 글
[LLM] Ollama 모델에서 OpenAI Chat API 사용하기 (0) | 2025.02.15 |
---|---|
[LLM] Ollama Web-UI 설치 (0) | 2024.02.25 |
[VAE] beta-VAE (0) | 2023.05.11 |
[VAE] 변이형 오토인코더(Variational Autoencoder) (0) | 2023.04.30 |
[U-Net] 망막 혈관 세그멘테이션 (Retinal Vessel Segmentation) (0) | 2022.05.11 |
댓글