Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Pinkfish package
#15
Quote:Yes there is,so this a Notebook i run as test.
As you see no errors.
you have been really helpful. I am going through a painful period.
how can you not get any errors?

in this part
full code is here
in this part
for i, row in enumerate(ts.itertuples()):

    date = row.Index.to_pydatetime()
    high = row.high; low = row.low; close = row.close
    sma50 = row.sma50; sma200 = row.sma200
    end_flag = True if (i == len(ts) - 1) else False
    shares = 0
    
    # close all positions on last trade day
    if end_flag:
        shares = tlog.exit_trade(date, close)
    # buy
    elif (tlog.num_open_trades() == 0
          and row.sma50 > row.sma200 and ts['sma50'][i-1] <= ts['sma200'][i-1]):

        # enter buy in trade log
        shares = tlog.enter_trade(date, close)  
    # sell
    elif (tlog.num_open_trades() > 0
          and sma50 < sma200 and ts['sma50'][i-1] >= ts['sma200'][i-1]):

        # enter sell in trade log
        shares = tlog.exit_trade(date, close)

    if shares > 0:
        print("{0} BUY  {1} {2} @ {3:.2f}".format(
              date, shares, symbol, close))
    elif shares < 0:
        print("{0} SELL {1} {2} @ {3:.2f}".format(
              date, -shares, symbol, close))

    # record daily balance
    dbal.append(date, high, low, close, tlog.shares, tlog.cash)  

t1 = time.time()
total = t1-t0
print(total)
shares = tlog.exit_trade(date, close)

and if we go to the tlog.exit_trade()
"""
trade
---------
Assist with trading
"""

# Use future imports for python 3.0 forward compatibility
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

# Other imports
import pandas as pd

class TradeLog():
    """ trade log """

    def __init__(self):
        columns = ['entry_date', 'entry_price', 'long_short', 'qty',
                   'exit_date', 'exit_price', 'pl_points', 'pl_cash',
                   'cumul_total']
        self._tlog = pd.DataFrame(columns=columns)
        self.shares = 0

    def calc_shares(self, cash, price):
        """ calculate shares and remaining cash before entry """
        shares = int(cash / price)
        cash = cash - shares * price
        return shares, cash

    def calc_cash(self, cash, price, shares):
        """ calculate cash after exit """
        cash = cash + price*shares
        return cash

    def enter_trade(self, entry_date, entry_price, shares, long_short='long'):
        """ record trade entry in trade log """
        d = {'entry_date':entry_date, 'entry_price':entry_price, 'qty':shares, 
             'long_short':long_short}
        tmp = pd.DataFrame([d], columns=self._tlog.columns)
        self._tlog = self._tlog.append(tmp, ignore_index=True)

        # update shares
        if long_short == 'long':
            self.shares += shares
        else:
            self.shares -=shares

    def _get_open_trades(self):
        """ find the "integer" index of rows with NaN """
        return pd.isnull(self._tlog).any(1).to_numpy().nonzero()[0]
    
    def num_open_trades(self):
        """ return number of open orders, i.e. not closed out """
        return len(self._get_open_trades())

    def exit_trade(self, exit_date, exit_price, shares=-1, long_short='long'):
        """ record trade exit in trade log """

        rows = self._get_open_trades()
        idx = rows[0]

        entry_price = self._tlog['entry_price'][idx]
        shares = self._tlog['qty'][idx] if shares == -1 else shares
        pl_points = exit_price - entry_price
        pl_cash = pl_points * shares
        if idx == 0:
            cumul_total = pl_cash
        else:
            cumul_total = self._tlog.ix[idx - 1, 'cumul_total'] + pl_cash

        self._tlog.ix[idx, 'exit_date'] = exit_date
        self._tlog.ix[idx, 'exit_price'] = exit_price
        self._tlog.ix[idx, 'long_short'] = 'long'
        self._tlog.ix[idx, 'pl_points'] = pl_points
        self._tlog.ix[idx, 'pl_cash'] = pl_cash
        self._tlog.ix[idx, 'cumul_total'] = cumul_total

        # update shares
        if long_short == 'long':
            self.shares -= shares
        else:
            self.shares +=shares
        return idx

    def get_log(self):
        """ return Dataframe """
        return self._tlog

class TradeState:
    OPEN, CLOSE, HOLD, CASH = range(0, 4)

class DailyBal:
    """ Log for daily balance """

    def __init__(self):
        self._l = []  # list of daily balance tuples

    def _balance(self, date, high, low, close, shares, cash, state):
        """ calculates daily balance values """
        if state == TradeState.OPEN:
            # date, high, low, close, cash, state
            t = (date, close*shares + cash, close*shares + cash,
                 close*shares + cash, shares, cash, state)
        elif state == TradeState.CLOSE:
            t = (date, high*shares + cash, low*shares + cash,
                 close*shares + cash, shares, cash, state)
        elif state == TradeState.HOLD:
            t = (date, high*shares + cash, low*shares + cash,
                 close*shares + cash, shares, cash, state)
        elif state == TradeState.CASH:
            t = (date, cash, cash, cash,
                 shares, cash, state)
        return t

    def append(self, date, high, low, close, shares, cash, state):
        t = self._balance(date, high, low, close, shares, cash, state)
        self._l.append(t)

    def get_log(self):
        """ return Dataframe """
        columns = ['date', 'high', 'low', 'close', 'shares', 'cash', 'state']
        dbal = pd.DataFrame(self._l, columns=columns)
        dbal.set_index('date', inplace=True)
        return dbal
we can see the following part
def enter_trade(self, entry_date, entry_price, shares, long_short='long'):
def exit_trade(self, exit_date, exit_price, shares=-1, long_short='long'):

 def enter_trade(self, entry_date, entry_price, shares, long_short='long'):
        """ record trade entry in trade log """
        d = {'entry_date':entry_date, 'entry_price':entry_price, 'qty':shares, 
             'long_short':long_short}
        tmp = pd.DataFrame([d], columns=self._tlog.columns)
        self._tlog = self._tlog.append(tmp, ignore_index=True)

        # update shares
        if long_short == 'long':
            self.shares += shares
        else:
            self.shares -=shares

def exit_trade(self, exit_date, exit_price, shares=-1, long_short='long'):
        """ record trade exit in trade log """
 
        rows = self._get_open_trades()
        idx = rows[0]
 
        entry_price = self._tlog['entry_price'][idx]
        shares = self._tlog['qty'][idx] if shares == -1 else shares
        pl_points = exit_price - entry_price
        pl_cash = pl_points * shares
        if idx == 0:
            cumul_total = pl_cash
        else:
            cumul_total = self._tlog.ix[idx - 1, 'cumul_total'] + pl_cash
 
        self._tlog.ix[idx, 'exit_date'] = exit_date
        self._tlog.ix[idx, 'exit_price'] = exit_price
        self._tlog.ix[idx, 'long_short'] = 'long'
        self._tlog.ix[idx, 'pl_points'] = pl_points
        self._tlog.ix[idx, 'pl_cash'] = pl_cash
        self._tlog.ix[idx, 'cumul_total'] = cumul_total
 
        # update shares
        if long_short == 'long':
            self.shares -= shares
        else:
            self.shares +=shares
        return idx
then I get error
Error:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-21-ef62bb3159a8> in <module> 23 24 # enter buy in trade log ---> 25 shares = tlog.enter_trade(date, close) 26 # sell 27 elif (tlog.num_open_trades() > 0 TypeError: enter_trade() missing 1 required positional argument: 'shares'
if I do this, add shares
#tlog.enter_trade(date, close)
tlog.enter_trade(date, close,shares)

error disappears,
but giving me an error about the shares. TypeError: '<' not supported between instances of 'NoneType' and 'int'y
Reply


Messages In This Thread
Pinkfish package - by buunaanaa - May-15-2020, 05:22 AM
RE: Pinkfish package - by snippsat - May-15-2020, 06:20 AM
RE: Pinkfish package - by buunaanaa - May-15-2020, 05:48 PM
RE: Pinkfish package - by snippsat - May-15-2020, 06:31 PM
RE: Pinkfish package - by buunaanaa - May-15-2020, 07:22 PM
RE: Pinkfish package - by snippsat - May-15-2020, 10:04 PM
RE: Pinkfish package - by buunaanaa - May-16-2020, 04:48 PM
RE: Pinkfish package - by buunaanaa - May-18-2020, 05:49 AM
RE: Pinkfish package - by buunaanaa - May-16-2020, 07:55 PM
RE: Pinkfish package - by snippsat - May-16-2020, 06:33 PM
RE: Pinkfish package - by buunaanaa - May-17-2020, 04:24 PM
RE: Pinkfish package - by buunaanaa - May-18-2020, 05:43 PM
RE: Pinkfish package - by buunaanaa - May-18-2020, 07:11 PM
RE: Pinkfish package - by snippsat - May-16-2020, 09:48 PM
RE: Pinkfish package - by snippsat - May-17-2020, 04:47 PM
RE: Pinkfish package - by snippsat - May-18-2020, 10:44 AM
RE: Pinkfish package - by snippsat - May-18-2020, 08:10 PM

Forum Jump:

User Panel Messages

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