-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_web_demo.py
More file actions
135 lines (111 loc) · 3.72 KB
/
simple_web_demo.py
File metadata and controls
135 lines (111 loc) · 3.72 KB
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
128
129
130
131
132
133
134
135
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import pandas_ta as ta
from datetime import datetime, timedelta
# Configure page
st.set_page_config(
page_title="📊 Pandas-TA Demo",
page_icon="📊",
layout="wide"
)
# Title
st.title("📊 Pandas-TA Technical Analysis Demo")
st.markdown("**Simple demo of technical analysis indicators**")
# Sidebar
st.sidebar.header("🔧 Settings")
days = st.sidebar.slider("Days of Data", 30, 365, 90)
start_price = st.sidebar.number_input("Starting Price", 10.0, 1000.0, 150.0)
# Generate sample data
@st.cache_data
def generate_data(days, start_price):
dates = pd.date_range(start=datetime.now() - timedelta(days=days),
end=datetime.now(), freq='D')
np.random.seed(42)
returns = np.random.normal(0.001, 0.02, len(dates))
prices = [start_price]
for ret in returns[1:]:
prices.append(prices[-1] * (1 + ret))
data = []
for i, (date, close) in enumerate(zip(dates, prices)):
high = close * (1 + abs(np.random.normal(0, 0.01)))
low = close * (1 - abs(np.random.normal(0, 0.01)))
open_price = close + np.random.normal(0, close * 0.005)
volume = int(np.random.uniform(1000000, 5000000))
data.append({
'Date': date,
'Open': open_price,
'High': max(open_price, high, close),
'Low': min(open_price, low, close),
'Close': close,
'Volume': volume
})
df = pd.DataFrame(data)
df.set_index('Date', inplace=True)
return df
# Generate button
if st.sidebar.button("🚀 Generate Analysis"):
with st.spinner("Generating data and indicators..."):
# Generate data
df = generate_data(days, start_price)
# Calculate indicators
df['SMA_20'] = ta.sma(df['Close'], length=20)
df['RSI'] = ta.rsi(df['Close'], length=14)
st.success(f"✅ Generated {len(df)} days of data with indicators!")
# Store in session state
st.session_state['df'] = df
# Display results
if 'df' in st.session_state:
df = st.session_state['df']
# Show metrics
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Latest Price", f"${df['Close'].iloc[-1]:.2f}")
with col2:
st.metric("Latest RSI", f"{df['RSI'].iloc[-1]:.1f}")
with col3:
st.metric("Days of Data", len(df))
# Show chart
st.subheader("📈 Price Chart")
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8))
# Price and SMA
ax1.plot(df.index, df['Close'], label='Close Price', color='blue')
ax1.plot(df.index, df['SMA_20'], label='SMA 20', color='red')
ax1.set_title('Stock Price with SMA')
ax1.legend()
ax1.grid(True)
# RSI
ax2.plot(df.index, df['RSI'], label='RSI', color='purple')
ax2.axhline(y=70, color='red', linestyle='--', alpha=0.7)
ax2.axhline(y=30, color='green', linestyle='--', alpha=0.7)
ax2.set_title('RSI Indicator')
ax2.set_ylim(0, 100)
ax2.legend()
ax2.grid(True)
plt.tight_layout()
st.pyplot(fig)
# Show data table
st.subheader("📋 Data Table")
st.dataframe(df.tail(10))
# Download button
csv = df.to_csv()
st.download_button(
"📥 Download CSV",
csv,
"technical_analysis.csv",
"text/csv"
)
else:
st.info("👆 Click 'Generate Analysis' in the sidebar to start!")
st.markdown("""
### Features:
- Generate sample stock data
- Calculate SMA and RSI indicators
- Interactive charts
- Data table display
- CSV download
""")
# Footer
st.markdown("---")
st.markdown("**Powered by pandas-ta library** 📊")