TEST_AI / app.py
Nush88's picture
Update app.py
c17e95b verified
import streamlit as st
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
import yfinance as yf
import daal4py as d4p # Intel DAAL
import numpy as np
from sklearnex import patch_sklearn
# Apply scikit-learn optimizations
patch_sklearn()
# Initialize Hugging Face's sentiment analysis pipeline
@st.cache_resource
def load_sentiment_model():
return pipeline("sentiment-analysis", model="huggingface/llama-3b-instruct")
# Load LLaMA model for custom recommendations or Q&A
@st.cache_resource
def load_llama_model():
model_name = "meta-llama/Llama-2-7b-chat-hf" # Adjust this to your preferred model
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
return tokenizer, model
# Fetch stock data using Yahoo Finance
def fetch_stock_data(symbol):
ticker = yf.Ticker(symbol)
data = ticker.history(period="1mo") # Fetch 1 month of historical data
return data
# Compute Moving Average using Intel oneDAL
def compute_moving_average(prices, window=5):
# Convert prices to a NumPy array and reshape it for DAAL
price_array = np.array(prices, dtype=np.float64).reshape(-1, 1)
# Initialize Intel DAAL low-order moments algorithm (for moving average)
algorithm = d4p.low_order_moments()
# Apply rolling window and calculate moving averages
moving_averages = []
for i in range(len(price_array) - window + 1):
window_data = price_array[i:i + window]
result = algorithm.compute(window_data)
moving_averages.append(result.mean[0])
return moving_averages
# Perform technical analysis using Yahoo Finance and oneDAL
def technical_analysis(symbol):
data = fetch_stock_data(symbol)
if not data.empty:
# Extract closing prices from the fetched data
closing_prices = data['Close'].tolist()
dates = data.index.strftime('%Y-%m-%d').tolist()
# Compute 5-day moving average using oneDAL
moving_averages = compute_moving_average(closing_prices)
# Display latest date's price and moving average
latest_date = dates[-1]
latest_price = closing_prices[-1]
latest_moving_average = moving_averages[-1] if moving_averages else "N/A"
return {
"Date": latest_date,
"Closing Price": latest_price,
"5-Day Moving Average": latest_moving_average
}
return {}
# Streamlit Web App
def main():
st.title("Stock Analysis App with Yahoo Finance & Intel oneDAL")
st.write("""
This app provides a comprehensive stock analysis including:
- Sentiment Analysis of recent news
- Technical Analysis (Prices, Moving Average using Intel oneDAL)
- Buy/Sell/Hold Recommendations
""")
# Input: Stock symbol of a public listed company
company_symbol = st.text_input("Enter the stock symbol (e.g., AAPL, TSLA, GOOGL):")
if company_symbol:
try:
# Fetch stock data from Yahoo Finance API
stock_data = fetch_stock_data(company_symbol)
if not stock_data.empty:
# Display the fetched stock overview
st.subheader("Asset Overview")
st.dataframe(stock_data.tail()) # Show the last few rows of the data
# Split the sections into different boxes using Streamlit's expander
with st.expander("Technical Analysis (Intel oneDAL)"):
st.subheader("Technical Analysis")
tech_analysis = technical_analysis(company_symbol)
st.write(tech_analysis)
with st.expander("Sentiment Analysis"):
st.subheader("Sentiment Analysis")
sentiment_model = load_sentiment_model()
sentiment = sentiment_model(company_symbol) # Sentiment analysis on the stock name
st.write(sentiment)
with st.expander("Recommendation"):
st.subheader("Recommendation")
tokenizer, llama_model = load_llama_model()
stock_recommendation = recommendation(company_symbol, tokenizer, llama_model)
st.write(stock_recommendation)
else:
st.error(f"No data available for the symbol entered.")
except Exception as e:
st.error(f"An error occurred: {e}")
if __name__ == "__main__":
main()