QuantumLearner commited on
Commit
eec67e7
·
verified ·
1 Parent(s): ccbea09

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +128 -0
app.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ import yfinance as yf
5
+ import streamlit as st
6
+ import plotly.graph_objects as go
7
+ from plotly.subplots import make_subplots
8
+
9
+ # Helper function to fetch stock data
10
+ def fetch_stock_data(ticker: str, start_date: str, end_date: str) -> pd.DataFrame:
11
+ """Fetch stock data from Yahoo Finance."""
12
+ return yf.download(ticker, start=start_date, end=end_date)
13
+
14
+ # True Range Volatility Ratio
15
+ def calculate_volatility_ratio(data: pd.DataFrame, n: int = 14, ratio: float = 1.75) -> go.Figure:
16
+ data['High_Low'] = data['High'] - data['Low']
17
+ data['High_PrevClose'] = abs(data['High'] - data['Close'].shift())
18
+ data['Low_PrevClose'] = abs(data['Low'] - data['Close'].shift())
19
+ data['True_Range'] = data[['High_Low', 'High_PrevClose', 'Low_PrevClose']].max(axis=1)
20
+ data['EMA_True_Range'] = data['True_Range'].ewm(span=n, adjust=False).mean()
21
+ data['Volatility_Ratio'] = data['True_Range'] / data['EMA_True_Range']
22
+
23
+ fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1,
24
+ subplot_titles=('Close Price', 'Volatility Ratio'))
25
+
26
+ fig.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='Close Price'), row=1, col=1)
27
+ above_threshold = data['Volatility_Ratio'] > ratio
28
+ fig.add_trace(go.Scatter(x=data.index[above_threshold], y=data['Close'][above_threshold], mode='markers',
29
+ marker=dict(color='red', size=10), name=f'Volatility Ratio > {ratio}'), row=1, col=1)
30
+
31
+ fig.add_trace(go.Scatter(x=data.index, y=data['Volatility_Ratio'], mode='lines', name='Volatility Ratio'), row=2, col=1)
32
+ fig.add_hline(y=ratio, line=dict(color='red', dash='dash'), row=2, col=1)
33
+
34
+ fig.update_layout(title='Volatility Ratio with Buy/Sell Signals', xaxis_title='Date', yaxis_title='Price', yaxis2_title='Volatility Ratio')
35
+ return fig
36
+
37
+ # Volume Ratio with Dynamic Percentile
38
+ def calculate_volume_ratio(data: pd.DataFrame, percentile_threshold: float = 0.97) -> go.Figure:
39
+ data['50_day_MA'] = data['Close'].rolling(window=50).mean()
40
+ data['200_day_MA'] = data['Close'].rolling(window=200).mean()
41
+ data['Volume_MA20'] = data['Volume'].rolling(window=20).mean()
42
+ data['Volume_Ratio'] = data['Volume'] / data['Volume_MA20']
43
+
44
+ dynamic_percentile = data['Volume_Ratio'].quantile(percentile_threshold)
45
+ mask = data['Volume_Ratio'] > dynamic_percentile
46
+
47
+ fig = make_subplots(rows=3, cols=1, shared_xaxes=True, vertical_spacing=0.1,
48
+ subplot_titles=('Close Price and Volume', 'Volume Ratio', 'Histogram of Volume Ratio'),
49
+ specs=[[{"secondary_y": True}], [{}], [{}]])
50
+
51
+ # Plotting close price on primary y-axis
52
+ fig.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='Close Price', line=dict(color='blue')), row=1, col=1, secondary_y=False)
53
+
54
+ fig.add_trace(go.Scatter(x=data.index[mask], y=data['Close'][mask], mode='markers',
55
+ marker=dict(color='red', size=10), name='High Volume Ratio'), row=1, col=1, secondary_y=False)
56
+
57
+ fig.add_trace(go.Bar(x=data.index, y=data['Volume'], name='Volume', marker_color='gray', opacity=0.3), row=1, col=1, secondary_y=True)
58
+
59
+ fig.add_trace(go.Scatter(x=data.index, y=data['Volume_MA20'], mode='lines', name='20-day Volume MA', line=dict(color='purple')), row=1, col=1, secondary_y=True)
60
+
61
+ fig.add_trace(go.Scatter(x=data.index, y=data['Volume_Ratio'], mode='lines', name='Volume Ratio', line=dict(color='green')), row=2, col=1)
62
+ fig.add_hline(y=dynamic_percentile, line=dict(color='red', dash='dash'), row=2, col=1)
63
+
64
+ fig.add_trace(go.Histogram(x=data['Volume_Ratio'], nbinsx=50, name='Volume Ratio Distribution', marker_color='green', opacity=0.7), row=3, col=1)
65
+ fig.add_vline(x=dynamic_percentile, line=dict(color='red', dash='dash'), row=3, col=1)
66
+
67
+ fig.update_layout(title='Volume Ratio with Dynamic Percentile Threshold', xaxis_title='Date', yaxis1_title='Price', yaxis2_title='Volume', yaxis3_title='Volume Ratio', yaxis4_title='Frequency')
68
+ return fig
69
+
70
+ # Streamlit app
71
+ st.set_page_config(page_title="Technical Analysis", layout="wide")
72
+ st.title('Technical Analysis Indicators')
73
+
74
+ # Sidebar for method selection
75
+ selected = st.sidebar.radio("Select Analysis", ["Volatility Ratio", "Volume Ratio"])
76
+
77
+ # Sidebar for input parameters
78
+ st.sidebar.header("Input Parameters")
79
+ ticker = st.sidebar.text_input('Enter Stock Ticker', 'SIE.DE')
80
+ start_date = st.sidebar.date_input('Start Date', pd.to_datetime('2020-01-01'))
81
+ end_date = st.sidebar.date_input('End Date', pd.to_datetime('2024-12-31'))
82
+
83
+ # Fetch data
84
+ if 'data' not in st.session_state or st.sidebar.button('Fetch Data'):
85
+ st.session_state.data = fetch_stock_data(ticker, start_date, end_date)
86
+
87
+ data = st.session_state.data
88
+
89
+ # Display results based on the selected method
90
+ if selected == "Volatility Ratio":
91
+ st.markdown("""
92
+ ### Volatility Ratio
93
+
94
+ This method calculates the True Range Volatility Ratio, which helps identify periods of high volatility. A ratio above a specified threshold indicates high volatility.
95
+
96
+ **How to use:**
97
+ 1. Enter the stock ticker, start date, and end date.
98
+ 2. Set the number of days for the EMA calculation.
99
+ 3. Set the volatility ratio threshold.
100
+ 4. Click 'Fetch Data' to load the stock data.
101
+ 5. The chart will display the True Range Volatility Ratio and highlight points where the ratio exceeds the threshold.
102
+
103
+ **Results:**
104
+ The chart shows the close prices with highlighted points of high volatility and the Volatility Ratio over time.
105
+ """)
106
+ n = st.sidebar.number_input('Number of Days for EMA', min_value=1, value=14)
107
+ ratio = st.sidebar.slider('Volatility Ratio Threshold', min_value=1.0, max_value=3.0, value=1.75, step=0.1)
108
+ fig = calculate_volatility_ratio(data, n, ratio)
109
+ st.plotly_chart(fig)
110
+
111
+ elif selected == "Volume Ratio":
112
+ st.markdown("""
113
+ ### Volume Ratio with Dynamic Percentile
114
+
115
+ This method calculates the Volume Ratio and uses a dynamic percentile threshold to identify high volume periods. A volume ratio above the specified percentile indicates high trading activity.
116
+
117
+ **How to use:**
118
+ 1. Enter the stock ticker, start date, and end date.
119
+ 2. Set the percentile threshold.
120
+ 3. Click 'Fetch Data' to load the stock data.
121
+ 4. The chart will display the Volume Ratio and highlight points where the ratio exceeds the percentile threshold.
122
+
123
+ **Results:**
124
+ The chart shows the close prices with highlighted points of high volume and the Volume Ratio over time.
125
+ """)
126
+ percentile_threshold = st.sidebar.slider('Percentile Threshold', min_value=0.5, max_value=1.0, value=0.97, step=0.01)
127
+ fig = calculate_volume_ratio(data, percentile_threshold)
128
+ st.plotly_chart(fig)