In [1]:
import pandas as pd
import tradingWithPython as twp
assert twp.__version__ >= '0.0.12' , 'Please update your twp module '
# create example signals for demonstrating backterster functionality
price = pd.Series(arange(10)) # price, just a linear incrementing series
signal = pd.Series(index=price.index) # strategy signal, in $
signal[2] = 100 # go long 100$
signal[3] = 0 # exit
signal[6] = -100 # go short 100$
signal[8] = 0 # exit
pd.DataFrame({'price':price,'signal':signal}) # show price and signal as a table.
Out[1]:
In [2]:
# use price and signal to perform a backtest
bt = twp.Backtest(price,signal) # create class, simulate
bt.plotTrades() # plot price and trades (short=red markers, long=green markers)
figure()
bt.pnl.plot(style='x-') # plot pnl
title('pnl')
print 'Sharpe: ', bt.sharpe
# normally, daily change in shares (delta) is not included in the Backtest.data .
# Sometimes it is handy to have it, for adding transaction cost for example.
# You can easily add it :
bt.data['delta'] = bt.data['shares'].diff().fillna(0)
bt.data # output strategy data
Out[2]:
In [3]:
# start with getting some data to test on
import tradingWithPython.lib.yahooFinance as yahoo # yahoo finance module
price = yahoo.getHistoricData('SPY')['adj_close'][-2000:]
price.plot()
Out[3]:
In [5]:
figsize(10,6)
# sumulate two trades
signal = pd.Series(index=price.index) #init signal series
# while setting values this way, make sure that the dates are actually in the index
signal[pd.datetime(2008,1,3)] = -10000 # go short
signal[pd.datetime(2009,1,5)] = 10000 # go long 10k$ on this day
signal[pd.datetime(2013,1,8)] = 0 # close position
bt = twp.Backtest(price,signal,initialCash=0)
bt.plotTrades()
figure()
bt.pnl.plot()
title('pnl')
figure()
bt.data.plot()
title('all strategy data')
Out[5]:
'Data Mining & R' 카테고리의 다른 글
quantiacs : algorithmic trading competition (0) | 2016.05.10 |
---|---|
Trading VXX with nearest neighbors prediction (0) | 2016.05.10 |
AN INTRODUCTION TO BACKTESTING WITH PYTHON AND PANDAS (0) | 2016.05.09 |
오피니언마이닝에 기반한 주식 매매 시그널 - opinion mining, social mining (0) | 2016.05.04 |
sample ) 주가예측 프로그램 (0) | 2016.04.27 |