cryogenic22 commited on
Commit
eea31dc
·
verified ·
1 Parent(s): b3830e0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +244 -0
app.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import base64
3
+ from datetime import datetime
4
+ import json
5
+ import os
6
+ from openai import OpenAI
7
+ import requests
8
+ from PIL import Image
9
+ import io
10
+ from huggingface_hub import HfApi
11
+ import yaml
12
+
13
+ def load_huggingface_secret():
14
+ """Load OpenAI API key from Hugging Face secrets"""
15
+ try:
16
+ hf_api = HfApi()
17
+ # Fetch the secret from Hugging Face
18
+ secret = hf_api.get_secret('openai_api_key')
19
+ return secret
20
+ except Exception as e:
21
+ st.error(f"Error loading secret from Hugging Face: {str(e)}")
22
+ return None
23
+
24
+ def initialize_openai_client():
25
+ """Initialize OpenAI client with API key from Hugging Face"""
26
+ api_key = load_huggingface_secret()
27
+ if api_key:
28
+ return OpenAI(api_key=api_key)
29
+ return None
30
+
31
+ def create_prompt_template(chart_type, patterns, indicators):
32
+ """Creates a structured prompt for the LLM based on the chart and analysis needs"""
33
+ prompt = f"""You are an expert financial analyst. Please analyze this {chart_type} chart and provide insights in the following structured format:
34
+
35
+ 1. VISUAL ANALYSIS
36
+ - Identify and describe the main trend
37
+ - Note key price levels visible in the chart
38
+ - Describe any significant patterns: {', '.join(patterns) if patterns else 'all visible patterns'}
39
+ - Comment on volume trends if visible
40
+ - Analyze these technical indicators: {', '.join(indicators) if indicators else 'visible indicators'}
41
+
42
+ 2. TECHNICAL INTERPRETATION
43
+ - Current market structure and trend strength
44
+ - Key support and resistance levels with price points
45
+ - Any visible divergences or convergences
46
+ - Pattern reliability assessment
47
+
48
+ 3. RISK ANALYSIS
49
+ - Potential risk levels
50
+ - Risk/reward scenarios
51
+ - Warning signs or red flags
52
+ - Market context considerations
53
+
54
+ 4. ACTIONABLE INSIGHTS
55
+ - Potential trading scenarios
56
+ - Key price targets
57
+ - Suggested stop-loss levels
58
+ - Timeframe considerations
59
+
60
+ 5. SIMPLIFIED EXPLANATION
61
+ Provide a 2-3 sentence summary in simple terms for novice traders.
62
+
63
+ IMPORTANT: Clearly mark this as AI-generated analysis for informational purposes only.
64
+ """
65
+ return prompt
66
+
67
+ def analyze_chart_with_openai(client, image_data, prompt):
68
+ """Analyze chart using OpenAI's vision model"""
69
+ try:
70
+ # Encode image to base64
71
+ encoded_image = base64.b64encode(image_data).decode('utf-8')
72
+
73
+ # Create message with image and prompt
74
+ messages = [
75
+ {
76
+ "role": "user",
77
+ "content": [
78
+ {
79
+ "type": "text",
80
+ "text": prompt
81
+ },
82
+ {
83
+ "type": "image_url",
84
+ "image_url": {
85
+ "url": f"data:image/jpeg;base64,{encoded_image}"
86
+ }
87
+ }
88
+ ]
89
+ }
90
+ ]
91
+
92
+ # Call OpenAI API
93
+ response = client.chat.completions.create(
94
+ model="gpt-4-vision-preview",
95
+ messages=messages,
96
+ max_tokens=1000
97
+ )
98
+
99
+ return response.choices[0].message.content
100
+ except Exception as e:
101
+ st.error(f"Error in OpenAI analysis: {str(e)}")
102
+ return None
103
+
104
+ def save_chat_history(chat_history, filename=None):
105
+ """Saves chat history to a JSON file"""
106
+ if not os.path.exists("chat_histories"):
107
+ os.makedirs("chat_histories")
108
+
109
+ if filename is None:
110
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
111
+ filename = f"chat_history_{timestamp}.json"
112
+
113
+ filepath = os.path.join("chat_histories", filename)
114
+ with open(filepath, "w") as f:
115
+ json.dump(chat_history, f)
116
+ return filename
117
+
118
+ def load_chat_history(filename):
119
+ """Loads chat history from a JSON file"""
120
+ filepath = os.path.join("chat_histories", filename)
121
+ with open(filepath, "r") as f:
122
+ return json.load(f)
123
+
124
+ def main():
125
+ st.set_page_config(
126
+ page_title="Stock Chart Assistant",
127
+ layout="wide",
128
+ initial_sidebar_state="expanded"
129
+ )
130
+
131
+ # Initialize OpenAI client
132
+ client = initialize_openai_client()
133
+ if not client:
134
+ st.error("Failed to initialize OpenAI client. Please check your Hugging Face secrets.")
135
+ return
136
+
137
+ # Initialize session state for chat history
138
+ if 'chat_history' not in st.session_state:
139
+ st.session_state.chat_history = []
140
+
141
+ # Sidebar
142
+ with st.sidebar:
143
+ st.title("🚀 Chart Analysis AI")
144
+ upload_option = st.radio(
145
+ "Choose input method:",
146
+ ("Upload Image", "Take Screenshot", "Ask Question")
147
+ )
148
+
149
+ # File uploader
150
+ if upload_option == "Upload Image":
151
+ uploaded_file = st.file_uploader("Upload your chart", type=["png", "jpg", "jpeg"])
152
+ elif upload_option == "Take Screenshot":
153
+ st.button("Open Screenshot Tool", key="screenshot")
154
+ # Screenshot functionality would be implemented here
155
+
156
+ # Analysis Options
157
+ st.subheader("Analysis Options")
158
+ chart_type = st.selectbox(
159
+ "Chart Type",
160
+ ["Candlestick", "Line", "OHLC", "Area", "Other"]
161
+ )
162
+
163
+ patterns = st.multiselect(
164
+ "Patterns to Look For",
165
+ ["Double Top/Bottom", "Head and Shoulders", "Triangle",
166
+ "Flag", "Wedge", "Channel", "Support/Resistance"]
167
+ )
168
+
169
+ indicators = st.multiselect(
170
+ "Technical Indicators",
171
+ ["Moving Averages", "RSI", "MACD", "Bollinger Bands",
172
+ "Volume", "Stochastic", "ADX"]
173
+ )
174
+
175
+ # Main content area
176
+ st.title("📈 Stock Chart Analysis Assistant")
177
+
178
+ # Create two columns for layout
179
+ col1, col2 = st.columns([2, 1])
180
+
181
+ with col1:
182
+ if upload_option == "Ask Question":
183
+ user_question = st.text_input("What would you like to know about your chart?")
184
+
185
+ # Display uploaded image
186
+ if uploaded_file is not None:
187
+ st.image(uploaded_file, caption="Uploaded Chart", use_column_width=True)
188
+
189
+ if st.button("Analyze"):
190
+ if uploaded_file is None and upload_option != "Ask Question":
191
+ st.warning("Please upload an image or take a screenshot first.")
192
+ else:
193
+ with st.spinner("Analyzing chart..."):
194
+ # Generate prompt
195
+ prompt = create_prompt_template(chart_type, patterns, indicators)
196
+
197
+ if uploaded_file:
198
+ # Process image and get analysis
199
+ analysis_result = analyze_chart_with_openai(
200
+ client,
201
+ uploaded_file.getvalue(),
202
+ prompt
203
+ )
204
+
205
+ if analysis_result:
206
+ # Add to chat history
207
+ st.session_state.chat_history.append({
208
+ 'timestamp': datetime.now().isoformat(),
209
+ 'chart_type': chart_type,
210
+ 'analysis': analysis_result
211
+ })
212
+
213
+ # Display analysis
214
+ st.subheader("Analysis Results")
215
+ st.write(analysis_result)
216
+
217
+ # Risk warning
218
+ st.warning(
219
+ "⚠️ This analysis is AI-generated and for informational purposes only. "
220
+ "Do not make trading decisions solely based on this information."
221
+ )
222
+
223
+ with col2:
224
+ st.subheader("Chat History")
225
+
226
+ # Display chat history
227
+ for chat in st.session_state.chat_history:
228
+ with st.expander(f"Analysis from {chat['timestamp'][:16]}"):
229
+ st.write(chat['analysis'])
230
+
231
+ # Save chat options
232
+ save_name = st.text_input("Save chat as (optional):")
233
+ if st.button("Save Chat"):
234
+ if st.session_state.chat_history:
235
+ filename = save_chat_history(
236
+ st.session_state.chat_history,
237
+ f"{save_name}.json" if save_name else None
238
+ )
239
+ st.success(f"Chat saved as {filename}")
240
+ else:
241
+ st.warning("No chat history to save.")
242
+
243
+ if __name__ == "__main__":
244
+ main()