-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathAI_Technical_Analysis.py
More file actions
113 lines (93 loc) · 4.4 KB
/
AI_Technical_Analysis.py
File metadata and controls
113 lines (93 loc) · 4.4 KB
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
## Source: @DeepCharts Youtube Channel (https://www.youtube.com/@DeepCharts)
#### NOTE: Set yfinance to the following version to get chart working: "pip install yfinance==0.2.40"
import streamlit as st
import yfinance as yf
import pandas as pd
import plotly.graph_objects as go
import ollama
import tempfile
import base64
import os
# Set up Streamlit app
st.set_page_config(layout="wide")
st.title("AI-Powered Technical Stock Analysis Dashboard")
st.sidebar.header("Configuration")
# Input for stock ticker and date range
ticker = st.sidebar.text_input("Enter Stock Ticker (e.g., AAPL):", "AAPL")
start_date = st.sidebar.date_input("Start Date", value=pd.to_datetime("2023-01-01"))
end_date = st.sidebar.date_input("End Date", value=pd.to_datetime("2024-12-14"))
# Fetch stock data
if st.sidebar.button("Fetch Data"):
st.session_state["stock_data"] = yf.download(ticker, start=start_date, end=end_date)
st.success("Stock data loaded successfully!")
# Check if data is available
if "stock_data" in st.session_state:
data = st.session_state["stock_data"]
# Plot candlestick chart
fig = go.Figure(data=[
go.Candlestick(
x=data.index,
open=data['Open'],
high=data['High'],
low=data['Low'],
close=data['Close'],
name="Candlestick" # Replace "trace 0" with "Candlestick"
)
])
# Sidebar: Select technical indicators
st.sidebar.subheader("Technical Indicators")
indicators = st.sidebar.multiselect(
"Select Indicators:",
["20-Day SMA", "20-Day EMA", "20-Day Bollinger Bands", "VWAP"],
default=["20-Day SMA"]
)
# Helper function to add indicators to the chart
def add_indicator(indicator):
if indicator == "20-Day SMA":
sma = data['Close'].rolling(window=20).mean()
fig.add_trace(go.Scatter(x=data.index, y=sma, mode='lines', name='SMA (20)'))
elif indicator == "20-Day EMA":
ema = data['Close'].ewm(span=20).mean()
fig.add_trace(go.Scatter(x=data.index, y=ema, mode='lines', name='EMA (20)'))
elif indicator == "20-Day Bollinger Bands":
sma = data['Close'].rolling(window=20).mean()
std = data['Close'].rolling(window=20).std()
bb_upper = sma + 2 * std
bb_lower = sma - 2 * std
fig.add_trace(go.Scatter(x=data.index, y=bb_upper, mode='lines', name='BB Upper'))
fig.add_trace(go.Scatter(x=data.index, y=bb_lower, mode='lines', name='BB Lower'))
elif indicator == "VWAP":
data['VWAP'] = (data['Close'] * data['Volume']).cumsum() / data['Volume'].cumsum()
fig.add_trace(go.Scatter(x=data.index, y=data['VWAP'], mode='lines', name='VWAP'))
# Add selected indicators to the chart
for indicator in indicators:
add_indicator(indicator)
fig.update_layout(xaxis_rangeslider_visible=False)
st.plotly_chart(fig)
# Analyze chart with LLaMA 3.2 Vision
st.subheader("AI-Powered Analysis")
if st.button("Run AI Analysis"):
with st.spinner("Analyzing the chart, please wait..."):
# Save chart as a temporary image
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmpfile:
fig.write_image(tmpfile.name)
tmpfile_path = tmpfile.name
# Read image and encode to Base64
with open(tmpfile_path, "rb") as image_file:
image_data = base64.b64encode(image_file.read()).decode('utf-8')
# Prepare AI analysis request
messages = [{
'role': 'user',
'content': """You are a Stock Trader specializing in Technical Analysis at a top financial institution.
Analyze the stock chart's technical indicators and provide a buy/hold/sell recommendation.
Base your recommendation only on the candlestick chart and the displayed technical indicators.
First, provide the recommendation, then, provide your detailed reasoning.
""",
'images': [image_data]
}]
response = ollama.chat(model='llama3.2-vision', messages=messages)
# Display AI analysis result
st.write("**AI Analysis Results:**")
st.write(response["message"]["content"])
# Clean up temporary file
os.remove(tmpfile_path)