eagle0504 commited on
Commit
2cfe73f
·
verified ·
1 Parent(s): bb57a43

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +51 -15
app.py CHANGED
@@ -248,13 +248,17 @@ def get_ai_response(question, stock_data, api_key):
248
  try:
249
  client = anthropic.Anthropic(api_key=api_key)
250
 
251
- # Prepare context
 
 
 
 
252
  context = f"""
253
  You are a financial analyst AI assistant specializing in CoreWeave (CRWV) stock analysis.
254
 
255
  Current stock data available:
256
- - Latest Close Price: ${stock_data['Close'].iloc[-1]:.2f}
257
- - Daily Change: {((stock_data['Close'].iloc[-1] / stock_data['Close'].iloc[-2]) - 1) * 100:.2f}%
258
  - Volume: {stock_data['Volume'].iloc[-1]:,}
259
  - 52-week High: ${stock_data['High'].max():.2f}
260
  - 52-week Low: ${stock_data['Low'].min():.2f}
@@ -266,18 +270,43 @@ def get_ai_response(question, stock_data, api_key):
266
  clearly state your limitations.
267
  """
268
 
269
- message = client.messages.create(
270
- model="claude-3-sonnet-20240229",
271
- max_tokens=1000,
272
- temperature=0.7,
273
- system=context,
274
- messages=[{"role": "user", "content": question}]
275
- )
276
 
277
- return message.content[0].text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
278
 
279
  except Exception as e:
280
- return f"Error getting AI response: {str(e)}"
 
 
 
 
 
 
 
 
281
 
282
  # Main app
283
  def main():
@@ -411,6 +440,12 @@ def main():
411
  st.markdown("---")
412
  st.subheader("🤖 AI Stock Analyst")
413
 
 
 
 
 
 
 
414
  # Chat interface
415
  chat_container = st.container()
416
 
@@ -431,13 +466,14 @@ def main():
431
  # Chat input
432
  user_question = st.text_input(
433
  "Ask me anything about CoreWeave stock:",
434
- placeholder="e.g., What's your analysis of the current price trend?"
 
435
  )
436
 
437
  col_send, col_clear = st.columns([1, 1])
438
 
439
  with col_send:
440
- if st.button("Send", type="primary") and user_question:
441
  # Add user message to history
442
  st.session_state.chat_history.append({
443
  'role': 'user',
@@ -474,7 +510,7 @@ def main():
474
  cols = st.columns(len(sample_questions))
475
  for i, question in enumerate(sample_questions):
476
  with cols[i]:
477
- if st.button(question, key=f"sample_{i}"):
478
  st.session_state.chat_history.append({'role': 'user', 'content': question})
479
  ai_response = get_ai_response(question, hist_data, api_key)
480
  st.session_state.chat_history.append({'role': 'assistant', 'content': ai_response})
 
248
  try:
249
  client = anthropic.Anthropic(api_key=api_key)
250
 
251
+ # Prepare context with current stock data
252
+ latest_price = stock_data['Close'].iloc[-1]
253
+ prev_price = stock_data['Close'].iloc[-2] if len(stock_data) > 1 else latest_price
254
+ daily_change = ((latest_price / prev_price) - 1) * 100 if prev_price != 0 else 0
255
+
256
  context = f"""
257
  You are a financial analyst AI assistant specializing in CoreWeave (CRWV) stock analysis.
258
 
259
  Current stock data available:
260
+ - Latest Close Price: ${latest_price:.2f}
261
+ - Daily Change: {daily_change:.2f}%
262
  - Volume: {stock_data['Volume'].iloc[-1]:,}
263
  - 52-week High: ${stock_data['High'].max():.2f}
264
  - 52-week Low: ${stock_data['Low'].min():.2f}
 
270
  clearly state your limitations.
271
  """
272
 
273
+ # Try multiple model names in order of preference
274
+ models_to_try = [
275
+ "claude-3-5-sonnet-20241022", # Latest Sonnet 3.5
276
+ "claude-3-5-sonnet-20240620", # Previous Sonnet 3.5
277
+ "claude-3-sonnet-20240229", # Original Sonnet 3
278
+ "claude-3-haiku-20240307" # Fallback to Haiku
279
+ ]
280
 
281
+ for model_name in models_to_try:
282
+ try:
283
+ message = client.messages.create(
284
+ model=model_name,
285
+ max_tokens=1000,
286
+ temperature=0.7,
287
+ system=context,
288
+ messages=[{"role": "user", "content": question}]
289
+ )
290
+ return message.content[0].text
291
+
292
+ except Exception as model_error:
293
+ if "not_found_error" in str(model_error):
294
+ continue # Try next model
295
+ else:
296
+ return f"Error with model {model_name}: {str(model_error)}"
297
+
298
+ return "Unable to connect to AI service. Please check your API key or try again later."
299
 
300
  except Exception as e:
301
+ error_msg = str(e)
302
+ if "authentication" in error_msg.lower():
303
+ return "❌ Invalid API key. Please check your Anthropic API key and try again."
304
+ elif "rate_limit" in error_msg.lower():
305
+ return "⏳ Rate limit exceeded. Please wait a moment and try again."
306
+ elif "insufficient" in error_msg.lower():
307
+ return "💳 Insufficient credits. Please check your Anthropic account balance."
308
+ else:
309
+ return f"❌ AI service error: {error_msg}"
310
 
311
  # Main app
312
  def main():
 
440
  st.markdown("---")
441
  st.subheader("🤖 AI Stock Analyst")
442
 
443
+ # API Key status
444
+ if api_key:
445
+ st.success("✅ API key provided - AI features enabled")
446
+ else:
447
+ st.warning("⚠️ Please enter your Anthropic API key in the sidebar to enable AI chat")
448
+
449
  # Chat interface
450
  chat_container = st.container()
451
 
 
466
  # Chat input
467
  user_question = st.text_input(
468
  "Ask me anything about CoreWeave stock:",
469
+ placeholder="e.g., What's your analysis of the current price trend?",
470
+ disabled=not api_key
471
  )
472
 
473
  col_send, col_clear = st.columns([1, 1])
474
 
475
  with col_send:
476
+ if st.button("Send", type="primary", disabled=not api_key) and user_question:
477
  # Add user message to history
478
  st.session_state.chat_history.append({
479
  'role': 'user',
 
510
  cols = st.columns(len(sample_questions))
511
  for i, question in enumerate(sample_questions):
512
  with cols[i]:
513
+ if st.button(question, key=f"sample_{i}", disabled=not api_key):
514
  st.session_state.chat_history.append({'role': 'user', 'content': question})
515
  ai_response = get_ai_response(question, hist_data, api_key)
516
  st.session_state.chat_history.append({'role': 'assistant', 'content': ai_response})