File size: 4,646 Bytes
4c527e5
 
 
 
1149444
 
 
 
4c527e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
120
121
122
123
import streamlit as st
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
import requests
import daal4py as d4p  # Intel DAAL
import numpy as np
import dpctl
from sklearnex import patch_sklearn, config_context
patch_sklearn()

# Alpha Vantage API Setup (replace with your API key)
ALPHA_VANTAGE_API_KEY = "your_alpha_vantage_api_key"

# 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 Alpha Vantage
def fetch_stock_data(symbol):
    url = f"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={symbol}&apikey={ALPHA_VANTAGE_API_KEY}"
    response = requests.get(url)
    return response.json().get("Time Series (Daily)", {})

# Compute Moving Average using Intel oneDAL
def compute_moving_average(prices, window=5):
    # Convert prices to a NumPy array and reshape it for DAAL
    import numpy as np
    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 Alpha Vantage and oneDAL
def technical_analysis(symbol):
    data = fetch_stock_data(symbol)
    
    if data:
        # Extract closing prices from the time series data
        closing_prices = [float(v['4. close']) for v in data.values()]
        dates = list(data.keys())

        # 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[0]
        latest_price = closing_prices[0]
        latest_moving_average = moving_averages[0] 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 Intel oneDAL")
    st.write("""
    This app provides a comprehensive stock analysis including:
    - Sentiment Analysis of recent news
    - Fundamental Analysis (Market Cap, PE Ratio, EPS)
    - 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 Alpha Vantage API
            stock_data = fetch_stock_data(company_symbol)
            
            if stock_data:
                # Display the fetched stock overview
                st.subheader("Asset Overview")
                st.json(stock_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_analysis(company_symbol, sentiment_model)
                    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()