File size: 5,281 Bytes
e74d865 |
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 |
import pandas as pd
import pandas_ta as ta
import plotly.graph_objects as go
import streamlit as st
from ai_insights import get_ai_insight # Import AI insight function
def calculate_indicators(data, ma_window, rsi_window, macd_fast, macd_slow, macd_signal):
"""
Calculates Moving Average (MA), Bollinger Bands, RSI, MACD, and displays them in a 2x2 grid in Streamlit.
Also includes AI-generated insights next to each chart.
Args:
data (pandas.DataFrame): Stock data.
ma_window (int): Moving Average window.
rsi_window (int): RSI window.
macd_fast (int): MACD Fast period.
macd_slow (int): MACD Slow period.
macd_signal (int): MACD Signal period.
Returns:
pandas.DataFrame: Data with calculated indicators.
"""
# π **Calculate Moving Average (MA)**
data['MA'] = data['Close'].rolling(window=ma_window).mean()
# π **Calculate Bollinger Bands**
data['stddev'] = data['Close'].rolling(window=ma_window).std()
data['Upper_BB'] = data['MA'] + (2 * data['stddev'])
data['Lower_BB'] = data['MA'] - (2 * data['stddev'])
# π **Calculate RSI**
delta = data['Close'].diff(1)
gain = (delta.where(delta > 0, 0)).rolling(window=rsi_window).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=rsi_window).mean()
rs = gain / loss
data['RSI'] = 100 - (100 / (1 + rs))
# π **Calculate MACD**
data['MACD'] = data['Close'].ewm(span=macd_fast, adjust=False).mean() - data['Close'].ewm(span=macd_slow, adjust=False).mean()
data['MACD_Signal'] = data['MACD'].ewm(span=macd_signal, adjust=False).mean()
data['MACD_Hist'] = data['MACD'] - data['MACD_Signal']
# π **Create Candlestick Chart with Bollinger Bands & MA**
fig_candlestick = go.Figure()
fig_candlestick.add_trace(go.Candlestick(
x=data.index,
open=data['Open'], high=data['High'],
low=data['Low'], close=data['Close'],
name="Candlestick",
increasing_line_color="green",
decreasing_line_color="red"
))
fig_candlestick.add_trace(go.Scatter(x=data.index, y=data['MA'], mode='lines', name=f"{ma_window}-day MA", line=dict(color="blue")))
fig_candlestick.add_trace(go.Scatter(x=data.index, y=data['Upper_BB'], mode='lines', name="Upper BB", line=dict(color="purple", dash='dot')))
fig_candlestick.add_trace(go.Scatter(x=data.index, y=data['Lower_BB'], mode='lines', name="Lower BB", line=dict(color="purple", dash='dot')))
fig_candlestick.update_layout(title="π Stock Price with Bollinger Bands & MA", xaxis_rangeslider_visible=True, template="plotly_dark", height=500, width=900)
# π **Create RSI Chart**
fig_rsi = go.Figure()
fig_rsi.add_trace(go.Scatter(x=data.index, y=data['RSI'], mode='lines', name="RSI", line=dict(color="orange")))
fig_rsi.add_trace(go.Scatter(x=data.index, y=[70]*len(data), mode='lines', name="Overbought (70)", line=dict(color="red", dash='dash')))
fig_rsi.add_trace(go.Scatter(x=data.index, y=[30]*len(data), mode='lines', name="Oversold (30)", line=dict(color="green", dash='dash')))
fig_rsi.update_layout(title="π Relative Strength Index (RSI)", xaxis_rangeslider_visible=False, template="plotly_dark", height=500, width=900)
# π **Create MACD Chart**
fig_macd = go.Figure()
fig_macd.add_trace(go.Scatter(x=data.index, y=data['MACD'], mode='lines', name="MACD", line=dict(color="blue")))
fig_macd.add_trace(go.Scatter(x=data.index, y=data['MACD_Signal'], mode='lines', name="MACD Signal", line=dict(color="red")))
fig_macd.add_trace(go.Bar(x=data.index, y=data['MACD_Hist'], name="MACD Histogram", marker_color="purple"))
fig_macd.update_layout(title="π MACD Indicator", xaxis_rangeslider_visible=False, template="plotly_dark", height=500, width=900)
# π **Display Charts One Below Another**
st.subheader("π Stock Price with Bollinger Bands & Moving Averages")
st.plotly_chart(fig_candlestick, use_container_width=True) # π Stock Chart
st.subheader("π Relative Strength Index (RSI)")
st.plotly_chart(fig_rsi, use_container_width=True) # π RSI Chart
st.subheader("π MACD Indicator")
st.plotly_chart(fig_macd, use_container_width=True) # π MACD Chart
print(data.columns)
'''
# π **Display Charts and AI Insights in a 2x2 Grid**
col1, col2 = st.columns((7, 1.5)) # 2/3 chart, 1/3 AI insight
with col1:
st.plotly_chart(fig_candlestick, use_container_width=True) # π Stock Price
with col2:
st.subheader("π‘ AI Insight for Moving Average")
st.write(ma_insight)
st.subheader("π‘ AI Insight for Bollinger Bands")
st.write(bb_insight)
col3, col4 = st.columns((7, 1.5))
with col3:
st.plotly_chart(fig_rsi, use_container_width=True) # π RSI
with col4:
st.subheader("π‘ AI Insight for RSI")
st.write(rsi_insight)
col5, col6 = st.columns((7, 1.5))
with col5:
st.plotly_chart(fig_macd, use_container_width=True) # π MACD
with col6:
st.subheader("π‘ AI Insight for MACD")
st.write(macd_insight)
'''
return data # β
Return only data, all charts & AI insights are displayed in Streamlit
|