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.embeddings import GooglePalmEmbeddings from langchain.llms import GooglePalm from langchain.document_loaders import UnstructuredURLLoader #load urls into docoument-loader from langchain.chains.question_answering import load_qa_chain from langchain.indexes import VectorstoreIndexCreator #vectorize db index with chromadb from langchain.text_splitter import CharacterTextSplitter #text splitter from langchain.chains import RetrievalQA from langchain.document_loaders import UnstructuredPDFLoader #load pdf from langchain.agents import create_pandas_dataframe_agent import google.generativeai as palm isPswdValid = True # Set to True to temporarily disable password checking palm_api_key = st.secrets["PALM_API_KEY"] try: pswdVal = st.query_params()['pwd'][0] if pswdVal==st.secrets["PSWD"]: isPswdValid = True except: pass if not isPswdValid: st.write("Invalid Password") else: # Initialize language model api_key = palm_api_key # put your API key here os.environ["GOOGLE_API_KEY"] = palm_api_key palm.configure(api_key=palm_api_key) llm = GooglePalm() llm.temperature = 0.1 # 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 # 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) from langchain.document_loaders import DataFrameLoader loader = DataFrameLoader(df) index = VectorstoreIndexCreator(embedding=GooglePalmEmbeddings()).from_loaders([loader]) # index = VectorstoreIndexCreator( # embedding=GooglePalmEmbeddings(), # text_splitter=CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)).from_loaders(loader) chain = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=index.vectorstore.as_retriever(), input_key="question") # 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. """ # Initializing the agent agent = create_pandas_dataframe_agent(llm, df[['Date', 'Open', 'High', 'Low', 'Close']].tail(10), verbose=False) answer = agent.run(chatTextStr) # # Query PaLM API # try: # response = palm.generate_text( # prompt=chatTextStr, # temperature=0.1, # max_output_tokens=500 # ) # st.write(response.result) # except Exception as e: # st.error(f"Error using Google PaLM API: {e}") st.markdown(""" Google Gemini API analysis: {answer} """) # User Interaction st.header("Custom Analysis") start_date = st.date_input("Select start date:", value=pd.to_datetime("2024-01-01")) end_date = st.date_input("Select end date:", value=pd.to_datetime("2024-09-30")) # Ensure all dates are timezone-naive df['Date'] = pd.to_datetime(df['Date']).dt.tz_localize(None) start_date = pd.to_datetime(start_date).tz_localize(None) end_date = pd.to_datetime(end_date).tz_localize(None) # Filter the DataFrame based on the date range filtered_df = df[(df['Date'] >= start_date) & (df['Date'] <= end_date)] st.write(filtered_df)