import pandas as pd
from datetime import datetime, timezone
import pytz
from zipline import TradingAlgorithm
# from zipline.utils.factory import load_bars_from_yahoo
from zipline.api import symbols, order, sid, history, get_open_orders
from fintools.get_DataArray import get_DataArray
start = datetime(2010, 1, 1, 0, 0, 0, 0, pytz.utc)
end = datetime.today().replace(tzinfo=timezone.utc)
assets = ['TLT','SPY']
da = get_DataArray(assets, start, end)
data = da.to_pandas().transpose(1,2,0)
def initialize(context):
context.stocks = symbols('TLT', 'SPY')
print ('STOCKS = \n\n{}'.format(context.stocks))
context.count = 0
def handle_data(context,data):
# note alternative ways of ordering
if context.count == 0:
for security in data:
print ('\n\nSECURITY = {}\n\nDATA = \n\n{}'.format((security, sid(security)), data[security]))
order (sid(security), 1)
df = data.history(context.stocks, 'close', 1, '1d')
print ('\n\nHISTORY\n\n{}\n\nPOSITIONS\n'.format(df))
order (context.stocks[0], 2)
order (context.stocks[1], 3)
order (sid(df.columns[0]), 5)
order (sid(df.columns[1]), 10)
context.count += 1
if context.count < 3:
print (get_open_orders().items)
print ('\n{}'.format(context.portfolio.positions))
pass
algo_obj = TradingAlgorithm(initialize=initialize,
handle_data=handle_data)
# Run algorithm
perf_manual = algo_obj.run(data)