Pages

jeudi 20 juin 2013

Backtesting: Cleaning up the code


In the previous post we tried to see the same strategy either on a monthly basis, when positions are closed or on a daily basis try to see how the trade evolves while open.

There was some code repeated for many variations of a strategy so I regrouped it in a function:


def generatePL(port):
    port = port.fillna(0.0)
    port = port.shift(1).resample(freq,how='first')
    port_rets = (port * returns).sum(axis=1)+collat
    #generate daily weigths for m2m
    port2=port.shift(-1).resample('D').shift().fillna(method='ffill').resample('B',how='first')
    port_rets2=(port2*daily_cumrets).sum(axis=1)+collat_cumrets
    port_rets2 = port_rets2.fillna(0.0)
    port_rets_d=(1+port_rets2).pct_change()
    dr=port_rets_d.resample(freq).index[:-1]+BDay()
    port_rets_d[dr]=(port2.loc[dr]*daily_rets.loc[dr]).sum(axis=1)+collat_d.loc[dr]

    return(port_rets,port_rets_d)

The way the daily weights are recalculated from the monthly ones has changed a little because there was a mismatch when the last day of the month wasn't a business day. It is now working perfectly.

Now to simulate a strategy, one need the function to get the weights (as I posted in the previous post) and that one.

The code looks like that:

(port_rets,port_rets_d)=generatePL(uniform_weight(px))
results['Uniform']= port_rets
results_d['Uniform']= port_rets_d

One should also keep in mind that futures are daily cash settled and we should earn interest on the cash generated during the month. Given that average monthly returns are less than 1% on average, interest in these can safely be neglected in our case.

One can probably improve the strategy further. Either changing the trading frequency (why one month, maybe 1 week works better), adding filters (maybe we want to go all cash when the average volatility is too high) or combining with different strategy less correlated (combining basis indicator with momentum indicator should work as both strategy are well documented).
Our strategy doesn't evolve many parameters that can be changed but still one should be careful when optimizing.
Assume a given strategy doesn't really work, if there is many parameters that can be tuned, we will find a set of parameters less bad than others on a given time period. Maybe the strategy will even be profitable with these but the chance it will work in the future is slim.
We can't know for sure we are not in that case but if the strategy seem to work with many parameters, it is more likely that it will continue to work.

2 commentaires:

  1. Commodity market fluctuations depends upon the global market activities.The best solution will be Provided by us only.
    http://commodityonlinetips.in

    RépondreSupprimer
  2. There are many factor influencing the trade outcome.
    http://100mcxtips.in

    RépondreSupprimer