eshan6704 commited on
Commit
8e6de5c
·
verified ·
1 Parent(s): 402949b

Update chart_builder.py

Browse files
Files changed (1) hide show
  1. chart_builder.py +64 -63
chart_builder.py CHANGED
@@ -1,82 +1,83 @@
1
  # chart_builder.py
 
2
  import pandas as pd
3
- import plotly.graph_objects as go
4
- from plotly.subplots import make_subplots
5
 
6
- def build_chart(df, indicators, symbol="Stock"):
7
  """
8
- Build Plotly chart with main OHLC + optional subplots for indicators.
9
- Inject JS to toggle each indicator dynamically.
 
 
10
  """
11
- fig = make_subplots(
12
- rows=2, cols=1,
13
- shared_xaxes=True,
14
- row_heights=[0.7, 0.3],
15
- vertical_spacing=0.05,
16
- subplot_titles=(f"{symbol} Price", "Indicators")
17
- )
18
 
19
- # --- Main chart: OHLC + MA ---
20
  fig.add_trace(go.Candlestick(
21
- x=df.index, open=df['Open'], high=df['High'],
22
- low=df['Low'], close=df['Close'], name='OHLC'
23
- ), row=1, col=1)
 
 
 
 
24
 
25
- # MA on main chart
26
- for ma in ['SMA20', 'SMA50']:
27
- if ma in indicators:
 
28
  fig.add_trace(go.Scatter(
29
- x=df.index, y=indicators[ma],
30
- mode='lines', name=ma
31
- ), row=1, col=1)
 
 
 
32
 
33
- # --- Subplot for MACD/RSI/SuperTrend ---
34
- indicator_row = 2
35
- for ind_name in ['MACD', 'RSI', 'SuperTrend']:
36
- if ind_name in indicators:
37
- data = indicators[ind_name]
38
- if isinstance(data, pd.DataFrame):
39
- for col in data.columns:
40
- fig.add_trace(go.Scatter(
41
- x=df.index, y=data[col],
42
- mode='lines', name=f"{ind_name}-{col}",
43
- visible=False # Start hidden, toggle later
44
- ), row=indicator_row, col=1)
45
- else:
46
- fig.add_trace(go.Scatter(
47
- x=df.index, y=data,
48
- mode='lines', name=ind_name,
49
- visible=False
50
- ), row=indicator_row, col=1)
 
 
 
51
 
52
  # --- Layout ---
53
  fig.update_layout(
 
 
 
 
 
 
54
  height=700,
55
- showlegend=True,
56
- title=f"{symbol} Chart with Indicators",
57
- xaxis_rangeslider_visible=False
58
  )
59
 
60
- # --- Inject JS for toggle buttons ---
61
- toggle_script = """
62
- <script>
63
- function toggleIndicator(indName) {
64
- var gd = document.querySelectorAll('.js-plotly-plot')[0];
65
- var update = {visible: []};
66
- gd.data.forEach(function(trace) {
67
- if(trace.name.includes(indName)) {
68
- trace.visible = !trace.visible;
69
- }
70
- });
71
- Plotly.redraw(gd);
72
- }
73
- </script>
74
- <div style="margin-top:10px;">
75
- <button onclick="toggleIndicator('MACD')">Toggle MACD</button>
76
- <button onclick="toggleIndicator('RSI')">Toggle RSI</button>
77
- <button onclick="toggleIndicator('SuperTrend')">Toggle SuperTrend</button>
78
  </div>
79
  """
80
 
81
- chart_html = fig.to_html(full_html=False, include_plotlyjs='cdn') + toggle_script
82
- return chart_html
 
1
  # chart_builder.py
2
+ import plotly.graph_objs as go
3
  import pandas as pd
 
 
4
 
5
+ def build_chart(df, indicators=None):
6
  """
7
+ Build OHLC chart with volume and optional indicators.
8
+
9
+ df : DataFrame with 'Open','High','Low','Close','Volume'
10
+ indicators : dict {name: Series or DataFrame} from indicater.py
11
  """
12
+ if indicators is None:
13
+ indicators = {}
14
+
15
+ fig = go.Figure()
 
 
 
16
 
17
+ # --- Main OHLC Candlestick chart ---
18
  fig.add_trace(go.Candlestick(
19
+ x=df.index,
20
+ open=df['Open'],
21
+ high=df['High'],
22
+ low=df['Low'],
23
+ close=df['Close'],
24
+ name='Price'
25
+ ))
26
 
27
+ # --- Overlay indicators on main chart (SMA, EMA) ---
28
+ overlay_indicators = ['SMA5','SMA20','SMA50','SMA200','EMA5','EMA20','EMA50','EMA200']
29
+ for ind in overlay_indicators:
30
+ if ind in indicators:
31
  fig.add_trace(go.Scatter(
32
+ x=df.index,
33
+ y=indicators[ind],
34
+ mode='lines',
35
+ name=ind,
36
+ visible='legendonly' # default off, toggle via legend
37
+ ))
38
 
39
+ # --- Volume subplot ---
40
+ fig.add_trace(go.Bar(
41
+ x=df.index,
42
+ y=df['Volume'],
43
+ name='Volume',
44
+ marker_color='lightblue',
45
+ yaxis='y2'
46
+ ))
47
+
48
+ # --- Subplot indicators (MACD, RSI, SuperTrend, etc.) ---
49
+ subplots = ['MACD','MACD_signal','MACD_hist','RSI','STOCH','ADX','CCI','OBV','SuperTrend']
50
+ for ind in subplots:
51
+ if ind in indicators:
52
+ fig.add_trace(go.Scatter(
53
+ x=df.index,
54
+ y=indicators[ind],
55
+ mode='lines',
56
+ name=ind,
57
+ visible='legendonly',
58
+ yaxis='y3'
59
+ ))
60
 
61
  # --- Layout ---
62
  fig.update_layout(
63
+ xaxis=dict(domain=[0,1]),
64
+ yaxis=dict(title='Price'),
65
+ yaxis2=dict(title='Volume', overlaying='y', side='right', showgrid=False, position=0.15),
66
+ yaxis3=dict(title='Indicators', anchor='free', overlaying='y', side='right', position=0.85),
67
+ legend=dict(orientation='h', y=-0.2),
68
+ margin=dict(l=50, r=50, t=50, b=100),
69
  height=700,
70
+ template='plotly_white'
 
 
71
  )
72
 
73
+ # --- Add HTML + JS for toggle (legend already allows visibility control) ---
74
+ chart_html = fig.to_html(full_html=False, include_plotlyjs='cdn')
75
+
76
+ # Add optional instructions
77
+ instructions = """
78
+ <div style="margin:10px 0;color:#555;">
79
+ <b>Instructions:</b> Click legend items to enable/disable indicators and overlays.
 
 
 
 
 
 
 
 
 
 
 
80
  </div>
81
  """
82
 
83
+ return instructions + chart_html