This notebook provides the same code presented in the online tutorial available here however we have sweep_time=None
which allows closed PnL in JPY to accumulate, as seen below.
In [1]:
%pylab inline
import sys
sys.path.append("..")
from blotter import blotter
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
pd.options.display.max_rows = 10
blt = blotter.Blotter(
prices="../doc/data/prices",
interest_rates="../doc/data/daily_interest_rates.csv",
accrual_time=pd.Timedelta(16, unit="h"),
eod_time=pd.Timedelta(16, unit="h"),
sweep_time=None,
base_ccy="USD",
margin_charge=0.015
)
blt.connect_market_data()
In [2]:
blt.define_generic("AUDUSD", ccy="USD", margin=0, multiplier=1,
commission=2.5, isFX=True)
blt.define_generic("USDJPY", ccy="JPY", margin=0, multiplier=1,
commission=2.5, isFX=True)
blt.map_instrument(generic="AUDUSD", instrument="AUDUSD")
blt.map_instrument("USDJPY", "USDJPY")
blt.define_generic("CL", ccy="USD", margin=0.1, multiplier=1000,
commission=2.5, isFX=False)
blt.map_instrument("CL", "CLZ2008")
In [3]:
crude = pd.read_csv("../doc/data/prices/CLZ2008.csv", parse_dates=True, index_col=0)
aud = pd.read_csv("../doc/data/prices/AUDUSD.csv", parse_dates=True, index_col=0)
jpy = pd.read_csv("../doc/data/prices/USDJPY.csv", parse_dates=True, index_col=0)
In [4]:
timestamps = pd.date_range("2008-01-02", "2008-05-27", freq="b")
timestamps = timestamps + pd.Timedelta("16h")
timestamps = (timestamps.intersection(crude.index)
.intersection(aud.index).intersection(jpy.index))
ts = timestamps[0]
blt.trade(ts, "CLZ2008", 10, float(crude.loc[ts]))
aud_alpha = np.sign(np.log(aud / aud.shift(5))).fillna(value=0)
jpy_alpha = np.sign(np.log(jpy / jpy.shift(5))).fillna(value=0)
signal = pd.concat([aud_alpha, jpy_alpha], axis=1)
signal.columns = ["AUDUSD", "USDJPY"]
signal.plot(title="Alphas", figsize=(12, 8))
Out[4]:
In [5]:
signal.tail()
Out[5]:
In [6]:
def calc_trade(position, alpha):
if position.empty:
return alpha
else:
return alpha*1000000 - position
In [7]:
for ts in timestamps:
pos = blt.get_instruments()
pos = pos.drop("CLZ2008")
trds = calc_trade(pos, signal.loc[ts,:])
aud_qty = float(trds.loc["AUDUSD"])
aud_price = float(aud.loc[ts])
jpy_qty = float(trds.loc["USDJPY"])
jpy_price = float(jpy.loc[ts])
blt.trade(ts, "AUDUSD", aud_qty, aud_price)
blt.trade(ts, "USDJPY", jpy_qty, jpy_price)
In [8]:
blt.get_instruments()
Out[8]:
In [9]:
ts = pd.Timestamp("2008-05-28T16:00:00")
blt.get_holdings_value(ts)
Out[9]:
In [10]:
prices = {"AUDUSD": aud, "USDJPY": jpy, "CLZ2008": crude}
instrs = blt.get_instruments()
for instr, qty in instrs.iteritems():
price = float(prices[instr].loc[ts])
blt.trade(ts, instr, -qty, price)
In [11]:
blt.get_holdings_history()
Out[11]:
In [12]:
ts = pd.Timestamp("2008-05-29T16:00:00")
blt.automatic_events(ts)
In [13]:
pnls = blt.get_pnl_history()
pnls
pnls["USD"].plot(title="USD PnL", figsize=(12, 8))
pnls["JPY"].plot(title="JPY PnL", figsize=(12, 8))
Out[13]:
In [14]:
blt.event_log[-10:]
Out[14]: