In [1]:
    
import pandas as pd
import datetime
import pinkfish as pf
# format price data
pd.options.display.float_format = '{:0.2f}'.format
%matplotlib inline
    
In [2]:
    
symbol = '^GSPC'
capital = 10000
start = datetime.datetime(2016, 1, 1)
end = datetime.datetime.now()
    
Define high trade periods
In [3]:
    
period = 20
    
Timeseries
In [4]:
    
ts = pf.fetch_timeseries(symbol)
ts = pf.select_tradeperiod(ts, start, end, use_adj=False)
# Add technical indicator: X day high, and X day low
period_high = pd.Series(ts.close).rolling(period).max()
ts['period_high'] = period_high
ts, start = pf.finalize_timeseries(ts, start)
tlog = pf.TradeLog(symbol)
dbal = pf.DailyBal()
    
In [5]:
    
pf.TradeLog.cash = capital
for i, row in enumerate(ts.itertuples()):
    date = row.Index.to_pydatetime()
    high = row.high; low = row.low; close = row.close; 
    end_flag = pf.is_last_row(ts, i)
    shares = 0
    # buy
    if (tlog.shares == 0
        and high > row.period_high
        and not end_flag):
        # enter buy in trade log
        shares = tlog.buy(date, close)
    # sell
    elif end_flag:
        # enter sell in trade log
        shares = tlog.sell(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)
    
    
Get logs
In [6]:
    
tlog = tlog.get_log()
dbal = dbal.get_log(tlog)
    
In [7]:
    
tlog.tail()
    
    Out[7]:
The first 20 day high occurred on 2/22/2016, so we bought on the close that day. We held onto the present, then sold the positon.