File size: 4,487 Bytes
2cb0e1b
 
c17e95b
2cb0e1b
 
c17e95b
2cb0e1b
c17e95b
 
2cb0e1b
 
 
 
 
 
 
 
 
 
 
 
 
 
c17e95b
2cb0e1b
c17e95b
 
 
2cb0e1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c17e95b
2cb0e1b
 
 
c17e95b
 
 
 
2cb0e1b
 
 
 
 
c17e95b
 
 
2cb0e1b
 
 
 
 
 
 
 
 
 
c17e95b
2cb0e1b
 
 
 
 
 
 
 
 
 
 
 
c17e95b
2cb0e1b
 
c17e95b
2cb0e1b
 
c17e95b
2cb0e1b
 
 
 
 
 
 
 
 
 
c17e95b
2cb0e1b
 
 
 
 
 
 
 
 
 
 
 
 
 
c17e95b
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
114
115
116
117
118
119
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()