log.debug("<STR_LIT>")<EOL>self.seen = {}<EOL>self.ignore(self, self.__dict__, self.obj, self.seen, self._ignore)<EOL>self.ignore_caller()<EOL>self.maxdepth = maxdepth<EOL>count = <NUM_LIT:0><EOL>log.debug("<STR_LIT>")<EOL>for result in self._gen(self.obj):<EOL><INDENT>log.debug("<STR_LIT>")<EOL>yield result<EOL>count += <NUM_LIT:1><EOL>if maxresults and count >= maxresults:<EOL><INDENT>yield <NUM_LIT:0>, <NUM_LIT:0>, "<STR_LIT>"<EOL>return<EOL><DEDENT><DEDENT>

Walk the object tree, ignoring duplicates and circular refs.


def decode_timestamp(data: str) -> datetime.datetime:

year = <NUM_LIT> + int(data[<NUM_LIT:0>:<NUM_LIT:2>])<EOL>month = int(data[<NUM_LIT:2>:<NUM_LIT:4>])<EOL>day = int(data[<NUM_LIT:4>:<NUM_LIT:6>])<EOL>hour = int(data[<NUM_LIT:6>:<NUM_LIT:8>])<EOL>minute = int(data[<NUM_LIT:8>:<NUM_LIT:10>])<EOL>second = int(data[<NUM_LIT:10>:<NUM_LIT:12>])<EOL>if minute == <NUM_LIT>:<EOL><INDENT>minute = <NUM_LIT:0><EOL>hour += <NUM_LIT:1><EOL><DEDENT>return datetime.datetime(year=year, month=month, day=day, hour=hour,<EOL>minute=minute, second=second)<EOL>

Decode timestamp using bespoke decoder.
Cannot use simple strptime since the ness panel contains a bug
that P199E zone and state updates emitted on the hour cause a minute
value of `60` to be sent, causing strptime to fail. This decoder handles
this edge case.


@classmethod<EOL><INDENT>def decode(cls, _data: str) -> '<STR_LIT>':<DEDENT>

<EOL>data = DataIterator(_data)<EOL>_LOGGER.debug("<STR_LIT>", _data)<EOL>start = data.take_hex()<EOL>address = None<EOL>if has_address(start, len(_data)):<EOL><INDENT>address = data.take_hex(half=is_user_interface_req(start))<EOL><DEDENT>length = data.take_hex()<EOL>data_length = length & <NUM_LIT><EOL>seq = length >> <NUM_LIT:7><EOL>command = CommandType(data.take_hex())<EOL>msg_data = data.take_bytes(data_length,<EOL>half=is_user_interface_req(start))<EOL>timestamp = None<EOL>if has_timestamp(start):<EOL><INDENT>timestamp = decode_timestamp(data.take_bytes(<NUM_LIT:6>))<EOL><DEDENT>checksum = data.take_hex()  <EOL>if not data.is_consumed():<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return Packet(<EOL>is_user_interface_resp=(is_user_interface_resp(start) and<EOL>command == CommandType.USER_INTERFACE),<EOL>address=address,<EOL>seq=seq,<EOL>command=command,<EOL>data=msg_data,<EOL>timestamp=timestamp,<EOL>)<EOL>

Packets are ASCII encoded data. Packet layout is as follows:

+---------------------------------------------------------------------------+
| start | address | length | command | data | timestamp | checksum | finish |
| hex   | hex     | hex    | hex     | str  | dec       | hex      | crlf   |
| 1     | 1       | 1      | 1       | n    | 6         | 1        |        |
+---------------------------------------------------------------------------+

Timestamp:
    Timestamps are formatted in the following format, where each field is
    decimal encoded:

    YY MM DD HH MM SS

Checksum:
    Calculated by...?

Since data is ASCII encoded, each byte uses 2 ASCII character to be
represented. However, we cannot simply do a hex decode on the entire
message, since the timestamp and data fields are represented using a
non-hex representation and therefore must be manually decoded.


_LOGGER.debug("<STR_LIT>")<EOL>await asyncio.gather(<EOL>self.send_command('<STR_LIT>'),<EOL>self.send_command('<STR_LIT>'),<EOL>)<EOL>


await asyncio.sleep(self._update_interval)<EOL>while not self._closed:<EOL><INDENT>await self.update()<EOL>await asyncio.sleep(self._update_interval)<EOL><DEDENT>

Schedule a state update to keep the connection alive


def _handle_system_status_event(self, event: SystemStatusEvent) -> None:

if event.type == SystemStatusEvent.EventType.UNSEALED:<EOL><INDENT>return self._update_zone(event.zone, True)<EOL><DEDENT>elif event.type == SystemStatusEvent.EventType.SEALED:<EOL><INDENT>return self._update_zone(event.zone, False)<EOL><DEDENT>elif event.type == SystemStatusEvent.EventType.ALARM:<EOL><INDENT>return self._update_arming_state(ArmingState.TRIGGERED)<EOL><DEDENT>elif event.type == SystemStatusEvent.EventType.ALARM_RESTORE:<EOL><INDENT>if self.arming_state != ArmingState.DISARMED:<EOL><INDENT>return self._update_arming_state(ArmingState.ARMED)<EOL><DEDENT><DEDENT>elif event.type == SystemStatusEvent.EventType.ENTRY_DELAY_START:<EOL><INDENT>return self._update_arming_state(ArmingState.ENTRY_DELAY)<EOL><DEDENT>elif event.type == SystemStatusEvent.EventType.ENTRY_DELAY_END:<EOL><INDENT>pass<EOL><DEDENT>elif event.type == SystemStatusEvent.EventType.EXIT_DELAY_START:<EOL><INDENT>return self._update_arming_state(ArmingState.EXIT_DELAY)<EOL><DEDENT>elif event.type == SystemStatusEvent.EventType.EXIT_DELAY_END:<EOL><INDENT>if self.arming_state == ArmingState.EXIT_DELAY:<EOL><INDENT>return self._update_arming_state(ArmingState.ARMED)<EOL><DEDENT><DEDENT>elif event.type in Alarm.ARM_EVENTS:<EOL><INDENT>return self._update_arming_state(ArmingState.ARMING)<EOL><DEDENT>elif event.type == SystemStatusEvent.EventType.DISARMED:<EOL><INDENT>return self._update_arming_state(ArmingState.DISARMED)<EOL><DEDENT>elif event.type == SystemStatusEvent.EventType.ARMING_DELAYED:<EOL><INDENT>pass<EOL><DEDENT>

DISARMED -> ARMED_AWAY -> EXIT_DELAY_START -> EXIT_DELAY_END
 (trip): -> ALARM -> OUTPUT_ON -> ALARM_RESTORE
    (disarm): -> DISARMED -> OUTPUT_OFF
 (disarm): -> DISARMED
 (disarm before EXIT_DELAY_END): -> DISARMED -> EXIT_DELAY_END

TODO(NW): Check ALARM_RESTORE state transition to move back into ARMED_AWAY state


ports = []<EOL>if not os.path.exists(PROC_TCP):<EOL><INDENT>return ports<EOL><DEDENT>with open(PROC_TCP) as fh:<EOL><INDENT>for line in fh:<EOL><INDENT>if '<STR_LIT>' not in line:<EOL><INDENT>continue<EOL><DEDENT>parts = line.lstrip('<STR_LIT:U+0020>').split('<STR_LIT:U+0020>')<EOL>if parts[<NUM_LIT:2>] != '<STR_LIT>':<EOL><INDENT>continue<EOL><DEDENT>local_port = parts[<NUM_LIT:1>].split('<STR_LIT::>')[<NUM_LIT:1>]<EOL>local_port = int('<STR_LIT>' + local_port, base=<NUM_LIT:16>)<EOL>ports.append(local_port)<EOL><DEDENT><DEDENT>return ports<EOL>

Reads listening ports from /proc/net/tcp


idx = self._padding<EOL>while idx < len(self._data):<EOL><INDENT>tobject, hole = self._read_next(idx, len(self._data))<EOL>if tobject is None:<EOL><INDENT>return<EOL><DEDENT>if hole:<EOL><INDENT>idx += hole[<NUM_LIT:1>]  <EOL><DEDENT>idx += tobject.bytes_length + self._padding<EOL>yield tobject, hole<EOL><DEDENT>

An iterator that yields a tuple of (thrift object, hole), where
hole is a tuple of (start, skipped) bytes.


<EOL>if len(data) < cls.MIN_MESSAGE_SIZE:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if protocol is None:<EOL><INDENT>protocol = cls.detect_protocol(data, fallback_protocol)<EOL><DEDENT>trans = TTransport.TMemoryBuffer(data)<EOL>proto = protocol(trans)<EOL>header = None<EOL>if finagle_thrift:<EOL><INDENT>try:<EOL><INDENT>header = ThriftStruct.read(<EOL>proto,<EOL>max_fields,<EOL>max_list_size,<EOL>max_map_size,<EOL>max_set_size,<EOL>read_values)<EOL><DEDENT>except:<EOL><INDENT>trans = TTransport.TMemoryBuffer(data)<EOL>proto = protocol(trans)<EOL><DEDENT><DEDENT>method, mtype, seqid = proto.readMessageBegin()<EOL>mtype = cls.message_type_to_str(mtype)<EOL>if len(method) == <NUM_LIT:0> or method.isspace() or method.startswith('<STR_LIT:U+0020>'):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if len(method) > cls.MAX_METHOD_LENGTH:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>valid = range(<NUM_LIT>, <NUM_LIT>)<EOL>if any(ord(char) not in valid for char in method):<EOL><INDENT>raise ValueError('<STR_LIT>' % method)<EOL><DEDENT>args = ThriftStruct.read(<EOL>proto,<EOL>max_fields,<EOL>max_list_size,<EOL>max_map_size,<EOL>max_set_size,<EOL>read_values)<EOL>proto.readMessageEnd()<EOL>msglen = trans._buffer.tell()<EOL>return cls(method, mtype, seqid, args, header, msglen), msglen<EOL>

tries to deserialize a message, might fail if data is missing


last_timestamp = <NUM_LIT:0><EOL>data = []<EOL>for packet in self.pop(nbytes):<EOL><INDENT>last_timestamp = packet.timestamp<EOL>data.append(packet.data.data)<EOL><DEDENT>return '<STR_LIT>'.join(data), last_timestamp<EOL>

similar to pop, but returns payload + last timestamp


return (isinstance(other, self.__class__)<EOL>and<EOL>len(self.fields) == len(other.fields)<EOL>and<EOL>all(a.is_isomorphic_to(b) for a, b in zip(self.fields,<EOL>other.fields)))<EOL>

Returns true if all fields of other struct are isomorphic to this
struct's fields


return len(self._fields)<EOL>


@classmethod<EOL><INDENT>def of_structs(cls, a, b):<DEDENT>

t_diff = ThriftDiff(a, b)<EOL>t_diff._do_diff()<EOL>return t_diff<EOL>

Diff two thrift structs and return the result as a ThriftDiff instance


return self._fields_with_different_value<EOL>

List of isomorphically equivalent field pairs for which value is NOT
equal


return self._fields_with_same_value<EOL>

List of isomorphically equivalent fields for which value is also equal
Note: this doesn't return a list of 'pairs'


return self._fields_only_in_b<EOL>

List of fields exclusive to second struct


return self._common_fields<EOL>

List of isomorphically equivalent field pairs which may or may not have
same value


<EOL>domain = "<STR_LIT>"<EOL>save_url = urljoin(domain, "<STR_LIT>")<EOL>headers = {<EOL>'<STR_LIT>': user_agent,<EOL>"<STR_LIT:host>": "<STR_LIT>",<EOL>}<EOL>logger.debug("<STR_LIT>".format(domain + "<STR_LIT:/>"))<EOL>get_kwargs = dict(<EOL>timeout=<NUM_LIT>,<EOL>allow_redirects=True,<EOL>headers=headers,<EOL>)<EOL>if proxies:<EOL><INDENT>get_kwargs['<STR_LIT>'] = proxies<EOL><DEDENT>response = requests.get(domain + "<STR_LIT:/>", **get_kwargs)<EOL>response.raise_for_status()<EOL>html = str(response.content)<EOL>try:<EOL><INDENT>unique_id = html.split('<STR_LIT>', <NUM_LIT:1>)[<NUM_LIT:1>].split('<STR_LIT>', <NUM_LIT:1>)[<NUM_LIT:1>].split('<STR_LIT:">', <NUM_LIT:1>)[<NUM_LIT:0>]<EOL>logger.debug("<STR_LIT>".format(unique_id))<EOL><DEDENT>except IndexError:<EOL><INDENT>logger.warn("<STR_LIT>")<EOL>unique_id = None<EOL><DEDENT>data = {<EOL>"<STR_LIT:url>": target_url,<EOL>"<STR_LIT>": <NUM_LIT:1>,<EOL>}<EOL>if unique_id:<EOL><INDENT>data.update({"<STR_LIT>": unique_id})<EOL><DEDENT>post_kwargs = dict(<EOL>timeout=<NUM_LIT>,<EOL>allow_redirects=True,<EOL>headers=headers,<EOL>data=data<EOL>)<EOL>if proxies:<EOL><INDENT>post_kwargs['<STR_LIT>'] = proxies<EOL><DEDENT>logger.debug("<STR_LIT>".format(save_url))<EOL>response = requests.post(save_url, **post_kwargs)<EOL>response.raise_for_status()<EOL>if '<STR_LIT>' in response.headers:<EOL><INDENT>memento = str(response.headers['<STR_LIT>']).split('<STR_LIT>')[<NUM_LIT:1>]<EOL>logger.debug("<STR_LIT>".format(memento))<EOL>return memento<EOL><DEDENT>if '<STR_LIT>' in response.headers:<EOL><INDENT>memento = response.headers['<STR_LIT>']<EOL>logger.debug("<STR_LIT>".format(memento))<EOL>return memento<EOL><DEDENT>logger.debug("<STR_LIT>")<EOL>for i, r in enumerate(response.history):<EOL><INDENT>logger.debug("<STR_LIT>".format(i))<EOL>logger.debug(r.headers)<EOL>if '<STR_LIT>' in r.headers:<EOL><INDENT>memento = r.headers['<STR_LIT>']<EOL>logger.debug("<STR_LIT>".format(i+<NUM_LIT:1>, memento))<EOL>return memento<EOL><DEDENT><DEDENT>logger.error("<STR_LIT>")<EOL>logger.error("<STR_LIT>".format(response.status_code))<EOL>logger.error(response.headers)<EOL>logger.error(response.text)<EOL>raise Exception("<STR_LIT>")<EOL>

Archives the provided URL using archive.is

Returns the URL where the capture is stored.


with open(os.path.join(*paths), '<STR_LIT:r>') as f:<EOL><INDENT>return f.read()<EOL><DEDENT>

Build a file path from *paths* and return the contents.


expon = _np.int(_np.floor(_np.log10(_np.abs(x))))<EOL>mant = x/_np.power(<NUM_LIT:10>, expon)<EOL>return (mant, expon)<EOL>

Finds the mantissa and exponent of a number :math:`x` such that :math:`x = m 10^e`.

Parameters
----------

x : float
    Number :math:`x` such that :math:`x = m 10^e`.

Returns
-------

mantissa : float
    Number :math:`m` such that :math:`x = m 10^e`.
exponent : float
    Number :math:`e` such that :math:`x = m 10^e`.


def linspacestep(start, stop, step=<NUM_LIT:1>):

<EOL>numsteps = _np.int((stop-start)/step)<EOL>return _np.linspace(start, start+step*numsteps, numsteps+<NUM_LIT:1>)<EOL>

Create a vector of values over an interval with a specified step size.

Parameters
----------

start : float
    The beginning of the interval.
stop : float
    The end of the interval.
step : float
    The step size.

Returns
-------
vector : :class:`numpy.ndarray`
    The vector of values.


if key in f.keys():<EOL><INDENT>val = f[key].value<EOL>if default is None:<EOL><INDENT>return val<EOL><DEDENT>else:<EOL><INDENT>if _np.shape(val) == _np.shape(default):<EOL><INDENT>return val<EOL><DEDENT><DEDENT><DEDENT>return default<EOL>

Gets an array from datasets.

.. versionadded:: 1.4


<EOL>verbose = kwargs.pop('<STR_LIT>', False)<EOL>popt, pcov = _spopt.curve_fit(*args, **kwargs)<EOL>func = args[<NUM_LIT:0>]<EOL>x    = args[<NUM_LIT:1>]<EOL>y    = args[<NUM_LIT:2>]<EOL>ddof = len(popt)<EOL>try:<EOL><INDENT>sigma = kwargs['<STR_LIT>']<EOL>if sigma is None:<EOL><INDENT>sigma = _np.ones(len(y))<EOL><DEDENT>y_expect = func(x, *popt)<EOL>chisq_red = _chisquare(y, y_expect, sigma, ddof, verbose=verbose)<EOL>pcov = pcov / chisq_red<EOL>return popt, pcov, chisq_red<EOL><DEDENT>except ValueError:<EOL><INDENT>print('<STR_LIT:hello>')<EOL><DEDENT>

Use the reduced chi square to unscale :mod:`scipy`'s scaled :func:`scipy.optimize.curve_fit`. *\*args* and *\*\*kwargs* are passed through to :func:`scipy.optimize.curve_fit`. The tuple *popt, pcov, chisq_red* is returned, where *popt* is the optimal values for the parameters, *pcov* is the estimated covariance of *popt*, and *chisq_red* is the reduced chi square. See http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.optimize.curve_fit.html.


return self._chisq_red<EOL>


if self._y is None:<EOL><INDENT>self._y = self.y_unweighted/self.y_error<EOL><DEDENT>return self._y<EOL>

The :math:`X` weighted properly by the errors from *y_error*


if self._beta is None:<EOL><INDENT>self._beta = _np.dot(_np.linalg.pinv(self.X) , self.y)<EOL><DEDENT>return self._beta<EOL>

The result :math:`\\beta` of the linear least squares


return self._emit<EOL>

Emittance of the beam, :math:`\\epsilon = \\sqrt{ \\langle x^2 \\rangle \\langle {x'}^2 \\rangle - \\langle x x' \\rangle^2 }`


return _sltr.GeV2gamma(self.E)<EOL>


return _np.sqrt(self.emit/self.beta(self.E))<EOL>


return self._phi<EOL>


return _np.mean(self.xp**<NUM_LIT:2>, axis=<NUM_LIT:0>)<EOL>

The beam divergence :math:`\\langle x'^2 \\rangle`.


return _np.mean(self.x**<NUM_LIT:2>, axis=<NUM_LIT:0>)<EOL>

The beam variance :math:`\\langle x^2 \\rangle`.


return self._x<EOL>


return self._k_xi<EOL>


return self._s<EOL>


return _np.mean(self.x*self.xp, axis=<NUM_LIT:0>)<EOL>

The beam correlation :math:`\\langle x x' \\rangle`.


return self.N_e / ( (<NUM_LIT:2>*_np.pi)**(<NUM_LIT:3>/<NUM_LIT:2>) * self.sig_r**<NUM_LIT:2> * self.sig_xi)<EOL>


return self._sig_r<EOL>


return r0*_np.cos(_np.sqrt(self.k_small) * x)<EOL>

Approximate trajectory function for small (:math:`r_0 < \\sigma_r`) oscillations.


y1_0 = q0<EOL>y0_0 = <NUM_LIT:0><EOL>y0   = [y0_0, y1_0]<EOL>y = _sp.integrate.odeint(self._func, y0, x, Dfun=self._gradient, rtol=self.rtol, atol=self.atol)<EOL>return y[:, <NUM_LIT:1>]<EOL>

Numerically solved trajectory function for initial conditons :math:`q(0) = q_0` and :math:`q'(0) = 0`.


return <NUM_LIT:2>*_np.pi/_np.sqrt(self.k_small)<EOL>

The wavelength for small (:math:`r_0 < \\sigma_r`) oscillations.


return self.species.mass<EOL>


return amu * self.species.mass<EOL>


return self._E<EOL>


alpha = -self.sxxp/self.emit<EOL>return alpha<EOL>


return self._sxxp<EOL>

Beam moment where :math:`\\text{sxxp} = \\langle x x' \\rangle`.


return self._sxp<EOL>

Beam moment where :math:`\\text{sxp}^2 = \\langle x'^2 \\rangle`.


return self._emit*_sltr.GeV2gamma(self.E)<EOL>

Normalized beam emittance :math:`\\gamma \\epsilon`.


return self._dE<EOL>


return self._sig_x<EOL>


return self._sig_y<EOL>


return self.N_e / (<NUM_LIT:4>*_np.sqrt(<NUM_LIT:3>) * _np.pi * self.sig_x * self.sig_y * self.sig_xi)<EOL>


return self._n_p<EOL>


return self._beta<EOL>


return self._xp<EOL>


return self._emit<EOL>


return self._sig_delta<EOL>

Beam energy spread :math:`\\sigma_\\delta`.


return self._delta<EOL>


return self._mean<EOL>


return self._step<EOL>


def githubtunnel(user1, server1, user2, server2, port, verbose, stanford=False):

if stanford:<EOL><INDENT>port_shift = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>port_shift = <NUM_LIT:0><EOL><DEDENT>command1 = '<STR_LIT>'.format(port-<NUM_LIT:1>-port_shift, server2, user1, server1)<EOL>command2 = '<STR_LIT>'.format(port-port_shift, port-port_shift-<NUM_LIT:1>, user2)<EOL>command3 = '<STR_LIT>'.format(port, port-<NUM_LIT:1>, user2)<EOL>if verbose:<EOL><INDENT>print(command1)<EOL>if stanford:<EOL><INDENT>print(command2)<EOL><DEDENT>print(command3)<EOL><DEDENT>try:<EOL><INDENT>call(shlex.split(command1))<EOL>if stanford:<EOL><INDENT>call(shlex.split(command2))<EOL><DEDENT>call(shlex.split(command3))<EOL><DEDENT>except:<EOL><INDENT>print('<STR_LIT>')<EOL>pass<EOL><DEDENT>

Opens a nested tunnel, first to *user1*@*server1*, then to *user2*@*server2*, for accessing on *port*.

If *verbose* is true, prints various ssh commands.

If *stanford* is true, shifts ports up by 1.

Attempts to get *user1*, *user2* from environment variable ``USER_NAME`` if called from the command line.


command = '<STR_LIT>'.format(file_in, file_out)<EOL>_subprocess.call(_shlex.split(command))<EOL>

Uses `ImageMagick <http://www.imagemagick.org/>`_ to convert an input *file_in* pdf to a *file_out* png. (Untested with other formats.)

Parameters
----------

file_in : str
    The path to the pdf file to be converted.
file_out : str
    The path to the png file to be written.


<EOL>K           = _np.float_(K)<EOL>quad_length = _np.float_(quad_length)<EOL>energy      = _np.float_(energy)<EOL>Brho = energy/_np.float_(<NUM_LIT>)<EOL>BDES = K*Brho*quad_length<EOL>logger.log(level=loggerlevel, msg='<STR_LIT>'.format(<EOL>bdes        = BDES        ,<EOL>quad_length = quad_length ,<EOL>energy      = energy      ,<EOL>K           = K<EOL>)<EOL>)<EOL>return BDES<EOL>

Returns the BDES for a quadrupole with geometric strength *K* and length *quad_length* for a beam with a given *energy*.
Converts a geometric focusing strength :math:`K` into a quadrupole :math:`B_des`.

Parameters
----------
K : float
    The geometric focusing strength :math:`K`.
quad_length : float
    The length of the quadrupole in meters.
energy : float
    The design energy of the beam in GeV.

Returns
-------
bdes : float
    The magnet value of :math:`B_des`.


def fitimageslice(img, res_x, res_y, xslice, yslice, avg_e_func=None, h5file=None, plot=False):

<EOL>x_start = xslice[<NUM_LIT:0>]<EOL>x_end   = xslice[<NUM_LIT:1>]<EOL>y_start = yslice[<NUM_LIT:0>]<EOL>y_end   = yslice[<NUM_LIT:1>]<EOL>y_low = _np.round(y_start-<NUM_LIT:0.5>) + <NUM_LIT:0.5><EOL>y_high = _np.round(y_end-<NUM_LIT:0.5>) + <NUM_LIT:0.5><EOL>y_px = linspacestep(<NUM_LIT:1>, img.shape[<NUM_LIT:0>])<EOL>y_bool = _np.logical_and(y_low < y_px, y_px < y_high)<EOL>strip = img[y_bool, x_start:x_end]<EOL>histdata = _np.sum(strip, <NUM_LIT:0>)<EOL>xbins = len(histdata)<EOL>x = _np.linspace(<NUM_LIT:1>, xbins, xbins)*res_x<EOL>varbool  = True<EOL>gaussout = _sp.GaussResults(<EOL>x,<EOL>histdata,<EOL>sigma_y    = _np.ones(xbins),<EOL>variance   = varbool,<EOL>background = True,<EOL>p0         = [<NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT:0>]<EOL>)<EOL>if avg_e_func is not None:<EOL><INDENT>relcounts = _np.sum(strip, <NUM_LIT:1>) / _np.float(_np.sum(strip))<EOL>Eavg = <NUM_LIT:0><EOL>for i, val in enumerate(linspacestep(y_low, y_high-<NUM_LIT:1>)):<EOL><INDENT>Eavg = Eavg + avg_e_func(val, val+<NUM_LIT:1>, h5file, res_y)*relcounts[i]<EOL><DEDENT>return Eavg, gaussout<EOL><DEDENT>else:<EOL><INDENT>return gaussout<EOL><DEDENT>

Fits a gaussian to a slice of an image *img* specified by *xslice* x-coordinates and *yslice* y-coordinates. *res_x* and *res_y* specify image resolution in x and y. *avg_e_func* is a function that returns the energy of the image as a function of x. It should have the form:

*avg_e_func(x_1, x_2, h5file, res_y)*

Fits a gaussian to a slice of an image.

Parameters
----------

img : array
    Image to be fitted.
res_x : int
    Image resolution in :math:`x`.
res_y : int
    Image resolution in :math:`y`.
xslice : (int, int)
    Slice coordinates in :math:`x`
yslice : (int, int)
    Slice coordinates in :math:`y`
avg_e_func : function
    Of the form *avg_e_func(x_1, x_2, h5file, res_y)*, returns the energy of the image as a function of :math:`x`.
h5file : h5file
    Instance from dataset.
plot : boolean
    Whether to plot or not.


<EOL>x_size = array.shape[<NUM_LIT:0>]+<NUM_LIT:1><EOL>y_size = array.shape[<NUM_LIT:1>]+<NUM_LIT:1><EOL>x = _np.empty((x_size, y_size))<EOL>y = _np.empty((x_size, y_size))<EOL>for i in range(x_size):<EOL><INDENT>for j in range(y_size):<EOL><INDENT>x[i, j], y[i, j] = px_to_units(i-<NUM_LIT:0.5>, j-<NUM_LIT:0.5>)<EOL><DEDENT><DEDENT>return x, y<EOL>

Return axes :code:`x, y` for *array* to be used with :func:`matplotlib.pyplot.color`.

*px_to_units* is a function to convert pixels to units. By default, returns pixels.


return self._AxesImage<EOL>

The :class:`matplotlib.image.AxesImage` from :meth:`matplotlib.axes.Axes.imshow`.


return self.minslider.val<EOL>


return self._ax_img<EOL>

The :class:`matplotlib.axes.Axes` used for :meth:`matplotlib.axes.Axes.imshow`.


return self._image<EOL>


return _np.max(self.image)<EOL>


figs = plt.get_fignums()<EOL>x       = <NUM_LIT:0><EOL>y       = <NUM_LIT:0><EOL>toppad  = <NUM_LIT><EOL>size = np.array([<NUM_LIT:0>, <NUM_LIT:0>])<EOL>if ( len(figs) != <NUM_LIT:0> ):<EOL><INDENT>fig     = plt.figure(figs[<NUM_LIT:0>])<EOL>screen  = fig.canvas.window.get_screen()<EOL>screenx = screen.get_monitor_geometry(screen.get_primary_monitor())<EOL>screenx = screenx[<NUM_LIT:2>]<EOL>fig = plt.figure(figs[<NUM_LIT:0>])<EOL>fig.canvas.manager.window.move(x, y)<EOL>maxy = np.array(fig.canvas.manager.window.get_position())[<NUM_LIT:1>]<EOL>size = np.array(fig.canvas.manager.window.get_size())<EOL>y    = maxy<EOL>x += size[<NUM_LIT:0>]+<NUM_LIT:1><EOL>for fig in figs[<NUM_LIT:1>:]:<EOL><INDENT>fig  = plt.figure(fig)<EOL>size = np.array(fig.canvas.manager.window.get_size())<EOL>if ( x+size[<NUM_LIT:0>] > screenx ):<EOL><INDENT>x    = <NUM_LIT:0><EOL>y    = maxy<EOL>maxy = y+size[<NUM_LIT:1>]+toppad<EOL><DEDENT>else:<EOL><INDENT>maxy = max(maxy, y+size[<NUM_LIT:1>]+toppad)<EOL><DEDENT>fig.canvas.manager.window.move(x, y)<EOL>x += size[<NUM_LIT:0>] + <NUM_LIT:1><EOL><DEDENT><DEDENT>


return self._ax_img<EOL>


return self._images[self._image_ind]<EOL>


if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>imgmax = _np.max(self.images[<NUM_LIT:0>])<EOL>for img in self.images:<EOL><INDENT>imax = _np.max(img)<EOL>if imax > imgmax:<EOL><INDENT>imgmax = imax<EOL><DEDENT><DEDENT>self._imgmax = imgmax<EOL><DEDENT>return self._imgmax<EOL>


def imshow_batch(images, cbar=True, show=True, pdf=None, figsize=(<NUM_LIT:16>, <NUM_LIT:12>), rows=<NUM_LIT:2>, columns=<NUM_LIT:2>, cmap=None, **kwargs):

<EOL>images = _np.array(images)<EOL>gs = _gridspec.GridSpec(rows, columns)<EOL>num_imgs = images.shape[<NUM_LIT:0>]<EOL>max_ind = num_imgs-<NUM_LIT:1><EOL>per_page = rows*columns<EOL>num_pages = _np.int(_np.ceil(num_imgs/per_page))<EOL>fig_array = _np.empty(shape=num_pages, dtype=object)<EOL>if num_pages > <NUM_LIT:1>:<EOL><INDENT>logger.info('<STR_LIT>')<EOL><DEDENT>if pdf is not None:<EOL><INDENT>f = _PdfPages(pdf)<EOL><DEDENT>for p in range(num_pages):<EOL><INDENT>fig_array[p] = _plt.figure(figsize=figsize)<EOL>pg_max_ind = _np.min( [(p+<NUM_LIT:1>) * per_page - <NUM_LIT:1>, max_ind] )<EOL>num_rows = _np.int(_np.ceil((pg_max_ind+<NUM_LIT:1> - p * per_page) / columns))<EOL>for i in range(num_rows):<EOL><INDENT>i_min_ind = p * per_page + i * columns<EOL>col_max_ind = _np.min([i_min_ind + columns - <NUM_LIT:1>, max_ind])<EOL>for j, image in enumerate(images[i_min_ind:col_max_ind+<NUM_LIT:1>]):<EOL><INDENT>ax = fig_array[p].add_subplot(gs[i, j])<EOL>try:<EOL><INDENT>if _np.issubdtype(image.dtype, _np.integer):<EOL><INDENT>image = _np.array(image, dtype=float)<EOL><DEDENT><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>plot = ax.imshow(image, **kwargs)<EOL>if cmap is not None:<EOL><INDENT>plot.set_cmap(cmap)<EOL><DEDENT>if cbar:<EOL><INDENT>fig_array[p].colorbar(plot)<EOL><DEDENT><DEDENT><DEDENT>fig_array[p].tight_layout()<EOL>if pdf is not None:<EOL><INDENT>f.savefig(fig_array[p])<EOL><DEDENT>if not show:<EOL><INDENT>_plt.close(fig_array[p])<EOL><DEDENT><DEDENT>if pdf is not None:<EOL><INDENT>f.close()<EOL><DEDENT>return fig_array<EOL>

Plots an array of *images* to a single window of size *figsize* with *rows* and *columns*.

* *cmap*: Specifies color map
* *cbar*: Add color bars
* *show*: If false, dismisses each window after it is created and optionally saved
* *pdf*: Save to a pdf of filename *pdf*
* *\*\*kwargs* passed to :class:`matplotlib.axis.imshow`


if self._erelease is None:<EOL><INDENT>raise IOError('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return self._erelease<EOL><DEDENT>

The ending mouse click from :class:`RectangleSelector <scisalt.matplotlib.RectangleSelector.RectangleSelector>`.


return self._RectangleSelector<EOL>

The instance of :class:`matplotlib.widgets.RectangleSelector`.


return self.x1-self.x0<EOL>


return [self.y0, self.y1]<EOL>


if self.selfunc is not None:<EOL><INDENT>return self.selfunc(self)<EOL><DEDENT>

The results of :func:`selfunc(instance) <scisalt.matplotlib.RectangleSelector.selfunc>` where *instance* is this class.


return self._x1<EOL>


return self._y0<EOL>


return self._y1<EOL>


return [self.x0, self.x1]<EOL>


return self._x0<EOL>


def hist2d(x, y, bins=<NUM_LIT:10>, labels=None, aspect="<STR_LIT>", plot=True, fig=None, ax=None, interpolation='<STR_LIT:none>', cbar=True, **kwargs):

h_range   = kwargs.pop('<STR_LIT>', None)<EOL>h_normed  = kwargs.pop('<STR_LIT>', None)<EOL>h_weights = kwargs.pop('<STR_LIT>', None)<EOL>h, xe, ye = _np.histogram2d(x, y, bins=bins, range=h_range, normed=h_normed, weights=h_weights)<EOL>extent    = [xe[<NUM_LIT:0>], xe[-<NUM_LIT:1>], ye[<NUM_LIT:0>], ye[-<NUM_LIT:1>]]<EOL>if plot:<EOL><INDENT>if ax is None:<EOL><INDENT>if fig is None:<EOL><INDENT>fig = _figure('<STR_LIT>')<EOL><DEDENT>ax = fig.gca()<EOL>ax.clear()<EOL><DEDENT>img = ax.imshow(h.transpose(), extent=extent, interpolation=interpolation, aspect=aspect, **kwargs)<EOL>if cbar:<EOL><INDENT>_colorbar(ax=ax, im=img)<EOL><DEDENT>if labels is not None:<EOL><INDENT>_addlabel(labels[<NUM_LIT:0>], labels[<NUM_LIT:1>], labels[<NUM_LIT:2>])<EOL><DEDENT><DEDENT>return h, extent<EOL>

Creates a 2-D histogram of data *x*, *y* with *bins*, *labels* = :code:`[title, xlabel, ylabel]`, aspect ration *aspect*. Attempts to use axis *ax* first, then the current axis of *fig*, then the last axis, to use an already-created window.

Plotting (*plot*) is on by default, setting false doesn't attempt to create a figure.

*interpolation* sets the interpolation type of :meth:`matplotlib.axis.imshow`.

Returns a handle and extent as :code:`h, extent`


return self._sorted_y[<NUM_LIT:0>]<EOL>


return self._sorted_x[<NUM_LIT:0>]<EOL>


return self._sorted_y[<NUM_LIT:1>]<EOL>


def print2elog(author='<STR_LIT>', title='<STR_LIT>', text='<STR_LIT>', link=None, file=None, now=None):

<EOL>if now is None:<EOL><INDENT>now  = _dt.datetime.now()<EOL><DEDENT>fulltime = now.strftime('<STR_LIT>')<EOL>if not ((link is None) ^ (file is None)):<EOL><INDENT>link_copied = _copy_file(link, fulltime)<EOL>file_copied = _copy_file(file, fulltime)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>loader = _jj.PackageLoader('<STR_LIT>', '<STR_LIT>')<EOL>env = _jj.Environment(loader=loader, trim_blocks=True)<EOL>template = env.get_template('<STR_LIT>')<EOL>stream = template.stream(author=author, title=title, text=text, link=link_copied, file=file_copied, now=now)<EOL>with _tempfile.TemporaryDirectory() as dirname:<EOL><INDENT>filename = '<STR_LIT>'.format(fulltime)<EOL>filepath = _os.path.join(dirname, filename)<EOL>with open(filepath, '<STR_LIT>') as fid:<EOL><INDENT>stream.dump(fid)<EOL><DEDENT>finalpath = _os.path.join(basedir, filename)<EOL>_shutil.copyfile(filepath, finalpath)<EOL><DEDENT>

Prints to the elog.

Parameters
----------

author : str, optional
    Author of the elog.
title : str, optional
    Title of the elog.
link : str, optional
    Path to a thumbnail.
file : str, optional
    Path to a file.
now : :class:`datetime.datetime`
    Time of the elog.


<EOL>mcclogs, physlogs = self.selectedLogs()<EOL>success = True<EOL>if mcclogs != []:<EOL><INDENT>if not self.acceptedUser("<STR_LIT>"):<EOL><INDENT>QMessageBox().warning(self, "<STR_LIT>", "<STR_LIT>")<EOL>return<EOL><DEDENT>fileName = self.xmlSetup("<STR_LIT>", mcclogs)<EOL>if fileName is None:<EOL><INDENT>return<EOL><DEDENT>if not self.imagePixmap.isNull():<EOL><INDENT>self.prepareImages(fileName, "<STR_LIT>")<EOL><DEDENT>success = self.sendToLogbook(fileName, "<STR_LIT>")<EOL><DEDENT>if physlogs != []:<EOL><INDENT>for i in range(len(physlogs)):<EOL><INDENT>fileName = self.xmlSetup("<STR_LIT>", physlogs[i])<EOL>if fileName is None:<EOL><INDENT>return<EOL><DEDENT>if not self.imagePixmap.isNull():<EOL><INDENT>self.prepareImages(fileName, "<STR_LIT>")<EOL><DEDENT>success_phys = self.sendToLogbook(fileName, "<STR_LIT>", physlogs[i])<EOL>success = success and success_phys<EOL><DEDENT><DEDENT>self.done(success)<EOL>

Process user inputs and subit logbook entry when user clicks Submit button


mcclogs = []<EOL>physlogs = []<EOL>for i in range(len(self.logMenus)):<EOL><INDENT>logType = self.logMenus[i].selectedType()<EOL>log = self.logMenus[i].selectedProgram()<EOL>if logType == "<STR_LIT>":<EOL><INDENT>if log not in mcclogs:<EOL><INDENT>mcclogs.append(log)<EOL><DEDENT><DEDENT>elif logType == "<STR_LIT>":<EOL><INDENT>if log not in physlogs:<EOL><INDENT>physlogs.append(log)<EOL><DEDENT><DEDENT><DEDENT>return mcclogs, physlogs<EOL>


from xml.etree.ElementTree import Element, SubElement, ElementTree<EOL>from datetime import datetime<EOL>curr_time = datetime.now()<EOL>if logType == "<STR_LIT>":<EOL><INDENT>log_entry = Element('<STR_LIT>')<EOL>title     = SubElement(log_entry, '<STR_LIT:title>')<EOL>program   = SubElement(log_entry, '<STR_LIT>')<EOL>timestamp = SubElement(log_entry, '<STR_LIT>')<EOL>priority  = SubElement(log_entry, '<STR_LIT>')<EOL>os_user   = SubElement(log_entry, '<STR_LIT>')<EOL>hostname  = SubElement(log_entry, '<STR_LIT>')<EOL>text      = SubElement(log_entry, '<STR_LIT:text>')<EOL>log_user  = SubElement(log_entry, '<STR_LIT>')<EOL>logbook = []<EOL>for i in range(len(logList)):<EOL><INDENT>logbook.append(SubElement(log_entry, '<STR_LIT>'))<EOL>logbook[i].text = logList[i].lower()<EOL><DEDENT>log_entry.attrib['<STR_LIT:type>'] = "<STR_LIT>"<EOL>program.text = "<STR_LIT>"<EOL>priority.text = "<STR_LIT>"<EOL>os_user.text = "<STR_LIT>"<EOL>hostname.text = "<STR_LIT>"<EOL>text.attrib['<STR_LIT:type>'] = "<STR_LIT>"<EOL>if not self.imagePixmap.isNull():<EOL><INDENT>attachment = SubElement(log_entry, '<STR_LIT>')<EOL>attachment.attrib['<STR_LIT:name>'] = "<STR_LIT>"<EOL>attachment.attrib['<STR_LIT:type>'] = "<STR_LIT>" + self.imageType<EOL>attachment.text = curr_time.strftime("<STR_LIT>") + str(curr_time.microsecond) + "<STR_LIT:.>" + self.imageType<EOL><DEDENT>timestamp.text = curr_time.strftime("<STR_LIT>")<EOL>fileName = "<STR_LIT>" + curr_time.strftime("<STR_LIT>") + str(curr_time.microsecond) + "<STR_LIT>"<EOL><DEDENT>else:  <EOL><INDENT>timeString = curr_time.strftime("<STR_LIT>")<EOL>log_entry = Element(None)<EOL>severity  = SubElement(log_entry, '<STR_LIT>')<EOL>location  = SubElement(log_entry, '<STR_LIT:location>')<EOL>keywords  = SubElement(log_entry, '<STR_LIT>')<EOL>time      = SubElement(log_entry, '<STR_LIT:time>')<EOL>isodate   = SubElement(log_entry, '<STR_LIT>')<EOL>log_user  = SubElement(log_entry, '<STR_LIT>')<EOL>category  = SubElement(log_entry, '<STR_LIT>')<EOL>title     = SubElement(log_entry, '<STR_LIT:title>')<EOL>metainfo  = SubElement(log_entry, '<STR_LIT>')<EOL>if not self.imagePixmap.isNull():<EOL><INDENT>imageFile = SubElement(log_entry, '<STR_LIT>')<EOL>imageFile.text = timeString + "<STR_LIT>" + self.imageType<EOL>thumbnail = SubElement(log_entry, '<STR_LIT:file>')<EOL>thumbnail.text = timeString + "<STR_LIT>"<EOL><DEDENT>text      = SubElement(log_entry, '<STR_LIT:text>')  <EOL>log_entry.attrib['<STR_LIT:type>'] = "<STR_LIT>"<EOL>category.text = "<STR_LIT>"<EOL>location.text = "<STR_LIT>"<EOL>severity.text = "<STR_LIT>"<EOL>keywords.text = "<STR_LIT:none>"<EOL>time.text = curr_time.strftime("<STR_LIT>")<EOL>isodate.text = curr_time.strftime("<STR_LIT>")<EOL>metainfo.text = timeString + "<STR_LIT>"<EOL>fileName = "<STR_LIT>" + metainfo.text<EOL><DEDENT>log_user.text = str(self.logui.userName.text())<EOL>title.text = str(self.logui.titleEntry.text())<EOL>if title.text == "<STR_LIT>":<EOL><INDENT>QMessageBox().warning(self, "<STR_LIT>", "<STR_LIT>")<EOL>return None<EOL><DEDENT>text.text = str(self.logui.textEntry.toPlainText())<EOL>if text.text == "<STR_LIT>":<EOL><INDENT>text.text = "<STR_LIT:U+0020>"<EOL><DEDENT>xmlFile = open(fileName, "<STR_LIT:w>")<EOL>if logType == "<STR_LIT>":<EOL><INDENT>ElementTree(log_entry).write(xmlFile)<EOL><DEDENT>else:<EOL><INDENT>xmlString = self.prettify(log_entry)<EOL>xmlFile.write(xmlString)<EOL><DEDENT>xmlFile.write("<STR_LIT:\n>")  <EOL>xmlFile.close()<EOL>return fileName.rstrip("<STR_LIT>")<EOL>

Create xml file with fields from logbook form.


labelSizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)<EOL>labelSizePolicy.setHorizontalStretch(<NUM_LIT:0>)<EOL>labelSizePolicy.setVerticalStretch(<NUM_LIT:0>)<EOL>menuSizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)<EOL>menuSizePolicy.setHorizontalStretch(<NUM_LIT:0>)<EOL>menuSizePolicy.setVerticalStretch(<NUM_LIT:0>)<EOL>logTypeLayout = QHBoxLayout()<EOL>logTypeLayout.setSpacing(<NUM_LIT:0>)<EOL>typeLabel = QLabel("<STR_LIT>")<EOL>typeLabel.setMinimumSize(QSize(<NUM_LIT>, <NUM_LIT:0>))<EOL>typeLabel.setMaximumSize(QSize(<NUM_LIT>, <NUM_LIT>))<EOL>typeLabel.setSizePolicy(labelSizePolicy)<EOL>logTypeLayout.addWidget(typeLabel)<EOL>self.logType = QComboBox(self)<EOL>self.logType.setMinimumSize(QSize(<NUM_LIT:100>, <NUM_LIT:0>))<EOL>self.logType.setMaximumSize(QSize(<NUM_LIT>, <NUM_LIT>))<EOL>menuSizePolicy.setHeightForWidth(self.logType.sizePolicy().hasHeightForWidth())<EOL>self.logType.setSizePolicy(menuSizePolicy)<EOL>logTypeLayout.addWidget(self.logType)<EOL>logTypeLayout.setStretch(<NUM_LIT:1>, <NUM_LIT:6>)<EOL>programLayout = QHBoxLayout()<EOL>programLayout.setSpacing(<NUM_LIT:0>)<EOL>programLabel = QLabel("<STR_LIT>")<EOL>programLabel.setMinimumSize(QSize(<NUM_LIT>, <NUM_LIT:0>))<EOL>programLabel.setMaximumSize(QSize(<NUM_LIT>, <NUM_LIT>))<EOL>programLabel.setSizePolicy(labelSizePolicy)<EOL>programLayout.addWidget(programLabel)<EOL>self.programName = QComboBox(self)<EOL>self.programName.setMinimumSize(QSize(<NUM_LIT:100>, <NUM_LIT:0>))<EOL>self.programName.setMaximumSize(QSize(<NUM_LIT>, <NUM_LIT>))<EOL>menuSizePolicy.setHeightForWidth(self.programName.sizePolicy().hasHeightForWidth())<EOL>self.programName.setSizePolicy(menuSizePolicy)<EOL>programLayout.addWidget(self.programName)<EOL>programLayout.setStretch(<NUM_LIT:1>, <NUM_LIT:6>)<EOL>if self.initialInstance:<EOL><INDENT>self.logButton = QPushButton("<STR_LIT:+>", self)<EOL>self.logButton.setToolTip("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>self.logButton = QPushButton("<STR_LIT:->")<EOL>self.logButton.setToolTip("<STR_LIT>")<EOL><DEDENT>self.logButton.setMinimumSize(QSize(<NUM_LIT:16>, <NUM_LIT:16>))  <EOL>self.logButton.setMaximumSize(QSize(<NUM_LIT:16>, <NUM_LIT:16>))  <EOL>self.logButton.setObjectName("<STR_LIT>")<EOL>self.logButton.setStyleSheet("<STR_LIT>")<EOL>self._logSelectLayout = QHBoxLayout()<EOL>self._logSelectLayout.setSpacing(<NUM_LIT:6>)<EOL>self._logSelectLayout.addLayout(logTypeLayout)<EOL>self._logSelectLayout.addLayout(programLayout)<EOL>self._logSelectLayout.addWidget(self.logButton)<EOL>self._logSelectLayout.setStretch(<NUM_LIT:0>, <NUM_LIT:6>)<EOL>self._logSelectLayout.setStretch(<NUM_LIT:1>, <NUM_LIT:6>)<EOL>


<EOL>QObject.connect(self.logType, SIGNAL("<STR_LIT>"), self.changeLogType)<EOL>


if self.logMenuCount > <NUM_LIT:1> and menu is not None:<EOL><INDENT>menu.removeMenu()<EOL>self.logMenus.remove(menu)<EOL>self.logMenuCount -= <NUM_LIT:1><EOL><DEDENT>


from xml.etree import ElementTree<EOL>from re import sub<EOL>rawString = ElementTree.tostring(elem, '<STR_LIT:utf-8>')<EOL>parsedString = sub(r'<STR_LIT>', '<STR_LIT:\n>', rawString)  <EOL>return parsedString[<NUM_LIT:1>:]<EOL>


def prepareImages(self, fileName, logType):

import subprocess<EOL>if self.imageType == "<STR_LIT>":<EOL><INDENT>self.imagePixmap.save(fileName + "<STR_LIT>", "<STR_LIT>", -<NUM_LIT:1>)<EOL>if logType == "<STR_LIT>":<EOL><INDENT>makePostScript = "<STR_LIT>" + fileName + "<STR_LIT>" + fileName + "<STR_LIT>"<EOL>process = subprocess.Popen(makePostScript, shell=True)<EOL>process.wait()<EOL>thumbnailPixmap = self.imagePixmap.scaled(<NUM_LIT>, <NUM_LIT>, Qt.KeepAspectRatio)<EOL>thumbnailPixmap.save(fileName + "<STR_LIT>", "<STR_LIT>", -<NUM_LIT:1>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>renameImage = "<STR_LIT>" + self.image + "<STR_LIT:U+0020>" + fileName + "<STR_LIT>"<EOL>process = subprocess.Popen(renameImage, shell=True)<EOL>process.wait()<EOL>if logType == "<STR_LIT>":<EOL><INDENT>thumbnailPixmap = self.imagePixmap.scaled(<NUM_LIT>, <NUM_LIT>, Qt.KeepAspectRatio)<EOL>thumbnailPixmap.save(fileName + "<STR_LIT>", "<STR_LIT>", -<NUM_LIT:1>)<EOL><DEDENT><DEDENT>

Convert supplied QPixmap object to image file.


from urllib2 import urlopen, URLError, HTTPError<EOL>import json<EOL>isApproved = False<EOL>userName = str(self.logui.userName.text())<EOL>if userName == "<STR_LIT>":<EOL><INDENT>return False  <EOL><DEDENT>if logType == "<STR_LIT>":<EOL><INDENT>networkFault = False<EOL>data = []<EOL>log_url = "<STR_LIT>" + userName<EOL>try:<EOL><INDENT>data = urlopen(log_url, None, <NUM_LIT:5>).read()<EOL>data = json.loads(data)<EOL><DEDENT>except URLError as error:<EOL><INDENT>print("<STR_LIT>" + str(error.reason))<EOL>networkFault = True<EOL><DEDENT>except HTTPError as error:<EOL><INDENT>print("<STR_LIT>" + str(error.reason))<EOL>networkFault = True<EOL><DEDENT>if networkFault:<EOL><INDENT>msgBox = QMessageBox()<EOL>msgBox.setText("<STR_LIT>")<EOL>msgBox.setInformativeText("<STR_LIT>")<EOL>msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)<EOL>msgBox.setDefaultButton(QMessageBox.Ok)<EOL>if msgBox.exec_() == QMessageBox.Ok:<EOL><INDENT>isApproved = True<EOL><DEDENT><DEDENT>if data != [] and (data is not None):<EOL><INDENT>isApproved = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>isApproved = True<EOL><DEDENT>return isApproved<EOL>

Verify enetered user name is on accepted MCC logbook list.


def addLogbooks(self, type=None, logs=[], default="<STR_LIT>"):

if type is not None and len(logs) != <NUM_LIT:0>:<EOL><INDENT>if type in self.logList:<EOL><INDENT>for logbook in logs:<EOL><INDENT>if logbook not in self.logList.get(type)[<NUM_LIT:0>]:<EOL><INDENT>self.logList.get(type)[<NUM_LIT:0>].append(logbook)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>self.logList[type] = []<EOL>self.logList[type].append(logs)<EOL><DEDENT>if len(self.logList[type]) > <NUM_LIT:1> and default != "<STR_LIT>":<EOL><INDENT>self.logList.get(type)[<NUM_LIT:1>] == default<EOL><DEDENT>else:<EOL><INDENT>self.logList.get(type).append(default)<EOL><DEDENT>self.logType.clear()<EOL>self.logType.addItems(list(self.logList.keys()))<EOL>self.changeLogType()<EOL><DEDENT>


self.logui.titleEntry.clear()<EOL>self.logui.textEntry.clear()<EOL>while self.logMenuCount > <NUM_LIT:1>:<EOL><INDENT>self.removeLogbook(self.logMenus[-<NUM_LIT:1>])<EOL><DEDENT>


return t<EOL>


p[<NUM_LIT:0>] = p[<NUM_LIT:1>]<EOL>


if isinstance(p[<NUM_LIT:1>], list):<EOL><INDENT>if isinstance(p[<NUM_LIT:1>][<NUM_LIT:0>], list):<EOL><INDENT>p[<NUM_LIT:0>] = p[<NUM_LIT:1>][<NUM_LIT:0>] + [p[<NUM_LIT:2>]]<EOL><DEDENT>else:<EOL><INDENT>p[<NUM_LIT:0>] = p[<NUM_LIT:1>] + p[<NUM_LIT:2>]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>p[<NUM_LIT:0>] = [p[<NUM_LIT:1>], p[<NUM_LIT:2>]]<EOL><DEDENT>

action_blocks : action_blocks action_block


p[<NUM_LIT:0>] = p[<NUM_LIT:1>] + [p[<NUM_LIT:2>]]<EOL>


t.value = float(t.value)<EOL>return t<EOL>


t.value = int(t.value)<EOL>return t<EOL>


bytestring = hex(N)<EOL>bytestring = bytestring[<NUM_LIT:2>:] if bytestring.startswith('<STR_LIT>') else bytestring<EOL>bytestring = bytestring[:-<NUM_LIT:1>] if bytestring.endswith('<STR_LIT:L>') else bytestring<EOL>bytestring = '<STR_LIT:0>' + bytestring if (len(bytestring) % <NUM_LIT:2>) != <NUM_LIT:0> else bytestring<EOL>bytestring = binascii.unhexlify(bytestring)<EOL>if blocksize > <NUM_LIT:0> and len(bytestring) % blocksize != <NUM_LIT:0>:<EOL><INDENT>bytestring = '<STR_LIT:\x00>' *(blocksize - (len(bytestring) % blocksize)) + bytestring<EOL><DEDENT>return bytestring<EOL>

Given an input integer ``N``, ``long_to_bytes`` returns the representation of ``N`` in bytes.
    If ``blocksize`` is greater than ``1`` then the output string will be right justified and then padded with zero-bytes,
    such that the return values length is a multiple of ``blocksize``.


def _save_without_sending(self, *args, **kwargs):

self.do_not_send = True<EOL>super(MailerMessage, self).save(*args, **kwargs)<EOL>

Saves the MailerMessage instance without sending the e-mail. This ensures
other models (e.g. `Attachment`) have something to relate to in the database.


if offset is None:<EOL><INDENT>offset = getattr(settings, '<STR_LIT>', defaults.MAILQUEUE_CLEAR_OFFSET)<EOL><DEDENT>if type(offset) is int:<EOL><INDENT>offset = datetime.timedelta(hours=offset)<EOL><DEDENT>delete_before = timezone.now() - offset<EOL>self.filter(sent=True, last_attempt__lte=delete_before).delete()<EOL>


def compute_volume_exposures(shares_held, volumes, percentile):

shares_held = shares_held.replace(<NUM_LIT:0>, np.nan)<EOL>shares_longed = shares_held[shares_held > <NUM_LIT:0>]<EOL>shares_shorted = -<NUM_LIT:1> * shares_held[shares_held < <NUM_LIT:0>]<EOL>shares_grossed = shares_held.abs()<EOL>longed_frac = shares_longed.divide(volumes)<EOL>shorted_frac = shares_shorted.divide(volumes)<EOL>grossed_frac = shares_grossed.divide(volumes)<EOL>longed_threshold = <NUM_LIT:100> * longed_frac.apply(<EOL>partial(np.nanpercentile, q=<NUM_LIT:100> * percentile),<EOL>axis='<STR_LIT>',<EOL>)<EOL>shorted_threshold = <NUM_LIT:100> * shorted_frac.apply(<EOL>partial(np.nanpercentile, q=<NUM_LIT:100> * percentile),<EOL>axis='<STR_LIT>',<EOL>)<EOL>grossed_threshold = <NUM_LIT:100> * grossed_frac.apply(<EOL>partial(np.nanpercentile, q=<NUM_LIT:100> * percentile),<EOL>axis='<STR_LIT>',<EOL>)<EOL>return longed_threshold, shorted_threshold, grossed_threshold<EOL>

Returns arrays of pth percentile of long, short and gross volume exposures
of an algorithm's held shares

Parameters
----------
shares_held : pd.DataFrame
    Daily number of shares held by an algorithm.
    - See full explanation in create_risk_tear_sheet

volume : pd.DataFrame
    Daily volume per asset
    - See full explanation in create_risk_tear_sheet

percentile : float
    Percentile to use when computing and plotting volume exposures
    - See full explanation in create_risk_tear_sheet


positions_wo_cash = positions.drop('<STR_LIT>', axis='<STR_LIT>')<EOL>gross_exposure = positions_wo_cash.abs().sum(axis='<STR_LIT>')<EOL>style_factor_exposure = positions_wo_cash.multiply(risk_factor).divide(gross_exposure, axis='<STR_LIT:index>')<EOL>tot_style_factor_exposure = style_factor_exposure.sum(axis='<STR_LIT>',<EOL>skipna=True)<EOL>return tot_style_factor_exposure<EOL>

Returns style factor exposure of an algorithm's positions

Parameters
----------
positions : pd.DataFrame
    Daily equity positions of algorithm, in dollars.
    - See full explanation in create_risk_tear_sheet

risk_factor : pd.DataFrame
    Daily risk factor per asset.
    - DataFrame with dates as index and equities as columns
    - Example:
                     Equity(24   Equity(62
                       [AAPL])      [ABT])
    2017-04-03	  -0.51284     1.39173
    2017-04-04	  -0.73381     0.98149
    2017-04-05	  -0.90132     1.13981


if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>color_list = plt.cm.gist_rainbow(np.linspace(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:5>))<EOL>ax.stackplot(gross_exposures[<NUM_LIT:0>].index, gross_exposures,<EOL>labels=CAP_BUCKETS.keys(), colors=color_list, alpha=<NUM_LIT>,<EOL>baseline='<STR_LIT>')<EOL>ax.axhline(<NUM_LIT:0>, color='<STR_LIT:k>', linestyle='<STR_LIT:->')<EOL>ax.set(title='<STR_LIT>',<EOL>ylabel='<STR_LIT>')<EOL>return ax<EOL>

Plots outputs of compute_cap_exposures as area charts

Parameters
----------
gross_exposures : array
    Arrays of gross market cap exposures (output of compute_cap_exposures).


def plot_sector_exposures_net(net_exposures, sector_dict=None, ax=None):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>if sector_dict is None:<EOL><INDENT>sector_names = SECTORS.values()<EOL><DEDENT>else:<EOL><INDENT>sector_names = sector_dict.values()<EOL><DEDENT>color_list = plt.cm.gist_rainbow(np.linspace(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:11>))<EOL>for i in range(len(net_exposures)):<EOL><INDENT>ax.plot(net_exposures[i], color=color_list[i], alpha=<NUM_LIT>,<EOL>label=sector_names[i])<EOL><DEDENT>ax.set(title='<STR_LIT>',<EOL>ylabel='<STR_LIT>')<EOL>return ax<EOL>

Plots output of compute_sector_exposures as line graphs

Parameters
----------
net_exposures : arrays
    Arrays of net sector exposures (output of compute_sector_exposures).

sector_dict : dict or OrderedDict
    Dictionary of all sectors
    - See full description in compute_sector_exposures


def plot_volume_exposures_gross(grossed_threshold, percentile, ax=None):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>ax.plot(grossed_threshold.index, grossed_threshold,<EOL>color='<STR_LIT:b>', label='<STR_LIT>')<EOL>ax.axhline(<NUM_LIT:0>, color='<STR_LIT:k>')<EOL>ax.set(title='<STR_LIT>',<EOL>ylabel='<STR_LIT>'<EOL>.format(<NUM_LIT:100> * percentile))<EOL>ax.legend(frameon=True, framealpha=<NUM_LIT:0.5>)<EOL>return ax<EOL>

Plots outputs of compute_volume_exposures as line graphs

Parameters
----------
grossed_threshold : pd.Series
    Series of grossed volume exposures (output of
    compute_volume_exposures).

percentile : float
    Percentile to use when computing and plotting volume exposures
    - See full explanation in create_risk_tear_sheet


def plot_sector_exposures_longshort(long_exposures, short_exposures,<EOL>sector_dict=SECTORS, ax=None):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>if sector_dict is None:<EOL><INDENT>sector_names = SECTORS.values()<EOL><DEDENT>else:<EOL><INDENT>sector_names = sector_dict.values()<EOL><DEDENT>color_list = plt.cm.gist_rainbow(np.linspace(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:11>))<EOL>ax.stackplot(long_exposures[<NUM_LIT:0>].index, long_exposures,<EOL>labels=sector_names, colors=color_list, alpha=<NUM_LIT>,<EOL>baseline='<STR_LIT>')<EOL>ax.stackplot(long_exposures[<NUM_LIT:0>].index, short_exposures,<EOL>colors=color_list, alpha=<NUM_LIT>, baseline='<STR_LIT>')<EOL>ax.axhline(<NUM_LIT:0>, color='<STR_LIT:k>', linestyle='<STR_LIT:->')<EOL>ax.set(title='<STR_LIT>',<EOL>ylabel='<STR_LIT>')<EOL>ax.legend(loc='<STR_LIT>', frameon=True, framealpha=<NUM_LIT:0.5>)<EOL>return ax<EOL>

Plots outputs of compute_sector_exposures as area charts

Parameters
----------
long_exposures, short_exposures : arrays
    Arrays of long and short sector exposures (output of
    compute_sector_exposures).

sector_dict : dict or OrderedDict
    Dictionary of all sectors
    - See full description in compute_sector_exposures


if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>color_list = plt.cm.gist_rainbow(np.linspace(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:5>))<EOL>cap_names = CAP_BUCKETS.keys()<EOL>for i in range(len(net_exposures)):<EOL><INDENT>ax.plot(net_exposures[i], color=color_list[i], alpha=<NUM_LIT>,<EOL>label=cap_names[i])<EOL><DEDENT>ax.axhline(<NUM_LIT:0>, color='<STR_LIT:k>', linestyle='<STR_LIT:->')<EOL>ax.set(title='<STR_LIT>',<EOL>ylabel='<STR_LIT>')<EOL>return ax<EOL>

Plots outputs of compute_cap_exposures as line graphs

Parameters
----------
net_exposures : array
    Arrays of gross market cap exposures (output of compute_cap_exposures).


def compute_sector_exposures(positions, sectors, sector_dict=SECTORS):

sector_ids = sector_dict.keys()<EOL>long_exposures = []<EOL>short_exposures = []<EOL>gross_exposures = []<EOL>net_exposures = []<EOL>positions_wo_cash = positions.drop('<STR_LIT>', axis='<STR_LIT>')<EOL>long_exposure = positions_wo_cash[positions_wo_cash > <NUM_LIT:0>].sum(axis='<STR_LIT>')<EOL>short_exposure = positions_wo_cash[positions_wo_cash < <NUM_LIT:0>].abs().sum(axis='<STR_LIT>')<EOL>gross_exposure = positions_wo_cash.abs().sum(axis='<STR_LIT>')<EOL>for sector_id in sector_ids:<EOL><INDENT>in_sector = positions_wo_cash[sectors == sector_id]<EOL>long_sector = in_sector[in_sector > <NUM_LIT:0>].sum(axis='<STR_LIT>').divide(long_exposure)<EOL>short_sector = in_sector[in_sector < <NUM_LIT:0>].sum(axis='<STR_LIT>').divide(short_exposure)<EOL>gross_sector = in_sector.abs().sum(axis='<STR_LIT>').divide(gross_exposure)<EOL>net_sector = long_sector.subtract(short_sector)<EOL>long_exposures.append(long_sector)<EOL>short_exposures.append(short_sector)<EOL>gross_exposures.append(gross_sector)<EOL>net_exposures.append(net_sector)<EOL><DEDENT>return long_exposures, short_exposures, gross_exposures, net_exposures<EOL>

Returns arrays of long, short and gross sector exposures of an algorithm's
positions

Parameters
----------
positions : pd.DataFrame
    Daily equity positions of algorithm, in dollars.
    - See full explanation in compute_style_factor_exposures.

sectors : pd.DataFrame
    Daily Morningstar sector code per asset
    - See full explanation in create_risk_tear_sheet

sector_dict : dict or OrderedDict
    Dictionary of all sectors
    - Keys are sector codes (e.g. ints or strings) and values are sector
      names (which must be strings)
    - Defaults to Morningstar sectors


if not have_bayesian:<EOL><INDENT>raise NotImplementedError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>if live_start_date is None:<EOL><INDENT>raise NotImplementedError(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>live_start_date = ep.utils.get_utc_timestamp(live_start_date)<EOL>df_train = returns.loc[returns.index < live_start_date]<EOL>df_test = returns.loc[returns.index >= live_start_date]<EOL>print("<STR_LIT>")<EOL>previous_time = time()<EOL>start_time = previous_time<EOL>trace_t, ppc_t = bayesian.run_model('<STR_LIT:t>', df_train,<EOL>returns_test=df_test,<EOL>samples=samples, ppc=True,<EOL>progressbar=progressbar)<EOL>previous_time = timer("<STR_LIT>", previous_time)<EOL>print("<STR_LIT>")<EOL>trace_best = bayesian.run_model('<STR_LIT>', df_train,<EOL>returns_test=df_test,<EOL>samples=samples,<EOL>progressbar=progressbar)<EOL>previous_time = timer("<STR_LIT>", previous_time)<EOL>fig = plt.figure(figsize=(<NUM_LIT>, <NUM_LIT:10> * <NUM_LIT:2>))<EOL>gs = gridspec.GridSpec(<NUM_LIT:9>, <NUM_LIT:2>, wspace=<NUM_LIT>, hspace=<NUM_LIT>)<EOL>axs = []<EOL>row = <NUM_LIT:0><EOL>ax_cone = plt.subplot(gs[row, :])<EOL>bayesian.plot_bayes_cone(df_train, df_test, ppc_t, ax=ax_cone)<EOL>previous_time = timer("<STR_LIT>", previous_time)<EOL>row += <NUM_LIT:1><EOL>axs.append(plt.subplot(gs[row, <NUM_LIT:0>]))<EOL>axs.append(plt.subplot(gs[row, <NUM_LIT:1>]))<EOL>row += <NUM_LIT:1><EOL>axs.append(plt.subplot(gs[row, <NUM_LIT:0>]))<EOL>axs.append(plt.subplot(gs[row, <NUM_LIT:1>]))<EOL>row += <NUM_LIT:1><EOL>axs.append(plt.subplot(gs[row, <NUM_LIT:0>]))<EOL>axs.append(plt.subplot(gs[row, <NUM_LIT:1>]))<EOL>row += <NUM_LIT:1><EOL>axs.append(plt.subplot(gs[row, :]))<EOL>bayesian.plot_best(trace=trace_best, axs=axs)<EOL>previous_time = timer("<STR_LIT>", previous_time)<EOL>row += <NUM_LIT:1><EOL>ax_ret_pred_day = plt.subplot(gs[row, <NUM_LIT:0>])<EOL>ax_ret_pred_week = plt.subplot(gs[row, <NUM_LIT:1>])<EOL>day_pred = ppc_t[:, <NUM_LIT:0>]<EOL>p5 = scipy.stats.scoreatpercentile(day_pred, <NUM_LIT:5>)<EOL>sns.distplot(day_pred,<EOL>ax=ax_ret_pred_day<EOL>)<EOL>ax_ret_pred_day.axvline(p5, linestyle='<STR_LIT>', linewidth=<NUM_LIT>)<EOL>ax_ret_pred_day.set_xlabel('<STR_LIT>')<EOL>ax_ret_pred_day.set_ylabel('<STR_LIT>')<EOL>ax_ret_pred_day.text(<NUM_LIT>, <NUM_LIT>, '<STR_LIT>' % p5,<EOL>verticalalignment='<STR_LIT>',<EOL>horizontalalignment='<STR_LIT:right>',<EOL>transform=ax_ret_pred_day.transAxes)<EOL>previous_time = timer("<STR_LIT>", previous_time)<EOL>week_pred = (<EOL>np.cumprod(ppc_t[:, :<NUM_LIT:5>] + <NUM_LIT:1>, <NUM_LIT:1>) - <NUM_LIT:1>)[:, -<NUM_LIT:1>]<EOL>p5 = scipy.stats.scoreatpercentile(week_pred, <NUM_LIT:5>)<EOL>sns.distplot(week_pred,<EOL>ax=ax_ret_pred_week<EOL>)<EOL>ax_ret_pred_week.axvline(p5, linestyle='<STR_LIT>', linewidth=<NUM_LIT>)<EOL>ax_ret_pred_week.set_xlabel('<STR_LIT>')<EOL>ax_ret_pred_week.set_ylabel('<STR_LIT>')<EOL>ax_ret_pred_week.text(<NUM_LIT>, <NUM_LIT>, '<STR_LIT>' % p5,<EOL>verticalalignment='<STR_LIT>',<EOL>horizontalalignment='<STR_LIT:right>',<EOL>transform=ax_ret_pred_week.transAxes)<EOL>previous_time = timer("<STR_LIT>", previous_time)<EOL>if benchmark_rets is not None:<EOL><INDENT>print("<STR_LIT>")<EOL>benchmark_rets = benchmark_rets.loc[df_train.index]<EOL>trace_alpha_beta = bayesian.run_model('<STR_LIT>', df_train,<EOL>bmark=benchmark_rets,<EOL>samples=samples,<EOL>progressbar=progressbar)<EOL>previous_time = timer("<STR_LIT>", previous_time)<EOL>row += <NUM_LIT:1><EOL>ax_alpha = plt.subplot(gs[row, <NUM_LIT:0>])<EOL>ax_beta = plt.subplot(gs[row, <NUM_LIT:1>])<EOL>sns.distplot((<NUM_LIT:1> + trace_alpha_beta['<STR_LIT>'][<NUM_LIT:100>:])**<NUM_LIT> - <NUM_LIT:1>,<EOL>ax=ax_alpha)<EOL>sns.distplot(trace_alpha_beta['<STR_LIT>'][<NUM_LIT:100>:], ax=ax_beta)<EOL>ax_alpha.set_xlabel('<STR_LIT>')<EOL>ax_alpha.set_ylabel('<STR_LIT>')<EOL>ax_beta.set_xlabel('<STR_LIT>')<EOL>ax_beta.set_ylabel('<STR_LIT>')<EOL>previous_time = timer("<STR_LIT>", previous_time)<EOL><DEDENT>if stoch_vol:<EOL><INDENT>returns_cutoff = <NUM_LIT><EOL>print(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(returns_cutoff)<EOL>)<EOL>if df_train.size > returns_cutoff:<EOL><INDENT>df_train_truncated = df_train[-returns_cutoff:]<EOL><DEDENT>_, trace_stoch_vol = bayesian.model_stoch_vol(df_train_truncated)<EOL>previous_time = timer(<EOL>"<STR_LIT>", previous_time)<EOL>row += <NUM_LIT:1><EOL>ax_volatility = plt.subplot(gs[row, :])<EOL>bayesian.plot_stoch_vol(<EOL>df_train_truncated, trace=trace_stoch_vol, ax=ax_volatility)<EOL>previous_time = timer(<EOL>"<STR_LIT>", previous_time)<EOL><DEDENT>total_time = time() - start_time<EOL>print("<STR_LIT>".format(total_time))<EOL>gs.tight_layout(fig)<EOL>if return_fig:<EOL><INDENT>return fig<EOL><DEDENT>

Generate a number of Bayesian distributions and a Bayesian
cone plot of returns.

Plots: Sharpe distribution, annual volatility distribution,
annual alpha distribution, beta distribution, predicted 1 and 5
day returns distributions, and a cumulative returns cone plot.

Parameters
----------
returns : pd.Series
    Daily returns of the strategy, noncumulative.
     - See full explanation in create_full_tear_sheet.
benchmark_rets : pd.Series, optional
    Daily noncumulative returns of the benchmark.
     - This is in the same style as returns.
live_start_date : datetime, optional
    The point in time when the strategy began live
    trading, after its backtest period.
samples : int, optional
    Number of posterior samples to draw.
return_fig : boolean, optional
    If True, returns the figure that was plotted on.
stoch_vol : boolean, optional
    If True, run and plot the stochastic volatility model
progressbar : boolean, optional
    If True, show a progress bar


if (unadjusted_returns is None) and (slippage is not None) and(transactions is not None):<EOL><INDENT>unadjusted_returns = returns.copy()<EOL>returns = txn.adjust_returns_for_slippage(returns, positions,<EOL>transactions, slippage)<EOL><DEDENT>positions = utils.check_intraday(estimate_intraday, returns,<EOL>positions, transactions)<EOL>create_returns_tear_sheet(<EOL>returns,<EOL>positions=positions,<EOL>transactions=transactions,<EOL>live_start_date=live_start_date,<EOL>cone_std=cone_std,<EOL>benchmark_rets=benchmark_rets,<EOL>bootstrap=bootstrap,<EOL>turnover_denom=turnover_denom,<EOL>header_rows=header_rows,<EOL>set_context=set_context)<EOL>create_interesting_times_tear_sheet(returns,<EOL>benchmark_rets=benchmark_rets,<EOL>set_context=set_context)<EOL>if positions is not None:<EOL><INDENT>create_position_tear_sheet(returns, positions,<EOL>hide_positions=hide_positions,<EOL>set_context=set_context,<EOL>sector_mappings=sector_mappings,<EOL>estimate_intraday=False)<EOL>if transactions is not None:<EOL><INDENT>create_txn_tear_sheet(returns, positions, transactions,<EOL>unadjusted_returns=unadjusted_returns,<EOL>estimate_intraday=False,<EOL>set_context=set_context)<EOL>if round_trips:<EOL><INDENT>create_round_trip_tear_sheet(<EOL>returns=returns,<EOL>positions=positions,<EOL>transactions=transactions,<EOL>sector_mappings=sector_mappings,<EOL>estimate_intraday=False)<EOL><DEDENT>if market_data is not None:<EOL><INDENT>create_capacity_tear_sheet(returns, positions, transactions,<EOL>market_data,<EOL>liquidation_daily_vol_limit=<NUM_LIT>,<EOL>last_n_days=<NUM_LIT>,<EOL>estimate_intraday=False)<EOL><DEDENT><DEDENT>if style_factor_panel is not None:<EOL><INDENT>create_risk_tear_sheet(positions, style_factor_panel, sectors,<EOL>caps, shares_held, volumes, percentile)<EOL><DEDENT>if factor_returns is not None and factor_loadings is not None:<EOL><INDENT>create_perf_attrib_tear_sheet(returns, positions, factor_returns,<EOL>factor_loadings, transactions,<EOL>pos_in_dollars=pos_in_dollars,<EOL>factor_partitions=factor_partitions)<EOL><DEDENT><DEDENT>if bayesian:<EOL><INDENT>create_bayesian_tear_sheet(returns,<EOL>live_start_date=live_start_date,<EOL>benchmark_rets=benchmark_rets,<EOL>set_context=set_context)<EOL><DEDENT>

Generate a number of tear sheets that are useful
for analyzing a strategy's performance.

- Fetches benchmarks if needed.
- Creates tear sheets for returns, and significant events.
    If possible, also creates tear sheets for position analysis,
    transaction analysis, and Bayesian analysis.

Parameters
----------
returns : pd.Series
    Daily returns of the strategy, noncumulative.
     - Time series with decimal returns.
     - Example:
        2015-07-16    -0.012143
        2015-07-17    0.045350
        2015-07-20    0.030957
        2015-07-21    0.004902
positions : pd.DataFrame, optional
    Daily net position values.
     - Time series of dollar amount invested in each position and cash.
     - Days where stocks are not held can be represented by 0 or NaN.
     - Non-working capital is labelled 'cash'
     - Example:
        index         'AAPL'         'MSFT'          cash
        2004-01-09    13939.3800     -14012.9930     711.5585
        2004-01-12    14492.6300     -14624.8700     27.1821
        2004-01-13    -13853.2800    13653.6400      -43.6375
transactions : pd.DataFrame, optional
    Executed trade volumes and fill prices.
    - One row per trade.
    - Trades on different names that occur at the
      same time will have identical indicies.
    - Example:
        index                  amount   price    symbol
        2004-01-09 12:18:01    483      324.12   'AAPL'
        2004-01-09 12:18:01    122      83.10    'MSFT'
        2004-01-13 14:12:23    -75      340.43   'AAPL'
market_data : pd.Panel, optional
    Panel with items axis of 'price' and 'volume' DataFrames.
    The major and minor axes should match those of the
    the passed positions DataFrame (same dates and symbols).
slippage : int/float, optional
    Basis points of slippage to apply to returns before generating
    tearsheet stats and plots.
    If a value is provided, slippage parameter sweep
    plots will be generated from the unadjusted returns.
    Transactions and positions must also be passed.
    - See txn.adjust_returns_for_slippage for more details.
live_start_date : datetime, optional
    The point in time when the strategy began live trading,
    after its backtest period. This datetime should be normalized.
hide_positions : bool, optional
    If True, will not output any symbol names.
bayesian: boolean, optional
    If True, causes the generation of a Bayesian tear sheet.
round_trips: boolean, optional
    If True, causes the generation of a round trip tear sheet.
sector_mappings : dict or pd.Series, optional
    Security identifier to sector mapping.
    Security ids as keys, sectors as values.
estimate_intraday: boolean or str, optional
    Instead of using the end-of-day positions, use the point in the day
    where we have the most $ invested. This will adjust positions to
    better approximate and represent how an intraday strategy behaves.
    By default, this is 'infer', and an attempt will be made to detect
    an intraday strategy. Specifying this value will prevent detection.
cone_std : float, or tuple, optional
    If float, The standard deviation to use for the cone plots.
    If tuple, Tuple of standard deviation values to use for the cone plots
     - The cone is a normal distribution with this standard deviation
         centered around a linear regression.
bootstrap : boolean (optional)
    Whether to perform bootstrap analysis for the performance
    metrics. Takes a few minutes longer.
turnover_denom : str
    Either AGB or portfolio_value, default AGB.
    - See full explanation in txn.get_turnover.
factor_returns : pd.Dataframe, optional
    Returns by factor, with date as index and factors as columns
factor_loadings : pd.Dataframe, optional
    Factor loadings for all days in the date range, with date and
    ticker as index, and factors as columns.
pos_in_dollars : boolean, optional
    indicates whether positions is in dollars
header_rows : dict or OrderedDict, optional
    Extra rows to display at the top of the perf stats table.
set_context : boolean, optional
    If True, set default plotting style context.
     - See plotting.context().
factor_partitions : dict, optional
    dict specifying how factors should be separated in perf attrib
    factor returns and risk exposures plots
    - See create_perf_attrib_tear_sheet().


positions = utils.check_intraday(estimate_intraday, returns,<EOL>positions, transactions)<EOL>vertical_sections = <NUM_LIT:6> if unadjusted_returns is not None else <NUM_LIT:4><EOL>fig = plt.figure(figsize=(<NUM_LIT>, vertical_sections * <NUM_LIT:6>))<EOL>gs = gridspec.GridSpec(vertical_sections, <NUM_LIT:3>, wspace=<NUM_LIT:0.5>, hspace=<NUM_LIT:0.5>)<EOL>ax_turnover = plt.subplot(gs[<NUM_LIT:0>, :])<EOL>ax_daily_volume = plt.subplot(gs[<NUM_LIT:1>, :], sharex=ax_turnover)<EOL>ax_turnover_hist = plt.subplot(gs[<NUM_LIT:2>, :])<EOL>ax_txn_timings = plt.subplot(gs[<NUM_LIT:3>, :])<EOL>plotting.plot_turnover(<EOL>returns,<EOL>transactions,<EOL>positions,<EOL>ax=ax_turnover)<EOL>plotting.plot_daily_volume(returns, transactions, ax=ax_daily_volume)<EOL>try:<EOL><INDENT>plotting.plot_daily_turnover_hist(transactions, positions,<EOL>ax=ax_turnover_hist)<EOL><DEDENT>except ValueError:<EOL><INDENT>warnings.warn('<STR_LIT>', UserWarning)<EOL><DEDENT>plotting.plot_txn_time_hist(transactions, ax=ax_txn_timings)<EOL>if unadjusted_returns is not None:<EOL><INDENT>ax_slippage_sweep = plt.subplot(gs[<NUM_LIT:4>, :])<EOL>plotting.plot_slippage_sweep(unadjusted_returns,<EOL>positions,<EOL>transactions,<EOL>ax=ax_slippage_sweep<EOL>)<EOL>ax_slippage_sensitivity = plt.subplot(gs[<NUM_LIT:5>, :])<EOL>plotting.plot_slippage_sensitivity(unadjusted_returns,<EOL>positions,<EOL>transactions,<EOL>ax=ax_slippage_sensitivity<EOL>)<EOL><DEDENT>for ax in fig.axes:<EOL><INDENT>plt.setp(ax.get_xticklabels(), visible=True)<EOL><DEDENT>if return_fig:<EOL><INDENT>return fig<EOL><DEDENT>

Generate a number of plots for analyzing a strategy's transactions.

Plots: turnover, daily volume, and a histogram of daily volume.

Parameters
----------
returns : pd.Series
    Daily returns of the strategy, noncumulative.
     - See full explanation in create_full_tear_sheet.
positions : pd.DataFrame
    Daily net position values.
     - See full explanation in create_full_tear_sheet.
transactions : pd.DataFrame
    Prices and amounts of executed trades. One row per trade.
     - See full explanation in create_full_tear_sheet.
unadjusted_returns : pd.Series, optional
    Daily unadjusted returns of the strategy, noncumulative.
    Will plot additional swippage sweep analysis.
     - See pyfolio.plotting.plot_swippage_sleep and
       pyfolio.plotting.plot_slippage_sensitivity
estimate_intraday: boolean or str, optional
    Approximate returns for intraday strategies.
    See description in create_full_tear_sheet.
return_fig : boolean, optional
    If True, returns the figure that was plotted on.


if benchmark_rets is not None:<EOL><INDENT>returns = utils.clip_returns_to_benchmark(returns, benchmark_rets)<EOL><DEDENT>plotting.show_perf_stats(returns, benchmark_rets,<EOL>positions=positions,<EOL>transactions=transactions,<EOL>turnover_denom=turnover_denom,<EOL>bootstrap=bootstrap,<EOL>live_start_date=live_start_date,<EOL>header_rows=header_rows)<EOL>plotting.show_worst_drawdown_periods(returns)<EOL>vertical_sections = <NUM_LIT:11><EOL>if live_start_date is not None:<EOL><INDENT>vertical_sections += <NUM_LIT:1><EOL>live_start_date = ep.utils.get_utc_timestamp(live_start_date)<EOL><DEDENT>if benchmark_rets is not None:<EOL><INDENT>vertical_sections += <NUM_LIT:1><EOL><DEDENT>if bootstrap:<EOL><INDENT>vertical_sections += <NUM_LIT:1><EOL><DEDENT>fig = plt.figure(figsize=(<NUM_LIT>, vertical_sections * <NUM_LIT:6>))<EOL>gs = gridspec.GridSpec(vertical_sections, <NUM_LIT:3>, wspace=<NUM_LIT:0.5>, hspace=<NUM_LIT:0.5>)<EOL>ax_rolling_returns = plt.subplot(gs[:<NUM_LIT:2>, :])<EOL>i = <NUM_LIT:2><EOL>ax_rolling_returns_vol_match = plt.subplot(gs[i, :],<EOL>sharex=ax_rolling_returns)<EOL>i += <NUM_LIT:1><EOL>ax_rolling_returns_log = plt.subplot(gs[i, :],<EOL>sharex=ax_rolling_returns)<EOL>i += <NUM_LIT:1><EOL>ax_returns = plt.subplot(gs[i, :],<EOL>sharex=ax_rolling_returns)<EOL>i += <NUM_LIT:1><EOL>if benchmark_rets is not None:<EOL><INDENT>ax_rolling_beta = plt.subplot(gs[i, :], sharex=ax_rolling_returns)<EOL>i += <NUM_LIT:1><EOL><DEDENT>ax_rolling_volatility = plt.subplot(gs[i, :], sharex=ax_rolling_returns)<EOL>i += <NUM_LIT:1><EOL>ax_rolling_sharpe = plt.subplot(gs[i, :], sharex=ax_rolling_returns)<EOL>i += <NUM_LIT:1><EOL>ax_drawdown = plt.subplot(gs[i, :], sharex=ax_rolling_returns)<EOL>i += <NUM_LIT:1><EOL>ax_underwater = plt.subplot(gs[i, :], sharex=ax_rolling_returns)<EOL>i += <NUM_LIT:1><EOL>ax_monthly_heatmap = plt.subplot(gs[i, <NUM_LIT:0>])<EOL>ax_annual_returns = plt.subplot(gs[i, <NUM_LIT:1>])<EOL>ax_monthly_dist = plt.subplot(gs[i, <NUM_LIT:2>])<EOL>i += <NUM_LIT:1><EOL>ax_return_quantiles = plt.subplot(gs[i, :])<EOL>i += <NUM_LIT:1><EOL>plotting.plot_rolling_returns(<EOL>returns,<EOL>factor_returns=benchmark_rets,<EOL>live_start_date=live_start_date,<EOL>cone_std=cone_std,<EOL>ax=ax_rolling_returns)<EOL>ax_rolling_returns.set_title(<EOL>'<STR_LIT>')<EOL>plotting.plot_rolling_returns(<EOL>returns,<EOL>factor_returns=benchmark_rets,<EOL>live_start_date=live_start_date,<EOL>cone_std=None,<EOL>volatility_match=(benchmark_rets is not None),<EOL>legend_loc=None,<EOL>ax=ax_rolling_returns_vol_match)<EOL>ax_rolling_returns_vol_match.set_title(<EOL>'<STR_LIT>')<EOL>plotting.plot_rolling_returns(<EOL>returns,<EOL>factor_returns=benchmark_rets,<EOL>logy=True,<EOL>live_start_date=live_start_date,<EOL>cone_std=cone_std,<EOL>ax=ax_rolling_returns_log)<EOL>ax_rolling_returns_log.set_title(<EOL>'<STR_LIT>')<EOL>plotting.plot_returns(<EOL>returns,<EOL>live_start_date=live_start_date,<EOL>ax=ax_returns,<EOL>)<EOL>ax_returns.set_title(<EOL>'<STR_LIT>')<EOL>if benchmark_rets is not None:<EOL><INDENT>plotting.plot_rolling_beta(<EOL>returns, benchmark_rets, ax=ax_rolling_beta)<EOL><DEDENT>plotting.plot_rolling_volatility(<EOL>returns, factor_returns=benchmark_rets, ax=ax_rolling_volatility)<EOL>plotting.plot_rolling_sharpe(<EOL>returns, ax=ax_rolling_sharpe)<EOL>plotting.plot_drawdown_periods(<EOL>returns, top=<NUM_LIT:5>, ax=ax_drawdown)<EOL>plotting.plot_drawdown_underwater(<EOL>returns=returns, ax=ax_underwater)<EOL>plotting.plot_monthly_returns_heatmap(returns, ax=ax_monthly_heatmap)<EOL>plotting.plot_annual_returns(returns, ax=ax_annual_returns)<EOL>plotting.plot_monthly_returns_dist(returns, ax=ax_monthly_dist)<EOL>plotting.plot_return_quantiles(<EOL>returns,<EOL>live_start_date=live_start_date,<EOL>ax=ax_return_quantiles)<EOL>if bootstrap and (benchmark_rets is not None):<EOL><INDENT>ax_bootstrap = plt.subplot(gs[i, :])<EOL>plotting.plot_perf_stats(returns, benchmark_rets,<EOL>ax=ax_bootstrap)<EOL><DEDENT>elif bootstrap:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>for ax in fig.axes:<EOL><INDENT>plt.setp(ax.get_xticklabels(), visible=True)<EOL><DEDENT>if return_fig:<EOL><INDENT>return fig<EOL><DEDENT>

Generate a number of plots for analyzing a strategy's returns.

- Fetches benchmarks, then creates the plots on a single figure.
- Plots: rolling returns (with cone), rolling beta, rolling sharpe,
    rolling Fama-French risk factors, drawdowns, underwater plot, monthly
    and annual return plots, daily similarity plots,
    and return quantile box plot.
- Will also print the start and end dates of the strategy,
    performance statistics, drawdown periods, and the return range.

Parameters
----------
returns : pd.Series
    Daily returns of the strategy, noncumulative.
     - See full explanation in create_full_tear_sheet.
positions : pd.DataFrame, optional
    Daily net position values.
     - See full explanation in create_full_tear_sheet.
transactions : pd.DataFrame, optional
    Executed trade volumes and fill prices.
    - See full explanation in create_full_tear_sheet.
live_start_date : datetime, optional
    The point in time when the strategy began live trading,
    after its backtest period.
cone_std : float, or tuple, optional
    If float, The standard deviation to use for the cone plots.
    If tuple, Tuple of standard deviation values to use for the cone plots
     - The cone is a normal distribution with this standard deviation
         centered around a linear regression.
benchmark_rets : pd.Series, optional
    Daily noncumulative returns of the benchmark.
     - This is in the same style as returns.
bootstrap : boolean, optional
    Whether to perform bootstrap analysis for the performance
    metrics. Takes a few minutes longer.
turnover_denom : str, optional
    Either AGB or portfolio_value, default AGB.
    - See full explanation in txn.get_turnover.
header_rows : dict or OrderedDict, optional
    Extra rows to display at the top of the perf stats table.
return_fig : boolean, optional
    If True, returns the figure that was plotted on.


portfolio_exposures, perf_attrib_data = perf_attrib.perf_attrib(<EOL>returns, positions, factor_returns, factor_loadings, transactions,<EOL>pos_in_dollars=pos_in_dollars<EOL>)<EOL>display(Markdown("<STR_LIT>"))<EOL>perf_attrib.show_perf_attrib_stats(returns, positions, factor_returns,<EOL>factor_loadings, transactions,<EOL>pos_in_dollars)<EOL>vertical_sections = <NUM_LIT:1> + <NUM_LIT:2> * max(len(factor_partitions), <NUM_LIT:1>)<EOL>current_section = <NUM_LIT:0><EOL>fig = plt.figure(figsize=[<NUM_LIT>, vertical_sections * <NUM_LIT:6>])<EOL>gs = gridspec.GridSpec(vertical_sections, <NUM_LIT:1>,<EOL>wspace=<NUM_LIT:0.5>, hspace=<NUM_LIT:0.5>)<EOL>perf_attrib.plot_returns(perf_attrib_data,<EOL>ax=plt.subplot(gs[current_section]))<EOL>current_section += <NUM_LIT:1><EOL>if factor_partitions is not None:<EOL><INDENT>for factor_type, partitions in factor_partitions.iteritems():<EOL><INDENT>columns_to_select = perf_attrib_data.columns.intersection(<EOL>partitions<EOL>)<EOL>perf_attrib.plot_factor_contribution_to_perf(<EOL>perf_attrib_data[columns_to_select],<EOL>ax=plt.subplot(gs[current_section]),<EOL>title=(<EOL>'<STR_LIT>'<EOL>).format(factor_type)<EOL>)<EOL>current_section += <NUM_LIT:1><EOL><DEDENT>for factor_type, partitions in factor_partitions.iteritems():<EOL><INDENT>perf_attrib.plot_risk_exposures(<EOL>portfolio_exposures[portfolio_exposures.columns<EOL>.intersection(partitions)],<EOL>ax=plt.subplot(gs[current_section]),<EOL>title='<STR_LIT>'.format(factor_type)<EOL>)<EOL>current_section += <NUM_LIT:1><EOL><DEDENT><DEDENT>else:<EOL><INDENT>perf_attrib.plot_factor_contribution_to_perf(<EOL>perf_attrib_data,<EOL>ax=plt.subplot(gs[current_section])<EOL>)<EOL>current_section += <NUM_LIT:1><EOL>perf_attrib.plot_risk_exposures(<EOL>portfolio_exposures,<EOL>ax=plt.subplot(gs[current_section])<EOL>)<EOL><DEDENT>gs.tight_layout(fig)<EOL>if return_fig:<EOL><INDENT>return fig<EOL><DEDENT>

Generate plots and tables for analyzing a strategy's performance.

Parameters
----------
returns : pd.Series
    Returns for each day in the date range.

positions: pd.DataFrame
    Daily holdings (in dollars or percentages), indexed by date.
    Will be converted to percentages if positions are in dollars.
    Short positions show up as cash in the 'cash' column.

factor_returns : pd.DataFrame
    Returns by factor, with date as index and factors as columns

factor_loadings : pd.DataFrame
    Factor loadings for all days in the date range, with date
    and ticker as index, and factors as columns.

transactions : pd.DataFrame, optional
    Prices and amounts of executed trades. One row per trade.
     - See full explanation in create_full_tear_sheet.
     - Default is None.

pos_in_dollars : boolean, optional
    Flag indicating whether `positions` are in dollars or percentages
    If True, positions are in dollars.

return_fig : boolean, optional
    If True, returns the figure that was plotted on.

factor_partitions : dict
    dict specifying how factors should be separated in factor returns
    and risk exposures plots
    - Example:
      {'style': ['momentum', 'size', 'value', ...],
       'sector': ['technology', 'materials', ... ]}


positions = utils.check_intraday(estimate_intraday, returns,<EOL>positions, transactions)<EOL>print("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>max_days_by_ticker = capacity.get_max_days_to_liquidate_by_ticker(<EOL>positions, market_data,<EOL>max_bar_consumption=liquidation_daily_vol_limit,<EOL>capital_base=<NUM_LIT>,<EOL>mean_volume_window=<NUM_LIT:5>)<EOL>max_days_by_ticker.index = (<EOL>max_days_by_ticker.index.map(utils.format_asset))<EOL>print("<STR_LIT>")<EOL>utils.print_table(<EOL>max_days_by_ticker[max_days_by_ticker.days_to_liquidate ><EOL>days_to_liquidate_limit])<EOL>max_days_by_ticker_lnd = capacity.get_max_days_to_liquidate_by_ticker(<EOL>positions, market_data,<EOL>max_bar_consumption=liquidation_daily_vol_limit,<EOL>capital_base=<NUM_LIT>,<EOL>mean_volume_window=<NUM_LIT:5>,<EOL>last_n_days=last_n_days)<EOL>max_days_by_ticker_lnd.index = (<EOL>max_days_by_ticker_lnd.index.map(utils.format_asset))<EOL>print("<STR_LIT>".format(last_n_days))<EOL>utils.print_table(<EOL>max_days_by_ticker_lnd[max_days_by_ticker_lnd.days_to_liquidate > <NUM_LIT:1>])<EOL>llt = capacity.get_low_liquidity_transactions(transactions, market_data)<EOL>llt.index = llt.index.map(utils.format_asset)<EOL>print('<STR_LIT>'<EOL>'<STR_LIT>'.format(trade_daily_vol_limit * <NUM_LIT:100>))<EOL>utils.print_table(<EOL>llt[llt['<STR_LIT>'] > trade_daily_vol_limit * <NUM_LIT:100>])<EOL>llt = capacity.get_low_liquidity_transactions(<EOL>transactions, market_data, last_n_days=last_n_days)<EOL>print("<STR_LIT>".format(last_n_days))<EOL>utils.print_table(<EOL>llt[llt['<STR_LIT>'] > trade_daily_vol_limit * <NUM_LIT:100>])<EOL>bt_starting_capital = positions.iloc[<NUM_LIT:0>].sum() / (<NUM_LIT:1> + returns.iloc[<NUM_LIT:0>])<EOL>fig, ax_capacity_sweep = plt.subplots(figsize=(<NUM_LIT>, <NUM_LIT:6>))<EOL>plotting.plot_capacity_sweep(returns, transactions, market_data,<EOL>bt_starting_capital,<EOL>min_pv=<NUM_LIT>,<EOL>max_pv=<NUM_LIT>,<EOL>step_size=<NUM_LIT>,<EOL>ax=ax_capacity_sweep)<EOL>

Generates a report detailing portfolio size constraints set by
least liquid tickers. Plots a "capacity sweep," a curve describing
projected sharpe ratio given the slippage penalties that are
applied at various capital bases.

Parameters
----------
returns : pd.Series
    Daily returns of the strategy, noncumulative.
     - See full explanation in create_full_tear_sheet.
positions : pd.DataFrame
    Daily net position values.
     - See full explanation in create_full_tear_sheet.
transactions : pd.DataFrame
    Prices and amounts of executed trades. One row per trade.
     - See full explanation in create_full_tear_sheet.
market_data : pd.Panel
    Panel with items axis of 'price' and 'volume' DataFrames.
    The major and minor axes should match those of the
    the passed positions DataFrame (same dates and symbols).
liquidation_daily_vol_limit : float
    Max proportion of a daily bar that can be consumed in the
    process of liquidating a position in the
    "days to liquidation" analysis.
trade_daily_vol_limit : float
    Flag daily transaction totals that exceed proportion of
    daily bar.
last_n_days : integer
    Compute max position allocation and dollar volume for only
    the last N days of the backtest
days_to_liquidate_limit : integer
    Display all tickers with greater max days to liquidation.
estimate_intraday: boolean or str, optional
    Approximate returns for intraday strategies.
    See description in create_full_tear_sheet.


dtlp = days_to_liquidate_positions(positions, market_data,<EOL>max_bar_consumption=max_bar_consumption,<EOL>capital_base=capital_base,<EOL>mean_volume_window=mean_volume_window)<EOL>if last_n_days is not None:<EOL><INDENT>dtlp = dtlp.loc[dtlp.index.max() - pd.Timedelta(days=last_n_days):]<EOL><DEDENT>pos_alloc = pos.get_percent_alloc(positions)<EOL>pos_alloc = pos_alloc.drop('<STR_LIT>', axis=<NUM_LIT:1>)<EOL>liq_desc = pd.DataFrame()<EOL>liq_desc['<STR_LIT>'] = dtlp.unstack()<EOL>liq_desc['<STR_LIT>'] = pos_alloc.unstack() * <NUM_LIT:100><EOL>liq_desc.index.levels[<NUM_LIT:0>].name = '<STR_LIT>'<EOL>liq_desc.index.levels[<NUM_LIT:1>].name = '<STR_LIT:date>'<EOL>worst_liq = liq_desc.reset_index().sort_values(<EOL>'<STR_LIT>', ascending=False).groupby('<STR_LIT>').first()<EOL>return worst_liq<EOL>

Finds the longest estimated liquidation time for each traded
name over the course of backtest (or last n days of the backtest).

Parameters
----------
positions: pd.DataFrame
    Contains daily position values including cash
    - See full explanation in tears.create_full_tear_sheet
market_data : pd.Panel
    Panel with items axis of 'price' and 'volume' DataFrames.
    The major and minor axes should match those of the
    the passed positions DataFrame (same dates and symbols).
max_bar_consumption : float
    Max proportion of a daily bar that can be consumed in the
    process of liquidating a position.
capital_base : integer
    Capital base multiplied by portfolio allocation to compute
    position value that needs liquidating.
mean_volume_window : float
    Trailing window to use in mean volume calculation.
last_n_days : integer
    Compute for only the last n days of the passed backtest data.

Returns
-------
days_to_liquidate : pd.DataFrame
    Max Number of days required to fully liquidate each traded name.
    Index of symbols. Columns for days_to_liquidate and the corresponding
    date and position_alloc on that day.


txn_daily_w_bar = daily_txns_with_bar_data(transactions, market_data)<EOL>txn_daily_w_bar.index.name = '<STR_LIT:date>'<EOL>txn_daily_w_bar = txn_daily_w_bar.reset_index()<EOL>if last_n_days is not None:<EOL><INDENT>md = txn_daily_w_bar.date.max() - pd.Timedelta(days=last_n_days)<EOL>txn_daily_w_bar = txn_daily_w_bar[txn_daily_w_bar.date > md]<EOL><DEDENT>bar_consumption = txn_daily_w_bar.assign(<EOL>max_pct_bar_consumed=(<EOL>txn_daily_w_bar.amount/txn_daily_w_bar.volume)*<NUM_LIT:100><EOL>).sort_values('<STR_LIT>', ascending=False)<EOL>max_bar_consumption = bar_consumption.groupby('<STR_LIT>').first()<EOL>return max_bar_consumption[['<STR_LIT:date>', '<STR_LIT>']]<EOL>

For each traded name, find the daily transaction total that consumed
the greatest proportion of available daily bar volume.

Parameters
----------
transactions : pd.DataFrame
    Prices and amounts of executed trades. One row per trade.
     - See full explanation in create_full_tear_sheet.
market_data : pd.Panel
    Panel with items axis of 'price' and 'volume' DataFrames.
    The major and minor axes should match those of the
    the passed positions DataFrame (same dates and symbols).
last_n_days : integer
    Compute for only the last n days of the passed backtest data.


def show_perf_stats(returns, factor_returns=None, positions=None,<EOL>transactions=None, turnover_denom='<STR_LIT>',<EOL>live_start_date=None, bootstrap=False,<EOL>header_rows=None):

if bootstrap:<EOL><INDENT>perf_func = timeseries.perf_stats_bootstrap<EOL><DEDENT>else:<EOL><INDENT>perf_func = timeseries.perf_stats<EOL><DEDENT>perf_stats_all = perf_func(<EOL>returns,<EOL>factor_returns=factor_returns,<EOL>positions=positions,<EOL>transactions=transactions,<EOL>turnover_denom=turnover_denom)<EOL>date_rows = OrderedDict()<EOL>if len(returns.index) > <NUM_LIT:0>:<EOL><INDENT>date_rows['<STR_LIT>'] = returns.index[<NUM_LIT:0>].strftime('<STR_LIT>')<EOL>date_rows['<STR_LIT>'] = returns.index[-<NUM_LIT:1>].strftime('<STR_LIT>')<EOL><DEDENT>if live_start_date is not None:<EOL><INDENT>live_start_date = ep.utils.get_utc_timestamp(live_start_date)<EOL>returns_is = returns[returns.index < live_start_date]<EOL>returns_oos = returns[returns.index >= live_start_date]<EOL>positions_is = None<EOL>positions_oos = None<EOL>transactions_is = None<EOL>transactions_oos = None<EOL>if positions is not None:<EOL><INDENT>positions_is = positions[positions.index < live_start_date]<EOL>positions_oos = positions[positions.index >= live_start_date]<EOL>if transactions is not None:<EOL><INDENT>transactions_is = transactions[(transactions.index <<EOL>live_start_date)]<EOL>transactions_oos = transactions[(transactions.index ><EOL>live_start_date)]<EOL><DEDENT><DEDENT>perf_stats_is = perf_func(<EOL>returns_is,<EOL>factor_returns=factor_returns,<EOL>positions=positions_is,<EOL>transactions=transactions_is,<EOL>turnover_denom=turnover_denom)<EOL>perf_stats_oos = perf_func(<EOL>returns_oos,<EOL>factor_returns=factor_returns,<EOL>positions=positions_oos,<EOL>transactions=transactions_oos,<EOL>turnover_denom=turnover_denom)<EOL>if len(returns.index) > <NUM_LIT:0>:<EOL><INDENT>date_rows['<STR_LIT>'] = int(len(returns_is) /<EOL>APPROX_BDAYS_PER_MONTH)<EOL>date_rows['<STR_LIT>'] = int(len(returns_oos) /<EOL>APPROX_BDAYS_PER_MONTH)<EOL><DEDENT>perf_stats = pd.concat(OrderedDict([<EOL>('<STR_LIT>', perf_stats_is),<EOL>('<STR_LIT>', perf_stats_oos),<EOL>('<STR_LIT>', perf_stats_all),<EOL>]), axis=<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>if len(returns.index) > <NUM_LIT:0>:<EOL><INDENT>date_rows['<STR_LIT>'] = int(len(returns) /<EOL>APPROX_BDAYS_PER_MONTH)<EOL><DEDENT>perf_stats = pd.DataFrame(perf_stats_all, columns=['<STR_LIT>'])<EOL><DEDENT>for column in perf_stats.columns:<EOL><INDENT>for stat, value in perf_stats[column].iteritems():<EOL><INDENT>if stat in STAT_FUNCS_PCT:<EOL><INDENT>perf_stats.loc[stat, column] = str(np.round(value * <NUM_LIT:100>,<EOL><NUM_LIT:1>)) + '<STR_LIT:%>'<EOL><DEDENT><DEDENT><DEDENT>if header_rows is None:<EOL><INDENT>header_rows = date_rows<EOL><DEDENT>else:<EOL><INDENT>header_rows = OrderedDict(header_rows)<EOL>header_rows.update(date_rows)<EOL><DEDENT>utils.print_table(<EOL>perf_stats,<EOL>float_format='<STR_LIT>'.format,<EOL>header_rows=header_rows,<EOL>)<EOL>

Prints some performance metrics of the strategy.

- Shows amount of time the strategy has been run in backtest and
  out-of-sample (in live trading).

- Shows Omega ratio, max drawdown, Calmar ratio, annual return,
  stability, Sharpe ratio, annual volatility, alpha, and beta.

Parameters
----------
returns : pd.Series
    Daily returns of the strategy, noncumulative.
     - See full explanation in tears.create_full_tear_sheet.
factor_returns : pd.Series, optional
    Daily noncumulative returns of the benchmark factor to which betas are
    computed. Usually a benchmark such as market returns.
     - This is in the same style as returns.
positions : pd.DataFrame, optional
    Daily net position values.
     - See full explanation in create_full_tear_sheet.
transactions : pd.DataFrame, optional
    Prices and amounts of executed trades. One row per trade.
    - See full explanation in tears.create_full_tear_sheet
turnover_denom : str, optional
    Either AGB or portfolio_value, default AGB.
    - See full explanation in txn.get_turnover.
live_start_date : datetime, optional
    The point in time when the strategy began live trading, after
    its backtest period.
bootstrap : boolean, optional
    Whether to perform bootstrap analysis for the performance
    metrics.
     - For more information, see timeseries.perf_stats_bootstrap
header_rows : dict or OrderedDict, optional
    Extra rows to display at the top of the displayed table.


def plot_round_trip_lifetimes(round_trips, disp_amount=<NUM_LIT:16>, lsize=<NUM_LIT>, ax=None):

if ax is None:<EOL><INDENT>ax = plt.subplot()<EOL><DEDENT>symbols_sample = round_trips.symbol.unique()<EOL>np.random.seed(<NUM_LIT:1>)<EOL>sample = np.random.choice(round_trips.symbol.unique(), replace=False,<EOL>size=min(disp_amount, len(symbols_sample)))<EOL>sample_round_trips = round_trips[round_trips.symbol.isin(sample)]<EOL>symbol_idx = pd.Series(np.arange(len(sample)), index=sample)<EOL>for symbol, sym_round_trips in sample_round_trips.groupby('<STR_LIT>'):<EOL><INDENT>for _, row in sym_round_trips.iterrows():<EOL><INDENT>c = '<STR_LIT:b>' if row.long else '<STR_LIT:r>'<EOL>y_ix = symbol_idx[symbol] + <NUM_LIT><EOL>ax.plot([row['<STR_LIT>'], row['<STR_LIT>']],<EOL>[y_ix, y_ix], color=c,<EOL>linewidth=lsize, solid_capstyle='<STR_LIT>')<EOL><DEDENT><DEDENT>ax.set_yticks(range(disp_amount))<EOL>ax.set_yticklabels([utils.format_asset(s) for s in sample])<EOL>ax.set_ylim((-<NUM_LIT:0.5>, min(len(sample), disp_amount) - <NUM_LIT:0.5>))<EOL>blue = patches.Rectangle([<NUM_LIT:0>, <NUM_LIT:0>], <NUM_LIT:1>, <NUM_LIT:1>, color='<STR_LIT:b>', label='<STR_LIT>')<EOL>red = patches.Rectangle([<NUM_LIT:0>, <NUM_LIT:0>], <NUM_LIT:1>, <NUM_LIT:1>, color='<STR_LIT:r>', label='<STR_LIT>')<EOL>leg = ax.legend(handles=[blue, red], loc='<STR_LIT>',<EOL>frameon=True, framealpha=<NUM_LIT:0.5>)<EOL>leg.get_frame().set_edgecolor('<STR_LIT>')<EOL>ax.grid(False)<EOL>return ax<EOL>

Plots timespans and directions of a sample of round trip trades.

Parameters
----------
round_trips : pd.DataFrame
    DataFrame with one row per round trip trade.
    - See full explanation in round_trips.extract_round_trips
ax : matplotlib.Axes, optional
    Axes upon which to plot.

Returns
-------
ax : matplotlib.Axes
    The axes that were plotted on.


def plot_gross_leverage(returns, positions, ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>gl = timeseries.gross_lev(positions)<EOL>gl.plot(lw=<NUM_LIT:0.5>, color='<STR_LIT>', legend=False, ax=ax, **kwargs)<EOL>ax.axhline(gl.mean(), color='<STR_LIT:g>', linestyle='<STR_LIT>', lw=<NUM_LIT:3>)<EOL>ax.set_title('<STR_LIT>')<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_xlabel('<STR_LIT>')<EOL>return ax<EOL>

Plots gross leverage versus date.

Gross leverage is the sum of long and short exposure per share
divided by net asset value.

Parameters
----------
returns : pd.Series
    Daily returns of the strategy, noncumulative.
     - See full explanation in tears.create_full_tear_sheet.
positions : pd.DataFrame
    Daily net position values.
     - See full explanation in create_full_tear_sheet.
ax : matplotlib.Axes, optional
    Axes upon which to plot.
**kwargs, optional
    Passed to plotting function.

Returns
-------
ax : matplotlib.Axes
    The axes that were plotted on.


total_pnl = round_trips['<STR_LIT>'].sum()<EOL>pnl_attribution = round_trips.groupby('<STR_LIT>')['<STR_LIT>'].sum() / total_pnl<EOL>pnl_attribution.name = '<STR_LIT>'<EOL>pnl_attribution.index = pnl_attribution.index.map(utils.format_asset)<EOL>utils.print_table(<EOL>pnl_attribution.sort_values(<EOL>inplace=False,<EOL>ascending=False,<EOL>),<EOL>name='<STR_LIT>',<EOL>float_format='<STR_LIT>'.format,<EOL>)<EOL>

Prints the share of total PnL contributed by each
traded name.

Parameters
----------
round_trips : pd.DataFrame
    DataFrame with one row per round trip trade.
    - See full explanation in round_trips.extract_round_trips
ax : matplotlib.Axes, optional
    Axes upon which to plot.

Returns
-------
ax : matplotlib.Axes
    The axes that were plotted on.


def plot_monthly_returns_heatmap(returns, ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>monthly_ret_table = ep.aggregate_returns(returns, '<STR_LIT>')<EOL>monthly_ret_table = monthly_ret_table.unstack().round(<NUM_LIT:3>)<EOL>sns.heatmap(<EOL>monthly_ret_table.fillna(<NUM_LIT:0>) *<EOL><NUM_LIT>,<EOL>annot=True,<EOL>annot_kws={"<STR_LIT:size>": <NUM_LIT:9>},<EOL>alpha=<NUM_LIT:1.0>,<EOL>center=<NUM_LIT:0.0>,<EOL>cbar=False,<EOL>cmap=matplotlib.cm.RdYlGn,<EOL>ax=ax, **kwargs)<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_xlabel('<STR_LIT>')<EOL>ax.set_title("<STR_LIT>")<EOL>return ax<EOL>

Plots a heatmap of returns by month.

Parameters
----------
returns : pd.Series
    Daily returns of the strategy, noncumulative.
     - See full explanation in tears.create_full_tear_sheet.
ax : matplotlib.Axes, optional
    Axes upon which to plot.
**kwargs, optional
    Passed to seaborn plotting function.

Returns
-------
ax : matplotlib.Axes
    The axes that were plotted on.


if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>ax.set_xlabel('<STR_LIT>')<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_yscale('<STR_LIT>' if logy else '<STR_LIT>')<EOL>if volatility_match and factor_returns is None:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>elif volatility_match and factor_returns is not None:<EOL><INDENT>bmark_vol = factor_returns.loc[returns.index].std()<EOL>returns = (returns / returns.std()) * bmark_vol<EOL><DEDENT>cum_rets = ep.cum_returns(returns, <NUM_LIT:1.0>)<EOL>y_axis_formatter = FuncFormatter(utils.two_dec_places)<EOL>ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))<EOL>if factor_returns is not None:<EOL><INDENT>cum_factor_returns = ep.cum_returns(<EOL>factor_returns[cum_rets.index], <NUM_LIT:1.0>)<EOL>cum_factor_returns.plot(lw=<NUM_LIT:2>, color='<STR_LIT>',<EOL>label=factor_returns.name, alpha=<NUM_LIT>,<EOL>ax=ax, **kwargs)<EOL><DEDENT>if live_start_date is not None:<EOL><INDENT>live_start_date = ep.utils.get_utc_timestamp(live_start_date)<EOL>is_cum_returns = cum_rets.loc[cum_rets.index < live_start_date]<EOL>oos_cum_returns = cum_rets.loc[cum_rets.index >= live_start_date]<EOL><DEDENT>else:<EOL><INDENT>is_cum_returns = cum_rets<EOL>oos_cum_returns = pd.Series([])<EOL><DEDENT>is_cum_returns.plot(lw=<NUM_LIT:3>, color='<STR_LIT>', alpha=<NUM_LIT>,<EOL>label='<STR_LIT>', ax=ax, **kwargs)<EOL>if len(oos_cum_returns) > <NUM_LIT:0>:<EOL><INDENT>oos_cum_returns.plot(lw=<NUM_LIT:4>, color='<STR_LIT>', alpha=<NUM_LIT>,<EOL>label='<STR_LIT>', ax=ax, **kwargs)<EOL>if cone_std is not None:<EOL><INDENT>if isinstance(cone_std, (float, int)):<EOL><INDENT>cone_std = [cone_std]<EOL><DEDENT>is_returns = returns.loc[returns.index < live_start_date]<EOL>cone_bounds = cone_function(<EOL>is_returns,<EOL>len(oos_cum_returns),<EOL>cone_std=cone_std,<EOL>starting_value=is_cum_returns[-<NUM_LIT:1>])<EOL>cone_bounds = cone_bounds.set_index(oos_cum_returns.index)<EOL>for std in cone_std:<EOL><INDENT>ax.fill_between(cone_bounds.index,<EOL>cone_bounds[float(std)],<EOL>cone_bounds[float(-std)],<EOL>color='<STR_LIT>', alpha=<NUM_LIT:0.5>)<EOL><DEDENT><DEDENT><DEDENT>if legend_loc is not None:<EOL><INDENT>ax.legend(loc=legend_loc, frameon=True, framealpha=<NUM_LIT:0.5>)<EOL><DEDENT>ax.axhline(<NUM_LIT:1.0>, linestyle='<STR_LIT>', color='<STR_LIT>', lw=<NUM_LIT:2>)<EOL>return ax<EOL>

Plots cumulative rolling returns versus some benchmarks'.

Backtest returns are in green, and out-of-sample (live trading)
returns are in red.

Additionally, a non-parametric cone plot may be added to the
out-of-sample returns region.

Parameters
----------
returns : pd.Series
    Daily returns of the strategy, noncumulative.
     - See full explanation in tears.create_full_tear_sheet.
factor_returns : pd.Series, optional
    Daily noncumulative returns of the benchmark factor to which betas are
    computed. Usually a benchmark such as market returns.
     - This is in the same style as returns.
live_start_date : datetime, optional
    The date when the strategy began live trading, after
    its backtest period. This date should be normalized.
logy : bool, optional
    Whether to log-scale the y-axis.
cone_std : float, or tuple, optional
    If float, The standard deviation to use for the cone plots.
    If tuple, Tuple of standard deviation values to use for the cone plots
     - See timeseries.forecast_cone_bounds for more details.
legend_loc : matplotlib.loc, optional
    The location of the legend on the plot.
volatility_match : bool, optional
    Whether to normalize the volatility of the returns to those of the
    benchmark returns. This helps compare strategies with different
    volatilities. Requires passing of benchmark_rets.
cone_function : function, optional
    Function to use when generating forecast probability cone.
    The function signiture must follow the form:
    def cone(in_sample_returns (pd.Series),
             days_to_project_forward (int),
             cone_std= (float, or tuple),
             starting_value= (int, or float))
    See timeseries.forecast_cone_bootstrap for an example.
ax : matplotlib.Axes, optional
    Axes upon which to plot.
**kwargs, optional
    Passed to plotting function.

Returns
-------
ax : matplotlib.Axes
    The axes that were plotted on.


def plot_sector_allocations(returns, sector_alloc, ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>sector_alloc.plot(title='<STR_LIT>',<EOL>alpha=<NUM_LIT:0.5>, ax=ax, **kwargs)<EOL>box = ax.get_position()<EOL>ax.set_position([box.x0, box.y0 + box.height * <NUM_LIT:0.1>,<EOL>box.width, box.height * <NUM_LIT>])<EOL>ax.legend(loc='<STR_LIT>', frameon=True, framealpha=<NUM_LIT:0.5>,<EOL>bbox_to_anchor=(<NUM_LIT:0.5>, -<NUM_LIT>), ncol=<NUM_LIT:5>)<EOL>ax.set_xlim((sector_alloc.index[<NUM_LIT:0>], sector_alloc.index[-<NUM_LIT:1>]))<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_xlabel('<STR_LIT>')<EOL>return ax<EOL>

Plots the sector exposures of the portfolio over time.

Parameters
----------
returns : pd.Series
    Daily returns of the strategy, noncumulative.
     - See full explanation in tears.create_full_tear_sheet.
sector_alloc : pd.DataFrame
    Portfolio allocation of positions. See pos.get_sector_alloc.
ax : matplotlib.Axes, optional
    Axes upon which to plot.
**kwargs, optional
    Passed to plotting function.

Returns
-------
ax : matplotlib.Axes
    The axes that were plotted on.


def plot_return_quantiles(returns, live_start_date=None, ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>is_returns = returns if live_start_date is Noneelse returns.loc[returns.index < live_start_date]<EOL>is_weekly = ep.aggregate_returns(is_returns, '<STR_LIT>')<EOL>is_monthly = ep.aggregate_returns(is_returns, '<STR_LIT>')<EOL>sns.boxplot(data=[is_returns, is_weekly, is_monthly],<EOL>palette=["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>ax=ax, **kwargs)<EOL>if live_start_date is not None:<EOL><INDENT>oos_returns = returns.loc[returns.index >= live_start_date]<EOL>oos_weekly = ep.aggregate_returns(oos_returns, '<STR_LIT>')<EOL>oos_monthly = ep.aggregate_returns(oos_returns, '<STR_LIT>')<EOL>sns.swarmplot(data=[oos_returns, oos_weekly, oos_monthly], ax=ax,<EOL>color="<STR_LIT>",<EOL>marker="<STR_LIT:d>", **kwargs)<EOL>red_dots = matplotlib.lines.Line2D([], [], color="<STR_LIT>", marker="<STR_LIT:d>",<EOL>label="<STR_LIT>",<EOL>linestyle='<STR_LIT>')<EOL>ax.legend(handles=[red_dots], frameon=True, framealpha=<NUM_LIT:0.5>)<EOL><DEDENT>ax.set_xticklabels(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'])<EOL>ax.set_title('<STR_LIT>')<EOL>return ax<EOL>

Creates a box plot of daily, weekly, and monthly return
distributions.

Parameters
----------
returns : pd.Series
    Daily returns of the strategy, noncumulative.
     - See full explanation in tears.create_full_tear_sheet.
live_start_date : datetime, optional
    The point in time when the strategy began live trading, after
    its backtest period.
ax : matplotlib.Axes, optional
    Axes upon which to plot.
**kwargs, optional
    Passed to seaborn plotting function.

Returns
-------
ax : matplotlib.Axes
    The axes that were plotted on.


def plot_slippage_sensitivity(returns, positions, transactions,<EOL>ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>avg_returns_given_slippage = pd.Series()<EOL>for bps in range(<NUM_LIT:1>, <NUM_LIT:100>):<EOL><INDENT>adj_returns = txn.adjust_returns_for_slippage(returns, positions,<EOL>transactions, bps)<EOL>avg_returns = ep.annual_return(adj_returns)<EOL>avg_returns_given_slippage.loc[bps] = avg_returns<EOL><DEDENT>avg_returns_given_slippage.plot(alpha=<NUM_LIT:1.0>, lw=<NUM_LIT:2>, ax=ax)<EOL>ax.set_title('<STR_LIT>')<EOL>ax.set_xticks(np.arange(<NUM_LIT:0>, <NUM_LIT:100>, <NUM_LIT:10>))<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_xlabel('<STR_LIT>')<EOL>return ax<EOL>

Plots curve relating per-dollar slippage to average annual returns.

Parameters
----------
returns : pd.Series
    Timeseries of portfolio returns to be adjusted for various
    degrees of slippage.
positions : pd.DataFrame
    Daily net position values.
     - See full explanation in tears.create_full_tear_sheet.
transactions : pd.DataFrame
    Prices and amounts of executed trades. One row per trade.
     - See full explanation in tears.create_full_tear_sheet.
ax : matplotlib.Axes, optional
    Axes upon which to plot.
**kwargs, optional
    Passed to seaborn plotting function.

Returns
-------
ax : matplotlib.Axes
    The axes that were plotted on.