Jumper-Clown commited on
Commit
9f633b0
1 Parent(s): eda3576

add test trend indicators

Browse files
__pycache__/page_symbol_details.cpython-312.pyc CHANGED
Binary files a/__pycache__/page_symbol_details.cpython-312.pyc and b/__pycache__/page_symbol_details.cpython-312.pyc differ
 
__pycache__/trends.cpython-312.pyc CHANGED
Binary files a/__pycache__/trends.cpython-312.pyc and b/__pycache__/trends.cpython-312.pyc differ
 
__pycache__/ui.cpython-312.pyc CHANGED
Binary files a/__pycache__/ui.cpython-312.pyc and b/__pycache__/ui.cpython-312.pyc differ
 
page_symbol_details.py CHANGED
@@ -4,6 +4,7 @@ from plotly.subplots import make_subplots
4
  from streamlit_plotly_events import plotly_events
5
  import plotly.graph_objects as go
6
 
 
7
  import data_retriever
8
  import trends
9
  import ui
@@ -34,7 +35,7 @@ def run():
34
  # max time period
35
  st.text_input('No. of years look-back:', value=1, key="years_back")
36
  years_back = int(st.session_state.years_back)
37
- weeks_back = years_back*12*4
38
 
39
  symbol_prices = data_retriever.get_current_stock_data(symbol, weeks_back)
40
  if not any(symbol_prices):
@@ -55,17 +56,38 @@ def run():
55
  # indicator_datasets = indicators.create_indicators(dates, symbol_prices)
56
  # ui.create_indicators(fig1, indicator_datasets)
57
  # trend lines
58
- sigma_multiplier = st.slider(label='min trend deviation', min_value=1.0, max_value=10.0, value=3.0, step=0.1)
59
- sigma_dates, sigma_values = trends.trend_line(symbol_prices_backtest.index, np.array(symbol_prices_backtest['Close']), min_trend_size=21, sigma_multiplier=sigma_multiplier)
60
- ui.create_markers(candleFigure, sigma_dates, sigma_values, f"{sigma_multiplier} Deviations from regression line", 'Deviations')
61
-
62
- # vwap
63
- vwap = trends.vwap(symbol_prices_backtest)
64
- ui.create_line(candleFigure, backtest_dates, vwap, "Volume Weighted Average Price (VWAP)", "VWAP")
65
-
66
- # bollinger bands
67
- bollinger_dates, bollinger_low, bollinger_high = trends.bollinger_bands(backtest_dates, symbol_prices_backtest)
68
- ui.create_fill_area(candleFigure, bollinger_dates, bollinger_low, bollinger_high, "Bollinger Bands")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
  # plot all
71
  candleFigure.update_layout(title="Symbol Ticker",
@@ -75,17 +97,26 @@ def run():
75
  selected_points = plotly_events(candleFigure, click_event=True, hover_event=False, select_event=False, key='3')
76
 
77
  if st.checkbox('Tests'):
78
- testFigure = make_subplots(rows=1, cols=1)
79
- ui.create_line(testFigure, dates, symbol_prices['Volume'], "Volume")
80
- ui.add_mouse_indicator(testFigure, selected_points, min=np.min(symbol_prices['Volume']),
81
- max=np.max(symbol_prices['Volume']))
82
- test_id = st.plotly_chart(testFigure, use_container_width=True, key='test')
83
-
84
- fft_steps = st.slider(label='FFT Steps', min_value=8, max_value=128, value=16, step=8)
85
- specFig1 = ui.create_spectrogram(dates, symbol_prices['Close'], sampling_frequency=1, num_points_fft=fft_steps,
86
- overlap_percent=0.0, title="Close Price Spectrogram")
87
- specFig2 = ui.create_spectrogram(dates, symbol_prices['Volume'], sampling_frequency=1, num_points_fft=fft_steps,
88
- overlap_percent=0.0, title="Volume Spectrogram")
 
 
 
 
 
 
 
 
 
89
 
90
  if st.checkbox('Sector Trends'):
91
  # plot the trend of the market as a candlestick graph.
 
4
  from streamlit_plotly_events import plotly_events
5
  import plotly.graph_objects as go
6
 
7
+ import calculator
8
  import data_retriever
9
  import trends
10
  import ui
 
35
  # max time period
36
  st.text_input('No. of years look-back:', value=1, key="years_back")
37
  years_back = int(st.session_state.years_back)
38
+ weeks_back = years_back * 12 * 4
39
 
40
  symbol_prices = data_retriever.get_current_stock_data(symbol, weeks_back)
41
  if not any(symbol_prices):
 
56
  # indicator_datasets = indicators.create_indicators(dates, symbol_prices)
57
  # ui.create_indicators(fig1, indicator_datasets)
58
  # trend lines
59
+ # sigma_multiplier = st.slider(label='min trend deviation', min_value=1.0, max_value=10.0, value=3.0, step=0.1)
60
+ # sigma_dates, sigma_values = trends.trend_line(symbol_prices_backtest.index, np.array(symbol_prices_backtest['Close']), min_trend_size=21, sigma_multiplier=sigma_multiplier)
61
+ # ui.create_markers(candleFigure, sigma_dates, sigma_values, f"{sigma_multiplier} Deviations from regression line", 'Deviations')
62
+
63
+ # # vwap
64
+ # vwap = trends.vwap(symbol_prices_backtest)
65
+ # ui.create_line(candleFigure, backtest_dates, vwap, "Volume Weighted Average Price (VWAP)", "VWAP")
66
+
67
+ # # bollinger bands
68
+ # bollinger_dates, bollinger_low, bollinger_high = trends.bollinger_bands(backtest_dates, symbol_prices_backtest)
69
+ # ui.create_fill_area(candleFigure, bollinger_dates, bollinger_low, bollinger_high, "Bollinger Bands")
70
+
71
+ normalization_factor = 0.20*(max(symbol_prices['Close']) - min(symbol_prices['Close']))
72
+
73
+ # trend deviation area
74
+ period = 7
75
+ trend_deviation = trends.trend_deviation(symbol_prices['Close'][:], period=period)
76
+ trend_deviation_norm = calculator.normalize(trend_deviation, low=0.0, high=normalization_factor)
77
+ price_offset_low = [price - vol for price, vol in zip(symbol_prices['Close'][period:], trend_deviation_norm)]
78
+ price_offset_high = [price + vol for price, vol in zip(symbol_prices['Close'][period:], trend_deviation_norm)]
79
+ ui.create_fill_area(candleFigure, dates[period:], price_offset_low, price_offset_high, "Trend Deviation", color="rgba(0,50,50,0.3)")
80
+
81
+ # trade volume area
82
+ volume_norm = calculator.normalize(symbol_prices['Volume'], low=0.0, high=normalization_factor)
83
+ log_volume_offset_low = [price - vol for price, vol in
84
+ zip(symbol_prices['Close'], volume_norm)]
85
+ log_volume_offset_high = [price + vol for price, vol in
86
+ zip(symbol_prices['Close'], volume_norm)]
87
+ ui.create_fill_area(candleFigure, dates, log_volume_offset_low, log_volume_offset_high, "Volume Bands", color="rgba(100,20,0,0.3)")
88
+
89
+ sma_dates, deltas_sma = trends.sma(dates, symbol_prices['Close'], period)
90
+ ui.create_line(candleFigure, sma_dates, deltas_sma, f"Close price {period} day SMA")
91
 
92
  # plot all
93
  candleFigure.update_layout(title="Symbol Ticker",
 
97
  selected_points = plotly_events(candleFigure, click_event=True, hover_event=False, select_event=False, key='3')
98
 
99
  if st.checkbox('Tests'):
100
+ # testFigure = make_subplots(rows=1, cols=1)
101
+ # ui.create_line(testFigure, dates, symbol_prices['Volume'], "Volume")
102
+ # ui.add_mouse_indicator(testFigure, selected_points, min=np.min(symbol_prices['Volume']),
103
+ # max=np.max(symbol_prices['Volume']))
104
+ # testFigure.update_layout(title="Volume")
105
+ # test_id = st.plotly_chart(testFigure, use_container_width=True, key='test')
106
+
107
+ deltas = [cur - symbol_prices['Close'][max(0, idx - 1)] for idx, cur in enumerate(symbol_prices['Close'])]
108
+ testFigure2 = make_subplots(rows=1, cols=1)
109
+ ui.create_line(testFigure2, dates, deltas, "Deltas")
110
+ ui.add_mouse_indicator(testFigure2, selected_points, min=np.min(deltas),
111
+ max=np.max(deltas))
112
+ testFigure2.update_layout(title="Deltas")
113
+
114
+ ui.create_heatmap(dates, deltas, title="Deltas heatmap")
115
+
116
+ # sma
117
+ sma_dates, deltas_sma = trends.sma(dates, deltas)
118
+ ui.create_line(testFigure2, sma_dates, deltas_sma, "Deltas SMA")
119
+ test_id = st.plotly_chart(testFigure2, use_container_width=True, key='test2')
120
 
121
  if st.checkbox('Sector Trends'):
122
  # plot the trend of the market as a candlestick graph.
trends.py CHANGED
@@ -1,6 +1,7 @@
1
  from collections import defaultdict
2
 
3
  import numpy as np
 
4
 
5
  import calculator
6
  import data_retriever
@@ -116,11 +117,19 @@ def vwap(symbol_price_data):
116
  return vwap_values
117
 
118
 
 
 
 
 
 
 
 
 
119
  def bollinger_bands(dates, symbol_price_data, n_days_deviation=20, deviation_multiplier=2):
120
  bollinger_dates, bollinger_high, bollinger_low = [], [], []
121
  closes = symbol_price_data['Close']
122
 
123
- for index in range(0, len(closes) - n_days_deviation):
124
  bollinger_dates.append(dates[index + n_days_deviation])
125
 
126
  closes_subset = closes[index:index + n_days_deviation]
@@ -133,3 +142,28 @@ def bollinger_bands(dates, symbol_price_data, n_days_deviation=20, deviation_mul
133
 
134
  def support_lines():
135
  a = 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from collections import defaultdict
2
 
3
  import numpy as np
4
+ import scipy as sp
5
 
6
  import calculator
7
  import data_retriever
 
117
  return vwap_values
118
 
119
 
120
+ def sma(dates, data_list, n_days=20):
121
+ res_dates, res_values = [], []
122
+ res_dates = dates[n_days-1:]
123
+ for index in range(len(data_list) - n_days + 1):
124
+ res_values.append(np.mean(data_list[index:index + n_days]))
125
+ return res_dates, res_values
126
+
127
+
128
  def bollinger_bands(dates, symbol_price_data, n_days_deviation=20, deviation_multiplier=2):
129
  bollinger_dates, bollinger_high, bollinger_low = [], [], []
130
  closes = symbol_price_data['Close']
131
 
132
+ for index in range(len(closes) - n_days_deviation):
133
  bollinger_dates.append(dates[index + n_days_deviation])
134
 
135
  closes_subset = closes[index:index + n_days_deviation]
 
142
 
143
  def support_lines():
144
  a = 1
145
+
146
+
147
+ # the volatility is the average deviation from the current trend.
148
+ # this is measured by doing linear regression over each period, then calculating the deviation of values from that line.
149
+ def trend_deviation(prices, period=32):
150
+ np_dates = np.array([ts.timestamp() for ts in prices.index])
151
+ np_values = np.array(prices)
152
+
153
+ value_count = len(prices)
154
+
155
+ avg_deviations = []
156
+ for index in range(value_count-period):
157
+ np_dates_subset = np_dates[index:index+period+1]
158
+ np_values_subset = np_values[index:index+period+1]
159
+ m, c = calculator.linear_regression_line(np_dates_subset, np_values_subset)
160
+ predicted_values = m * np_dates_subset + c
161
+
162
+ deviation_sum = 0
163
+ for value, predicted_value in zip(np_values_subset, predicted_values):
164
+ deviation = abs(value - predicted_value)
165
+ deviation_sum += deviation
166
+ avg_deviation = deviation_sum/period
167
+ avg_deviations.append(avg_deviation)
168
+
169
+ return avg_deviations
ui.py CHANGED
@@ -102,7 +102,7 @@ def create_fill_area(fig, dates, y_low, y_high, title, color='rgba(0,100,80,0.2)
102
  fig.add_trace(fill_area)
103
 
104
 
105
- def create_spectrogram(dates, data_list, sampling_frequency=1, num_points_fft=128, overlap_percent=50.0, title="title"):
106
  data_list = calculator.normalize(data_list, 1, -1)
107
 
108
  # Spectrogram
@@ -111,10 +111,15 @@ def create_spectrogram(dates, data_list, sampling_frequency=1, num_points_fft=12
111
 
112
  dates_subset = [dates[int(bin)] for bin in bins]
113
 
 
 
 
 
 
114
  trace = [go.Heatmap(
115
  x=dates_subset,
116
  y=freqs,
117
- z=10 * np.log10(pxx),
118
  colorscale='Jet',
119
  )]
120
  layout = go.Layout(
@@ -123,10 +128,49 @@ def create_spectrogram(dates, data_list, sampling_frequency=1, num_points_fft=12
123
  xaxis=dict(title='Time'), # y-axis label
124
  )
125
  fig = go.Figure(data=trace, layout=layout)
 
126
  st.plotly_chart(fig, use_container_width=True)
127
 
128
  return fig
129
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  def add_mouse_indicator(fig, selected_points, min, max):
131
  if any(selected_points):
132
  fig.add_shape(
 
102
  fig.add_trace(fill_area)
103
 
104
 
105
+ def create_spectrogram(dates, data_list, sampling_frequency=1, num_points_fft=128, overlap_percent=50.0, title="title", log_scale=True):
106
  data_list = calculator.normalize(data_list, 1, -1)
107
 
108
  # Spectrogram
 
111
 
112
  dates_subset = [dates[int(bin)] for bin in bins]
113
 
114
+ if log_scale:
115
+ z = 10 * np.log10(pxx)
116
+ else:
117
+ z = pxx
118
+
119
  trace = [go.Heatmap(
120
  x=dates_subset,
121
  y=freqs,
122
+ z=z,
123
  colorscale='Jet',
124
  )]
125
  layout = go.Layout(
 
128
  xaxis=dict(title='Time'), # y-axis label
129
  )
130
  fig = go.Figure(data=trace, layout=layout)
131
+ fig.update_layout(title=title)
132
  st.plotly_chart(fig, use_container_width=True)
133
 
134
  return fig
135
 
136
+
137
+ def create_heatmap(dates, data_list, bin_count=10, time_steps=20, title='title'):
138
+ time_width = int(len(dates)/time_steps)
139
+ dates_subset = [dates[index*time_width] for index in range(time_steps)]
140
+ min_val = np.min(data_list)
141
+ max_val = np.max(data_list)
142
+ delta = (max_val-min_val)
143
+ min_val -= 0.2*delta
144
+ max_val += 0.2*delta
145
+ delta = (max_val-min_val)
146
+
147
+ bin_width = delta/(bin_count + 1)
148
+ bins = np.arange(min_val, max_val, bin_width)
149
+
150
+ values = np.empty(shape=(time_steps, bin_count))
151
+ for time_index in range(time_steps):
152
+ data_subset = data_list[time_index*time_width:time_index*time_width+time_width]
153
+ counts, res_bins = np.histogram(data_subset, bins=bins)
154
+ values[time_index:] = counts
155
+
156
+ trace = [go.Heatmap(
157
+ x=dates_subset,
158
+ y=bins,
159
+ z=values.transpose(),
160
+ colorscale='Jet',
161
+ )]
162
+ layout = go.Layout(
163
+ title=title,
164
+ yaxis=dict(title='Values'), # x-axis label
165
+ xaxis=dict(title='Time'), # y-axis label
166
+ )
167
+ fig = go.Figure(data=trace, layout=layout)
168
+ fig.update_layout(title=title)
169
+ st.plotly_chart(fig, use_container_width=True)
170
+
171
+ return fig
172
+
173
+
174
  def add_mouse_indicator(fig, selected_points, min, max):
175
  if any(selected_points):
176
  fig.add_shape(