Skip to main content

Python Code for Trading Indicators

Hi Everyone,

I am back with some random things again. So today i will share codes of popular trading indicators which you can use while creating your own trader with machine learning in python.

so at first you need to import the below libraries

import numpy as np
import pandas as pd
from pandas_datareader import data as web
import matplotlib.pyplot as plt

then after the above step is done then you need to assign few of the local variables you can also take them as input as per your requirement

stock_name="SBI" #for nifty: ^NSEI
n = 20 #window size
start_date = "2021-04-01"
end_date = "2021-06-03"

then after it is done you need to create a function which can be used to extract the data from the yahoo finance and for that the code is provided below

def getData():
    stock_data = web.DataReader(stock_name, start=start_date, end=end_date, data_source='yahoo')
    stock_df=pd.DataFrame(stock_data)
    return stock_df

The above code will return data having below symbols

Symbols:-
        'High', 'Low', 'Open', 'Close', 'Volume', 'Adj Close', 'MA_20',
       'EMA_20', 'Momentum_20', 'ROC_20', 'ATR_20', 'BollingerB_20',
       'Bollinger%b_20', 'PP', 'R1', 'S1', 'R2', 'S2', 'R3', 'S3', 'SO%k',
       'SO%d_20', 'Trix_20', 'Mass Index', 'Vortex_20', 'RSI_20', 'Chaikin',
       'MFI_20', 'OBV_20', 'Force_20', 'EoM_20', 'CCI_20', 'Copp_20',
       'KelChM_20', 'KelChU_20', 'KelChD_20', 'Ultimate_Osc', 'Donchian_20',
       'STD_20'

df1 = getData()


After all the above steps are done you can move forward with indicators function. Use can use multiple indicators or single as per your needs.

1-> Exponential Moving Average:-

def exponential_moving_average(df, n):
  EMA = pd.Series(df['Close'].ewm(span=n, min_periods=n).mean(), name='EMA_' + str(n))
  df = df.join(EMA)
  return df


2-> Moving Average:-

def moving_average(df, n):
  MA = pd.Series(df['Close'].rolling(n, min_periods=n).mean(), name='MA_' + str(n))
  df = df.join(MA)
  return df


3-> Momentum:-

def momentum(df, n):
  M = pd.Series(df['Close'].diff(n), name='Momentum_' + str(n))
  df = df.join(M)
  return df


4-> Rate of change:-

def rate_of_change(df, n):
  M = df['Close'].diff(n - 1)
  N = df['Close'].shift(n - 1)
  ROC = pd.Series(M / N, name='ROC_' + str(n))
  df = df.join(ROC)
  return df


5-> Average True Range:-

def average_true_range(df, n):
  i = 0
  TR_l = [0]
  while i < df.shape[0]-2: #df.index[-1]:
      TR = max(df['High'][i +1], df['Close'][i]) - min(df['Low'][i + 1], df['Close'][i])
      TR_l.append(TR)
      i = i + 1
  TR_s = pd.Series(TR_l)
  ATR = pd.Series(TR_s.ewm(span=n, min_periods=n).mean(), name='ATR_' + str(n))
  df = df.join(ATR)
  return df

6-> Bollinger Bands:-

def bollinger_bands(df, n):
  MA = pd.Series(df['Close'].rolling(n, min_periods=n).mean())
  MSD = pd.Series(df['Close'].rolling(n, min_periods=n).std())
  b1 = 4 * MSD / MA
  B1 = pd.Series(b1, name='BollingerB_' + str(n))
  df = df.join(B1)
  b2 = (df['Close'] - MA + 2 * MSD) / (4 * MSD)
  B2 = pd.Series(b2, name='Bollingerb_' + str(n))
  df = df.join(B2)
  return df


7-> PPSR:-

def ppsr(df):
  """Calculate Pivot Points, Supports and Resistances for given data"""
  PP = pd.Series((df['High'] + df['Low'] + df['Close']) / 3)
  R1 = pd.Series(2 * PP - df['Low'])
  S1 = pd.Series(2 * PP - df['High'])
  R2 = pd.Series(PP + df['High'] - df['Low'])
  S2 = pd.Series(PP - df['High'] + df['Low'])
  R3 = pd.Series(df['High'] + 2 * (PP - df['Low']))
  S3 = pd.Series(df['Low'] - 2 * (df['High'] - PP))
  psr = {'PP': PP, 'R1': R1, 'S1': S1, 'R2': R2, 'S2': S2, 'R3': R3, 'S3': S3}
  PSR = pd.DataFrame(psr)
  df = df.join(PSR)
  return df


8-> Stochastic Oscillator:-

def stochastic_oscillator_k(df):
  SOk = pd.Series((df['Close'] - df['Low']) / (df['High'] - df['Low']), name='SO%k')
  df = df.join(SOk)
  return df


9-> Stochastic Oscillator:-

def stochastic_oscillator_d(df, n):
  SOk = pd.Series((df['Close'] - df['Low']) / (df['High'] - df['Low']), name='SO%k')
  SOd = pd.Series(SOk.ewm(span=n, min_periods=n).mean(), name='SO%d_' + str(n))
  df = df.join(SOd)
  return df


10-> Trix:-

def trix(df, n):
  EX1 = df['Close'].ewm(span=n, min_periods=n).mean()
  EX2 = EX1.ewm(span=n, min_periods=n).mean()
  EX3 = EX2.ewm(span=n, min_periods=n).mean()
  i = 0
  ROC_l = [np.nan]
  while i + 1 <= df.shape[0]-1:
      ROC = (EX3[i + 1] - EX3[i]) / EX3[i]
      ROC_l.append(ROC)
      i = i + 1
  Trix = pd.Series(ROC_l, name='Trix_' + str(n))
  df = df.join(Trix)
  return df


11-> Average Directional Movement Index:-

def average_directional_movement_index(df, n, n_ADX):
  i = 0
  UpI = []
  DoI = []
  while i + 1 <= df.index[-1]:
      UpMove = df.loc[i + 1, 'High'] - df.loc[i, 'High']
      DoMove = df.loc[i, 'Low'] - df.loc[i + 1, 'Low']
      if UpMove > DoMove and UpMove > 0:
          UpD = UpMove
      else:
          UpD = 0
      UpI.append(UpD)
      if DoMove > UpMove and DoMove > 0:
          DoD = DoMove
      else:
          DoD = 0
      DoI.append(DoD)
      i = i + 1
  i = 0
  TR_l = [0]
  while i < df.index[-1]:
      TR = max(df.loc[i + 1, 'High'], df.loc[i, 'Close']) - min(df.loc[i + 1, 'Low'], df.loc[i, 'Close'])
      TR_l.append(TR)
      i = i + 1
  TR_s = pd.Series(TR_l)
  ATR = pd.Series(TR_s.ewm(span=n, min_periods=n).mean())
  UpI = pd.Series(UpI)
  DoI = pd.Series(DoI)
  PosDI = pd.Series(UpI.ewm(span=n, min_periods=n).mean() / ATR)
  NegDI = pd.Series(DoI.ewm(span=n, min_periods=n).mean() / ATR)
  ADX = pd.Series((abs(PosDI - NegDI) / (PosDI + NegDI)).ewm(span=n_ADX, min_periods=n_ADX).mean(),
                  name='ADX_' + str(n) + '_' + str(n_ADX))
  df = df.join(ADX)
  return df


12-> MACD:-

def macd(df, n_fast, n_slow):
  EMAfast = pd.Series(df['Close'].ewm(span=n_fast, min_periods=n_slow).mean())
  EMAslow = pd.Series(df['Close'].ewm(span=n_slow, min_periods=n_slow).mean())
  MACD = pd.Series(EMAfast - EMAslow, name='MACD_' + str(n_fast) + '_' + str(n_slow))
  MACDsign = pd.Series(MACD.ewm(span=9, min_periods=9).mean(), name='MACDsign_' + str(n_fast) + '_' + str(n_slow))
  MACDdiff = pd.Series(MACD - MACDsign, name='MACDdiff_' + str(n_fast) + '_' + str(n_slow))
  df = df.join(MACD)
  df = df.join(MACDsign)
  df = df.join(MACDdiff)
  return df


13-> Mass Index:-

def mass_index(df):
  Range = df['High'] - df['Low']
  EX1 = Range.ewm(span=9, min_periods=9).mean()
  EX2 = EX1.ewm(span=9, min_periods=9).mean()
  Mass = EX1 / EX2
  MassI = pd.Series(Mass.rolling(25).sum(), name='Mass Index')
  df = df.join(MassI)
  return df


14-> Vortex Indicator:-

def vortex_indicator(df, n):
  i = 0
  TR = [0]
  while i < df.shape[0]-1:
      Range = max(df['High'][i + 1], df['Close'][i]) - min(df['Low'][i + 1], df['Close'][i])
      TR.append(Range)
      i = i + 1
  i = 0
  VM = [0]
  while i < df.shape[0]-1:
      Range = abs(df['High'][i + 1] - df['Low'][i]) - abs(df['Low'][i + 1] - df['High'][i])
      VM.append(Range)
      i = i + 1
  VI = pd.Series(pd.Series(VM).rolling(n).sum() / pd.Series(TR).rolling(n).sum(), name='Vortex_' + str(n))
  df = df.join(VI)
  return df

15-> KST Oscillator:-

def kst_oscillator(df, r1, r2, r3, r4, n1, n2, n3, n4):
  M = df['Close'].diff(r1 - 1)
  N = df['Close'].shift(r1 - 1)
  ROC1 = M / N
  M = df['Close'].diff(r2 - 1)
  N = df['Close'].shift(r2 - 1)
  ROC2 = M / N
  M = df['Close'].diff(r3 - 1)
  N = df['Close'].shift(r3 - 1)
  ROC3 = M / N
  M = df['Close'].diff(r4 - 1)
  N = df['Close'].shift(r4 - 1)
  ROC4 = M / N
  KST = pd.Series(
      ROC1.rolling(n1).sum() + ROC2.rolling(n2).sum() * 2 + ROC3.rolling(n3).sum() * 3 + ROC4.rolling(n4).sum() * 4,
      name='KST_' + str(r1) + '_' + str(r2) + '_' + str(r3) + '_' + str(r4) + '_' + str(n1) + '_' + str(
          n2) + '_' + str(n3) + '_' + str(n4))
  df = df.join(KST)
  return df


16-> Relative Strength Index:-

def relative_strength_index(df, n):
  i = 0
  UpI = [0]
  DoI = [0]
  while i + 1 <= df.shape[0]-1:
      UpMove = df['High'][i + 1] - df['High'][i]
      DoMove = df['Low'][i] - df['Low'][i + 1]
      if UpMove > DoMove and UpMove > 0:
          UpD = UpMove
      else:
          UpD = 0
      UpI.append(UpD)
      if DoMove > UpMove and DoMove > 0:
          DoD = DoMove
      else:
          DoD = 0
      DoI.append(DoD)
      i = i + 1
  UpI = pd.Series(UpI)
  DoI = pd.Series(DoI)
  PosDI = pd.Series(UpI.ewm(span=n, min_periods=n).mean())
  NegDI = pd.Series(DoI.ewm(span=n, min_periods=n).mean())
  RSI = pd.Series(PosDI / (PosDI + NegDI), name='RSI_' + str(n))
  df = df.join(RSI)
  return df


17-> True Strength Index:-

def true_strength_index(df, r, s):
  M = pd.Series(df['Close'].diff(1))
  aM = abs(M)
  EMA1 = pd.Series(M.ewm(span=r, min_periods=r).mean())
  aEMA1 = pd.Series(aM.ewm(span=r, min_periods=r).mean())
  EMA2 = pd.Series(EMA1.ewm(span=s, min_periods=s).mean())
  aEMA2 = pd.Series(aEMA1.ewm(span=s, min_periods=s).mean())
  TSI = pd.Series(EMA2 / aEMA2, name='TSI_' + str(r) + '_' + str(s))
  df = df.join(TSI)
  return df


18-> Accumulation Distribution:-

def accumulation_distribution(df, n):
  ad = (2 * df['Close'] - df['High'] - df['Low']) / (df['High'] - df['Low']) * df['Volume']
  M = ad.diff(n - 1)
  N = ad.shift(n - 1)
  ROC = M / N
  AD = pd.Series(ROC, name='Acc/Dist_ROC_' + str(n))
  df = df.join(AD)
  return df


19-> Chaikin Oscillator:-

def chaikin_oscillator(df):
  ad = (2 * df['Close'] - df['High'] - df['Low']) / (df['High'] - df['Low']) * df['Volume']
  Chaikin = pd.Series(ad.ewm(span=3, min_periods=3).mean() - ad.ewm(span=10, min_periods=10).mean(), name='Chaikin')
  df = df.join(Chaikin)
  return df


20-> Money Flow Index:-

def money_flow_index(df, n):
  PP = (df['High'] + df['Low'] + df['Close']) / 3
  i = 0
  PosMF = [0]
  while i < df.shape[0]-1:
      if PP[i + 1] > PP[i]:
          PosMF.append(PP[i + 1] * df['Volume'][i + 1])
      else:
          PosMF.append(0)
      i = i + 1
  PosMF = pd.Series(PosMF)
  TotMF = PP * df['Volume']
  MFR = pd.Series(PosMF / TotMF)
  MFI = pd.Series(MFR.rolling(n, min_periods=n).mean(), name='MFI_' + str(n))
  df = df.join(MFI)
  return df


21-> On Balance Volume:-

 def on_balance_volume(df, n):
  i = 0
  OBV = [0]
  while i < df.shape[0]-1:
      if df['Close'][i + 1] - df['Close'][i] > 0:
          OBV.append(df['Volume'][i + 1])
      if df['Close'][i + 1] - df['Close'][i] == 0:
          OBV.append(0)
      if df['Close'][i + 1] - df['Close'][i] < 0:
          OBV.append(-df['Volume'][i + 1])
      i = i + 1
  OBV = pd.Series(OBV)
  OBV_ma = pd.Series(OBV.rolling(n, min_periods=n).mean(), name='OBV_' + str(n))
  df = df.join(OBV_ma)
  return df


22-> Force Index:-

def force_index(df, n):
  F = pd.Series(df['Close'].diff(n) * df['Volume'].diff(n), name='Force_' + str(n))
  df = df.join(F)
  return df


23-> Ease of Movement:-

def ease_of_movement(df, n):
  EoM = (df['High'].diff(1) + df['Low'].diff(1)) * (df['High'] - df['Low']) / (2 * df['Volume'])
  Eom_ma = pd.Series(EoM.rolling(n, min_periods=n).mean(), name='EoM_' + str(n))
  df = df.join(Eom_ma)
  return df


24-> Commodity Channel Index:-

def commodity_channel_index(df, n):
  PP = (df['High'] + df['Low'] + df['Close']) / 3
  CCI = pd.Series((PP - PP.rolling(n, min_periods=n).mean()) / PP.rolling(n, min_periods=n).std(),
                  name='CCI_' + str(n))
  df = df.join(CCI)
  return df


25-> Coppock Curve:-

def coppock_curve(df, n):
  M = df['Close'].diff(int(n * 11 / 10) - 1)
  N = df['Close'].shift(int(n * 11 / 10) - 1)
  ROC1 = M / N
  M = df['Close'].diff(int(n * 14 / 10) - 1)
  N = df['Close'].shift(int(n * 14 / 10) - 1)
  ROC2 = M / N
  Copp = pd.Series((ROC1 + ROC2).ewm(span=n, min_periods=n).mean(), name='Copp_' + str(n))
  df = df.join(Copp)
  return df


26-> Keltner Channel:-

def keltner_channel(df, n):
  KelChM = pd.Series(((df['High'] + df['Low'] + df['Close']) / 3).rolling(n, min_periods=n).mean(),
                     name='KelChM_' + str(n))
  KelChU = pd.Series(((4 * df['High'] - 2 * df['Low'] + df['Close']) / 3).rolling(n, min_periods=n).mean(),
                     name='KelChU_' + str(n))
  KelChD = pd.Series(((-2 * df['High'] + 4 * df['Low'] + df['Close']) / 3).rolling(n, min_periods=n).mean(),
                     name='KelChD_' + str(n))
  df = df.join(KelChM)
  df = df.join(KelChU)
  df = df.join(KelChD)
  return df


27-> Ultimate Oscillator:-

def ultimate_oscillator(df):
  i = 0
  TR_l = [0]
  BP_l = [0]
  while i < df.shape[0]-1:
      TR = max(df['High'][i + 1], df['Close'][i]) - min(df['Low'][i + 1], df['Close'][i])
      TR_l.append(TR)
      BP = df['Low'][i + 1] - min(df['Low'][i + 1], df['Close'][i])
      BP_l.append(BP)
      i = i + 1
  UltO = pd.Series((4 * pd.Series(BP_l).rolling(7).sum() / pd.Series(TR_l).rolling(7).sum()) + (
              2 * pd.Series(BP_l).rolling(14).sum() / pd.Series(TR_l).rolling(14).sum()) + (
                               pd.Series(BP_l).rolling(28).sum() / pd.Series(TR_l).rolling(28).sum()),
                   name='Ultimate_Osc')
  df = df.join(UltO)
  return df


28-> Donchin Channel:-

def donchian_channel(df, n):
  i = 0
  dc_l = []
  while i < n - 1:
      dc_l.append(0)
      i += 1

  i = 0
  while i + n - 1 < df.shape[0]:
      dc = max(df['High'][i:i + n - 1]) - min(df['Low'][i:i + n - 1])
      dc_l.append(dc)
      i += 1

  donchian_chan = pd.Series(dc_l, name='Donchian_' + str(n))
  donchian_chan = donchian_chan.shift(n - 1)
  return df.join(donchian_chan)


29-> Standard Deviations:-

 def standard_deviation(df, n):
  df = df.join(pd.Series(df['Close'].rolling(n, min_periods=n).std(), name='STD_' + str(n)))
  return df

When you have decided that which strategy(Single or multiple indicators totally on your wish) you want to use then you can call the function like below

df = standard_deviation(df, n)

It will store the result in the dataframe with an increased column.

you can fill NA value in dataframes through this formula

df=df.fillna(method='ffill')

ffill for forward fill & bfill for backward. ffill is quite favorable as if bffill is done then data can become biased.

To store the data in csv format

df.to_csv('trade.csv', index=False)

For plotting graph use matplotlib & you can also share the code in case you have succesfully implemented the code with learning module.

Comments

Popular posts from this blog

Google Dorks list

Google Dorks are used for searching websites in google search engine or in CLI. It can also help you in hacking as it shows the specific results which contains your search strings. Some of the Google Dorks are given below I tried to include all of them and sorry if any duplicacy. You can download or view this from  here about.php?cartID= accinfo.php?cartId= acclogin.php?cartID= add.php?bookid= add_cart.php?num= addcart.php? addItem.php add-to-cart.php?ID= addToCart.php?idProduct= addtomylist.php?ProdId= adminEditProductFields.php?intProdID= advSearch_h.php?idCategory= affiliate.php?ID= affiliate-agreement.cfm?storeid= affiliates.php?id= ancillary.php?ID= archive.php?id= article.php?id= phpx?PageID basket.php?id= Book.php?bookID= book_list.php?bookid= book_view.php?bookid= BookDetails.php?ID= browse.php?catid= browse_item_details.php Browse_Item_Details.php?Store_Id= buy.php? buy.php?bookid= bycategory.php?id= cardinfo.php?card= cart.php?action= ...

Hack SQL vulnerable websites with sqlmap

As the web is expanding day by day same way the hackers are also gaining new ways to access the data of your or any random website all you need to do is few lines of code and you are all done. Today i will tell you most common way to hack a website without any restrictions all you need is a vulnerable site and you are all done. NOTE: This is for educational purpose only. I am not responsible for anything. Try at your own risk. SQLMAP is availabe in linux and mac OS. If not you can install it via apt and other possible ways. syntax > sqlmap / [ ,options/ ] First of all make your device ready for hacking that is by installing necessary software's and files like Tor , Orbot  (Android),  Orfox (Android) or any other tor supported browser. And don't use it for your personal works. And if possible use VM's for hacking to make it more anonymous. Run tor or orbot and connect via VPN to be anonymous (i.e to hide and secure yourself). then you can open terminal on...