Invicto69 commited on
Commit
9a42782
·
verified ·
1 Parent(s): 3b63311

Synced repo using 'sync_with_huggingface' Github Action

Browse files
app.py CHANGED
@@ -1,148 +1,100 @@
1
- from dash import Dash, Input, Output, State, callback, dcc, html
2
- import dash_bootstrap_components as dbc
3
- import pandas as pd
4
- from indicators import SMC
5
- from data_fetcher import fetch
6
- from strategies import smc_plot_backtest, smc_ema_plot_backtest
7
-
8
- # Load symbols data
9
- symbols = pd.read_csv('data/Ticker_List_NSE_India.csv')
10
-
11
- # Initialize the app with a Bootstrap theme
12
- app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
13
-
14
- # Function to create the layout
15
- app.layout = dbc.Container([
16
- dbc.Row([
17
- html.H1("Algorithmic Trading Dashboard", className="text-center mb-4")
18
- ]),
19
-
20
- dbc.Row([
21
- html.Label("Select Company Name", className="form-label"),
22
- dcc.Dropdown(
23
- id="name",
24
- options=[{"label": name, "value": name} for name in symbols['NAME OF COMPANY'].unique()],
25
- value='',
26
- placeholder="Select a company",
27
- className="mb-3"
28
- ),
29
-
30
- html.Label("Select Strategy", className="form-label"),
31
- dcc.Dropdown(
32
- id="strategy",
33
- options=['SMC', 'SMC with EMA'],
34
- value='',
35
- placeholder="Select Strategy",
36
- className="mb-3"
37
- ),
38
-
39
- html.Label("Swing High/Low Window Size", className="form-label"),
40
- dcc.Input(
41
- id="window",
42
- type="number",
43
- value=10,
44
- placeholder="Enter window size",
45
- className="form-control mb-3"
46
- ),
47
-
48
- ]),
49
-
50
- html.Div([
51
- dbc.Row([
52
- dbc.Col([
53
- html.Label("Fast EMA Length: ", className="form-label"),
54
- dcc.Input(
55
- id="ema1",
56
- type="number",
57
- value=9,
58
- placeholder="Enter EMA Length",
59
- # className="form-control mb-3"
60
- className = "text-nowrap"
61
- ),
62
- ], md=8),
63
-
64
- dbc.Col([
65
- html.Label("Slow EMA Length: ", className="form-label"),
66
- dcc.Input(
67
- id="ema2",
68
- type="number",
69
- value=21,
70
- placeholder="Enter EMA size",
71
- # className="form-control mb-3"
72
- className="text-nowrap"
73
- ),
74
-
75
- dbc.Col([dcc.Checklist(['Close on EMA crossover'], id='closecross', className="text-nowrap")]),
76
-
77
- ]),
78
- ]),
79
- ], style={'display': 'block'}, id='smc_ema'
80
- ),
81
-
82
- dbc.Button("Run", id="submit-button", color="primary", className="w-100 mb-4"),
83
-
84
- dbc.Row([
85
- html.H5("Order Block Chart", className="text-center mb-3"),
86
- html.Iframe(
87
- src="assets/SMC.html",
88
- style={"height": "450px", "width": "95%", "border": "none"},
89
- className="mb-4"
90
- ),
91
-
92
- html.H5("Backtest Results", className="text-center mb-3"),
93
- html.Iframe(
94
- src="assets/backtest_results.html",
95
- style={"height": "1067px", "width": "95%", "border": "none"}
96
- ),
97
- ])
98
- ], fluid=True)
99
-
100
-
101
- @callback(
102
- Output("smc_ema", 'style'),
103
- Input("strategy", 'value')
104
- )
105
- def update_layout(strategy):
106
- if strategy=='SMC with EMA':
107
- return {'display':'block'}
108
- else:
109
- return {'display':'none'}
110
-
111
-
112
- # Callback for updating the visualizations
113
- @callback(
114
- Input("submit-button", "n_clicks"),
115
- State("name", "value"),
116
- State("window", "value"),
117
- State("strategy", "value"),
118
- State("ema1", "value"),
119
- State("ema2", "value"),
120
- State("closecross", "value")
121
- )
122
- def update_visuals(n_clicks, name, window, strategy, ema1, ema2, closecross):
123
- if n_clicks <= 0 or not name:
124
- return
125
-
126
- # Clear existing files
127
- open('assets/backtest_results.html', 'w').close()
128
- open('assets/SMC.html', 'w').close()
129
-
130
- ticker = symbols[symbols['NAME OF COMPANY'] == name]['YahooEquiv'].values[0]
131
- data = fetch(ticker, '1mo', '15m')
132
-
133
- fig = SMC(data=data, swing_hl_window_sz=window).plot(show=False).update_layout(title=dict(text=ticker))
134
-
135
- print(strategy)
136
- if strategy=='SMC':
137
- smc_plot_backtest(data, 'assets/backtest_results.html', swing_hl=window)
138
- elif strategy=='SMC with EMA':
139
- smc_ema_plot_backtest(data, 'assets/backtest_results.html', ema1, ema2, closecross)
140
-
141
- fig.write_html('assets/SMC.html')
142
-
143
- if __name__ == "__main__":
144
- # Clear initial files
145
- open('assets/backtest_results.html', 'w').close()
146
- open('assets/SMC.html', 'w').close()
147
-
148
- app.run(debug=True)
 
1
+ import gradio as gr
2
+ from indicators import SMC
3
+ from utils import smc_plot_backtest, smc_ema_plot_backtest, smc_structure_plot_backtest, fetch
4
+ import pandas as pd
5
+
6
+ symbols = pd.read_csv('data/Ticker_List_NSE_India.csv')
7
+ limits = pd.read_csv('data/yahoo_limits.csv')
8
+
9
+ def run(stock, interval, period, strategy, swing_hl, ema1=9, ema2=21, cross_close=False):
10
+ # Downloading ticker data.
11
+ ticker = symbols[symbols['NAME OF COMPANY'] == stock]['YahooEquiv'].values[0]
12
+ data = fetch(ticker, period, interval)
13
+
14
+ # Plotting signal plot based on strategy.
15
+ if strategy == "Order Block" or strategy == "Order Block with EMA":
16
+ signal_plot = (SMC(data=data, swing_hl_window_sz=swing_hl).
17
+ plot(order_blocks=True, swing_hl=True, show=False).
18
+ update_layout(title=dict(text=ticker)))
19
+ else:
20
+ signal_plot = (SMC(data=data, swing_hl_window_sz=swing_hl).
21
+ plot(swing_hl_v2=True, structure=True, show=False).
22
+ update_layout(title=dict(text=ticker)))
23
+
24
+ backtest_plot = gr.Plot()
25
+
26
+
27
+ # Plotting backtest plot based on strategy.
28
+ if strategy == "Order Block":
29
+ backtest_plot = smc_plot_backtest(data, 'test.html', swing_hl)
30
+ if strategy == "Order Block with EMA":
31
+ backtest_plot = smc_ema_plot_backtest(data, 'test.html', ema1, ema2, cross_close)
32
+ if strategy == "Structure trading":
33
+ backtest_plot = smc_structure_plot_backtest(data, 'test.html', swing_hl)
34
+
35
+ return signal_plot, backtest_plot
36
+
37
+
38
+ with gr.Blocks(fill_width=True) as app:
39
+ gr.Markdown(
40
+ '# Algorithmic Trading Dashboard'
41
+ )
42
+ stock = gr.Dropdown(symbols['NAME OF COMPANY'].unique().tolist(), label='Select Company', value=None)
43
+
44
+ with gr.Row():
45
+ interval = gr.Dropdown(limits['interval'].tolist(), label='Select Interval', value=None)
46
+
47
+ period_list = ['1d', '5d', '1mo', '3mo', '6mo', '1y', '2y', '5y', '10y', 'ytd', 'max']
48
+ period = gr.Dropdown(label = 'Select Period', choices=[])
49
+
50
+ # Updating period based on interval
51
+ def update_period(interval):
52
+ limit = limits[limits['interval'] == interval]['limit'].values[0]
53
+ idx = period_list.index(limit)
54
+ return gr.Dropdown(period_list[:idx+1]+['max'], interactive=True, label='Select Period')
55
+
56
+ interval.change(update_period, [interval], [period])
57
+
58
+ with gr.Row():
59
+ strategy = gr.Dropdown(['Order Block', 'Order Block with EMA', 'Structure trading'], label='Strategy', value=None)
60
+ swing_hl = gr.Number(label="Swing High/Low Window Size", value=10, interactive=True)
61
+
62
+ @gr.render(inputs=[strategy])
63
+ def show_extra(strat):
64
+ if strat == "Order Block with EMA":
65
+ with gr.Row():
66
+ ema1 = gr.Number(label='Fast EMA length', value=9)
67
+ ema2 = gr.Number(label='Slow EMA length', value=21)
68
+ cross_close = gr.Checkbox(label='Close trade on EMA crossover')
69
+ input = [stock, interval, period, strategy, swing_hl, ema1, ema2, cross_close]
70
+
71
+ elif strat == "Order Block" or strat == "Structure trading":
72
+ input = [stock, interval, period, strategy, swing_hl]
73
+ else:
74
+ input = []
75
+
76
+ btn.click(
77
+ run,
78
+ inputs=input,
79
+ outputs=[signal_plot, backtest_plot]
80
+ )
81
+
82
+ examples = gr.Examples(
83
+ examples=[
84
+ ["Reliance Industries Limited", "15m", "max", "Order Block", 10],
85
+ ["Reliance Industries Limited", "15m", "max", "Order Block with EMA", 10],
86
+ ["Reliance Industries Limited", "15m", "max", "Structure trading", 20],
87
+ ],
88
+ example_labels=['Order Block', 'Order Block with EMA', 'Structure trading'],
89
+ inputs=[stock, interval, period, strategy, swing_hl]
90
+ )
91
+
92
+ btn = gr.Button("Run")
93
+
94
+ with gr.Row():
95
+ signal_plot = gr.Plot(label='Signal plot')
96
+
97
+ with gr.Row():
98
+ backtest_plot = gr.Plot(label='Backtesting plot')
99
+
100
+ app.launch(debug=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
data/Ticker_List_NSE_India.csv CHANGED
The diff for this file is too large to render. See raw diff
 
data/ind_nifty50list.csv ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Company Name,Industry,Symbol,Series,ISIN Code
2
+ Adani Enterprises Ltd.,Metals & Mining,ADANIENT,EQ,INE423A01024
3
+ Adani Ports and Special Economic Zone Ltd.,Services,ADANIPORTS,EQ,INE742F01042
4
+ Apollo Hospitals Enterprise Ltd.,Healthcare,APOLLOHOSP,EQ,INE437A01024
5
+ Asian Paints Ltd.,Consumer Durables,ASIANPAINT,EQ,INE021A01026
6
+ Axis Bank Ltd.,Financial Services,AXISBANK,EQ,INE238A01034
7
+ Bajaj Auto Ltd.,Automobile and Auto Components,BAJAJ-AUTO,EQ,INE917I01010
8
+ Bajaj Finance Ltd.,Financial Services,BAJFINANCE,EQ,INE296A01024
9
+ Bajaj Finserv Ltd.,Financial Services,BAJAJFINSV,EQ,INE918I01026
10
+ Bharat Electronics Ltd.,Capital Goods,BEL,EQ,INE263A01024
11
+ Bharat Petroleum Corporation Ltd.,Oil Gas & Consumable Fuels,BPCL,EQ,INE029A01011
12
+ Bharti Airtel Ltd.,Telecommunication,BHARTIARTL,EQ,INE397D01024
13
+ Britannia Industries Ltd.,Fast Moving Consumer Goods,BRITANNIA,EQ,INE216A01030
14
+ Cipla Ltd.,Healthcare,CIPLA,EQ,INE059A01026
15
+ Coal India Ltd.,Oil Gas & Consumable Fuels,COALINDIA,EQ,INE522F01014
16
+ Dr. Reddy's Laboratories Ltd.,Healthcare,DRREDDY,EQ,INE089A01031
17
+ Dummy ITC Ltd.,Consumer Services,DUMMYITC,EQ,DUM154A01025
18
+ Eicher Motors Ltd.,Automobile and Auto Components,EICHERMOT,EQ,INE066A01021
19
+ Grasim Industries Ltd.,Construction Materials,GRASIM,EQ,INE047A01021
20
+ HCL Technologies Ltd.,Information Technology,HCLTECH,EQ,INE860A01027
21
+ HDFC Bank Ltd.,Financial Services,HDFCBANK,EQ,INE040A01034
22
+ HDFC Life Insurance Company Ltd.,Financial Services,HDFCLIFE,EQ,INE795G01014
23
+ Hero MotoCorp Ltd.,Automobile and Auto Components,HEROMOTOCO,EQ,INE158A01026
24
+ Hindalco Industries Ltd.,Metals & Mining,HINDALCO,EQ,INE038A01020
25
+ Hindustan Unilever Ltd.,Fast Moving Consumer Goods,HINDUNILVR,EQ,INE030A01027
26
+ ICICI Bank Ltd.,Financial Services,ICICIBANK,EQ,INE090A01021
27
+ ITC Ltd.,Fast Moving Consumer Goods,ITC,EQ,INE154A01025
28
+ IndusInd Bank Ltd.,Financial Services,INDUSINDBK,EQ,INE095A01012
29
+ Infosys Ltd.,Information Technology,INFY,EQ,INE009A01021
30
+ JSW Steel Ltd.,Metals & Mining,JSWSTEEL,EQ,INE019A01038
31
+ Kotak Mahindra Bank Ltd.,Financial Services,KOTAKBANK,EQ,INE237A01028
32
+ Larsen & Toubro Ltd.,Construction,LT,EQ,INE018A01030
33
+ Mahindra & Mahindra Ltd.,Automobile and Auto Components,M&M,EQ,INE101A01026
34
+ Maruti Suzuki India Ltd.,Automobile and Auto Components,MARUTI,EQ,INE585B01010
35
+ NTPC Ltd.,Power,NTPC,EQ,INE733E01010
36
+ Nestle India Ltd.,Fast Moving Consumer Goods,NESTLEIND,EQ,INE239A01024
37
+ Oil & Natural Gas Corporation Ltd.,Oil Gas & Consumable Fuels,ONGC,EQ,INE213A01029
38
+ Power Grid Corporation of India Ltd.,Power,POWERGRID,EQ,INE752E01010
39
+ Reliance Industries Ltd.,Oil Gas & Consumable Fuels,RELIANCE,EQ,INE002A01018
40
+ SBI Life Insurance Company Ltd.,Financial Services,SBILIFE,EQ,INE123W01016
41
+ Shriram Finance Ltd.,Financial Services,SHRIRAMFIN,EQ,INE721A01047
42
+ State Bank of India,Financial Services,SBIN,EQ,INE062A01020
43
+ Sun Pharmaceutical Industries Ltd.,Healthcare,SUNPHARMA,EQ,INE044A01036
44
+ Tata Consultancy Services Ltd.,Information Technology,TCS,EQ,INE467B01029
45
+ Tata Consumer Products Ltd.,Fast Moving Consumer Goods,TATACONSUM,EQ,INE192A01025
46
+ Tata Motors Ltd.,Automobile and Auto Components,TATAMOTORS,EQ,INE155A01022
47
+ Tata Steel Ltd.,Metals & Mining,TATASTEEL,EQ,INE081A01020
48
+ Tech Mahindra Ltd.,Information Technology,TECHM,EQ,INE669C01036
49
+ Titan Company Ltd.,Consumer Durables,TITAN,EQ,INE280A01028
50
+ Trent Ltd.,Consumer Services,TRENT,EQ,INE849A01020
51
+ UltraTech Cement Ltd.,Construction Materials,ULTRACEMCO,EQ,INE481G01011
52
+ Wipro Ltd.,Information Technology,WIPRO,EQ,INE075A01022
data/yahoo_limits.csv ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ interval,limit
2
+ 1m,5d
3
+ 2m,1mo
4
+ 5m,1mo
5
+ 15m,1mo
6
+ 30m,1mo
7
+ 1h,2y
8
+ 1d,ytd
9
+ 5d,ytd
10
+ 1wk,ytd
11
+ 1mo,ytd
12
+ 3mo,ytd
indicators.py CHANGED
@@ -504,8 +504,8 @@ class SMC:
504
  fig.update_xaxes(rangebreaks=[dict(dvalue=5 * 60 * 1000, values=dt_breaks)])
505
 
506
  if order_blocks:
507
- print(self.order_blocks.head())
508
- print(self.order_blocks.index.to_list())
509
 
510
  ob_df = self.data.iloc[self.order_blocks.index.to_list()]
511
  # print(ob_df)
@@ -610,7 +610,8 @@ def EMA(array, n):
610
  return pd.Series(array).ewm(span=n, adjust=False).mean()
611
 
612
  if __name__ == "__main__":
613
- from data_fetcher import fetch
 
614
  data = fetch('ICICIBANK.NS', period='1mo', interval='15m')
615
  data = fetch('RELIANCE.NS', period='1mo', interval='15m')
616
  data['Date'] = data.index.to_series()
 
504
  fig.update_xaxes(rangebreaks=[dict(dvalue=5 * 60 * 1000, values=dt_breaks)])
505
 
506
  if order_blocks:
507
+ # print(self.order_blocks.head())
508
+ # print(self.order_blocks.index.to_list())
509
 
510
  ob_df = self.data.iloc[self.order_blocks.index.to_list()]
511
  # print(ob_df)
 
610
  return pd.Series(array).ewm(span=n, adjust=False).mean()
611
 
612
  if __name__ == "__main__":
613
+ from utils import fetch
614
+
615
  data = fetch('ICICIBANK.NS', period='1mo', interval='15m')
616
  data = fetch('RELIANCE.NS', period='1mo', interval='15m')
617
  data['Date'] = data.index.to_series()
requirements.txt CHANGED
@@ -1,8 +1,7 @@
1
- backtesting==0.3.3
2
- numpy==2.2.0
3
- pandas==2.2.3
4
- bokeh==3.1.0
5
- yfinance==0.2.50
6
- plotly==5.24.1
7
- dash==2.18.2
8
- dash-bootstrap-components==1.6.0
 
1
+ backtesting==0.3.3
2
+ numpy==2.2.0
3
+ pandas==2.2.3
4
+ bokeh==3.1.0
5
+ yfinance==0.2.50
6
+ plotly==5.24.1
7
+ gradio==5.9.1
 
strategies.py CHANGED
@@ -1,7 +1,6 @@
1
  from backtesting import Backtest, Strategy
2
  from backtesting.lib import SignalStrategy, TrailingStrategy
3
  from indicators import SMC, EMA
4
- from data_fetcher import fetch
5
  import pandas as pd
6
  import numpy as np
7
 
@@ -152,28 +151,14 @@ class SMCStructure(TrailingStrategy):
152
  return swings['Level'].iloc[-2]
153
 
154
 
155
- def smc_plot_backtest(data, filename, swing_hl, **kwargs):
156
- bt = Backtest(data, SMC_test, **kwargs)
157
- bt.run(swing_hl=swing_hl)
158
- return bt.plot(filename=filename, open_browser=False)
159
-
160
- def smc_ema_plot_backtest(data, filename, ema1, ema2, closecross, **kwargs):
161
- bt = Backtest(data, SMC_ema, **kwargs)
162
- bt.run(ema1=ema1, ema2=ema2, close_on_crossover=closecross)
163
- return bt.plot(filename=filename, open_browser=False)
164
-
165
- def smc_structure_backtest(data, filename, swing_hl, **kwargs):
166
- bt = Backtest(data, SMCStructure, **kwargs)
167
- bt.run(swing_window=swing_hl)
168
- return bt.plot(filename=filename, open_browser=False)
169
-
170
  if __name__ == "__main__":
 
171
  # data = fetch('ICICIBANK.NS', period='1mo', interval='15m')
172
  data = fetch('RELIANCE.NS', period='1mo', interval='15m')
173
  # data = fetch('AXISBANK.NS', period='1mo', interval='15m')
174
  # bt = Backtest(data, SMC_ema, commission=.002)
175
  # bt.run(ema1 = 9, ema2 = 21, close_on_crossover=True)
176
  bt = Backtest(data, SMCStructure, commission = .002, trade_on_close=True)
177
- bt.run()
178
 
179
- bt.plot()
 
1
  from backtesting import Backtest, Strategy
2
  from backtesting.lib import SignalStrategy, TrailingStrategy
3
  from indicators import SMC, EMA
 
4
  import pandas as pd
5
  import numpy as np
6
 
 
151
  return swings['Level'].iloc[-2]
152
 
153
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  if __name__ == "__main__":
155
+ from utils import fetch
156
  # data = fetch('ICICIBANK.NS', period='1mo', interval='15m')
157
  data = fetch('RELIANCE.NS', period='1mo', interval='15m')
158
  # data = fetch('AXISBANK.NS', period='1mo', interval='15m')
159
  # bt = Backtest(data, SMC_ema, commission=.002)
160
  # bt.run(ema1 = 9, ema2 = 21, close_on_crossover=True)
161
  bt = Backtest(data, SMCStructure, commission = .002, trade_on_close=True)
162
+ print(bt.run())
163
 
164
+ # bt.plot()
utils.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import yfinance as yf
2
+ from backtesting import Backtest
3
+
4
+ from strategies import SMC_test, SMC_ema, SMCStructure
5
+
6
+ def fetch(symbol, period, interval):
7
+ df = yf.download(symbol, period=period, interval=interval)
8
+ df.columns =df.columns.get_level_values(0)
9
+ return df
10
+
11
+ def smc_plot_backtest(data, filename, swing_hl, **kwargs):
12
+ bt = Backtest(data, SMC_test, **kwargs)
13
+ bt.run(swing_hl=swing_hl)
14
+ return bt.plot(filename=filename, open_browser=False)
15
+
16
+ def smc_ema_plot_backtest(data, filename, ema1, ema2, closecross, **kwargs):
17
+ bt = Backtest(data, SMC_ema, **kwargs)
18
+ bt.run(ema1=ema1, ema2=ema2, close_on_crossover=closecross)
19
+ return bt.plot(filename=filename, open_browser=False)
20
+
21
+ def smc_structure_plot_backtest(data, filename, swing_hl, **kwargs):
22
+ bt = Backtest(data, SMCStructure, **kwargs)
23
+ bt.run(swing_window=swing_hl)
24
+ return bt.plot(filename=filename, open_browser=False)
25
+
26
+ def smc_backtest(data, swing_hl, **kwargs):
27
+ return Backtest(data, SMC_test, **kwargs).run(swing_hl=swing_hl)
28
+
29
+ def smc_ema_backtest(data, ema1, ema2, closecross, **kwargs):
30
+ return Backtest(data, SMC_ema, **kwargs).run(ema1=ema1, ema2=ema2, close_on_crossover=closecross)
31
+
32
+ def smc_structure_backtest(data, swing_hl, **kwargs):
33
+ return Backtest(data, SMCStructure, **kwargs).run(swing_hl=swing_hl)
34
+
35
+ if __name__ == "__main__":
36
+ # data = fetch('RELIANCE.NS', period='1y', interval='15m')
37
+ df = yf.download('RELIANCE.NS', period='1yr', interval='15m')