Margot API Reference

Introduction

Our journey with Margot begins with data.

To the quantitative trader, data is the link to the observable universe upon which we overlaycour ideas, to seek to uncover statistical or seasonality effects, mispricings or premium for carrying risk.

Margot data aims to provide a framework within which we can encapsulate this complexity, making the act of defining trading algorithms as declarative and as simple as possible.

BackTest

class margot.BackTest(algo, start_balance=100000)

Backtest an trading algo that’s a descendent of BaseAlgo.

Warning

BackTest is still a work in progress - it probably doesn’t even work yet!

algo

A boolean indicating if we like SPAM or not.

starting_balance

An integer count of the eggs we have laid.

calculate_returns()

Calculate returns.

Assumes the trade is made the next period after a signal is generated.

You should construct your MargotDataFrame to be indexed by the trading periods (e.g. days).

create_trade_signals_timeseries()

Create time-series of when position changes occur.

Return the subset of the positions time-series to indicate positions

when signals indicate trade should be placed.

Returns

A dataframe of signals when changes to positions are

suggested.

Return type

pd.DataFrame

create_position_timeseries(periods)

Create Position time-series from signals.

Runs through all of the backtest data, generating position indicating signals.

Parameters

periods (int) – the number of periods to backtest over, counted back from the end of the dataset. If no value is supplied then the whole dataset is used.

Returns

time-series of Positions

Return type

pd.DataFrame

run(periods=None)

Run the backtest.

Returns

[description]

Return type

[type]

volatility(days=30, periods=252)

Return a single float value for realised historical volatility.

TODO: Change the periods parameter to instead examine the data. :param days: Days to lookback. Defaults to 30. :type days: int, optional

BaseAlgo

class margot.BaseAlgo(market='XNYS')

A base class to inherit when implementing your trading algorithm.

You should at least implement signal() which is the output of a trading algorithm.

Parameters
  • env (dict) – a dictionary of environment variables, e.g. API keys. Overrides anything provided in sys env.

  • market (str) – The ISO code for the market we will use.

Raises
  • ValueError – the attribute, ‘data’ must be a reference to a MargotDataFrame.

  • NotImplementedError – If your subclass does not implement signal(), you will receive a NotImplementedError.

weekday(dt)

Return a human readable three letter day of week.

Convert the Python integer representation of day of week into a string.

e.g:

0: 'MON' (also known as self.MONDAY)

Note

You should always use the built in constants when passing days of the week. e.g. self.MONDAY, self.TUESDAY, … these map to the three charater strings.

Parameters

dt (datetime or pd.Timestamp) – The datetime to check

Returns

One of; ‘MON’, ‘TUE’, ‘WED’, ‘THU’, ‘FRI’, ‘SAT’, ‘SUN’

Return type

str

property next_close

Return a UTC pd.Timestamp of the next close of trading session.

Returns

Timestamp of the next close of cash session in UTC.

Return type

pd.Timestamp

signal() → list

Return a list of Position objects for a given datetime.

simulate_signal(when: datetime.datetime)

Simulate a signal from a point in time.

Stores the original MargotDataFrame referenced by self.data on a temporary reference so that the data attribute can be used by signal() to calculate positions at a point in history.

After running signal(), the full dataframe is re-referenced at self.data.

Parameters

when (datetime) – when in history to go back to

Returns

a list of Position objects.

Return type

list

MargotDataFrame

class margot.MargotDataFrame

A MargotDataFrame brings together symbols, columns, features and ratios.

Example:

class Equity(Symbol):
    adj_close = av.Column(function='historical_daily_adjusted',
                          time_series='adjusted_close')
    log_returns = finance.LogReturns(column='adj_close')
    realised_vol = finance.RealisedVolatility(column='log_returns',
                                              window=30)

class ExampleDF(MargotDataFrame):
    spy = Equity(symbol='SPY', trading_calendar='NYSE')
    vtwo = Equity(symbol='VTWO', trading_calendar='NYSE')
    spy_russ_ratio = Ratio(numerator=spy.adj_close,
                           denominator=vtwo.adj_close,
                           label='spy_russ')

mydf = ExampleDF()
to_pandas(periods: int = None, dropna=True) → pandas.core.frame.DataFrame

Return a pandas Dataframe representing this MargotDataFrame.

Parameters

periods (int, optional) – only return the tail n periods.

Returns

a Pandas dataframe representing all data from

the MargotDataFrame

Return type

pd.DataFrame

refresh()

Refresh all Symbols in this DataFrame.

property start_date

First Timestamp of the time-series index.

Returns

a pandas timestamp.

Return type

Timestamp

property end_date

Last Timestamp value of the time-series index.

Returns

a pandas timestamp.

Return type

Timestamp

property index

Return the time-series index.

Returns

a pandas timeseries index.

Return type

pd.Index

simulate(when)

Create a dataframe simulating a datetime in history.

Used for backtesting to simplify the writing of trading algorithms. After simulating a historical datetime, it is not possible to go back to the future.

Parameters

when (tz_aware datetime or pd.Timestamp) – when to go back to.

Position

class margot.Position(symbol: str, weight: float, order_type: str)

Represents a Position with a symbol and a weight.

Parameters
  • symbol (str) – The identifier of the symbol. e.g. ‘SPY’.

  • weight (float) – A value between -1.0 and +1.0 representing the weight of this symbol in the position list.

as_map()

Return the Position as a dictionary.

Ratio

class margot.Ratio(numerator, denominator, label, **kwargs)

Ratio of two series.

Ratio = numerator / denominator of two time-series.

Example:

my_ratio = Ratio(numerator=symbol_1.adj_close,
                 denominator=symbol_2.adj_close,
                 label='s1_s2_ratio')
Parameters
  • numerator (str) – the series to numerate the ratio

  • denominator (str) – the series to denominate the ratio

  • label (str) – give it a name for your dataframe. e.g. current_ratio

property latest

Return the latest value in this series.

Symbol

class margot.Symbol(symbol: str, trading_calendar: str)

A Symbol, represents a securitised tradable asset.

A symbol can contain columns and features as members.

Usage example:

class Equity(Symbol):
    adj_close = av.Column(function='historical_daily_adjusted',
                        time_series='adjusted_close')
    log_returns = finance.LogReturns(column='adj_close')
    realised_vol = finance.RealisedVolatility(column='log_returns',
                                            window=30)

spy = Equity(symbol='SPY', trading_calendar='NYSE')
Parameters
refresh()

Refresh all columns in this Symbol.

simulate(when=None)

Make the Symbol simulate a datetime in history.

Used for backtesting to simplify the writing of trading algorithms.

Parameters

when (tz_aware datetime or pd.Timestamp) – when to go back to.

Alphavantage

class margot.alphavantage.DailyAdjusted(time_series: str, *args, **kwargs)

A daily time series from AlphaVantage.

Example:

from margot import alphavantage as av

volume = av.DailyAdjusted(time_series='adjusted_close')
Parameters

time_series (str) – the name of the time-series that will be returned. Can be one of: ‘open’, ‘high’, ‘low’, ‘close’, ‘adjusted_close’, ‘volume’, ‘dividend_amount’ or ‘split_coefficient’.

clean(df)

Clean the dataframe.

Alphavantage has odd column names, so we’ll fix those.

fetch(symbol: str)

Fetch from remote - this could be the only service specific thing.

Parameters

symbol (str) – the name of the symbol to fetch

Financial features

class margot.finance.SimpleReturns(column: str, *args, **kwargs)

Simple returns are the percent change from yesterdays close to today’s close.

Internal implementation:

return series.pct_change().fillna(0)
Parameters

column (str) – The name of a price time series.

class margot.finance.LogReturns(column: str, *args, **kwargs)

Log returns can be summed over time.

Internal implementation:

return np.log(1 + series.pct_change().fillna(0))
Parameters

column (str) – The name of the price time series.

class margot.finance.RealisedVolatility(column: str, *args, **kwargs)

Realised volatility measures the variability of returns over a lookback window.

Internal implementation:

return series.rolling(window).std() * np.sqrt(252)
Parameters
  • column (str) – The name of a returns time series.

  • window (int) – Lookback window in trading days.

Raises

AttributeError – A lookback window is required.

class margot.finance.SimpleMovingAverage(column: str, *args, **kwargs)

Simple moving average of lookback window.

Internal implementation:

return series.rolling(window).mean()
Parameters
  • column (str) – The name of a returns time series.

  • window (int) – Lookback window in trading days.

get_label()

Return the label for this feature.

Override this to customise.

Returns

the label to be used in the pandas column.

Return type

str

class margot.finance.UpperBollingerBand(column: str, *args, **kwargs)

Upper bollinger band with window and standard deviation.

Internal implementation:

return series.rolling(window).mean() +
        series.rolling(self.window).mean().std() *
            self.width
Parameters
  • column (str) – The name of a returns time series.

  • window (int) – lookback in trading days. Defaults to 20

  • width (float) – width in standard deviations. Defaults to 2.0

class margot.finance.LowerBollingerBand(column: str, *args, **kwargs)

Lower bollinger band of window and standard deviation.

Internal implementation:

return series.rolling(window).mean() -
        series.rolling(self.window).mean().std() *
            self.width
Parameters
  • column (str) – The name of a returns time series.

  • window (int) – lookback in trading days. Defaults to 20

  • width (float) – width in standard deviations. Defaults to 2.0