desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Plots the curve of rolling Sharpe ratio.'
| def _plot_rolling_sharpe(self, stats, ax=None, **kwargs):
| def format_two_dec(x, pos):
return ('%.2f' % x)
sharpe = stats['rolling_sharpe']
if (ax is None):
ax = plt.gca()
y_axis_formatter = FuncFormatter(format_two_dec)
ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))
ax.xaxis.set_tick_params(reset=True)
ax.yaxis.grid(l... |
'Plots the underwater curve'
| def _plot_drawdown(self, stats, ax=None, **kwargs):
| def format_perc(x, pos):
return ('%.0f%%' % x)
drawdown = stats['drawdowns']
if (ax is None):
ax = plt.gca()
y_axis_formatter = FuncFormatter(format_perc)
ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))
ax.yaxis.grid(linestyle=':')
ax.xaxis.set_tick_params(reset... |
'Plots a heatmap of the monthly returns.'
| def _plot_monthly_returns(self, stats, ax=None, **kwargs):
| returns = stats['returns']
if (ax is None):
ax = plt.gca()
monthly_ret = perf.aggregate_returns(returns, 'monthly')
monthly_ret = monthly_ret.unstack()
monthly_ret = np.round(monthly_ret, 3)
monthly_ret.rename(columns={1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun', 7: 'Jul',... |
'Plots a barplot of returns by year.'
| def _plot_yearly_returns(self, stats, ax=None, **kwargs):
| def format_perc(x, pos):
return ('%.0f%%' % x)
returns = stats['returns']
if (ax is None):
ax = plt.gca()
y_axis_formatter = FuncFormatter(format_perc)
ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))
ax.yaxis.grid(linestyle=':')
yly_ret = (perf.aggregate_returns... |
'Outputs the statistics for the equity curve.'
| def _plot_txt_curve(self, stats, ax=None, **kwargs):
| def format_perc(x, pos):
return ('%.0f%%' % x)
returns = stats['returns']
cum_returns = stats['cum_returns']
if ('positions' not in stats):
trd_yr = 0
else:
positions = stats['positions']
trd_yr = (positions.shape[0] / ((returns.index[(-1)] - returns.index[0]).days / ... |
'Outputs the statistics for the trades.'
| def _plot_txt_trade(self, stats, ax=None, **kwargs):
| def format_perc(x, pos):
return ('%.0f%%' % x)
if (ax is None):
ax = plt.gca()
if ('positions' not in stats):
num_trades = 0
win_pct = 'N/A'
win_pct_str = 'N/A'
avg_trd_pct = 'N/A'
avg_win_pct = 'N/A'
avg_loss_pct = 'N/A'
max_win_pct = ... |
'Outputs the statistics for various time frames.'
| def _plot_txt_time(self, stats, ax=None, **kwargs):
| def format_perc(x, pos):
return ('%.0f%%' % x)
returns = stats['returns']
if (ax is None):
ax = plt.gca()
y_axis_formatter = FuncFormatter(format_perc)
ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))
mly_ret = perf.aggregate_returns(returns, 'monthly')
yly_ret =... |
'Plot the Tearsheet'
| def plot_results(self, filename=None):
| rc = {'lines.linewidth': 1.0, 'axes.facecolor': '0.995', 'figure.facecolor': '0.97', 'font.family': 'serif', 'font.serif': 'Ubuntu', 'font.monospace': 'Ubuntu Mono', 'font.size': 10, 'axes.labelsize': 10, 'axes.labelweight': 'bold', 'axes.titlesize': 10, 'xtick.labelsize': 8, 'ytick.labelsize': 8, 'legend.fontsi... |
'Takes in a portfolio handler.'
| def __init__(self, config, portfolio_handler):
| self.config = config
self.drawdowns = [0]
self.equity = []
self.equity_returns = [0.0]
self.timeseries = ['0000-00-00 00:00:00']
current_equity = PriceParser.display(portfolio_handler.portfolio.equity)
self.hwm = [current_equity]
self.equity.append(current_equity)
|
'Update all statistics that must be tracked over time.'
| def update(self, timestamp, portfolio_handler):
| if (timestamp != self.timeseries[(-1)]):
current_equity = PriceParser.display(portfolio_handler.portfolio.equity)
self.equity.append(current_equity)
self.timeseries.append(timestamp)
pct = (((self.equity[(-1)] - self.equity[(-2)]) / self.equity[(-1)]) * 100)
self.equity_retur... |
'Return a dict with all important results & stats.'
| def get_results(self):
| timeseries = self.timeseries
timeseries[0] = (pd.to_datetime(timeseries[1]) - pd.Timedelta(days=1))
statistics = {}
statistics['sharpe'] = self.calculate_sharpe()
statistics['drawdowns'] = pd.Series(self.drawdowns, index=timeseries)
statistics['max_drawdown'] = max(self.drawdowns)
statistics... |
'Calculate the sharpe ratio of our equity_returns.
Expects benchmark_return to be, for example, 0.01 for 1%'
| def calculate_sharpe(self, benchmark_return=0.0):
| excess_returns = (pd.Series(self.equity_returns) - (benchmark_return / 252))
return round(self.annualised_sharpe(excess_returns), 4)
|
'Calculate the annualised Sharpe ratio of a returns stream
based on a number of trading periods, N. N defaults to 252,
which then assumes a stream of daily returns.
The function assumes that the returns are the excess of
those compared to a benchmark.'
| def annualised_sharpe(self, returns, N=252):
| return ((np.sqrt(N) * returns.mean()) / returns.std())
|
'Calculate the percentage drop related to the "worst"
drawdown seen.'
| def calculate_max_drawdown_pct(self):
| drawdown_series = pd.Series(self.drawdowns)
equity_series = pd.Series(self.equity)
bottom_index = drawdown_series.idxmax()
try:
top_index = equity_series[:bottom_index].idxmax()
pct = (((equity_series.ix[top_index] - equity_series.ix[bottom_index]) / equity_series.ix[top_index]) * 100)
... |
'A simple script to plot the balance of the portfolio, or
"equity curve", as a function of time.'
| def plot_results(self):
| sns.set_palette('deep', desat=0.6)
sns.set_context(rc={'figure.figsize': (8, 4)})
fig = plt.figure()
fig.patch.set_facecolor('white')
df = pd.DataFrame()
df['equity'] = pd.Series(self.equity, index=self.timeseries)
df['equity_returns'] = pd.Series(self.equity_returns, index=self.timeseries)
... |
'Takes the CSV directory, the events queue and a possible
list of initial ticker symbols, then creates an (optional)
list of ticker subscriptions and associated prices.'
| def __init__(self, csv_dir, events_queue, init_tickers=None):
| self.csv_dir = csv_dir
self.events_queue = events_queue
self.continue_backtest = True
self.tickers = {}
self.tickers_data = {}
if (init_tickers is not None):
for ticker in init_tickers:
self.subscribe_ticker(ticker)
self.tick_stream = self._merge_sort_ticker_data()
|
'Opens the CSV files containing the equities ticks from
the specified CSV data directory, converting them into
them into a pandas DataFrame, stored in a dictionary.'
| def _open_ticker_price_csv(self, ticker):
| ticker_path = os.path.join(self.csv_dir, ('%s.csv' % ticker))
self.tickers_data[ticker] = pd.io.parsers.read_csv(ticker_path, header=0, parse_dates=True, dayfirst=True, index_col=1, names=('Ticker', 'Time', 'Bid', 'Ask'))
|
'Concatenates all of the separate equities DataFrames
into a single DataFrame that is time ordered, allowing tick
data events to be added to the queue in a chronological fashion.
Note that this is an idealised situation, utilised solely for
backtesting. In live trading ticks may arrive "out of order".'
| def _merge_sort_ticker_data(self):
| return pd.concat(self.tickers_data.values()).sort_index().iterrows()
|
'Subscribes the price handler to a new ticker symbol.'
| def subscribe_ticker(self, ticker):
| if (ticker not in self.tickers):
try:
self._open_ticker_price_csv(ticker)
dft = self.tickers_data[ticker]
row0 = dft.iloc[0]
ticker_prices = {'bid': PriceParser.parse(row0['Bid']), 'ask': PriceParser.parse(row0['Ask']), 'timestamp': dft.index[0]}
s... |
'Obtain all elements of the bar a row of dataframe
and return a TickEvent'
| def _create_event(self, index, ticker, row):
| bid = PriceParser.parse(row['Bid'])
ask = PriceParser.parse(row['Ask'])
tev = TickEvent(ticker, index, bid, ask)
return tev
|
'Place the next TickEvent onto the event queue.'
| def stream_next(self):
| try:
(index, row) = next(self.tick_stream)
except StopIteration:
self.continue_backtest = False
return
ticker = row['Ticker']
tev = self._create_event(index, ticker, row)
self._store_event(tev)
self.events_queue.put(tev)
|
'Unsubscribes the price handler from a current ticker symbol.'
| def unsubscribe_ticker(self, ticker):
| try:
self.tickers.pop(ticker, None)
self.tickers_data.pop(ticker, None)
except KeyError:
print(('Could not unsubscribe ticker %s as it was never subscribed.' % ticker))
|
'Returns the most recent actual timestamp for a given ticker'
| def get_last_timestamp(self, ticker):
| if (ticker in self.tickers):
timestamp = self.tickers[ticker]['timestamp']
return timestamp
else:
print(('Timestamp for ticker %s is not available from the %s.' % (ticker, self.__class__.__name__)))
return None
|
'Store price event for bid/ask'
| def _store_event(self, event):
| ticker = event.ticker
self.tickers[ticker]['bid'] = event.bid
self.tickers[ticker]['ask'] = event.ask
self.tickers[ticker]['timestamp'] = event.time
|
'Returns the most recent bid/ask price for a ticker.'
| def get_best_bid_ask(self, ticker):
| if (ticker in self.tickers):
bid = self.tickers[ticker]['bid']
ask = self.tickers[ticker]['ask']
return (bid, ask)
else:
print(('Bid/ask values for ticker %s are not available from the PriceHandler.' % ticker))
return (None, None)
|
'Store price event for closing price and adjusted closing price'
| def _store_event(self, event):
| ticker = event.ticker
self.tickers[ticker]['close'] = event.close_price
self.tickers[ticker]['adj_close'] = event.adj_close_price
self.tickers[ticker]['timestamp'] = event.time
|
'Returns the most recent actual (unadjusted) closing price.'
| def get_last_close(self, ticker):
| if (ticker in self.tickers):
close_price = self.tickers[ticker]['close']
return close_price
else:
print('Close price for ticker %s is not available from the YahooDailyBarPriceHandler.')
return None
|
'Takes the CSV directory, the events queue and a possible
list of initial ticker symbols then creates an (optional)
list of ticker subscriptions and associated prices.'
| def __init__(self, csv_dir, events_queue, init_tickers=None, start_date=None, end_date=None):
| self.csv_dir = csv_dir
self.events_queue = events_queue
self.continue_backtest = True
self.tickers = {}
self.tickers_data = {}
if (init_tickers is not None):
for ticker in init_tickers:
self.subscribe_ticker(ticker)
self.start_date = start_date
self.end_date = end_dat... |
'Opens the CSV files containing the equities ticks from
the specified CSV data directory, converting them into
them into a pandas DataFrame, stored in a dictionary.'
| def _open_ticker_price_csv(self, ticker):
| ticker_path = os.path.join(self.csv_dir, ('%s.csv' % ticker))
self.tickers_data[ticker] = pd.read_csv(ticker_path, names=['Date', 'Open', 'Low', 'High', 'Close', 'Volume', 'OpenInterest'], index_col='Date', parse_dates=True)
self.tickers_data[ticker]['Ticker'] = ticker
|
'Concatenates all of the separate equities DataFrames
into a single DataFrame that is time ordered, allowing tick
data events to be added to the queue in a chronological fashion.
Note that this is an idealised situation, utilised solely for
backtesting. In live trading ticks may arrive "out of order".'
| def _merge_sort_ticker_data(self):
| df = pd.concat(self.tickers_data.values()).sort_index()
start = None
end = None
if (self.start_date is not None):
start = df.index.searchsorted(self.start_date)
if (self.end_date is not None):
end = df.index.searchsorted(self.end_date)
if ((start is None) and (end is None)):
... |
'Subscribes the price handler to a new ticker symbol.'
| def subscribe_ticker(self, ticker):
| if (ticker not in self.tickers):
try:
self._open_ticker_price_csv(ticker)
dft = self.tickers_data[ticker]
row0 = dft.iloc[0]
close = PriceParser.parse(row0['Close'])
ticker_prices = {'close': close, 'adj_close': close, 'timestamp': dft.index[0]}
... |
'Obtain all elements of the bar from a row of dataframe
and return a BarEvent'
| def _create_event(self, index, period, ticker, row):
| open_price = PriceParser.parse(row['Open'])
low_price = PriceParser.parse(row['Low'])
high_price = PriceParser.parse(row['High'])
close_price = PriceParser.parse(row['Close'])
adj_close_price = PriceParser.parse(row['Close'])
volume = int(row['Volume'])
bev = BarEvent(ticker, index, period, ... |
'Place the next BarEvent onto the event queue.'
| def stream_next(self):
| try:
(index, row) = next(self.bar_stream)
except StopIteration:
self.continue_backtest = False
return
ticker = row['Ticker']
period = 60
bev = self._create_event(index, period, ticker, row)
self._store_event(bev)
self.events_queue.put(bev)
|
'Place the next PriceEvent (BarEvent or TickEvent) onto the event queue.'
| def stream_next(self):
| if (self.price_event is not None):
self._store_event(self.price_event)
self.events_queue.put(self.price_event)
self.price_event = None
|
'Takes the CSV directory, the events queue and a possible
list of initial ticker symbols then creates an (optional)
list of ticker subscriptions and associated prices.'
| def __init__(self, csv_dir, events_queue, init_tickers=None, start_date=None, end_date=None, calc_adj_returns=False):
| self.csv_dir = csv_dir
self.events_queue = events_queue
self.continue_backtest = True
self.tickers = {}
self.tickers_data = {}
if (init_tickers is not None):
for ticker in init_tickers:
self.subscribe_ticker(ticker)
self.start_date = start_date
self.end_date = end_dat... |
'Opens the CSV files containing the equities ticks from
the specified CSV data directory, converting them into
them into a pandas DataFrame, stored in a dictionary.'
| def _open_ticker_price_csv(self, ticker):
| ticker_path = os.path.join(self.csv_dir, ('%s.csv' % ticker))
self.tickers_data[ticker] = pd.io.parsers.read_csv(ticker_path, header=0, parse_dates=True, index_col=0, names=('Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close'))
self.tickers_data[ticker]['Ticker'] = ticker
|
'Concatenates all of the separate equities DataFrames
into a single DataFrame that is time ordered, allowing tick
data events to be added to the queue in a chronological fashion.
Note that this is an idealised situation, utilised solely for
backtesting. In live trading ticks may arrive "out of order".'
| def _merge_sort_ticker_data(self):
| df = pd.concat(self.tickers_data.values()).sort_index()
start = None
end = None
if (self.start_date is not None):
start = df.index.searchsorted(self.start_date)
if (self.end_date is not None):
end = df.index.searchsorted(self.end_date)
df['colFromIndex'] = df.index
df = df.so... |
'Subscribes the price handler to a new ticker symbol.'
| def subscribe_ticker(self, ticker):
| if (ticker not in self.tickers):
try:
self._open_ticker_price_csv(ticker)
dft = self.tickers_data[ticker]
row0 = dft.iloc[0]
close = PriceParser.parse(row0['Close'])
adj_close = PriceParser.parse(row0['Adj Close'])
ticker_prices = {'... |
'Obtain all elements of the bar from a row of dataframe
and return a BarEvent'
| def _create_event(self, index, period, ticker, row):
| open_price = PriceParser.parse(row['Open'])
high_price = PriceParser.parse(row['High'])
low_price = PriceParser.parse(row['Low'])
close_price = PriceParser.parse(row['Close'])
adj_close_price = PriceParser.parse(row['Adj Close'])
volume = int(row['Volume'])
bev = BarEvent(ticker, index, p... |
'Store price event for closing price and adjusted closing price'
| def _store_event(self, event):
| ticker = event.ticker
if self.calc_adj_returns:
prev_adj_close = (self.tickers[ticker]['adj_close'] / float(PriceParser.PRICE_MULTIPLIER))
cur_adj_close = (event.adj_close_price / float(PriceParser.PRICE_MULTIPLIER))
self.tickers[ticker]['adj_close_ret'] = ((cur_adj_close / prev_adj_clos... |
'Place the next BarEvent onto the event queue.'
| def stream_next(self):
| try:
(index, row) = next(self.bar_stream)
except StopIteration:
self.continue_backtest = False
return
ticker = row['Ticker']
period = 86400
bev = self._create_event(index, period, ticker, row)
self._store_event(bev)
self.events_queue.put(bev)
|
'Place the next PriceEvent (BarEvent or TickEvent) onto the event queue.'
| def stream_next(self):
| try:
price_event = next(self.price_event_iterator)
except StopIteration:
self.continue_backtest = False
return
except (EmptyTickEvent, EmptyBarEvent):
return
self._store_event(price_event)
self.events_queue.put(price_event)
|
'Obtain all elements of the bar from a row of dataframe
and return a BarEvent'
| def _create_event(self, index, period, ticker, row):
| try:
open_price = PriceParser.parse(row['Open'])
high_price = PriceParser.parse(row['High'])
low_price = PriceParser.parse(row['Low'])
close_price = PriceParser.parse(row['Close'])
adj_close_price = PriceParser.parse(row['Adj Close'])
volume = int(row['Volume'])
... |
'Obtain all elements of the bar a row of dataframe
and return a TickEvent'
| def _create_event(self, index, ticker, row):
| try:
bid = PriceParser.parse(row['Bid'])
ask = PriceParser.parse(row['Ask'])
tev = TickEvent(ticker, index, bid, ask)
return tev
except ValueError:
raise EmptyTickEvent(("row %s %s %s can't be convert to TickEvent" % (index, ticker, row)))
|
'Takes the the events queue, ticker and Pandas DataFrame'
| def __init__(self, df, ticker):
| self.data = df
self.ticker = ticker
self.tickers_lst = [ticker]
self._itr_bar = self.data.iterrows()
|
'Takes the the events queue, ticker and Pandas DataFrame'
| def __init__(self, df, period, ticker):
| self.data = df
self.period = period
self.ticker = ticker
self.tickers_lst = [ticker]
self._itr_bar = self.data.iterrows()
|
'This TestPositionSizer object simply modifies
the quantity to be 100 of any share transacted.'
| @abstractmethod
def size_order(self, portfolio, initial_order):
| raise NotImplementedError('Should implement size_order()')
|
'This NaivePositionSizer object follows all
suggestions from the initial order without
modification. Useful for testing simpler
strategies that do not reside in a larger
risk-managed portfolio.'
| def size_order(self, portfolio, initial_order):
| return initial_order
|
'This FixedPositionSizer object simply modifies
the quantity to be 100 of any share transacted.'
| def size_order(self, portfolio, initial_order):
| initial_order.quantity = self.default_quantity
return initial_order
|
'Size the order to reflect the dollar-weighting of the
current equity account size based on pre-specified
ticker weights.'
| def size_order(self, portfolio, initial_order):
| ticker = initial_order.ticker
if (initial_order.action == 'EXIT'):
cur_quantity = portfolio.positions[ticker].quantity
if (cur_quantity > 0):
initial_order.action = 'SLD'
initial_order.quantity = cur_quantity
else:
initial_order.action = 'BOT'
... |
'The PortfolioHandler is designed to interact with the
backtesting or live trading overall event-driven
architecture. It exposes two methods, on_signal and
on_fill, which handle how SignalEvent and FillEvent
objects are dealt with.
Each PortfolioHandler contains a Portfolio object,
which stores the actual Position obje... | def __init__(self, initial_cash, events_queue, price_handler, position_sizer, risk_manager):
| self.initial_cash = initial_cash
self.events_queue = events_queue
self.price_handler = price_handler
self.position_sizer = position_sizer
self.risk_manager = risk_manager
self.portfolio = Portfolio(price_handler, initial_cash)
|
'Take a SignalEvent object and use it to form a
SuggestedOrder object. These are not OrderEvent objects,
as they have yet to be sent to the RiskManager object.
At this stage they are simply "suggestions" that the
RiskManager will either verify, modify or eliminate.'
| def _create_order_from_signal(self, signal_event):
| if (signal_event.suggested_quantity is None):
quantity = 0
else:
quantity = signal_event.suggested_quantity
order = SuggestedOrder(signal_event.ticker, signal_event.action, quantity=quantity)
return order
|
'Once the RiskManager has verified, modified or eliminated
any order objects, they are placed onto the events queue,
to ultimately be executed by the ExecutionHandler.'
| def _place_orders_onto_queue(self, order_list):
| for order_event in order_list:
self.events_queue.put(order_event)
|
'Upon receipt of a FillEvent, the PortfolioHandler converts
the event into a transaction that gets stored in the Portfolio
object. This ensures that the broker and the local portfolio
are "in sync".
In addition, for backtesting purposes, the portfolio value can
be reasonably estimated in a realistic manner, simply by
m... | def _convert_fill_to_portfolio_update(self, fill_event):
| action = fill_event.action
ticker = fill_event.ticker
quantity = fill_event.quantity
price = fill_event.price
commission = fill_event.commission
self.portfolio.transact_position(action, ticker, quantity, price, commission)
|
'This is called by the backtester or live trading architecture
to form the initial orders from the SignalEvent.
These orders are sized by the PositionSizer object and then
sent to the RiskManager to verify, modify or eliminate.
Once received from the RiskManager they are converted into
full OrderEvent objects and sent ... | def on_signal(self, signal_event):
| initial_order = self._create_order_from_signal(signal_event)
sized_order = self.position_sizer.size_order(self.portfolio, initial_order)
order_events = self.risk_manager.refine_orders(self.portfolio, sized_order)
self._place_orders_onto_queue(order_events)
|
'This is called by the backtester or live trading architecture
to take a FillEvent and update the Portfolio object with new
or modified Positions.
In a backtesting environment these FillEvents will be simulated
by a model representing the execution, whereas in live trading
they will come directly from a brokerage (such... | def on_fill(self, fill_event):
| self._convert_fill_to_portfolio_update(fill_event)
|
'Update the portfolio to reflect current market value as
based on last bid/ask of each ticker.'
| def update_portfolio_value(self):
| self.portfolio._update_portfolio()
|
'Set up the backtest variables according to
what has been passed in.'
| def __init__(self, config, strategy, tickers, equity, start_date, end_date, events_queue, session_type='backtest', end_session_time=None, price_handler=None, portfolio_handler=None, compliance=None, position_sizer=None, execution_handler=None, risk_manager=None, statistics=None, sentiment_handler=None, title=None, benc... | self.config = config
self.strategy = strategy
self.tickers = tickers
self.equity = PriceParser.parse(equity)
self.start_date = start_date
self.end_date = end_date
self.events_queue = events_queue
self.price_handler = price_handler
self.portfolio_handler = portfolio_handler
self.c... |
'Initialises the necessary classes used
within the session.'
| def _config_session(self):
| if ((self.price_handler is None) and (self.session_type == 'backtest')):
self.price_handler = YahooDailyCsvBarPriceHandler(self.config.CSV_DATA_DIR, self.events_queue, self.tickers, start_date=self.start_date, end_date=self.end_date)
if (self.position_sizer is None):
self.position_sizer = FixedP... |
'Carries out an infinite while loop that polls the
events queue and directs each event to either the
strategy component of the execution handler. The
loop continue until the event queue has been
emptied.'
| def _run_session(self):
| if (self.session_type == 'backtest'):
print('Running Backtest...')
else:
print(('Running Realtime Session until %s' % self.end_session_time))
while self._continue_loop_condition():
try:
event = self.events_queue.get(False)
except queue.Empty:
... |
'Runs either a backtest or live session, and outputs performance when complete.'
| def start_trading(self, testing=False):
| self._run_session()
results = self.statistics.get_results()
print('---------------------------------')
print('Backtest complete.')
print(('Sharpe Ratio: %0.2f' % results['sharpe']))
print(('Max Drawdown: %0.2f%%' % (results['max_drawdown_pct'] * 100.0)))
if (not testing):
... |
'Purchase/sell multiple lots of AMZN, GOOG
at various prices/commissions to ensure
the arithmetic in calculating equity, drawdowns
and sharpe ratio is correct.'
| def test_calculating_statistics(self):
| price_handler = PriceHandlerMock()
self.portfolio = Portfolio(price_handler, PriceParser.parse(500000.0))
portfolio_handler = PortfolioHandlerMock(self.portfolio)
statistics = SimpleStatistics(self.config, portfolio_handler)
self.assertEqual(PriceParser.display(statistics.equity[0]), 500000.0)
s... |
'This PositionSizerMock object simply modifies
the quantity to be 100 of any share transacted.'
| def size_order(self, portfolio, initial_order):
| initial_order.quantity = 100
return initial_order
|
'This RiskManagerMock object simply lets the
sized order through, creates the corresponding
OrderEvent object and adds it to a list.'
| def refine_orders(self, portfolio, sized_order):
| order_event = OrderEvent(sized_order.ticker, sized_order.action, sized_order.quantity)
return [order_event]
|
'Set up the PortfolioHandler object supplying it with
$500,000.00 USD in initial cash.'
| def setUp(self):
| initial_cash = Decimal('500000.00')
events_queue = queue.Queue()
price_handler = PriceHandlerMock()
position_sizer = PositionSizerMock()
risk_manager = RiskManagerMock()
self.portfolio_handler = PortfolioHandler(initial_cash, events_queue, price_handler, position_sizer, risk_manager)
|
'Tests the "_create_order_from_signal" method
as a basic sanity check.'
| def test_create_order_from_signal_basic_check(self):
| signal_event = SignalEvent('MSFT', 'BOT')
order = self.portfolio_handler._create_order_from_signal(signal_event)
self.assertEqual(order.ticker, 'MSFT')
self.assertEqual(order.action, 'BOT')
self.assertEqual(order.quantity, 0)
|
'Tests the "_place_orders_onto_queue" method
as a basic sanity check.'
| def test_place_orders_onto_queue_basic_check(self):
| order = OrderEvent('MSFT', 'BOT', 100)
order_list = [order]
self.portfolio_handler._place_orders_onto_queue(order_list)
ret_order = self.portfolio_handler.events_queue.get()
self.assertEqual(ret_order.ticker, 'MSFT')
self.assertEqual(ret_order.action, 'BOT')
self.assertEqual(ret_order.quanti... |
'Tests the "_convert_fill_to_portfolio_update" method
as a basic sanity check.'
| def test_convert_fill_to_portfolio_update_basic_check(self):
| fill_event_buy = FillEvent(datetime.datetime.utcnow(), 'MSFT', 'BOT', 100, 'ARCA', Decimal('50.25'), Decimal('1.00'))
self.portfolio_handler._convert_fill_to_portfolio_update(fill_event_buy)
port = self.portfolio_handler.portfolio
self.assertEqual(port.cur_cash, Decimal('494974.00'))
fill_event_sell... |
'Tests the "on_signal" method as a basic sanity check.'
| def test_on_signal_basic_check(self):
| signal_event = SignalEvent('MSFT', 'BOT')
self.portfolio_handler.on_signal(signal_event)
ret_order = self.portfolio_handler.events_queue.get()
self.assertEqual(ret_order.ticker, 'MSFT')
self.assertEqual(ret_order.action, 'BOT')
self.assertEqual(ret_order.quantity, 100)
|
'Set up the Position object that will store the PnL.'
| def setUp(self):
| self.position = Position('BOT', 'XOM', 100, PriceParser.parse(74.78), PriceParser.parse(1.0), PriceParser.parse(74.78), PriceParser.parse(74.8))
|
'After the subsequent purchase, carry out two more buys/longs
and then close the position out with two additional sells/shorts.
The following prices have been tested against those calculated
via Interactive Brokers\' Trader Workstation (TWS).'
| def test_calculate_round_trip(self):
| self.position.transact_shares('BOT', 100, PriceParser.parse(74.63), PriceParser.parse(1.0))
self.position.transact_shares('BOT', 250, PriceParser.parse(74.62), PriceParser.parse(1.25))
self.position.transact_shares('SLD', 200, PriceParser.parse(74.58), PriceParser.parse(1.0))
self.position.transact_shar... |
'After the subsequent sale, carry out two more sells/shorts
and then close the position out with two additional buys/longs.
The following prices have been tested against those calculated
via Interactive Brokers\' Trader Workstation (TWS).'
| def test_calculate_round_trip(self):
| self.position.transact_shares('SLD', 100, PriceParser.parse(77.68), PriceParser.parse(1.0))
self.position.transact_shares('SLD', 50, PriceParser.parse(77.7), PriceParser.parse(1.0))
self.position.transact_shares('BOT', 100, PriceParser.parse(77.77), PriceParser.parse(1.0))
self.position.transact_shares(... |
'Set up the Portfolio object that will store the
collection of Position objects, supplying it with
$500,000.00 USD in initial cash.'
| def setUp(self):
| ph = PriceHandlerMock()
cash = PriceParser.parse(500000.0)
self.portfolio = Portfolio(ph, cash)
|
'Purchase/sell multiple lots of AMZN and GOOG
at various prices/commissions to check the
arithmetic and cost handling.'
| def test_calculate_round_trip(self):
| self.portfolio.transact_position('BOT', 'AMZN', 100, PriceParser.parse(566.56), PriceParser.parse(1.0))
self.portfolio.transact_position('BOT', 'AMZN', 200, PriceParser.parse(566.395), PriceParser.parse(1.0))
self.portfolio.transact_position('BOT', 'GOOG', 200, PriceParser.parse(707.5), PriceParser.parse(1.... |
'Set up the PriceHandler object with a small
set of initial tickers.'
| def setUp(self):
| self.config = settings.TEST
fixtures_path = self.config.CSV_DATA_DIR
events_queue = queue.Queue()
init_tickers = ['GOOG', 'AMZN', 'MSFT']
self.price_handler = HistoricCSVTickPriceHandler(fixtures_path, events_queue, init_tickers)
|
'The initialisation of the class will open the three
test CSV files, then merge and sort them. They will
then be stored in a member "tick_stream". This will
be used for streaming the ticks.'
| def test_stream_all_ticks(self):
| self.price_handler.stream_next()
self.assertEqual(self.price_handler.tickers['GOOG']['timestamp'].strftime('%d-%m-%Y %H:%M:%S.%f'), '01-02-2016 00:00:01.358000')
self.assertEqual(PriceParser.display(self.price_handler.tickers['GOOG']['bid'], 5), 683.56)
self.assertEqual(PriceParser.display(self.pr... |
'Tests the \'subscribe_ticker\' and \'unsubscribe_ticker\'
methods, and check that they raise exceptions when
appropriate.'
| def test_subscribe_unsubscribe(self):
| try:
self.price_handler.subscribe_ticker('GOOG')
except Exception as E:
self.fail(('subscribe_ticker() raised %s unexpectedly' % E))
self.assertTrue(('GOOG' in self.price_handler.tickers))
self.assertTrue(('GOOG' in self.price_handler.tickers_data))
self.price_handler.unsubs... |
'Tests that the \'get_best_bid_ask\' method produces the
correct values depending upon validity of ticker.'
| def test_get_best_bid_ask(self):
| (bid, ask) = self.price_handler.get_best_bid_ask('AMZN')
self.assertEqual(PriceParser.display(bid, 5), 502.10001)
self.assertEqual(PriceParser.display(ask, 5), 502.11999)
(bid, ask) = self.price_handler.get_best_bid_ask('C')
|
'Tests that the position sizer will open up new positions with
the correct weights.'
| def test_will_add_positions(self):
| order_a = SuggestedOrder('AAA', 'BOT', 0)
order_b = SuggestedOrder('BBB', 'BOT', 0)
sized_a = self.position_sizer.size_order(self.portfolio, order_a)
sized_b = self.position_sizer.size_order(self.portfolio, order_b)
self.assertEqual(sized_a.action, 'BOT')
self.assertEqual(sized_b.action, 'BOT')
... |
'Ensure positions will be liquidated completely when asked.
Include a long & a short.'
| def test_will_liquidate_positions(self):
| self.portfolio._add_position('BOT', 'AAA', 100, PriceParser.parse(60.0), 0.0)
self.portfolio._add_position('BOT', 'BBB', (-100), PriceParser.parse(60.0), 0.0)
exit_a = SuggestedOrder('AAA', 'EXIT', 0)
exit_b = SuggestedOrder('BBB', 'EXIT', 0)
sized_a = self.position_sizer.size_order(self.portfolio, ... |
'Determine if the current day is at the end of the month.'
| def _end_of_month(self, cur_time):
| cur_day = cur_time.day
end_day = calendar.monthrange(cur_time.year, cur_time.month)[1]
return (cur_day == end_day)
|
'Create a dictionary with each ticker as a key, with
a boolean value depending upon whether the ticker has
been "invested" yet. This is necessary to avoid sending
a liquidation signal on the first allocation.'
| def _create_invested_list(self):
| tickers_invested = {ticker: False for ticker in self.tickers}
return tickers_invested
|
'For a particular received BarEvent, determine whether
it is the end of the month (for that bar) and generate
a liquidation signal, as well as a purchase signal,
for each ticker.'
| def calculate_signals(self, event):
| if ((event.type in [EventType.BAR, EventType.TICK]) and self._end_of_month(event.time)):
ticker = event.ticker
if self.tickers_invested[ticker]:
liquidate_signal = SignalEvent(ticker, 'EXIT')
self.events_queue.put(liquidate_signal)
long_signal = SignalEvent(ticker, 'B... |
'Set up configuration.'
| def setUp(self):
| self.config = settings.TEST
self.testing = True
|
'Test buy_and_hold
Begins at 2000-01-01 00:00:00
End at 2014-01-01 00:00:00'
| def test_buy_and_hold_backtest(self):
| tickers = ['SPY']
filename = os.path.join(settings.TEST.OUTPUT_DIR, 'buy_and_hold_backtest.pkl')
results = examples.buy_and_hold_backtest.run(self.config, self.testing, tickers, filename)
for (key, expected) in [('sharpe', 0.25234757), ('max_drawdown_pct', 0.79589309)]:
value = float(results[key... |
'Test moving average crossover backtest
Begins at 2000-01-01 00:00:00
End at 2014-01-01 00:00:00'
| def test_moving_average_cross_backtest(self):
| tickers = ['AAPL', 'SPY']
filename = os.path.join(settings.TEST.OUTPUT_DIR, 'mac_backtest.pkl')
results = examples.moving_average_cross_backtest.run(self.config, self.testing, tickers, filename)
self.assertAlmostEqual(float(results['sharpe']), 0.643009566)
|
'Test monthly liquidation & rebalance strategy.'
| def test_monthly_liquidate_rebalance_backtest(self):
| tickers = ['SPY', 'AGG']
filename = os.path.join(settings.TEST.OUTPUT_DIR, 'monthly_liquidate_rebalance_backtest.pkl')
results = examples.monthly_liquidate_rebalance_backtest.run(self.config, self.testing, tickers, filename)
self.assertAlmostEqual(float(results['sharpe']), 0.2710491397280638)
|
'virtual method.'
| def start(self, addr, port):
| self._socket = socket.socket()
self._socket.bind((addr, port))
self._socket.listen(10)
KBEngine.registerReadFileDescriptor(self._socket.fileno(), self.onRecv)
|
''
| def processData(self, sock, datas):
| pass
|
'KBEngine method.
䜿çšaddTimeråïŒ åœæ¶éŽå°èŸŸå该æ¥å£è¢«è°çš
@param id : addTimer çè¿ååŒID
@param userArg : addTimer æåäžäžªåæ°æç»å
¥çæ°æ®'
| def onTimer(self, id, userArg):
| DEBUG_MSG(id, userArg)
|
'KBEngine method.
该entity被æ£åŒæ¿æŽ»äžºå¯äœ¿çšïŒ æ€æ¶entityå·²ç»å»ºç«äºclient对åºå®äœïŒ å¯ä»¥åšæ€å建å®ç
celléšåã'
| def onEntitiesEnabled(self):
| INFO_MSG(('account[%i] entities enable. mailbox:%s' % (self.id, self.client)))
|
'KBEngine method.'
| def onLogOnAttempt(self, ip, port, password):
| INFO_MSG(ip, port, password)
return KBEngine.LOG_ON_ACCEPT
|
'KBEngine method.'
| def onClientDeath(self):
| DEBUG_MSG(('Account[%i].onClientDeath:' % self.id))
self.destroy()
|
''
| def __init__(self, uid, filename):
| ClusterControllerHandler.__init__(self, uid)
self.filename = filename
|
''
| def do(self):
| self.queryAllInterfaces(MACHINES_ADDRESS, MACHINES_QUERY_ATTEMPT_COUNT, MACHINES_QUERY_WAIT_TIME)
cper = configparser.ConfigParser()
for i in range(COMPONENT_END_TYPE):
if (i in self.VALIDATE_CT):
cper.add_section(COMPONENT_NAME[i])
t2c = ([0] * len(COMPONENT_NAME))
vt = '%s, ... |
''
| def __init__(self, uid, filename):
| ClusterControllerHandler.__init__(self, uid)
self.filename = filename
|
''
| def do(self):
| cper = configparser.ConfigParser()
cper.read(filename)
expectCount = ([0] * COMPONENT_END_TYPE)
SIGNLE_CT = [DBMGR_TYPE, BASEAPPMGR_TYPE, CELLAPPMGR_TYPE, INTERFACES_TYPE, LOGGER_TYPE]
for ct in SIGNLE_CT:
secName = COMPONENT_NAME[ct]
optName = 'item_1'
if cper.has_option(sec... |
''
| def __init__(self, uid, machineIP):
| ClusterControllerHandler.__init__(self, uid)
self.machineIP = machineIP
|
''
| def do(self):
| for ct in self.VALIDATE_CT:
secName = COMPONENT_NAME[ct]
cid = self.makeCID(ct)
gus = self.makeGUS(ct)
print ("run '%s' in '%s', uid = %s, cid = %s, gus = %s" % (secName, self.machineIP, self.uid, cid, gus))
self.startServer(ct, cid, gus, s... |
''
| def __init__(self, componentType):
| ServerApp.ServerApp.__init__(self)
self.registerMsg(CONSOLE_PROFILECB_MSGID, self.onSpaceViewerMsg)
self.SpaceViewerData = []
self.componentType = componentType
assert (componentType in CMD_ID_querySpaceViewer)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.