<jupyter_start><jupyter_text>pinkfish-challengeBuy on the close on the SAME day a new 20 day high is set<jupyter_code># use future imports for python 3.x 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
import matplotlib.pyplot as plt
import datetime
from talib.abstract import *

# project imports
import pinkfish as pf

# format price data
pd.options.display.float_format = '{:0.2f}'.format

%matplotlib inline
symbol = '^GSPC'
#symbol = 'SPY'
capital = 10000
start = datetime.datetime(2016, 1, 1)
end = datetime.datetime.now()<jupyter_output><empty_output><jupyter_text>Define high trade periods<jupyter_code>period = 20<jupyter_output><empty_output><jupyter_text>Define Strategy Class<jupyter_code>class Strategy(object):

    def __init__(self, symbol, capital, start, end, period,
                 slippage_per_trade=0, commissions_per_trade=0):
        self._symbol = symbol
        self._capital = capital
        self._start = start
        self._end = end
        self._period = period
        self._slippage_per_trade = slippage_per_trade
        self._commissions_per_trade = commissions_per_trade

    def _algo(self):
        self._tlog.cash = self._capital
        start_flag = True
        end_flag = False

        for i, row in enumerate(self._ts.itertuples()):

            date = row.Index.to_pydatetime()
            high = row.high
            low = row.low
            close = row.close
            period_high = row.period_high
            end_flag = True if (i == len(self._ts) - 1) else False
            trade_state = None

            if date < self._start:
                continue
            elif start_flag:
                start_flag = False
                # set start and end
                self._start = date
                self._end = self._ts.index[-1]

            # buy
            if (self._tlog.num_open_trades() == 0
                and high > period_high
                and not end_flag):

                # enter buy in trade log
                shares = self._tlog.enter_trade(date, close)
                trade_state = pf.TradeState.OPEN
                print("{0} BUY  {1} {2} @ {3:.2f}".format(
                      date, shares, self._symbol, close))

            # sell
            elif end_flag:

                # enter sell in trade log
                shares = self._tlog.exit_trade(date, close)
                trade_state = pf.TradeState.CLOSE
                print("{0} SELL {1} {2} @ {3:.2f}".format(
                      date, shares, self._symbol, close))

            # hold
            else:
                trade_state = pf.TradeState.HOLD

            # record daily balance
            self._dbal.append(date, high, low, close,
                              self._tlog.shares, self._tlog.cash,
                              trade_state)

    def run(self):
        self._ts = pf.fetch_timeseries(self._symbol)
        self._ts = pf.select_tradeperiod(self._ts, self._start,
                                         self._end, use_adj=False)
        
        # Add technical indicator: X day high, and X day low
        period_high = pd.Series(self._ts.close).rolling(self._period).max()
        self._ts['period_high'] = period_high
        
        self._tlog = pf.TradeLog()
        self._dbal = pf.DailyBal()

        self._algo()

    def get_logs(self):
        """ return DataFrames """
        tlog = self._tlog.get_log()
        dbal = self._dbal.get_log()
        return tlog, dbal<jupyter_output><empty_output><jupyter_text>Run Strategy<jupyter_code>s = Strategy(symbol, capital, start, end, int(period))
s.run()
s._ts['2016-02-01':'2016-03-01']<jupyter_output>2016-02-22 00:00:00 BUY  5 ^GSPC @ 1945.50
2019-07-24 00:00:00 SELL 5 ^GSPC @ 3019.56<jupyter_text>Retrieve log DataFrames<jupyter_code>s.tlog, s.dbal = s.get_logs()
s.tlog.tail(100)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09668577124345876, 'fraction_numerical': 0.02342387241465238, 'mean_word_length': 2.0547945205479454, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '33629', 'license': 'MIT', 'n_tokens_mistral': 1344, 'n_tokens_neox': 1223, 'n_words': 286, 'path': 'examples/pinkfish-challenge/strategy.ipynb', 'repo_name': 'simongarisch/pinkfish', 'size': '4013'}