The first backtesting program written in Python

Source: Internet
Author: User
Tags assert

The first backtesting program written in Python

2016-08-06

1 defSavfig (Figureobj, fn_prefix1='Backtest8', fn_prefix2='_1_'):2     Importdatetime3fmt='%y_%m_%d_%h_%m_%s'4now =Datetime.datetime.now ()5Fname_savfig = fn_prefix1 + fn_prefix2 + now.strftime (FMT) +'. PNG'6Figureobj.savefig (Fname_savfig, facecolor=Fig.get_facecolor ())7 8 9 defBacktest8 (OHLC=OHLC, sd=1.0, n_short=2, n_long=20, f_savfig=False):TenU" " One Double Moving Averages strategy backtesting function A Signature:backtest8 (OHLC=OHLC, sd=1.0, n_short=2, n_long=20, F_savfig=false) - param:: - OHLC-DOHLCVA data, dataframe structure of the the sd-ma1/ma2 > SD trigger long-buy fast moving average/slow moving average threshold - f_savefig-flag for saving matplot output figures -      -      +      -     " " +     Importmatplotlib A     #import Seaborn as SNS at     #sns.set_style (' white ') -      -Myfontprops =Matplotlib.font_manager. Fontproperties ( -Fname='C:/windows/fonts/msyh.ttf')#Microsoft Ya-Black -                          -Mashort =PD. Series.rolling (OHLC. C, N_short). Mean () inMalong =PD. Series.rolling (OHLC. C, N_long). Mean () -  to      +Fig=plt.figure ()#Create new figure -Ohlc. C.plot (Grid=true, figsize= (8,4)) theMashort.plot (label='MA'+str (n_short)) *Malong.plot (grid=true,label='MA'+str (n_long)) $ #Ohlc.iloc[:,[0,1,2,3]].plot (Grid=false, figsize= (8,4))Panax Notoginseng #Ohlc.iloc[:,[0,1,2,3]].plot (grid=true,figsize= (8,4)) -Plt.legend (loc=' Best') thePlt.title (s=u'Historical share price', fontproperties=myfontprops) +     ifF_savfig: ASavfig (Fig,'Backtest8','_0_') the          + #sd=1.0 -Regime = Np.where (Mashort/malong > SD, 1, 0) $Regime = PD. Series (Regime, index=Mashort.index) $     Print('regime Length =%s'%regime.size) -          -Fig=plt.figure ()#Create new figure theRegime[:].plot (lw=1.5, ylim= ( -0.1, 1.1), figsize= (8,4), Title=u'regime') -     ifF_savfig:WuyiSavfig (Fig,'Backtest8','_1_') the          -Fig=plt.figure ()#Create new figure WuRegime[-100:].plot (lw=1.5, ylim= ( -0.1, 1.1), figsize= (8,4), Title=u'regime') -     ifF_savfig: AboutSavfig (Fig,'Backtest8','_2_') $      -      -      -PP_RATIO_BNH = Np.log (OHLC. C/OHLC. C.shift (1) ) APp_ratio_strategy = Regime.shift (1) *PP_RATIO_BNH +     #In the end, we sum up the daily yield and get the final cumulative rate of return . the     #(This is because we are using an exponential yield, so it is reasonable to accumulate the daily earnings), -     #This cumulative process can also be done easily with Dataframe's built-in function Cumsum: $NORM_RETURN_BNH =pp_ratio_bnh. Cumsum (). Apply (NP.EXP) theNorm_return_strategy =pp_ratio_strategy.cumsum (). Apply (NP.EXP) the      theFig=plt.figure ()#Create a new figure theNorm_return_strategy. Plot (lw=1.5, figsize= (8,4), Label=u'Strategy') -Norm_return_bnh. Plot (lw=1.5, label=u'BnH') in      thePlt.legend (loc=' Best') thePlt.title (s=u'strategic yield vs. historical price', fontproperties=myfontprops) About     ifF_savfig: theSavfig (Fig,'Backtest8','_3_') the      the     assert(Regime.index = = OHLC. C.index). All () ==true#' signal index not equals price index ' +     #assert is used to determine whether a statement is true or FALSE, and if false it will trigger a assertionerror error, an expression that prompts the developer for an error -     returnNorm_return_strategy, N_short, N_long, SD

Result diagram: There are four, mainly for the purpose of quality control.

1. Historical price

2. Trading Signals

3. A subset of the 2nd, zoom in to see clearly, technical indicators timing model details (how to trigger trading signals)

4. Rate of return on the strategy

Follow-up additions:

    1. Encapsulation into class

    2. Add a Performance strategy indicator: a whole bunch of stuff.
    3. Adding optimizations

    4. Perfect drawing program, intelligently Select input (data_obj, param, **kwargs)

The first backtesting program written in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.