Skip to content

Commit

Permalink
fixes #21
Browse files Browse the repository at this point in the history
  • Loading branch information
timkpaine committed May 29, 2019
1 parent b64e3d1 commit 5312090
Show file tree
Hide file tree
Showing 8 changed files with 69 additions and 31 deletions.
2 changes: 1 addition & 1 deletion aat/backtest.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def run(self, engine) -> None:
self.receive(line_to_data(row))
log.info('Backtest done, running analysis.')

self.callback(TickType.ANALYZE, engine.portfolio_value(), engine.query().query_tradereqs(), engine.query().query_traderesps())
self.callback(TickType.ANALYZE, engine)
log.info('Analysis completed.')

def receive(self, data: MarketData) -> None:
Expand Down
11 changes: 8 additions & 3 deletions aat/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,14 @@ def query_exchanges(self) -> List[ExchangeType]:
return self._exchanges

def _paginate(self, instrument: Instrument, lst: list, lst_sub: list, page: int = 1)-> list:
from_ = -1*page*100
to_ = -1*(page-1)*100
if page is not None:
from_ = -1*page*100
to_ = -1*(page-1)*100
else:
# all results
page = 0
from_ = 0
to_ = -1

if instrument:
return lst_sub[instrument][from_:to_] \
Expand Down Expand Up @@ -95,7 +101,6 @@ def push(self, data: MarketData) -> None:
self._last_price_by_asset_and_exchange[data.instrument] = {}
self._last_price_by_asset_and_exchange[data.instrument][data.exchange] = data
self._last_price_by_asset_and_exchange[data.instrument]['ANY'] = data
print("here", self._last_price_by_asset_and_exchange[data.instrument][data.exchange])

def push_tradereq(self, req: TradeRequest) -> None:
self._trade_reqs.append(req)
Expand Down
16 changes: 15 additions & 1 deletion aat/risk.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from datetime import datetime
from .config import RiskConfig
from .structs import TradeRequest, TradeResponse, Instrument
from .enums import Side, TradeResult, OrderType, RiskReason, ExchangeType
Expand Down Expand Up @@ -28,9 +29,19 @@ def _constructResp(self,
order_type: OrderType,
vol: float,
price: float,
time: datetime,
status: bool,
reason: RiskReason) -> TradeRequest:
resp = TradeRequest(side=side, exchange=exchange, instrument=instrument, order_type=order_type, volume=vol, price=price, risk_check=status, risk_reason=reason)
resp = TradeRequest(side=side,
exchange=exchange,
instrument=instrument,
order_type=order_type,
volume=vol,
price=price,
time=time,
risk_check=status,
risk_reason=reason,
)

if status == TradeResult.FILLED: # FIXME
self.outstanding += abs(vol * price) * (1 if side == Side.BUY else -1)
Expand Down Expand Up @@ -59,6 +70,7 @@ def request(self, req: TradeRequest) -> TradeRequest:
order_type=req.order_type,
vol=req.volume,
price=req.price,
time=req.time,
status=True,
reason=RiskReason.NONE)

Expand All @@ -72,6 +84,7 @@ def request(self, req: TradeRequest) -> TradeRequest:
order_type=req.order_type,
vol=volume,
price=req.price,
time=req.time,
status=True,
reason=RiskReason.PARTIAL)

Expand All @@ -83,6 +96,7 @@ def request(self, req: TradeRequest) -> TradeRequest:
order_type=req.order_type,
vol=volume,
price=req.price,
time=req.time,
status=False,
reason=RiskReason.FULL)

Expand Down
21 changes: 4 additions & 17 deletions aat/strategies/backtest.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def onTrade(self, data: MarketData):
self.state = ''

if self.state == 'buy' and self.prev_state != 'buy' and \
self.bought == 0.0: # watch for floating point error
self.bought == 0.0: # watch for floating point error
req = TradeRequest(side=Side.BUY,
# buy between .2 and 1 BTC
volume=max(min(1.0, data.volume), .2),
Expand All @@ -104,24 +104,15 @@ def onTrade(self, data: MarketData):
def onError(self, e: MarketData):
elog.critical(e)

def onAnalyze(self, _):
def onAnalyze(self, portfolio_value, requests, responses) -> None:
import pandas
import matplotlib.pyplot as plt
import seaborn as sns

# pd = pandas.DataFrame(self._actions,
# columns=['time', 'action', 'price'])

pd = pandas.DataFrame(self._portfolio_value, columns=['time', 'value'])
pd = pandas.DataFrame(portfolio_value, columns=['time', 'value'])
pd.set_index(['time'], inplace=True)

print(self.size, pd.iloc[1].value, pd.iloc[-1].value)
# sp500 = pandas.DataFrame()
# tmp = pandas.read_csv('./data/sp/sp500_v_kraken.csv')
# sp500['Date'] = pandas.to_datetime(tmp['Date'])
# sp500['Close'] = tmp['Close']
# sp500.set_index(['Date'], inplace=True)
# print(sp500)

sns.set_style('darkgrid')
fig, ax1 = plt.subplots()
Expand All @@ -131,13 +122,9 @@ def onAnalyze(self, _):

ax1.set_ylabel('Portfolio value($)')
ax1.set_xlabel('Date')
for xy in [self._portfolio_value[0]] + [self._portfolio_value[-1]]:
for xy in [portfolio_value[0]] + [portfolio_value[-1]]:
ax1.annotate('$%s' % xy[1], xy=xy, textcoords='data')

# ax2 = ax1.twinx()
# ax2.plot(sp500, 'r')
# ax2.set_ylabel('S&P500 ($)')

plt.show()

def onChange(self, data: MarketData) -> None:
Expand Down
43 changes: 39 additions & 4 deletions aat/strategies/buy_and_hold.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ def onTrade(self, data: MarketData) -> bool:
instrument=data.instrument,
order_type=OrderType.MARKET,
exchange=data.exchange,
price=data.price)
price=data.price,
time=data.time)
slog.info("requesting buy : %s", req)
self.requestBuy(self.onBuy, req)
return True
Expand All @@ -33,25 +34,59 @@ def onTrade(self, data: MarketData) -> bool:
def onError(self, e) -> None:
elog.critical(e)

def onAnalyze(self, portfolio_value, requests, responses) -> None:
def onAnalyze(self, engine) -> None:
import pandas
import matplotlib.pyplot as plt
import seaborn as sns

portfolio_value = engine.portfolio_value()
requests = engine.query().query_tradereqs()
responses = engine.query().query_traderesps()
trades = pandas.DataFrame([{'time': x.time, 'price': x.price} for x in engine.query().query_trades(instrument=requests[0].instrument, page=None)])
trades.set_index(['time'], inplace=True)

pd = pandas.DataFrame(portfolio_value, columns=['time', 'value'])
pd.set_index(['time'], inplace=True)

sns.set_style('darkgrid')
fig, ax1 = plt.subplots()
fig = plt.figure(figsize=(5, 8))
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

plt.title('BTC algo 1 performance')
ax1.plot(pd)

ax1.set_title('Performance')
ax1.set_ylabel('Portfolio value($)')
ax1.set_xlabel('Date')
for xy in [portfolio_value[0]] + [portfolio_value[-1]]:
ax1.annotate('$%s' % xy[1], xy=xy, textcoords='data')
ax2.annotate('$%s' % xy[1], xy=xy, textcoords='data')

ax2.set_title('Trades')
ax2.set_ylabel('Intent/Action')
ax2.set_xlabel('Date')

ax2.plot([x.time for x in requests if x.side == Side.BUY],
[x.price for x in requests if x.side == Side.BUY],
'2', color='y')
ax2.plot([x.time for x in requests if x.side == Side.SELL],
[x.price for x in requests if x.side == Side.SELL],
'1', color='y')
ax2.plot([x.time for x in responses if x.side == Side.BUY], # FIXME
[x.price for x in responses if x.side == Side.BUY],
'^', color='g')
ax2.plot([x.time for x in responses if x.side == Side.SELL], # FIXME
[x.price for x in responses if x.side == Side.SELL],
'v', color='r')
ax2.plot(trades)

y_bot, y_top = ax1.get_ylim()
x_bot, x_top = ax1.get_xlim()
ax2.set_ylim(y_bot, y_top)
ax2.set_xlim(x_bot, x_top)

plt.show()

print(requests)
print(responses)

Expand Down
4 changes: 2 additions & 2 deletions aat/structs.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ class TradeRequest:
order_type = OrderType
order_sub_type = OrderSubType, OrderSubType.NONE

time = datetime.datetime, datetime.datetime.now() # FIXME
time = datetime.datetime
risk_check = bool, False
risk_reason = RiskReason, RiskReason.NONE

Expand All @@ -156,7 +156,7 @@ class TradeResponse:
slippage = float, 0.0
transaction_cost = float, 0.0

time = datetime.datetime, datetime.datetime.now() # FIXME
time = datetime.datetime
status = TradeResult
order_id = str
remaining = float, 0.0
Expand Down
2 changes: 0 additions & 2 deletions aat/trading.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,6 @@ def recalculate_value(self, data: MarketData) -> None:
# self._portfolio_value = [[data.time, self._rk.total_funds]]
self._portfolio_value = [[data.time, volume*data.price]]
self._portfolio_value.append([data.time, volume*data.price])
print(f'\n{volume} {data.price} {volume*data.price} {data.time}\n')

def update_holdings(self, resp: TradeResponse) -> None:
# TODO move to risk
Expand Down Expand Up @@ -219,7 +218,6 @@ def _request(self,
req: TradeRequest,
callback_failure=None,
strat=None):
print('requesting!')
self.query().push_tradereq(req)
if not self._trading:
# not allowed to trade right now
Expand Down
1 change: 0 additions & 1 deletion aat/ui/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ def __init__(self,
for route, handler, h_kwargs in extra_handlers:
if 'trading_engine' in h_kwargs:
h_kwargs['trading_engine'] = trading_engine
print(extra_handlers)

super(ServerApplication, self).__init__(
extra_handlers + [
Expand Down

0 comments on commit 5312090

Please sign in to comment.