File size: 4,849 Bytes
7a000af
 
 
 
 
 
 
 
 
 
 
268cbf5
7a000af
 
 
 
08aff20
7a000af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
124
125
126
127
import streamlit as st
import yfinance as yf
import pandas as pd
import plotly.graph_objs as go
import numpy as np
from plotly.subplots import make_subplots
import os

from langchain_openai import ChatOpenAI


isPswdValid = False # Set to True to temporarily disable password checking
OPEN_ROUTER_KEY = st.secrets["OPEN_ROUTER_KEY"]
OPEN_ROUTER_MODEL = "meta-llama/llama-3.1-70b-instruct:free"

try:
    pswdVal = st.experimental_get_query_params()['pwd'][0]
    if pswdVal==st.secrets["PSWD"]:
        isPswdValid = True
except:
    pass

if not isPswdValid:
    st.write("Invalid Password")
else:
    # Initialize language model
    llm = ChatOpenAI(model=OPEN_ROUTER_MODEL, temperature=0.1, openai_api_key=OPEN_ROUTER_KEY, openai_api_base="https://openrouter.ai/api/v1")

    # Set the Streamlit app title and icon
    st.set_page_config(page_title="Stock Analysis", page_icon="📈")

    # Create a Streamlit sidebar for user input
    st.sidebar.title("Stock Analysis")
    ticker_symbol = st.sidebar.text_input("Enter Stock Ticker Symbol:", value='AAPL')
    start_date = st.sidebar.date_input("Start Date", pd.to_datetime('2024-01-01'))
    end_date = st.sidebar.date_input("End Date", pd.to_datetime('2024-10-01'))

    # Fetch stock data from Yahoo Finance
    try:
        stock_data = yf.download(ticker_symbol, start=start_date, end=end_date)
    except Exception as e:
        st.error("Error fetching stock data. Please check the ticker symbol and date range.")
    df = stock_data
    df.reset_index(inplace=True)  # Reset index to ensure 'Date' becomes a column
    
    # Technical Indicators
    st.header("Stock Price Chart")

    # Create figure with secondary y-axis
    fig = make_subplots(specs=[[{"secondary_y": True}]])

    # include candlestick with rangeselector
    fig.add_trace(go.Candlestick(x=df['Date'], # Except date, query all other data using Symbol
                    open=df['Open'][ticker_symbol], high=df['High'][ticker_symbol],
                    low=df['Low'][ticker_symbol], close=df['Close'][ticker_symbol]),
                secondary_y=True)

    # include a go.Bar trace for volumes
    fig.add_trace(go.Bar(x=df['Date'], y=df['Volume'][ticker_symbol]),
                secondary_y=False)

    fig.layout.yaxis2.showgrid=False
    st.plotly_chart(fig)

    # Technical Indicators
    st.header("Technical Indicators")

    # Moving Averages
    st.subheader("Moving Averages")
    df['SMA_20'] = df['Close'][ticker_symbol].rolling(window=20).mean()
    df['SMA_50'] = df['Close'][ticker_symbol].rolling(window=50).mean()
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=df['Date'], y=df['Close'][ticker_symbol], mode='lines', name='Close Price'))
    fig.add_trace(go.Scatter(x=df['Date'], y=df['SMA_20'], mode='lines', name='20-Day SMA'))
    fig.add_trace(go.Scatter(x=df['Date'], y=df['SMA_50'], mode='lines', name='50-Day SMA'))
    fig.update_layout(title="Moving Averages", xaxis_title="Date", yaxis_title="Price (USD)")
    st.plotly_chart(fig)

    # RSI (Manual Calculation)
    st.subheader("Relative Strength Index (RSI)")
    window_length = 14

    # Calculate the daily price changes
    delta = df['Close'][ticker_symbol].diff()

    # Separate gains and losses
    gain = delta.where(delta > 0, 0)
    loss = -delta.where(delta < 0, 0)

    # Calculate the average gain and average loss
    avg_gain = gain.rolling(window=window_length, min_periods=1).mean()
    avg_loss = loss.rolling(window=window_length, min_periods=1).mean()

    # Calculate the RSI
    rs = avg_gain / avg_loss
    df['RSI'] = 100 - (100 / (1 + rs))

    fig = go.Figure()
    fig.add_trace(go.Scatter(x=df['Date'], y=df['RSI'], mode='lines', name='RSI'))
    fig.add_hline(y=70, line_dash="dash", line_color="red", annotation_text="Overbought")
    fig.add_hline(y=30, line_dash="dash", line_color="green", annotation_text="Oversold")
    fig.update_layout(title="RSI Indicator", xaxis_title="Date", yaxis_title="RSI")
    st.plotly_chart(fig)

    # Volume Analysis
    st.subheader("Volume Analysis")
    fig = go.Figure()
    fig.add_trace(go.Bar(x=df['Date'], y=df['Volume'][ticker_symbol], name='Volume'))
    fig.update_layout(title="Volume Analysis", xaxis_title="Date", yaxis_title="Volume")
    st.plotly_chart(fig)

    # Additional Insights
    st.header("In-depth Analysis")
    # Prepare text for PaLM
    chatTextStr = f"""

    Analyze the following stock data for patterns, trends, and insights.

    Provide a detailed summary of key market movements.

    """

    answer = llm.predict(f'''

    I have yfinance data below on {ticker_symbol} symbol:



    {str(df[['Date', 'Open', 'High', 'Low', 'Close']].tail(30))}



    {chatTextStr}

    ''')
    st.write(answer)