Python code to calculate slippage and transaction charges

HI i would like to know how to calculate slippage and transaction cost in a strategy in python code when workin in spyder.

If i can get to know only the code for the same,it wpould be very helpful.

Here is a sample code to calculate slippages and transaction cost in Python. The slippage and transaction cost needs to be adjusted as per the instrument and market you are trading in.

  1. import numpy as np  
  2.  
  3. # Slippage per share.
  4. slippage = 0.1  
  5.  
  6. # 0.0025 is transaction cost per dollar of traded value.  
  7. trans_cost = 0.005  
  8.   
  9. # A function to determine the total amount after accouting for slippages and transaction cost  
  10. def cash(price, quantity, slippage, trans_cost):  
  11.     # Actual price expected  
  12.     price = price + (slippage * np.sign(quantity))  
  13.     # Total transaction cost  
  14.     cost = quantity * price * trans_cost  
  15.     return (price*quantity) + (cost * np.sign(quantity))  
  16.   
  17. # Buying  
  18. # Number of shares. 
  19. quantity = 10  
  20. # Last traded price of the instrument  
  21. price = 450  
  22. print('Cash paid after buying 10 shares', cash(price, quantity, slippage, trans_cost))  
  23.   
  24. # Selling   
  25. # Number of shares. A negative number indicates a sell order  
  26. quantity = -10  
  27. print('Cash received after selling 10 shares', cash(price, quantity, slippage, trans_cost))
We will be adding more techniques to estimate slippages and how to account for it during backtesting as practiced by traders in our course on Python for trading