buy-and-hold

buy, then never ever sell, until the end date :)


In [1]:
import pandas as pd
import datetime
import pinkfish as pf

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

Some global data


In [2]:
symbol = 'SPY'
capital = 10000
start = datetime.datetime(1900, 1, 1)
end = datetime.datetime.now()

Timeseries


In [3]:
# fetch timeseries, select, finalize
ts = pf.fetch_timeseries(symbol)
ts = pf.select_tradeperiod(ts, start, end, use_adj=True)
ts, start = pf.finalize_timeseries(ts, start)

# create tradelog and daily balance objects
tlog = pf.TradeLog(symbol)
dbal = pf.DailyBal()

In [4]:
ts


Out[4]:
high low open close volume adj_close
date
1993-01-29 26.20 26.07 26.20 26.18 1003200.00 26.18
1993-02-01 26.37 26.20 26.20 26.37 480500.00 26.37
1993-02-02 26.44 26.30 26.35 26.43 201300.00 26.43
1993-02-03 26.72 26.44 26.46 26.71 529400.00 26.71
1993-02-04 26.87 26.50 26.80 26.82 531500.00 26.82
... ... ... ... ... ... ...
2020-07-09 317.10 310.68 316.84 314.38 83354200.00 314.38
2020-07-10 317.88 312.76 314.31 317.59 57550400.00 317.59
2020-07-13 322.71 314.13 320.13 314.84 102997500.00 314.84
2020-07-14 319.76 312.00 313.30 318.92 93657000.00 318.92
2020-07-15 323.04 319.27 322.41 321.85 86896400.00 321.85

6915 rows × 6 columns

Algorithm


In [5]:
pf.TradeLog.cash = capital

# loop through timeseries
for i, row in enumerate(ts.itertuples()):

    date = row.Index.to_pydatetime()
    end_flag = pf.is_last_row(ts, i)

    # buy
    if tlog.shares == 0:
        tlog.buy(date, row.close)
    # sell
    elif end_flag:
        tlog.sell(date, row.close)

    # record daily balance
    dbal.append(date, row.high, row.low, row.close)

Retrieve logs


In [6]:
tlog = tlog.get_log()
dbal = dbal.get_log(tlog)

In [7]:
tlog.tail()


Out[7]:
entry_date entry_price exit_date exit_price pl_points pl_cash qty cumul_total direction symbol
0 1993-01-29 26.18 2020-07-15 321.85 295.67 112648.73 381 112648.73 LONG SPY

Get stats


In [8]:
stats = pf.stats(ts, tlog, dbal, capital)

Summary


In [9]:
pf.summary(stats)


Out[9]:
strategy
annual_return_rate 9.56
max_closed_out_drawdown -55.16
best_month 23.59
worst_month -30.98
sharpe_ratio 0.58
sortino_ratio 0.73
monthly_std 4.49

In [ ]: