Invicto69 commited on
Commit
a047e89
·
verified ·
1 Parent(s): 79e3a41

Synced repo using 'sync_with_huggingface' Github Action

Browse files
app.py CHANGED
@@ -1,9 +1,13 @@
1
  import streamlit as st
 
2
 
3
  def app():
4
  st.set_page_config(page_title="Algorithmic Trading Dashboard", layout="wide", initial_sidebar_state="auto",
5
  menu_items=None, page_icon=":chart_with_upwards_trend:")
6
 
 
 
 
7
  single_test = st.Page("page/single_backtest.py", title="Run Strategy")
8
  complete_test = st.Page("page/complete_backtest.py", title="Evaluate Strategy")
9
 
@@ -12,4 +16,5 @@ def app():
12
  pg.run()
13
 
14
  if __name__ == "__main__":
 
15
  app()
 
1
  import streamlit as st
2
+ from src.colorer import get_logger
3
 
4
  def app():
5
  st.set_page_config(page_title="Algorithmic Trading Dashboard", layout="wide", initial_sidebar_state="auto",
6
  menu_items=None, page_icon=":chart_with_upwards_trend:")
7
 
8
+ if "logger" not in st.session_state:
9
+ st.session_state.logger = get_logger()
10
+
11
  single_test = st.Page("page/single_backtest.py", title="Run Strategy")
12
  complete_test = st.Page("page/complete_backtest.py", title="Evaluate Strategy")
13
 
 
16
  pg.run()
17
 
18
  if __name__ == "__main__":
19
+ # run_logging()
20
  app()
indicators.py CHANGED
@@ -610,7 +610,7 @@ def EMA(array, n):
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')
 
610
  return pd.Series(array).ewm(span=n, adjust=False).mean()
611
 
612
  if __name__ == "__main__":
613
+ from src.utils import fetch
614
 
615
  data = fetch('ICICIBANK.NS', period='1mo', interval='15m')
616
  data = fetch('RELIANCE.NS', period='1mo', interval='15m')
page/complete_backtest.py CHANGED
@@ -1,9 +1,9 @@
1
  import streamlit as st
2
  import pandas as pd
3
  import time
 
4
  from streamlit.components import v1 as components
5
- from utils import complete_test
6
- from os import cpu_count
7
 
8
  def complete_backtest():
9
  @st.cache_data
 
1
  import streamlit as st
2
  import pandas as pd
3
  import time
4
+
5
  from streamlit.components import v1 as components
6
+ from src.utils import complete_test
 
7
 
8
  def complete_backtest():
9
  @st.cache_data
page/single_backtest.py CHANGED
@@ -3,7 +3,7 @@ import streamlit as st
3
  from streamlit.components import v1 as components
4
 
5
  from indicators import SMC
6
- from utils import fetch, run_strategy
7
 
8
  def algorithmic_trading_dashboard():
9
  @st.cache_data
 
3
  from streamlit.components import v1 as components
4
 
5
  from indicators import SMC
6
+ from src.utils import fetch, run_strategy
7
 
8
  def algorithmic_trading_dashboard():
9
  @st.cache_data
src/utils.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import yfinance as yf
2
+ from backtesting import Backtest
3
+ import pandas as pd
4
+ import os
5
+
6
+ from multiprocessing import Pool
7
+ from itertools import repeat
8
+ from functools import partial
9
+ from strategies import SMC_test, SMC_ema, SMCStructure
10
+ from src.colorer import get_logger, start_end_log
11
+
12
+ logger = get_logger()
13
+
14
+ @start_end_log
15
+ def fetch(symbol, period, interval):
16
+ logger.info(f"Fetching {symbol} for interval {interval} and period {period}")
17
+ df = yf.download(symbol, period=period, interval=interval, progress=False)
18
+ df.columns =df.columns.get_level_values(0)
19
+ return df
20
+
21
+ @start_end_log
22
+ def smc_backtest(data, filename, **kwargs):
23
+ bt = Backtest(data, SMC_test, cash=kwargs['cash'], commission=kwargs['commission'])
24
+ results = bt.run(swing_window=kwargs['swing_hl'])
25
+ bt.plot(filename=filename, open_browser=False)
26
+ return results
27
+
28
+ @start_end_log
29
+ def smc_ema_backtest(data, filename, **kwargs):
30
+ bt = Backtest(data, SMC_ema, cash=kwargs['cash'], commission=kwargs['commission'])
31
+ results = bt.run(swing_window=kwargs['swing_hl'], ema1=kwargs['ema1'], ema2=kwargs['ema2'], close_on_crossover=kwargs['cross_close'])
32
+ bt.plot(filename=filename, open_browser=False)
33
+ return results
34
+
35
+ @start_end_log
36
+ def smc_structure_backtest(data, filename, **kwargs):
37
+ bt = Backtest(data, SMCStructure, cash=kwargs['cash'], commission=kwargs['commission'])
38
+ results = bt.run(swing_window=kwargs['swing_hl'])
39
+ bt.plot(filename=filename, open_browser=False)
40
+ return results
41
+
42
+ @start_end_log
43
+ def run_strategy(ticker_symbol, strategy, period, interval, **kwargs):
44
+ logger.info(f'Running {strategy} for {ticker_symbol}')
45
+ # Fetching ohlc of random ticker_symbol.
46
+ retries = 3
47
+ for i in range(retries):
48
+ try:
49
+ data = fetch(ticker_symbol, period, interval)
50
+ except:
51
+ raise Exception(f"{ticker_symbol} data fetch failed")
52
+
53
+ if len(data) == 0:
54
+ if i < retries - 1:
55
+ print(f"Attempt{i + 1}: {ticker_symbol} ohlc is empty")
56
+ else:
57
+ raise Exception(f"{ticker_symbol} ohlc is empty")
58
+ else:
59
+ break
60
+
61
+ filename = f'{ticker_symbol}.html'
62
+
63
+ if strategy == "Order Block":
64
+ backtest_results = smc_backtest(data, filename, **kwargs)
65
+ elif strategy == "Order Block with EMA":
66
+ backtest_results = smc_ema_backtest(data, filename, **kwargs)
67
+ elif strategy == "Structure trading":
68
+ backtest_results = smc_structure_backtest(data, filename, **kwargs)
69
+ else:
70
+ raise Exception('Strategy not found')
71
+
72
+ with open(filename, 'r', encoding='utf-8') as f:
73
+ plot = f.read()
74
+
75
+ os.remove(filename)
76
+
77
+ # Converting pd.Series to pd.Dataframe
78
+ backtest_results = backtest_results.to_frame().transpose()
79
+
80
+ backtest_results['stock'] = ticker_symbol
81
+ backtest_results['plot'] = plot
82
+
83
+ # Reordering columns.
84
+ cols = ['stock', 'Start', 'End', 'Return [%]', 'Equity Final [$]', 'Buy & Hold Return [%]', '# Trades',
85
+ 'Win Rate [%]', 'Best Trade [%]', 'Worst Trade [%]', 'Avg. Trade [%]', 'plot']
86
+ backtest_results = backtest_results[cols]
87
+
88
+ backtest_results = backtest_results.rename(columns = {'Equity Final [$]': 'Equity Final [₹]'})
89
+
90
+ return backtest_results
91
+
92
+ @start_end_log
93
+ def complete_test(strategy: str, period: str, interval: str, multiprocess=True, **kwargs):
94
+ nifty50 = pd.read_csv("data/ind_nifty50list.csv")
95
+ ticker_list = pd.read_csv("data/Ticker_List_NSE_India.csv")
96
+
97
+ # Merging nifty50 and ticker_list dataframes to get 'YahooEquiv' column.
98
+ nifty50 = nifty50.merge(ticker_list, "inner", left_on=['Symbol'], right_on=['SYMBOL'])
99
+
100
+ if multiprocess:
101
+ with Pool() as p:
102
+ result = p.starmap(partial(run_strategy, **kwargs), zip(nifty50['YahooEquiv'].values, repeat(strategy), repeat(period), repeat(interval)))
103
+ else:
104
+ result = [run_strategy(nifty50['YahooEquiv'].values[i], strategy, period, interval, **kwargs) for i in range(len(nifty50))]
105
+
106
+ df = pd.concat(result)
107
+
108
+ df['plot'] = df['plot'].astype(str)
109
+ df = df.sort_values(by=['Return [%]'], ascending=False)
110
+
111
+ return df.reset_index().drop(columns=['index'])
112
+
113
+
114
+ if __name__ == "__main__":
115
+ # random_testing("")
116
+ # data = fetch('RELIANCE.NS', period='1y', interval='15m')
117
+ # df = yf.download('RELIANCE.NS', period='1yr', interval='15m')
118
+
119
+ rt = complete_test("Order Block", '1mo', '15m', swing_hl=20)
120
+ rt.to_excel('test/all_testing_2.xlsx', index=False)
121
+ print(rt)
strategies.py CHANGED
@@ -4,6 +4,10 @@ from indicators import SMC, EMA
4
  import pandas as pd
5
  import numpy as np
6
 
 
 
 
 
7
  class SMC_test(Strategy):
8
  swing_window = 10
9
  def init(self):
@@ -117,10 +121,9 @@ class SMCStructure(TrailingStrategy):
117
  try:
118
  self.buy(sl=stoploss, tp=target)
119
  except:
120
- print('Buying failed')
121
  if self.smc_s[-1] == 1:
122
  nearest = self.nearest_swing(self.data.df, self.swing_window)
123
- print(self.data.df.iloc[-1])
124
  if nearest > price:
125
  target = price - ((nearest - price) * .414)
126
  stoploss = price + (price - target)
@@ -128,7 +131,7 @@ class SMCStructure(TrailingStrategy):
128
  try:
129
  self.sell(sl=stoploss, tp=target, limit=float(price))
130
  except:
131
- print("Selling failed")
132
 
133
  # Additionally, set aggressive stop-loss on trades that have been open
134
  # for more than two days
@@ -154,7 +157,7 @@ class SMCStructure(TrailingStrategy):
154
  strategies = {'Order Block': SMC_test, 'Order Block with EMA': SMC_ema , 'Structure trading': SMCStructure}
155
 
156
  if __name__ == "__main__":
157
- from utils import fetch
158
  # data = fetch('ICICIBANK.NS', period='1mo', interval='15m')
159
  data = fetch('RELIANCE.NS', period='1mo', interval='15m')
160
  # data = fetch('AXISBANK.NS', period='1mo', interval='15m')
 
4
  import pandas as pd
5
  import numpy as np
6
 
7
+ from src.colorer import get_logger
8
+
9
+ logger = get_logger()
10
+
11
  class SMC_test(Strategy):
12
  swing_window = 10
13
  def init(self):
 
121
  try:
122
  self.buy(sl=stoploss, tp=target)
123
  except:
124
+ logger.warning(f'Buying failed at {price} with {stoploss=} and {target=}')
125
  if self.smc_s[-1] == 1:
126
  nearest = self.nearest_swing(self.data.df, self.swing_window)
 
127
  if nearest > price:
128
  target = price - ((nearest - price) * .414)
129
  stoploss = price + (price - target)
 
131
  try:
132
  self.sell(sl=stoploss, tp=target, limit=float(price))
133
  except:
134
+ logger.warning(f'Selling failed at {price} with {stoploss=} and {target=}')
135
 
136
  # Additionally, set aggressive stop-loss on trades that have been open
137
  # for more than two days
 
157
  strategies = {'Order Block': SMC_test, 'Order Block with EMA': SMC_ema , 'Structure trading': SMCStructure}
158
 
159
  if __name__ == "__main__":
160
+ from src.utils import fetch
161
  # data = fetch('ICICIBANK.NS', period='1mo', interval='15m')
162
  data = fetch('RELIANCE.NS', period='1mo', interval='15m')
163
  # data = fetch('AXISBANK.NS', period='1mo', interval='15m')