Spaces:
Sleeping
Sleeping
Commit
·
89171ff
1
Parent(s):
72ee182
upgraded stock market simulator
Browse files- app.py +138 -27
- requirements.txt +3 -0
app.py
CHANGED
@@ -3,10 +3,25 @@ import yfinance as yf
|
|
3 |
import pandas as pd
|
4 |
import plotly.graph_objs as go
|
5 |
import numpy as np
|
|
|
|
|
6 |
|
7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
try:
|
9 |
-
pswdVal = st.
|
10 |
if pswdVal==st.secrets["PSWD"]:
|
11 |
isPswdValid = True
|
12 |
except:
|
@@ -15,6 +30,13 @@ except:
|
|
15 |
if not isPswdValid:
|
16 |
st.write("Invalid Password")
|
17 |
else:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
# Set the Streamlit app title and icon
|
19 |
st.set_page_config(page_title="Stock Analysis", page_icon="📈")
|
20 |
|
@@ -29,31 +51,120 @@ else:
|
|
29 |
stock_data = yf.download(ticker_symbol, start=start_date, end=end_date)
|
30 |
except Exception as e:
|
31 |
st.error("Error fetching stock data. Please check the ticker symbol and date range.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
|
33 |
-
#
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
# Plot a candlestick chart
|
39 |
-
st.subheader("Candlestick Chart")
|
40 |
-
fig = go.Figure(data=[go.Candlestick(x=stock_data.index,
|
41 |
-
open=stock_data['Open'],
|
42 |
-
high=stock_data['High'],
|
43 |
-
low=stock_data['Low'],
|
44 |
-
close=stock_data['Close'])])
|
45 |
-
fig.update_layout(title=f'{ticker_symbol} Candlestick Chart', xaxis_title='Date', yaxis_title='Price')
|
46 |
st.plotly_chart(fig)
|
47 |
|
48 |
-
#
|
49 |
-
st.
|
50 |
-
|
51 |
-
|
52 |
-
st.
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
import pandas as pd
|
4 |
import plotly.graph_objs as go
|
5 |
import numpy as np
|
6 |
+
from plotly.subplots import make_subplots
|
7 |
+
import os
|
8 |
|
9 |
+
from langchain.embeddings import GooglePalmEmbeddings
|
10 |
+
from langchain.llms import GooglePalm
|
11 |
+
|
12 |
+
from langchain.document_loaders import UnstructuredURLLoader #load urls into docoument-loader
|
13 |
+
from langchain.chains.question_answering import load_qa_chain
|
14 |
+
from langchain.indexes import VectorstoreIndexCreator #vectorize db index with chromadb
|
15 |
+
from langchain.text_splitter import CharacterTextSplitter #text splitter
|
16 |
+
from langchain.chains import RetrievalQA
|
17 |
+
from langchain.document_loaders import UnstructuredPDFLoader #load pdf
|
18 |
+
from langchain.agents import create_pandas_dataframe_agent
|
19 |
+
import google.generativeai as palm
|
20 |
+
|
21 |
+
isPswdValid = True # Set to True to temporarily disable password checking
|
22 |
+
palm_api_key = st.secrets["PALM_API_KEY"]
|
23 |
try:
|
24 |
+
pswdVal = st.query_params()['pwd'][0]
|
25 |
if pswdVal==st.secrets["PSWD"]:
|
26 |
isPswdValid = True
|
27 |
except:
|
|
|
30 |
if not isPswdValid:
|
31 |
st.write("Invalid Password")
|
32 |
else:
|
33 |
+
# Initialize language model
|
34 |
+
api_key = palm_api_key # put your API key here
|
35 |
+
os.environ["GOOGLE_API_KEY"] = palm_api_key
|
36 |
+
palm.configure(api_key=palm_api_key)
|
37 |
+
llm = GooglePalm()
|
38 |
+
llm.temperature = 0.1
|
39 |
+
|
40 |
# Set the Streamlit app title and icon
|
41 |
st.set_page_config(page_title="Stock Analysis", page_icon="📈")
|
42 |
|
|
|
51 |
stock_data = yf.download(ticker_symbol, start=start_date, end=end_date)
|
52 |
except Exception as e:
|
53 |
st.error("Error fetching stock data. Please check the ticker symbol and date range.")
|
54 |
+
df = stock_data
|
55 |
+
df.reset_index(inplace=True) # Reset index to ensure 'Date' becomes a column
|
56 |
+
|
57 |
+
# Create figure with secondary y-axis
|
58 |
+
fig = make_subplots(specs=[[{"secondary_y": True}]])
|
59 |
+
|
60 |
+
# include candlestick with rangeselector
|
61 |
+
fig.add_trace(go.Candlestick(x=df['Date'], # Except date, query all other data using Symbol
|
62 |
+
open=df['Open'][ticker_symbol], high=df['High'][ticker_symbol],
|
63 |
+
low=df['Low'][ticker_symbol], close=df['Close'][ticker_symbol]),
|
64 |
+
secondary_y=True)
|
65 |
|
66 |
+
# include a go.Bar trace for volumes
|
67 |
+
fig.add_trace(go.Bar(x=df['Date'], y=df['Volume'][ticker_symbol]),
|
68 |
+
secondary_y=False)
|
69 |
+
|
70 |
+
fig.layout.yaxis2.showgrid=False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
st.plotly_chart(fig)
|
72 |
|
73 |
+
# Technical Indicators
|
74 |
+
st.header("Technical Indicators")
|
75 |
+
|
76 |
+
# Moving Averages
|
77 |
+
st.subheader("Moving Averages")
|
78 |
+
df['SMA_20'] = df['Close'][ticker_symbol].rolling(window=20).mean()
|
79 |
+
df['SMA_50'] = df['Close'][ticker_symbol].rolling(window=50).mean()
|
80 |
+
fig = go.Figure()
|
81 |
+
fig.add_trace(go.Scatter(x=df['Date'], y=df['Close'][ticker_symbol], mode='lines', name='Close Price'))
|
82 |
+
fig.add_trace(go.Scatter(x=df['Date'], y=df['SMA_20'], mode='lines', name='20-Day SMA'))
|
83 |
+
fig.add_trace(go.Scatter(x=df['Date'], y=df['SMA_50'], mode='lines', name='50-Day SMA'))
|
84 |
+
fig.update_layout(title="Moving Averages", xaxis_title="Date", yaxis_title="Price (USD)")
|
85 |
+
st.plotly_chart(fig)
|
86 |
+
|
87 |
+
# RSI (Manual Calculation)
|
88 |
+
st.subheader("Relative Strength Index (RSI)")
|
89 |
+
window_length = 14
|
90 |
+
|
91 |
+
# Calculate the daily price changes
|
92 |
+
delta = df['Close'][ticker_symbol].diff()
|
93 |
+
|
94 |
+
# Separate gains and losses
|
95 |
+
gain = delta.where(delta > 0, 0)
|
96 |
+
loss = -delta.where(delta < 0, 0)
|
97 |
+
|
98 |
+
# Calculate the average gain and average loss
|
99 |
+
avg_gain = gain.rolling(window=window_length, min_periods=1).mean()
|
100 |
+
avg_loss = loss.rolling(window=window_length, min_periods=1).mean()
|
101 |
+
|
102 |
+
# Calculate the RSI
|
103 |
+
rs = avg_gain / avg_loss
|
104 |
+
df['RSI'] = 100 - (100 / (1 + rs))
|
105 |
+
|
106 |
+
fig = go.Figure()
|
107 |
+
fig.add_trace(go.Scatter(x=df['Date'], y=df['RSI'], mode='lines', name='RSI'))
|
108 |
+
fig.add_hline(y=70, line_dash="dash", line_color="red", annotation_text="Overbought")
|
109 |
+
fig.add_hline(y=30, line_dash="dash", line_color="green", annotation_text="Oversold")
|
110 |
+
fig.update_layout(title="RSI Indicator", xaxis_title="Date", yaxis_title="RSI")
|
111 |
+
st.plotly_chart(fig)
|
112 |
+
|
113 |
+
# Volume Analysis
|
114 |
+
st.subheader("Volume Analysis")
|
115 |
+
fig = go.Figure()
|
116 |
+
fig.add_trace(go.Bar(x=df['Date'], y=df['Volume'][ticker_symbol], name='Volume'))
|
117 |
+
fig.update_layout(title="Volume Analysis", xaxis_title="Date", yaxis_title="Volume")
|
118 |
+
st.plotly_chart(fig)
|
119 |
+
|
120 |
+
loader = []
|
121 |
+
index = VectorstoreIndexCreator(
|
122 |
+
embedding=GooglePalmEmbeddings(),
|
123 |
+
text_splitter=CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)).from_loaders(loader)
|
124 |
+
chain = RetrievalQA.from_chain_type(llm=llm,
|
125 |
+
chain_type="stuff",
|
126 |
+
retriever=index.vectorstore.as_retriever(),
|
127 |
+
input_key="question")
|
128 |
+
|
129 |
+
# Additional Insights
|
130 |
+
st.header("In-depth Analysis")
|
131 |
+
# Prepare text for PaLM
|
132 |
+
chatTextStr = f"""
|
133 |
+
Analyze the following stock data for patterns, trends, and insights.
|
134 |
+
Provide a detailed summary of key market movements.
|
135 |
+
"""
|
136 |
+
|
137 |
+
# Initializing the agent
|
138 |
+
agent = create_pandas_dataframe_agent(llm, df[['Date', 'Open', 'High', 'Low', 'Close']].tail(10), verbose=False)
|
139 |
+
answer = agent.run(chatTextStr)
|
140 |
+
|
141 |
+
# # Query PaLM API
|
142 |
+
# try:
|
143 |
+
# response = palm.generate_text(
|
144 |
+
# prompt=chatTextStr,
|
145 |
+
# temperature=0.1,
|
146 |
+
# max_output_tokens=500
|
147 |
+
# )
|
148 |
+
# st.write(response.result)
|
149 |
+
# except Exception as e:
|
150 |
+
# st.error(f"Error using Google PaLM API: {e}")
|
151 |
+
|
152 |
+
st.markdown("""
|
153 |
+
Google Gemini API analysis:
|
154 |
+
{answer}
|
155 |
+
""")
|
156 |
+
|
157 |
+
# User Interaction
|
158 |
+
st.header("Custom Analysis")
|
159 |
+
start_date = st.date_input("Select start date:", value=pd.to_datetime("2024-01-01"))
|
160 |
+
end_date = st.date_input("Select end date:", value=pd.to_datetime("2024-09-30"))
|
161 |
+
|
162 |
+
# Ensure all dates are timezone-naive
|
163 |
+
df['Date'] = pd.to_datetime(df['Date']).dt.tz_localize(None)
|
164 |
+
start_date = pd.to_datetime(start_date).tz_localize(None)
|
165 |
+
end_date = pd.to_datetime(end_date).tz_localize(None)
|
166 |
+
|
167 |
+
# Filter the DataFrame based on the date range
|
168 |
+
filtered_df = df[(df['Date'] >= start_date) & (df['Date'] <= end_date)]
|
169 |
+
|
170 |
+
st.write(filtered_df)
|
requirements.txt
CHANGED
@@ -2,3 +2,6 @@ streamlit
|
|
2 |
yfinance
|
3 |
pandas
|
4 |
plotly
|
|
|
|
|
|
|
|
2 |
yfinance
|
3 |
pandas
|
4 |
plotly
|
5 |
+
google-generativeai
|
6 |
+
langchain==0.0.310
|
7 |
+
chromadb==0.4.14
|