In [1]:
import sys
import os

sys.path.append(os.path.abspath("../.."))

In [2]:
from pythonbacktest.datafeed import CSVDataFeed
from pythonbacktest.backtestengine import BasicBackTestEngine
from pythonbacktest.strategy import import_strategy
from pythonbacktest.broker import BackTestBroker
from pythonbacktest.tradelog import MemoryTradeLog
from pythonbacktest.charting import BokehChartRenderer
from pythonbacktest.indicator import IndicatorHistory
from pythonbacktest.animation import IndicatorsHistoryAnimation
from bokeh.io import output_notebook
from datetime import date
from IPython.display import HTML, display

# need this to set a playground for bokeh
output_notebook()


Loading BokehJS ...

In [3]:
TEST_DATA_PATH = os.path.abspath("../testdata/ACME")
INITIAL_BUDGET = 100000
DATE_TO_ANALYSIS = date(2016,1,2)

csv_data_feed = CSVDataFeed()
csv_data_feed.load_data(TEST_DATA_PATH)

trade_log = MemoryTradeLog()

broker = BackTestBroker(INITIAL_BUDGET, trade_log=trade_log, commision=1.0)

In [4]:
indicator_history = IndicatorHistory()

In [5]:
strategy_module = import_strategy(
    "basicSMAstrategy",
    os.path.abspath("basicsmastrategy.py"))

strategy = strategy_module.BasicSMAStrategy()

back_test_engine = BasicBackTestEngine(csv_data_feed, strategy, broker, indicator_history)
back_test_engine.start()

In [6]:
# testing done - let's display the final budget
print "Free cash: %s\n" % broker.free_cash

# print 5 last transactions
for transaction in trade_log.all_transactions[-6:-1]:
    print "[%s] - %s@%s, remaining cash: %s" % \
          (transaction.timestamp, transaction.transaction_type,
           transaction.transaction_price_per_share, transaction.cash_after)


Free cash: 99933.0

[2016-01-02 20:02:50] - BUY@45.93, remaining cash: 95352.0
[2016-01-02 20:13:10] - SELL@45.89, remaining cash: 99940.0
[2016-01-02 20:16:10] - BUY@45.97, remaining cash: 95342.0
[2016-01-02 20:29:05] - SELL@45.96, remaining cash: 99937.0
[2016-01-02 20:44:10] - BUY@45.97, remaining cash: 95339.0

In [ ]:
all_indicators = back_test_engine.all_indicators_per_day
indicators_per_day = all_indicators[DATE_TO_ANALYSIS]

indicators_to_display = [('close', 'gray'),
                        ('SMA200', 'blue'), 
                        ('SMA50', 'orange')]

volume_indicators = [('volume', 'red')]

bokeh_renderer = BokehChartRenderer()
bokeh_renderer.render_indicators(indicators_per_day, ['trade_buy', 'trade_sell'],
                                 indicators_to_display,
                                    volume_indicators)



In [ ]:
# let's introduce an animation
indicators_animation = IndicatorsHistoryAnimation(indicator_history, DATE_TO_ANALYSIS, 
                                                  canvassize=(10,10),
                                                  markers=['trade_buy', 'trade_sell'], 
                                                  indicators=[indicators_to_display, volume_indicators])
indicators_animation.start_animation()

In [ ]: