Python Forum
error on stock indicator code on balance volume
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
error on stock indicator code on balance volume
#11
I tried the "way" you said I got all in same line but when I used
print(aapl.index)
print(aapl.columns)
I got this
RangeIndex(start=0, stop=1845, step=1)
Index(['Date', 'Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume'], dtype='object')
I want to use obv column in my strategy but as it is not in column I am not able to use it in my conditions

also wen I set date as my index again my all obv values got nan
so basically we canot keep date as a index while displaying obv values??
Reply
#12
Do you need the OBV_1 column inside the on_balance_volume()?
Because it is being added only at the end of the function.

Here, after the on_balance_volume(), it is there:

aapl = on_balance_volume(aapl, n)
print(aapl.index)
print(aapl.columns)
print(aapl['OBV_1'])
Output:
RangeIndex(start=0, stop=17, step=1) Index(['Date', 'Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume', 'OBV_1'], dtype='object') 0 0.0 1 88102700.0 2 123432400.0 3 -138040000.0 4 -119282800.0 5 119282800.0 6 -115557400.0 7 -148614900.0 8 148614900.0 9 -108223500.0 10 -148516900.0 11 148516900.0 12 -153038200.0 13 -152038600.0 14 -220441900.0 15 220441900.0 16 266424900.0 Name: OBV_1, dtype: float64
Reply
#13
done thanku so much gontajones ...!!!!
Reply
#14
initial_capital= float(1000.0)
positions = pd.DataFrame(index=signals.index).fillna(0.0)
positions['AAPL'] = 100*signals['signal']
portfolio = positions.multiply(aapl['Adj Close'], axis=0)
pos_diff = positions.diff()
portfolio['holdings'] = (positions.multiply(aapl['Adj Close'], axis=0)).sum(axis=1)
portfolio['cash'] = initial_capital - (pos_diff.multiply(aapl['Adj Close'], axis=0)).sum(axis=1).cumsum()
portfolio['total'] = portfolio['cash'] + portfolio['holdings']
portfolio['returns'] = portfolio['total'].pct_change()


how can I generate
largest winning trade
largest loosing trade
gross profit
gross loss
profit factor from the above input
I don't wan tot use pyalgo trade library for that
Reply
#15
import pandas as pd
import numpy as np
import statsmodels.tsa.stattools as ts
import matplotlib.pyplot as plt
from scipy import optimize
data = pd.read_csv('aapl.csv')

data1 = data[['Date']]
    def backtest( init_capital, max_capital_deploy, buy_margin, sell_margin):
    
    # TODO :
    # daily MTM , exit on Stop loss and target, MDD, etc
    
    longwindow = int(parameters[0])
    shortwindow = int(parameters[1])

    
    if (longwindow < shortwindow) or (shortwindow < 1) or (init_capital <= 0) or (max_capital_deploy <=0) or (buy_margin < 0) or (sell_margin < 0)  :
        return 0

   
    short_moving_avg = ratio.rolling(window = shortwindow, center=False).mean()
    long_moving_avg = ratio.rolling(window = longwindow, center=False).mean()
    
    capital = init_capital
    qty1 = 0
    pos = 0
    margin_blocked = 0
    
    trade_pnl = []
    mtm_pl = []
    
    
    
    
    
    
    
    for i in range(len(data)):
        
        
        if capital <= 0:
            break
       

        if pos == 0:
          
            
            if  short_moving_avg[i] >  long_moving_avg[i]:
                
                
                pos = -1
                        
              
                p1 = price1[i]
                
                
               
                margin_blocked = capital * max_capital_deploy
                
               
                qty1 = -(margin_blocked / 2) // (p1 * sell_margin)
                
                
                
             
                
                if -qty1 < 1:
                    break
                
            elif   short_moving_avg[i] <  long_moving_avg[i]:
                
                pos = 1
                
              
                p1 = price1[i]
                
                
              
                margin_blocked = capital * max_capital_deploy
              
                qty1 = (margin_blocked / 2) // (p1 * buy_margin)
                
                
                
                
                
                if qty1 < 1 :
                    break
            
         
        elif pos < 0:  
                 
            if   short_moving_avg[i] >  long_moving_avg[i]:
               
                
                pnl = qty1 * (price1[i] - p1)
                if not fixedcapital:
                    capital += pnl
                
            trade_pnl = np.append(trade_pnl, pnl)
                
                
            margin_blocked = 0
            qty1 = 0
                
            pos = 0
        else:
            
               
            pnl = qty1 * (price1[i] - p1) 
            mtm_pl = np.append(mtm_pl, pnl)
                
           
               
                    
            trade_pnl = np.append(trade_pnl, pnl)
                    
                    
            margin_blocked = 0
            qty1 = 0
                    
            pos = 0
        else:
            
           
            
            if moving_window_z_score[i] > -exitlimit:
               
                
                pnl = qty1 * (price1[i] - p1) 
               

            trade_pnl = np.append(trade_pnl, pnl)
                
                
            margin_blocked = 0
            qty1 = 0
               
            pos = 0

        else:
              
                
            pnl = qty1 * (price1[i] - p1) 
            mtm_pl = np.append(mtm_pl, pnl)
                
                
                 trade_pnl = np.append(trade_pnl, pnl)
                    
                  
                 margin_blocked = 0
                    qty1 = 0
                  
                    pos = 0
                
            
       
    
    return capital, trade_pnl, mtm_pl
Error:
File "<ipython-input-101-0541da3091dd>", line 116 else: ^ SyntaxError: invalid syntax
I m new to python I want to fix this else issue also how I can call or print trade pnl and mtm pnl
Reply
#16
You can't use 2 else one after other.
To use an else you need first an if or an elif...
Reply
#17
ok I m trying to fix it..but how can I call the backtst function...
Reply
#18
It's hard to help for us who doesn't know what is the goal of your code.
Maybe you can explain what you want that this code (not only the function) do.
Reply
#19
def backtest( price1,init_capital, max_capital_deploy, buy_margin, sell_margin):
    longwindow = int(parameters[0])
    shortwindow = int(parameters[1])
    if (longwindow < shortwindow) or (shortwindow < 1) or (init_capital <= 0) or (max_capital_deploy <=0) or (buy_margin < 0) or (sell_margin < 0)  :
        return 0
    short_moving_avg = data.ewm(span=5).mean()
    long_moving_avg =  data.ewm(span=60).mean()
    
    
    # Simulate trading
    # Start with no money and no positions
    
    
    
    
    
    
    capital = init_capital
    qty1 = 0
    
    pos = 0
    margin_blocked = 0
    p1=0
    
    trade_pnl = []
    mtm_pl = []
        
    for i in range(len(ratio)):
        
        # if capital is eroded beyond a limit then exit
        if capital <= 0:
            break
        
        # if there is already exiting open position then no new position is to 
        # be taken till exii

        if pos == 0:
            # if there is no exiting open position then check if new position is to be taken 
            
            if short_moving_avg[i] > long_moving_avg:
               
                # Take a short position 
                pos = -1
                        
                # keep track of entry prices
                p1 = price1[i]
               
                # check how much capital is to be deployed
                margin_blocked = capital * max_capital_deploy
                
              
                
                # use FLOOR DIVISION to get integral qty
                qty1 = -(margin_blocked / 2) // (p1 * sell_margin)
                
               
                
                # if enough margin is not available no position will be taken
                
                if -qty1 < 1 :
                    break
                
            elif short_moving_avg[i] > long_moving_avg:
               
                # Take a long position
                pos = 1
                
                # keep track of entry prices
                p1 = price1[i]
               
                
                # check how much capital is to be deployed
                margin_blocked = capital * max_capital_deploy
                
            
               
                qty1 = (margin_blocked / 2) // (p1 * buy_margin)
                
              
                
              
                
                if qty1 < 1  :
                    break
            
            #else:
                # do nothing
            
        elif pos < 0:  
            # if there is exiting open short position then check for exit condition
            
            if short_moving_avg[i] >ong_moving_avg:
               
                # exit the short position
                
                # calculate the PL from the entry prices
                
                pnl = qty1 * (price1[i] - p1)
                if not fixedcapital:
                    capital += pnl
                
                trade_pnl = np.append(trade_pnl, pnl)
                
                # release the margin and all others
                margin_blocked = 0
                qty1 = 0
                
                pos = 0
            else:
                # calculate the MTM PL from the entry prices
                
                pnl = qty1 * (price1[i] - p1)
                mtm_pl = np.append(mtm_pl, pnl)
                
                # check for stop loss or target
                
               
                    
                trade_pnl = np.append(trade_pnl, pnl)
                    
                    # release the margin and all others
                margin_blocked = 0
                qty1 = 0
                   
                pos = 0
        else:
            # if there is exiting open long position then check for exit condition
            
            if short_moving_avg[i] <long_moving_avg:
              
                # exit the long position 
                # calculate the PL from the entry prices
                
                pnl = qty1 * (price1[i] - p1)
                if not fixedcapital:
                    capital += pnl

                trade_pnl = np.append(trade_pnl, pnl)
                
                # release the margin and all others
                margin_blocked = 0
                qty1 = 0
               
                pos = 0

            else:
                # calculate the MTM PL from the entry prices
                
                pnl = qty1 * (price1[i] - p1)
                mtm_pl = np.append(mtm_pl, pnl)
                
                # check for stop loss or target
                
                
                    
                trade_pnl = np.append(trade_pnl, pnl)
                    
                    # release the margin and all others
                margin_blocked = 0
                qty1 = 0
                    
                pos = 0
                
           
    
    return capital, trade_pnl, mtm_pl
i wan to test the basic strategy that is when short ema> long ema short the stock and exit the long position if any
and when short ema < long ema buy the stock and close the already open sell positoion if any
have written code for the same now i want to generate the trading profit and loss columns to pass it to the backtest function

I want to know how can I get the trd_pnl mtm_pnl
below is the error m getig
 cap, trdpnls, mtmpnls = backtest( price1,init_capital, max_capital_deploy, buy_margin, sell_margin)
    
Error:
NameError Traceback (most recent call last) <ipython-input-42-2e95ef66a812> in <module>() ----> 1 cap, trdpnls, mtmpnls = backtest( price1,init_capital, max_capital_deploy, buy_margin, sell_margin) 2 NameError: name 'price1' is not defined
Reply
#20
I have 4 dataframe
Df1
Df2
Df3
Df4
I calculate all df values..
But i want to plot graph using column from all 4 df on the top of first df..can you help how can i do that
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to accumulate volume of time series amdi40 3 2,259 Feb-15-2022, 02:23 PM
Last Post: amdi40
  Integrating for the volume of a torus in SciPy Nitram 2 3,635 Jan-08-2020, 04:45 PM
Last Post: Nitram

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020