signature:
def invert ( self ) :
    """Inverts each value in the heatmap , shifting low towards high values and vice versa .
 This changes each value to : :
 v ' = max - ( v - min )
 where ` ` v ` ` is the value at some spatial location , ` ` min ` ` is the minimum value in the heatmap
 and ` ` max ` ` is the maximum value .
 As the heatmap uses internally a 0.0 to 1.0 representation , this simply becomes ` ` v ' = 1.0 - v ` ` .
 Note that the attributes ` ` min _ value ` ` and ` ` max _ value ` ` are not switched . They both keep their values .
 This function can be useful e . g . when working with depth maps , where algorithms might have
 an easier time representing the furthest away points with zeros , requiring an inverted
 depth map .
 Returns
 arr _ inv : imgaug . HeatmapsOnImage
 Inverted heatmap ."""

implementation:
arr_inv = HeatmapsOnImage . from_0to1 ( 1 - self . arr_0to1 , shape = self . shape , min_value = self . min_value , max_value = self . max_value )
arr_inv . arr_was_2d = self . arr_was_2d
return arr_inv


signature:
def pad ( self , top = 0 , right = 0 , bottom = 0 , left = 0 , mode = "constant" , cval = 0.0 ) :
    """Pad the heatmaps on their top / right / bottom / left side .
 Parameters
 top : int , optional
 Amount of pixels to add at the top side of the heatmaps . Must be 0 or greater .
 right : int , optional
 Amount of pixels to add at the right side of the heatmaps . Must be 0 or greater .
 bottom : int , optional
 Amount of pixels to add at the bottom side of the heatmaps . Must be 0 or greater .
 left : int , optional
 Amount of pixels to add at the left side of the heatmaps . Must be 0 or greater .
 mode : string , optional
 Padding mode to use . See : func : ` numpy . pad ` for details .
 cval : number , optional
 Value to use for padding if ` mode ` is ` ` constant ` ` . See : func : ` numpy . pad ` for details .
 Returns
 imgaug . HeatmapsOnImage
 Padded heatmaps of height ` ` H ' = H + top + bottom ` ` and width ` ` W ' = W + left + right ` ` ."""

implementation:
arr_0to1_padded = ia . pad ( self . arr_0to1 , top = top , right = right , bottom = bottom , left = left , mode = mode , cval = cval )
return HeatmapsOnImage . from_0to1 ( arr_0to1_padded , shape = self . shape , min_value = self . min_value , max_value = self . max_value )


signature:
def pad_to_aspect_ratio ( self , aspect_ratio , mode = "constant" , cval = 0.0 , return_pad_amounts = False ) :
    """Pad the heatmaps on their sides so that they match a target aspect ratio .
 Depending on which dimension is smaller ( height or width ) , only the corresponding
 sides ( left / right or top / bottom ) will be padded . In each case , both of the sides will
 be padded equally .
 Parameters
 aspect _ ratio : float
 Target aspect ratio , given as width / height . E . g . 2.0 denotes the image having twice
 as much width as height .
 mode : str , optional
 Padding mode to use . See : func : ` numpy . pad ` for details .
 cval : number , optional
 Value to use for padding if ` mode ` is ` ` constant ` ` . See : func : ` numpy . pad ` for details .
 return _ pad _ amounts : bool , optional
 If False , then only the padded image will be returned . If True , a tuple with two
 entries will be returned , where the first entry is the padded image and the second
 entry are the amounts by which each image side was padded . These amounts are again a
 tuple of the form ( top , right , bottom , left ) , with each value being an integer .
 Returns
 heatmaps : imgaug . HeatmapsOnImage
 Padded heatmaps as HeatmapsOnImage object .
 pad _ amounts : tuple of int
 Amounts by which the heatmaps were padded on each side , given as a tuple ` ` ( top , right , bottom , left ) ` ` .
 This tuple is only returned if ` return _ pad _ amounts ` was set to True ."""

implementation:
arr_0to1_padded , pad_amounts = ia . pad_to_aspect_ratio ( self . arr_0to1 , aspect_ratio = aspect_ratio , mode = mode , cval = cval , return_pad_amounts = True )
heatmaps = HeatmapsOnImage . from_0to1 ( arr_0to1_padded , shape = self . shape , min_value = self . min_value , max_value = self . max_value )
if return_pad_amounts :
    return heatmaps , pad_amounts
else :
    return heatmaps


signature:
def avg_pool ( self , block_size ) :
    """Resize the heatmap ( s ) array using average pooling of a given block / kernel size .
 Parameters
 block _ size : int or tuple of int
 Size of each block of values to pool , aka kernel size . See : func : ` imgaug . pool ` for details .
 Returns
 imgaug . HeatmapsOnImage
 Heatmaps after average pooling ."""

implementation:
arr_0to1_reduced = ia . avg_pool ( self . arr_0to1 , block_size , cval = 0.0 )
return HeatmapsOnImage . from_0to1 ( arr_0to1_reduced , shape = self . shape , min_value = self . min_value , max_value = self . max_value )


signature:
def max_pool ( self , block_size ) :
    """Resize the heatmap ( s ) array using max - pooling of a given block / kernel size .
 Parameters
 block _ size : int or tuple of int
 Size of each block of values to pool , aka kernel size . See : func : ` imgaug . pool ` for details .
 Returns
 imgaug . HeatmapsOnImage
 Heatmaps after max - pooling ."""

implementation:
arr_0to1_reduced = ia . max_pool ( self . arr_0to1 , block_size )
return HeatmapsOnImage . from_0to1 ( arr_0to1_reduced , shape = self . shape , min_value = self . min_value , max_value = self . max_value )


signature:
def resize ( self , sizes , interpolation = "cubic" ) :
    """Resize the heatmap ( s ) array to the provided size given the provided interpolation .
 Parameters
 sizes : float or iterable of int or iterable of float
 New size of the array in ` ` ( height , width ) ` ` .
 See : func : ` imgaug . imgaug . imresize _ single _ image ` for details .
 interpolation : None or str or int , optional
 The interpolation to use during resize .
 See : func : ` imgaug . imgaug . imresize _ single _ image ` for details .
 Returns
 imgaug . HeatmapsOnImage
 Resized heatmaps object ."""

implementation:
arr_0to1_resized = ia . imresize_single_image ( self . arr_0to1 , sizes , interpolation = interpolation )
# cubic interpolation can lead to values outside of [ 0.0 , 1.0 ] ,
# see https : / / github . com / opencv / opencv / issues / 7195
# TODO area interpolation too ?
arr_0to1_resized = np . clip ( arr_0to1_resized , 0.0 , 1.0 )
return HeatmapsOnImage . from_0to1 ( arr_0to1_resized , shape = self . shape , min_value = self . min_value , max_value = self . max_value )


signature:
def to_uint8 ( self ) :
    """Convert this heatmaps object to a 0 - to - 255 array .
 Returns
 arr _ uint8 : ( H , W , C ) ndarray
 Heatmap as a 0 - to - 255 array ( dtype is uint8 ) ."""

implementation:
# TODO this always returns ( H , W , C ) , even if input ndarray was originall ( H , W )
# does it make sense here to also return ( H , W ) if self . arr _ was _ 2d ?
arr_0to255 = np . clip ( np . round ( self . arr_0to1 * 255 ) , 0 , 255 )
arr_uint8 = arr_0to255 . astype ( np . uint8 )
return arr_uint8


signature:
def from_uint8 ( arr_uint8 , shape , min_value = 0.0 , max_value = 1.0 ) :
    """Create a heatmaps object from an heatmap array containing values ranging from 0 to 255.
 Parameters
 arr _ uint8 : ( H , W ) ndarray or ( H , W , C ) ndarray
 Heatmap ( s ) array , where ` ` H ` ` is height , ` ` W ` ` is width and ` ` C ` ` is the number of heatmap channels .
 Expected dtype is uint8.
 shape : tuple of int
 Shape of the image on which the heatmap ( s ) is / are placed . NOT the shape of the
 heatmap ( s ) array , unless it is identical to the image shape ( note the likely
 difference between the arrays in the number of channels ) .
 If there is not a corresponding image , use the shape of the heatmaps array .
 min _ value : float , optional
 Minimum value for the heatmaps that the 0 - to - 255 array represents . This will usually
 be 0.0 . It is used when calling : func : ` imgaug . HeatmapsOnImage . get _ arr ` , which converts the
 underlying ` ` ( 0 , 255 ) ` ` array to value range ` ` ( min _ value , max _ value ) ` ` .
 max _ value : float , optional
 Maximum value for the heatmaps that 0 - to - 255 array represents .
 See parameter ` min _ value ` for details .
 Returns
 imgaug . HeatmapsOnImage
 Heatmaps object ."""

implementation:
arr_0to1 = arr_uint8 . astype ( np . float32 ) / 255.0
return HeatmapsOnImage . from_0to1 ( arr_0to1 , shape , min_value = min_value , max_value = max_value )


signature:
def from_0to1 ( arr_0to1 , shape , min_value = 0.0 , max_value = 1.0 ) :
    """Create a heatmaps object from an heatmap array containing values ranging from 0.0 to 1.0.
 Parameters
 arr _ 0to1 : ( H , W ) or ( H , W , C ) ndarray
 Heatmap ( s ) array , where ` ` H ` ` is height , ` ` W ` ` is width and ` ` C ` ` is the number of heatmap channels .
 Expected dtype is float32.
 shape : tuple of ints
 Shape of the image on which the heatmap ( s ) is / are placed . NOT the shape of the
 heatmap ( s ) array , unless it is identical to the image shape ( note the likely
 difference between the arrays in the number of channels ) .
 If there is not a corresponding image , use the shape of the heatmaps array .
 min _ value : float , optional
 Minimum value for the heatmaps that the 0 - to - 1 array represents . This will usually
 be 0.0 . It is used when calling : func : ` imgaug . HeatmapsOnImage . get _ arr ` , which converts the
 underlying ` ` ( 0.0 , 1.0 ) ` ` array to value range ` ` ( min _ value , max _ value ) ` ` .
 E . g . if you started with heatmaps in the range ` ` ( - 1.0 , 1.0 ) ` ` and projected these
 to ( 0.0 , 1.0 ) , you should call this function with ` ` min _ value = - 1.0 ` ` , ` ` max _ value = 1.0 ` `
 so that : func : ` imgaug . HeatmapsOnImage . get _ arr ` returns heatmap arrays having value
 range ( - 1.0 , 1.0 ) .
 max _ value : float , optional
 Maximum value for the heatmaps that to 0 - to - 255 array represents .
 See parameter min _ value for details .
 Returns
 heatmaps : imgaug . HeatmapsOnImage
 Heatmaps object ."""

implementation:
heatmaps = HeatmapsOnImage ( arr_0to1 , shape , min_value = 0.0 , max_value = 1.0 )
heatmaps . min_value = min_value
heatmaps . max_value = max_value
return heatmaps


signature:
def change_normalization ( cls , arr , source , target ) :
    """Change the value range of a heatmap from one min - max to another min - max .
 E . g . the value range may be changed from min = 0.0 , max = 1.0 to min = - 1.0 , max = 1.0.
 Parameters
 arr : ndarray
 Heatmap array to modify .
 source : tuple of float
 Current value range of the input array , given as ( min , max ) , where both are float values .
 target : tuple of float
 Desired output value range of the array , given as ( min , max ) , where both are float values .
 Returns
 arr _ target : ndarray
 Input array , with value range projected to the desired target value range ."""

implementation:
ia . do_assert ( ia . is_np_array ( arr ) )
if isinstance ( source , HeatmapsOnImage ) :
    source = ( source . min_value , source . max_value )
else :
    ia . do_assert ( isinstance ( source , tuple ) )
    ia . do_assert ( len ( source ) == 2 )
    ia . do_assert ( source [ 0 ] < source [ 1 ] )
if isinstance ( target , HeatmapsOnImage ) :
    target = ( target . min_value , target . max_value )
else :
    ia . do_assert ( isinstance ( target , tuple ) )
    ia . do_assert ( len ( target ) == 2 )
    ia . do_assert ( target [ 0 ] < target [ 1 ] )
# Check if source and target are the same ( with a tiny bit of tolerance )
# if so , evade compuation and just copy the array instead .
# This is reasonable , as source and target will often both be ( 0.0 , 1.0 ) .
eps = np . finfo ( arr . dtype ) . eps
mins_same = source [ 0 ] - 10 * eps < target [ 0 ] < source [ 0 ] + 10 * eps
maxs_same = source [ 1 ] - 10 * eps < target [ 1 ] < source [ 1 ] + 10 * eps
if mins_same and maxs_same :
    return np . copy ( arr )
min_source , max_source = source
min_target , max_target = target
diff_source = max_source - min_source
diff_target = max_target - min_target
arr_0to1 = ( arr - min_source ) / diff_source
arr_target = min_target + arr_0to1 * diff_target
return arr_target


signature:
def deepcopy ( self ) :
    """Create a deep copy of the Heatmaps object .
 Returns
 imgaug . HeatmapsOnImage
 Deep copy ."""

implementation: return HeatmapsOnImage ( self . get_arr ( ) , shape = self . shape , min_value = self . min_value , max_value = self . max_value )


signature:
def setdefault ( self , key : str , value : str ) -> str :
    """If the header ` key ` does not exist , then set it to ` value ` .
 Returns the header value ."""

implementation:
set_key = key . lower ( ) . encode ( "latin-1" )
set_value = value . encode ( "latin-1" )
for idx , ( item_key , item_value ) in enumerate ( self . _list ) :
    if item_key == set_key :
        return item_value . decode ( "latin-1" )
self . _list . append ( ( set_key , set_value ) )
return value


signature:
def append ( self , key : str , value : str ) -> None :
    """Append a header , preserving any duplicate entries ."""

implementation:
append_key = key . lower ( ) . encode ( "latin-1" )
append_value = value . encode ( "latin-1" )
self . _list . append ( ( append_key , append_value ) )


signature:
def request_response ( func : typing . Callable ) -> ASGIApp :
    """Takes a function or coroutine ` func ( request ) - > response ` ,
 and returns an ASGI application ."""

implementation:
is_coroutine = asyncio . iscoroutinefunction ( func )
async def app ( scope : Scope , receive : Receive , send : Send ) -> None :
    request = Request ( scope , receive = receive )
    if is_coroutine :
        response = await func ( request )
    else :
        response = await run_in_threadpool ( func , request )
    await response ( scope , receive , send )
return app


signature:
def websocket_session ( func : typing . Callable ) -> ASGIApp :
    """Takes a coroutine ` func ( session ) ` , and returns an ASGI application ."""

implementation:
# assert asyncio . iscoroutinefunction ( func ) , " WebSocket endpoints must be async "
async def app ( scope : Scope , receive : Receive , send : Send ) -> None :
    session = WebSocket ( scope , receive = receive , send = send )
    await func ( session )
return app


signature:
def compile_path ( path : str ) -> typing . Tuple [ typing . Pattern , str , typing . Dict [ str , Convertor ] ] :
    """Given a path string , like : " / { username : str } " , return a three - tuple
 of ( regex , format , { param _ name : convertor } ) .
 regex : " / ( ? P < username > [ ^ / ] + ) "
 format : " / { username } "
 convertors : { " username " : StringConvertor ( ) }"""

implementation:
path_regex = "^"
path_format = ""
idx = 0
param_convertors = { }
for match in PARAM_REGEX . finditer ( path ) :
    param_name , convertor_type = match . groups ( "str" )
    convertor_type = convertor_type . lstrip ( ":" )
    assert ( convertor_type in CONVERTOR_TYPES ) , f"Unknown path convertor '{convertor_type}'"
    convertor = CONVERTOR_TYPES [ convertor_type ]
    path_regex += path [ idx : match . start ( ) ]
    path_regex += f"(?P<{param_name}>{convertor.regex})"
    path_format += path [ idx : match . start ( ) ]
    path_format += "{%s}" % param_name
    param_convertors [ param_name ] = convertor
    idx = match . end ( )
path_regex += path [ idx : ] + "$"
path_format += path [ idx : ]
return re . compile ( path_regex ) , path_format , param_convertors


signature:
def get_endpoints ( self , routes : typing . List [ BaseRoute ] ) -> typing . List [ EndpointInfo ] :
    """Given the routes , yields the following information :
 - path
 eg : / users /
 - http _ method
 one of ' get ' , ' post ' , ' put ' , ' patch ' , ' delete ' , ' options '
 - func
 method ready to extract the docstring"""

implementation:
endpoints_info : list = [ ]
for route in routes :
    if isinstance ( route , Mount ) :
        routes = route . routes or [ ]
        sub_endpoints = [ EndpointInfo ( path = "" . join ( ( route . path , sub_endpoint . path ) ) , http_method = sub_endpoint . http_method , func = sub_endpoint . func , ) for sub_endpoint in self . get_endpoints ( routes ) ]
        endpoints_info . extend ( sub_endpoints )
    elif not isinstance ( route , Route ) or not route . include_in_schema :
        continue
    elif inspect . isfunction ( route . endpoint ) or inspect . ismethod ( route . endpoint ) :
        for method in route . methods or [ "GET" ] :
            if method == "HEAD" :
                continue
            endpoints_info . append ( EndpointInfo ( route . path , method . lower ( ) , route . endpoint ) )
    else :
        for method in [ "get" , "post" , "put" , "patch" , "delete" , "options" ] :
            if not hasattr ( route . endpoint , method ) :
                continue
            func = getattr ( route . endpoint , method )
            endpoints_info . append ( EndpointInfo ( route . path , method . lower ( ) , func ) )
return endpoints_info


signature:
def parse_docstring ( self , func_or_method : typing . Callable ) -> dict :
    """Given a function , parse the docstring as YAML and return a dictionary of info ."""

implementation:
docstring = func_or_method . __doc__
if not docstring :
    return { }
# We support having regular docstrings before the schema
# definition . Here we return just the schema part from
# the docstring .
docstring = docstring . split ( "---" ) [ - 1 ]
parsed = yaml . safe_load ( docstring )
if not isinstance ( parsed , dict ) : # A regular docstring ( not yaml formatted ) can return
# a simple string here , which wouldn ' t follow the schema .
    return { }
return parsed


signature:
def get_directories ( self , directory : str = None , packages : typing . List [ str ] = None ) -> typing . List [ str ] :
    """Given ` directory ` and ` packages ` arugments , return a list of all the
 directories that should be used for serving static files from ."""

implementation:
directories = [ ]
if directory is not None :
    directories . append ( directory )
for package in packages or [ ] :
    spec = importlib . util . find_spec ( package )
    assert spec is not None , f"Package {package!r} could not be found."
    assert ( spec . origin is not None ) , "Directory 'statics' in package {package!r} could not be found."
    directory = os . path . normpath ( os . path . join ( spec . origin , ".." , "statics" ) )
    assert os . path . isdir ( directory ) , "Directory 'statics' in package {package!r} could not be found."
    directories . append ( directory )
return directories


signature:
def get_path ( self , scope : Scope ) -> str :
    """Given the ASGI scope , return the ` path ` string to serve up ,
 with OS specific path seperators , and any ' . . ' , ' . ' components removed ."""

implementation: return os . path . normpath ( os . path . join ( * scope [ "path" ] . split ( "/" ) ) )


signature:
async def get_response ( self , path : str , scope : Scope ) -> Response :
    """Returns an HTTP response , given the incoming path , method and request headers ."""

implementation:
if scope [ "method" ] not in ( "GET" , "HEAD" ) :
    return PlainTextResponse ( "Method Not Allowed" , status_code = 405 )
if path . startswith ( ".." ) : # Most clients will normalize the path , so we shouldn ' t normally
# get this , but don ' t allow misbehaving clients to break out of
# the static files directory .
    return PlainTextResponse ( "Not Found" , status_code = 404 )
full_path , stat_result = await self . lookup_path ( path )
if stat_result and stat . S_ISREG ( stat_result . st_mode ) : # We have a static file to serve .
    return self . file_response ( full_path , stat_result , scope )
elif stat_result and stat . S_ISDIR ( stat_result . st_mode ) and self . html : # We ' re in HTML mode , and have got a directory URL .
# Check if we have ' index . html ' file to serve .
    index_path = os . path . join ( path , "index.html" )
    full_path , stat_result = await self . lookup_path ( index_path )
    if stat_result is not None and stat . S_ISREG ( stat_result . st_mode ) :
        if not scope [ "path" ] . endswith ( "/" ) : # Directory URLs should redirect to always end in " / " .
            url = URL ( scope = scope )
            url = url . replace ( path = url . path + "/" )
            return RedirectResponse ( url = url )
        return self . file_response ( full_path , stat_result , scope )
if self . html : # Check for ' 404 . html ' if we ' re in HTML mode .
    full_path , stat_result = await self . lookup_path ( "404.html" )
    if stat_result is not None and stat . S_ISREG ( stat_result . st_mode ) :
        return self . file_response ( full_path , stat_result , scope , status_code = 404 )
return PlainTextResponse ( "Not Found" , status_code = 404 )


signature:
async def check_config ( self ) -> None :
    """Perform a one - off configuration check that StaticFiles is actually
 pointed at a directory , so that we can raise loud errors rather than
 just returning 404 responses ."""

implementation:
if self . directory is None :
    return
try :
    stat_result = await aio_stat ( self . directory )
except FileNotFoundError :
    raise RuntimeError ( f"StaticFiles directory '{self.directory}' does not exist." )
if not ( stat . S_ISDIR ( stat_result . st_mode ) or stat . S_ISLNK ( stat_result . st_mode ) ) :
    raise RuntimeError ( f"StaticFiles path '{self.directory}' is not a directory." )


signature:
def is_not_modified ( self , response_headers : Headers , request_headers : Headers ) -> bool :
    """Given the request and response headers , return ` True ` if an HTTP
 " Not Modified " response could be returned instead ."""

implementation:
try :
    if_none_match = request_headers [ "if-none-match" ]
    etag = response_headers [ "etag" ]
    if if_none_match == etag :
        return True
except KeyError :
    pass
try :
    if_modified_since = parsedate ( request_headers [ "if-modified-since" ] )
    last_modified = parsedate ( response_headers [ "last-modified" ] )
    if ( if_modified_since is not None and last_modified is not None and if_modified_since >= last_modified ) :
        return True
except KeyError :
    pass
return False


signature:
def build_environ ( scope : Scope , body : bytes ) -> dict :
    """Builds a scope and request body into a WSGI environ object ."""

implementation:
environ = { "REQUEST_METHOD" : scope [ "method" ] , "SCRIPT_NAME" : scope . get ( "root_path" , "" ) , "PATH_INFO" : scope [ "path" ] , "QUERY_STRING" : scope [ "query_string" ] . decode ( "ascii" ) , "SERVER_PROTOCOL" : f"HTTP/{scope['http_version']}" , "wsgi.version" : ( 1 , 0 ) , "wsgi.url_scheme" : scope . get ( "scheme" , "http" ) , "wsgi.input" : io . BytesIO ( body ) , "wsgi.errors" : sys . stdout , "wsgi.multithread" : True , "wsgi.multiprocess" : True , "wsgi.run_once" : False , }
# Get server name and port - required in WSGI , not in ASGI
server = scope . get ( "server" ) or ( "localhost" , 80 )
environ [ "SERVER_NAME" ] = server [ 0 ]
environ [ "SERVER_PORT" ] = server [ 1 ]
# Get client IP address
if scope . get ( "client" ) :
    environ [ "REMOTE_ADDR" ] = scope [ "client" ] [ 0 ]
# Go through headers and make them into environ entries
for name , value in scope . get ( "headers" , [ ] ) :
    name = name . decode ( "latin1" )
    if name == "content-length" :
        corrected_name = "CONTENT_LENGTH"
    elif name == "content-type" :
        corrected_name = "CONTENT_TYPE"
    else :
        corrected_name = f"HTTP_{name}" . upper ( ) . replace ( "-" , "_" )
    # HTTPbis say only ASCII chars are allowed in headers , but we latin1 just in case
    value = value . decode ( "latin1" )
    if corrected_name in environ :
        value = environ [ corrected_name ] + "," + value
    environ [ corrected_name ] = value
return environ


signature:
async def receive ( self ) -> Message :
    """Receive ASGI websocket messages , ensuring valid state transitions ."""

implementation:
if self . client_state == WebSocketState . CONNECTING :
    message = await self . _receive ( )
    message_type = message [ "type" ]
    assert message_type == "websocket.connect"
    self . client_state = WebSocketState . CONNECTED
    return message
elif self . client_state == WebSocketState . CONNECTED :
    message = await self . _receive ( )
    message_type = message [ "type" ]
    assert message_type in { "websocket.receive" , "websocket.disconnect" }
    if message_type == "websocket.disconnect" :
        self . client_state = WebSocketState . DISCONNECTED
    return message
else :
    raise RuntimeError ( 'Cannot call "receive" once a disconnect message has been received.' )


signature:
async def send ( self , message : Message ) -> None :
    """Send ASGI websocket messages , ensuring valid state transitions ."""

implementation:
if self . application_state == WebSocketState . CONNECTING :
    message_type = message [ "type" ]
    assert message_type in { "websocket.accept" , "websocket.close" }
    if message_type == "websocket.close" :
        self . application_state = WebSocketState . DISCONNECTED
    else :
        self . application_state = WebSocketState . CONNECTED
    await self . _send ( message )
elif self . application_state == WebSocketState . CONNECTED :
    message_type = message [ "type" ]
    assert message_type in { "websocket.send" , "websocket.close" }
    if message_type == "websocket.close" :
        self . application_state = WebSocketState . DISCONNECTED
    await self . _send ( message )
else :
    raise RuntimeError ( 'Cannot call "send" once a close message has been sent.' )


signature:
def get_top_long_short_abs ( positions , top = 10 ) :
    """Finds the top long , short , and absolute positions .
 Parameters
 positions : pd . DataFrame
 The positions that the strategy takes over time .
 top : int , optional
 How many of each to find ( default 10 ) .
 Returns
 df _ top _ long : pd . DataFrame
 Top long positions .
 df _ top _ short : pd . DataFrame
 Top short positions .
 df _ top _ abs : pd . DataFrame
 Top absolute positions ."""

implementation:
positions = positions . drop ( 'cash' , axis = 'columns' )
df_max = positions . max ( )
df_min = positions . min ( )
df_abs_max = positions . abs ( ) . max ( )
df_top_long = df_max [ df_max > 0 ] . nlargest ( top )
df_top_short = df_min [ df_min < 0 ] . nsmallest ( top )
df_top_abs = df_abs_max . nlargest ( top )
return df_top_long , df_top_short , df_top_abs


signature:
def get_max_median_position_concentration ( positions ) :
    """Finds the max and median long and short position concentrations
 in each time period specified by the index of positions .
 Parameters
 positions : pd . DataFrame
 The positions that the strategy takes over time .
 Returns
 pd . DataFrame
 Columns are max long , max short , median long , and median short
 position concentrations . Rows are timeperiods ."""

implementation:
expos = get_percent_alloc ( positions )
expos = expos . drop ( 'cash' , axis = 1 )
longs = expos . where ( expos . applymap ( lambda x : x > 0 ) )
shorts = expos . where ( expos . applymap ( lambda x : x < 0 ) )
alloc_summary = pd . DataFrame ( )
alloc_summary [ 'max_long' ] = longs . max ( axis = 1 )
alloc_summary [ 'median_long' ] = longs . median ( axis = 1 )
alloc_summary [ 'median_short' ] = shorts . median ( axis = 1 )
alloc_summary [ 'max_short' ] = shorts . min ( axis = 1 )
return alloc_summary


signature:
def extract_pos ( positions , cash ) :
    """Extract position values from backtest object as returned by
 get _ backtest ( ) on the Quantopian research platform .
 Parameters
 positions : pd . DataFrame
 timeseries containing one row per symbol ( and potentially
 duplicate datetime indices ) and columns for amount and
 last _ sale _ price .
 cash : pd . Series
 timeseries containing cash in the portfolio .
 Returns
 pd . DataFrame
 Daily net position values .
 - See full explanation in tears . create _ full _ tear _ sheet ."""

implementation:
positions = positions . copy ( )
positions [ 'values' ] = positions . amount * positions . last_sale_price
cash . name = 'cash'
values = positions . reset_index ( ) . pivot_table ( index = 'index' , columns = 'sid' , values = 'values' )
if ZIPLINE :
    for asset in values . columns :
        if type ( asset ) in [ Equity , Future ] :
            values [ asset ] = values [ asset ] * asset . price_multiplier
values = values . join ( cash ) . fillna ( 0 )
# NOTE : Set name of DataFrame . columns to sid , to match the behavior
# of DataFrame . join in earlier versions of pandas .
values . columns . name = 'sid'
return values


signature:
def get_sector_exposures ( positions , symbol_sector_map ) :
    """Sum position exposures by sector .
 Parameters
 positions : pd . DataFrame
 Contains position values or amounts .
 - Example
 index ' AAPL ' ' MSFT ' ' CHK ' cash
 2004-01-09 13939.380 - 15012.993 - 403.870 1477.483
 2004-01-12 14492.630 - 18624.870 142.630 3989.610
 2004-01-13 - 13853.280 13653.640 - 100.980 100.000
 symbol _ sector _ map : dict or pd . Series
 Security identifier to sector mapping .
 Security ids as keys / index , sectors as values .
 - Example :
 { ' AAPL ' : ' Technology '
 ' MSFT ' : ' Technology '
 ' CHK ' : ' Natural Resources ' }
 Returns
 sector _ exp : pd . DataFrame
 Sectors and their allocations .
 - Example :
 index ' Technology ' ' Natural Resources ' cash
 2004-01-09 - 1073.613 - 403.870 1477.4830
 2004-01-12 - 4132.240 142.630 3989.6100
 2004-01-13 - 199.640 - 100.980 100.0000"""

implementation:
cash = positions [ 'cash' ]
positions = positions . drop ( 'cash' , axis = 1 )
unmapped_pos = np . setdiff1d ( positions . columns . values , list ( symbol_sector_map . keys ( ) ) )
if len ( unmapped_pos ) > 0 :
    warn_message = """Warning: Symbols {} have no sector mapping.
        They will not be included in sector allocations""" . format ( ", " . join ( map ( str , unmapped_pos ) ) )
    warnings . warn ( warn_message , UserWarning )
sector_exp = positions . groupby ( by = symbol_sector_map , axis = 1 ) . sum ( )
sector_exp [ 'cash' ] = cash
return sector_exp


signature:
def get_long_short_pos ( positions ) :
    """Determines the long and short allocations in a portfolio .
 Parameters
 positions : pd . DataFrame
 The positions that the strategy takes over time .
 Returns
 df _ long _ short : pd . DataFrame
 Long and short allocations as a decimal
 percentage of the total net liquidation"""

implementation:
pos_wo_cash = positions . drop ( 'cash' , axis = 1 )
longs = pos_wo_cash [ pos_wo_cash > 0 ] . sum ( axis = 1 ) . fillna ( 0 )
shorts = pos_wo_cash [ pos_wo_cash < 0 ] . sum ( axis = 1 ) . fillna ( 0 )
cash = positions . cash
net_liquidation = longs + shorts + cash
df_pos = pd . DataFrame ( { 'long' : longs . divide ( net_liquidation , axis = 'index' ) , 'short' : shorts . divide ( net_liquidation , axis = 'index' ) } )
df_pos [ 'net exposure' ] = df_pos [ 'long' ] + df_pos [ 'short' ]
return df_pos


signature:
def compute_style_factor_exposures ( positions , risk_factor ) :
    """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"""

implementation:
positions_wo_cash = positions . drop ( 'cash' , axis = 'columns' )
gross_exposure = positions_wo_cash . abs ( ) . sum ( axis = 'columns' )
style_factor_exposure = positions_wo_cash . multiply ( risk_factor ) . divide ( gross_exposure , axis = 'index' )
tot_style_factor_exposure = style_factor_exposure . sum ( axis = 'columns' , skipna = True )
return tot_style_factor_exposure


signature:
def plot_style_factor_exposures ( tot_style_factor_exposure , factor_name = None , ax = None ) :
    """Plots DataFrame output of compute _ style _ factor _ exposures as a line graph
 Parameters
 tot _ style _ factor _ exposure : pd . Series
 Daily style factor exposures ( output of compute _ style _ factor _ exposures )
 - Time series with decimal style factor exposures
 - Example :
 2017-04-24 0.037820
 2017-04-25 0.016413
 2017-04-26 - 0.021472
 2017-04-27 - 0.024859
 factor _ name : string
 Name of style factor , for use in graph title
 - Defaults to tot _ style _ factor _ exposure . name"""

implementation:
if ax is None :
    ax = plt . gca ( )
if factor_name is None :
    factor_name = tot_style_factor_exposure . name
ax . plot ( tot_style_factor_exposure . index , tot_style_factor_exposure , label = factor_name )
avg = tot_style_factor_exposure . mean ( )
ax . axhline ( avg , linestyle = '-.' , label = 'Mean = {:.3}' . format ( avg ) )
ax . axhline ( 0 , color = 'k' , linestyle = '-' )
_ , _ , y1 , y2 = plt . axis ( )
lim = max ( abs ( y1 ) , abs ( y2 ) )
ax . set ( title = 'Exposure to {}' . format ( factor_name ) , ylabel = '{} \n weighted exposure' . format ( factor_name ) , ylim = ( - lim , lim ) )
ax . legend ( frameon = True , framealpha = 0.5 )
return ax


signature:
def compute_sector_exposures ( positions , sectors , sector_dict = SECTORS ) :
    """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"""

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


signature:
def plot_sector_exposures_longshort ( long_exposures , short_exposures , sector_dict = SECTORS , ax = None ) :
    """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"""

implementation:
if ax is None :
    ax = plt . gca ( )
if sector_dict is None :
    sector_names = SECTORS . values ( )
else :
    sector_names = sector_dict . values ( )
color_list = plt . cm . gist_rainbow ( np . linspace ( 0 , 1 , 11 ) )
ax . stackplot ( long_exposures [ 0 ] . index , long_exposures , labels = sector_names , colors = color_list , alpha = 0.8 , baseline = 'zero' )
ax . stackplot ( long_exposures [ 0 ] . index , short_exposures , colors = color_list , alpha = 0.8 , baseline = 'zero' )
ax . axhline ( 0 , color = 'k' , linestyle = '-' )
ax . set ( title = 'Long and short exposures to sectors' , ylabel = 'Proportion of long/short exposure in sectors' )
ax . legend ( loc = 'upper left' , frameon = True , framealpha = 0.5 )
return ax


signature:
def plot_sector_exposures_gross ( gross_exposures , sector_dict = None , ax = None ) :
    """Plots output of compute _ sector _ exposures as area charts
 Parameters
 gross _ exposures : arrays
 Arrays of gross sector exposures ( output of compute _ sector _ exposures ) .
 sector _ dict : dict or OrderedDict
 Dictionary of all sectors
 - See full description in compute _ sector _ exposures"""

implementation:
if ax is None :
    ax = plt . gca ( )
if sector_dict is None :
    sector_names = SECTORS . values ( )
else :
    sector_names = sector_dict . values ( )
color_list = plt . cm . gist_rainbow ( np . linspace ( 0 , 1 , 11 ) )
ax . stackplot ( gross_exposures [ 0 ] . index , gross_exposures , labels = sector_names , colors = color_list , alpha = 0.8 , baseline = 'zero' )
ax . axhline ( 0 , color = 'k' , linestyle = '-' )
ax . set ( title = 'Gross exposure to sectors' , ylabel = 'Proportion of gross exposure \n in sectors' )
return ax


signature:
def plot_sector_exposures_net ( net_exposures , sector_dict = None , ax = None ) :
    """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"""

implementation:
if ax is None :
    ax = plt . gca ( )
if sector_dict is None :
    sector_names = SECTORS . values ( )
else :
    sector_names = sector_dict . values ( )
color_list = plt . cm . gist_rainbow ( np . linspace ( 0 , 1 , 11 ) )
for i in range ( len ( net_exposures ) ) :
    ax . plot ( net_exposures [ i ] , color = color_list [ i ] , alpha = 0.8 , label = sector_names [ i ] )
ax . set ( title = 'Net exposures to sectors' , ylabel = 'Proportion of net exposure \n in sectors' )
return ax


signature:
def compute_cap_exposures ( positions , caps ) :
    """Returns arrays of long , short and gross market cap 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 .
 caps : pd . DataFrame
 Daily Morningstar sector code per asset
 - See full explanation in create _ risk _ tear _ sheet"""

implementation:
long_exposures = [ ]
short_exposures = [ ]
gross_exposures = [ ]
net_exposures = [ ]
positions_wo_cash = positions . drop ( 'cash' , axis = 'columns' )
tot_gross_exposure = positions_wo_cash . abs ( ) . sum ( axis = 'columns' )
tot_long_exposure = positions_wo_cash [ positions_wo_cash > 0 ] . sum ( axis = 'columns' )
tot_short_exposure = positions_wo_cash [ positions_wo_cash < 0 ] . abs ( ) . sum ( axis = 'columns' )
for bucket_name , boundaries in CAP_BUCKETS . items ( ) :
    in_bucket = positions_wo_cash [ ( caps >= boundaries [ 0 ] ) & ( caps <= boundaries [ 1 ] ) ]
    gross_bucket = in_bucket . abs ( ) . sum ( axis = 'columns' ) . divide ( tot_gross_exposure )
    long_bucket = in_bucket [ in_bucket > 0 ] . sum ( axis = 'columns' ) . divide ( tot_long_exposure )
    short_bucket = in_bucket [ in_bucket < 0 ] . sum ( axis = 'columns' ) . divide ( tot_short_exposure )
    net_bucket = long_bucket . subtract ( short_bucket )
    gross_exposures . append ( gross_bucket )
    long_exposures . append ( long_bucket )
    short_exposures . append ( short_bucket )
    net_exposures . append ( net_bucket )
return long_exposures , short_exposures , gross_exposures , net_exposures


signature:
def plot_cap_exposures_longshort ( long_exposures , short_exposures , ax = None ) :
    """Plots outputs of compute _ cap _ exposures as area charts
 Parameters
 long _ exposures , short _ exposures : arrays
 Arrays of long and short market cap exposures ( output of
 compute _ cap _ exposures ) ."""

implementation:
if ax is None :
    ax = plt . gca ( )
color_list = plt . cm . gist_rainbow ( np . linspace ( 0 , 1 , 5 ) )
ax . stackplot ( long_exposures [ 0 ] . index , long_exposures , labels = CAP_BUCKETS . keys ( ) , colors = color_list , alpha = 0.8 , baseline = 'zero' )
ax . stackplot ( long_exposures [ 0 ] . index , short_exposures , colors = color_list , alpha = 0.8 , baseline = 'zero' )
ax . axhline ( 0 , color = 'k' , linestyle = '-' )
ax . set ( title = 'Long and short exposures to market caps' , ylabel = 'Proportion of long/short exposure in market cap buckets' )
ax . legend ( loc = 'upper left' , frameon = True , framealpha = 0.5 )
return ax


signature:
def plot_cap_exposures_gross ( gross_exposures , ax = None ) :
    """Plots outputs of compute _ cap _ exposures as area charts
 Parameters
 gross _ exposures : array
 Arrays of gross market cap exposures ( output of compute _ cap _ exposures ) ."""

implementation:
if ax is None :
    ax = plt . gca ( )
color_list = plt . cm . gist_rainbow ( np . linspace ( 0 , 1 , 5 ) )
ax . stackplot ( gross_exposures [ 0 ] . index , gross_exposures , labels = CAP_BUCKETS . keys ( ) , colors = color_list , alpha = 0.8 , baseline = 'zero' )
ax . axhline ( 0 , color = 'k' , linestyle = '-' )
ax . set ( title = 'Gross exposure to market caps' , ylabel = 'Proportion of gross exposure \n in market cap buckets' )
return ax


signature:
def plot_cap_exposures_net ( net_exposures , ax = None ) :
    """Plots outputs of compute _ cap _ exposures as line graphs
 Parameters
 net _ exposures : array
 Arrays of gross market cap exposures ( output of compute _ cap _ exposures ) ."""

implementation:
if ax is None :
    ax = plt . gca ( )
color_list = plt . cm . gist_rainbow ( np . linspace ( 0 , 1 , 5 ) )
cap_names = CAP_BUCKETS . keys ( )
for i in range ( len ( net_exposures ) ) :
    ax . plot ( net_exposures [ i ] , color = color_list [ i ] , alpha = 0.8 , label = cap_names [ i ] )
ax . axhline ( 0 , color = 'k' , linestyle = '-' )
ax . set ( title = 'Net exposure to market caps' , ylabel = 'Proportion of net exposure \n in market cap buckets' )
return ax


signature:
def compute_volume_exposures ( shares_held , volumes , percentile ) :
    """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"""

implementation:
shares_held = shares_held . replace ( 0 , np . nan )
shares_longed = shares_held [ shares_held > 0 ]
shares_shorted = - 1 * shares_held [ shares_held < 0 ]
shares_grossed = shares_held . abs ( )
longed_frac = shares_longed . divide ( volumes )
shorted_frac = shares_shorted . divide ( volumes )
grossed_frac = shares_grossed . divide ( volumes )
# NOTE : To work around a bug in ` quantile ` with nan - handling in
# pandas 0.18 , use np . nanpercentile by applying to each row of
# the dataframe . This is fixed in pandas 0.19.
# longed _ threshold = 100 * longed _ frac . quantile ( percentile , axis = ' columns ' )
# shorted _ threshold = 100 * shorted _ frac . quantile ( percentile , axis = ' columns ' )
# grossed _ threshold = 100 * grossed _ frac . quantile ( percentile , axis = ' columns ' )
longed_threshold = 100 * longed_frac . apply ( partial ( np . nanpercentile , q = 100 * percentile ) , axis = 'columns' , )
shorted_threshold = 100 * shorted_frac . apply ( partial ( np . nanpercentile , q = 100 * percentile ) , axis = 'columns' , )
grossed_threshold = 100 * grossed_frac . apply ( partial ( np . nanpercentile , q = 100 * percentile ) , axis = 'columns' , )
return longed_threshold , shorted_threshold , grossed_threshold


signature:
def plot_volume_exposures_longshort ( longed_threshold , shorted_threshold , percentile , ax = None ) :
    """Plots outputs of compute _ volume _ exposures as line graphs
 Parameters
 longed _ threshold , shorted _ threshold : pd . Series
 Series of longed and shorted 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"""

implementation:
if ax is None :
    ax = plt . gca ( )
ax . plot ( longed_threshold . index , longed_threshold , color = 'b' , label = 'long' )
ax . plot ( shorted_threshold . index , shorted_threshold , color = 'r' , label = 'short' )
ax . axhline ( 0 , color = 'k' )
ax . set ( title = 'Long and short exposures to illiquidity' , ylabel = '{}th percentile of proportion of volume (%)' . format ( 100 * percentile ) )
ax . legend ( frameon = True , framealpha = 0.5 )
return ax


signature:
def plot_volume_exposures_gross ( grossed_threshold , percentile , ax = None ) :
    """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"""

implementation:
if ax is None :
    ax = plt . gca ( )
ax . plot ( grossed_threshold . index , grossed_threshold , color = 'b' , label = 'gross' )
ax . axhline ( 0 , color = 'k' )
ax . set ( title = 'Gross exposure to illiquidity' , ylabel = '{}th percentile of \n proportion of volume (%)' . format ( 100 * percentile ) )
ax . legend ( frameon = True , framealpha = 0.5 )
return ax


signature:
def create_full_tear_sheet ( returns , positions = None , transactions = None , market_data = None , benchmark_rets = None , slippage = None , live_start_date = None , sector_mappings = None , bayesian = False , round_trips = False , estimate_intraday = 'infer' , hide_positions = False , cone_std = ( 1.0 , 1.5 , 2.0 ) , bootstrap = False , unadjusted_returns = None , style_factor_panel = None , sectors = None , caps = None , shares_held = None , volumes = None , percentile = None , turnover_denom = 'AGB' , set_context = True , factor_returns = None , factor_loadings = None , pos_in_dollars = True , header_rows = None , factor_partitions = FACTOR_PARTITIONS ) :
    """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 ( ) ."""

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


signature:
def create_simple_tear_sheet ( returns , positions = None , transactions = None , benchmark_rets = None , slippage = None , estimate_intraday = 'infer' , live_start_date = None , turnover_denom = 'AGB' , header_rows = None ) :
    """Simpler version of create _ full _ tear _ sheet ; generates summary performance
 statistics and important plots as a single image .
 - Plots : cumulative returns , rolling beta , rolling Sharpe , underwater ,
 exposure , top 10 holdings , total holdings , long / short holdings ,
 daily turnover , transaction time distribution .
 - Never accept market _ data input ( market _ data = None )
 - Never accept sector _ mappings input ( sector _ mappings = None )
 - Never perform bootstrap analysis ( bootstrap = False )
 - Never hide posistions on top 10 holdings plot ( hide _ positions = False )
 - Always use default cone _ std ( cone _ std = ( 1.0 , 1.5 , 2.0 ) )
 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 '
 benchmark _ rets : pd . Series , optional
 Daily returns of the benchmark , noncumulative .
 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 .
 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 .
 set _ context : boolean , optional
 If True , set default plotting style context ."""

implementation:
positions = utils . check_intraday ( estimate_intraday , returns , positions , transactions )
if ( slippage is not None ) and ( transactions is not None ) :
    returns = txn . adjust_returns_for_slippage ( returns , positions , transactions , slippage )
always_sections = 4
positions_sections = 4 if positions is not None else 0
transactions_sections = 2 if transactions is not None else 0
live_sections = 1 if live_start_date is not None else 0
benchmark_sections = 1 if benchmark_rets is not None else 0
vertical_sections = sum ( [ always_sections , positions_sections , transactions_sections , live_sections , benchmark_sections , ] )
if live_start_date is not None :
    live_start_date = ep . utils . get_utc_timestamp ( live_start_date )
plotting . show_perf_stats ( returns , benchmark_rets , positions = positions , transactions = transactions , turnover_denom = turnover_denom , live_start_date = live_start_date , header_rows = header_rows )
fig = plt . figure ( figsize = ( 14 , vertical_sections * 6 ) )
gs = gridspec . GridSpec ( vertical_sections , 3 , wspace = 0.5 , hspace = 0.5 )
ax_rolling_returns = plt . subplot ( gs [ : 2 , : ] )
i = 2
if benchmark_rets is not None :
    ax_rolling_beta = plt . subplot ( gs [ i , : ] , sharex = ax_rolling_returns )
    i += 1
ax_rolling_sharpe = plt . subplot ( gs [ i , : ] , sharex = ax_rolling_returns )
i += 1
ax_underwater = plt . subplot ( gs [ i , : ] , sharex = ax_rolling_returns )
i += 1
plotting . plot_rolling_returns ( returns , factor_returns = benchmark_rets , live_start_date = live_start_date , cone_std = ( 1.0 , 1.5 , 2.0 ) , ax = ax_rolling_returns )
ax_rolling_returns . set_title ( 'Cumulative returns' )
if benchmark_rets is not None :
    plotting . plot_rolling_beta ( returns , benchmark_rets , ax = ax_rolling_beta )
plotting . plot_rolling_sharpe ( returns , ax = ax_rolling_sharpe )
plotting . plot_drawdown_underwater ( returns , ax = ax_underwater )
if positions is not None : # Plot simple positions tear sheet
    ax_exposures = plt . subplot ( gs [ i , : ] )
    i += 1
    ax_top_positions = plt . subplot ( gs [ i , : ] , sharex = ax_exposures )
    i += 1
    ax_holdings = plt . subplot ( gs [ i , : ] , sharex = ax_exposures )
    i += 1
    ax_long_short_holdings = plt . subplot ( gs [ i , : ] )
    i += 1
    positions_alloc = pos . get_percent_alloc ( positions )
    plotting . plot_exposures ( returns , positions , ax = ax_exposures )
    plotting . show_and_plot_top_positions ( returns , positions_alloc , show_and_plot = 0 , hide_positions = False , ax = ax_top_positions )
    plotting . plot_holdings ( returns , positions_alloc , ax = ax_holdings )
    plotting . plot_long_short_holdings ( returns , positions_alloc , ax = ax_long_short_holdings )
    if transactions is not None : # Plot simple transactions tear sheet
        ax_turnover = plt . subplot ( gs [ i , : ] )
        i += 1
        ax_txn_timings = plt . subplot ( gs [ i , : ] )
        i += 1
        plotting . plot_turnover ( returns , transactions , positions , ax = ax_turnover )
        plotting . plot_txn_time_hist ( transactions , ax = ax_txn_timings )
for ax in fig . axes :
    plt . setp ( ax . get_xticklabels ( ) , visible = True )


signature:
def create_returns_tear_sheet ( returns , positions = None , transactions = None , live_start_date = None , cone_std = ( 1.0 , 1.5 , 2.0 ) , benchmark_rets = None , bootstrap = False , turnover_denom = 'AGB' , header_rows = None , return_fig = False ) :
    """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 ."""

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


signature:
def create_position_tear_sheet ( returns , positions , show_and_plot_top_pos = 2 , hide_positions = False , return_fig = False , sector_mappings = None , transactions = None , estimate_intraday = 'infer' ) :
    """Generate a number of plots for analyzing a
 strategy ' s positions and holdings .
 - Plots : gross leverage , exposures , top positions , and holdings .
 - Will also print the top positions held .
 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 .
 show _ and _ plot _ top _ pos : int , optional
 By default , this is 2 , and both prints and plots the
 top 10 positions .
 If this is 0 , it will only plot ; if 1 , it will only print .
 hide _ positions : bool , optional
 If True , will not output any symbol names .
 Overrides show _ and _ plot _ top _ pos to 0 to suppress text output .
 return _ fig : boolean , optional
 If True , returns the figure that was plotted on .
 sector _ mappings : dict or pd . Series , optional
 Security identifier to sector mapping .
 Security ids as keys , sectors as values .
 transactions : pd . DataFrame , optional
 Prices and amounts of executed trades . One row per trade .
 - See full explanation in create _ full _ tear _ sheet .
 estimate _ intraday : boolean or str , optional
 Approximate returns for intraday strategies .
 See description in create _ full _ tear _ sheet ."""

implementation:
positions = utils . check_intraday ( estimate_intraday , returns , positions , transactions )
if hide_positions :
    show_and_plot_top_pos = 0
vertical_sections = 7 if sector_mappings is not None else 6
fig = plt . figure ( figsize = ( 14 , vertical_sections * 6 ) )
gs = gridspec . GridSpec ( vertical_sections , 3 , wspace = 0.5 , hspace = 0.5 )
ax_exposures = plt . subplot ( gs [ 0 , : ] )
ax_top_positions = plt . subplot ( gs [ 1 , : ] , sharex = ax_exposures )
ax_max_median_pos = plt . subplot ( gs [ 2 , : ] , sharex = ax_exposures )
ax_holdings = plt . subplot ( gs [ 3 , : ] , sharex = ax_exposures )
ax_long_short_holdings = plt . subplot ( gs [ 4 , : ] )
ax_gross_leverage = plt . subplot ( gs [ 5 , : ] , sharex = ax_exposures )
positions_alloc = pos . get_percent_alloc ( positions )
plotting . plot_exposures ( returns , positions , ax = ax_exposures )
plotting . show_and_plot_top_positions ( returns , positions_alloc , show_and_plot = show_and_plot_top_pos , hide_positions = hide_positions , ax = ax_top_positions )
plotting . plot_max_median_position_concentration ( positions , ax = ax_max_median_pos )
plotting . plot_holdings ( returns , positions_alloc , ax = ax_holdings )
plotting . plot_long_short_holdings ( returns , positions_alloc , ax = ax_long_short_holdings )
plotting . plot_gross_leverage ( returns , positions , ax = ax_gross_leverage )
if sector_mappings is not None :
    sector_exposures = pos . get_sector_exposures ( positions , sector_mappings )
    if len ( sector_exposures . columns ) > 1 :
        sector_alloc = pos . get_percent_alloc ( sector_exposures )
        sector_alloc = sector_alloc . drop ( 'cash' , axis = 'columns' )
        ax_sector_alloc = plt . subplot ( gs [ 6 , : ] , sharex = ax_exposures )
        plotting . plot_sector_allocations ( returns , sector_alloc , ax = ax_sector_alloc )
for ax in fig . axes :
    plt . setp ( ax . get_xticklabels ( ) , visible = True )
if return_fig :
    return fig


signature:
def create_txn_tear_sheet ( returns , positions , transactions , unadjusted_returns = None , estimate_intraday = 'infer' , return_fig = False ) :
    """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 ."""

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


signature:
def create_round_trip_tear_sheet ( returns , positions , transactions , sector_mappings = None , estimate_intraday = 'infer' , return_fig = False ) :
    """Generate a number of figures and plots describing the duration ,
 frequency , and profitability of trade " round trips . "
 A round trip is started when a new long or short position is
 opened and is only completed when the number of shares in that
 position returns to or crosses zero .
 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 .
 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
 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 ."""

implementation:
positions = utils . check_intraday ( estimate_intraday , returns , positions , transactions )
transactions_closed = round_trips . add_closing_transactions ( positions , transactions )
# extract _ round _ trips requires BoD portfolio _ value
trades = round_trips . extract_round_trips ( transactions_closed , portfolio_value = positions . sum ( axis = 'columns' ) / ( 1 + returns ) )
if len ( trades ) < 5 :
    warnings . warn ( """Fewer than 5 round-trip trades made.
               Skipping round trip tearsheet.""" , UserWarning )
    return
round_trips . print_round_trip_stats ( trades )
plotting . show_profit_attribution ( trades )
if sector_mappings is not None :
    sector_trades = round_trips . apply_sector_mappings_to_round_trips ( trades , sector_mappings )
    plotting . show_profit_attribution ( sector_trades )
fig = plt . figure ( figsize = ( 14 , 3 * 6 ) )
gs = gridspec . GridSpec ( 3 , 2 , wspace = 0.5 , hspace = 0.5 )
ax_trade_lifetimes = plt . subplot ( gs [ 0 , : ] )
ax_prob_profit_trade = plt . subplot ( gs [ 1 , 0 ] )
ax_holding_time = plt . subplot ( gs [ 1 , 1 ] )
ax_pnl_per_round_trip_dollars = plt . subplot ( gs [ 2 , 0 ] )
ax_pnl_per_round_trip_pct = plt . subplot ( gs [ 2 , 1 ] )
plotting . plot_round_trip_lifetimes ( trades , ax = ax_trade_lifetimes )
plotting . plot_prob_profit_trade ( trades , ax = ax_prob_profit_trade )
trade_holding_times = [ x . days for x in trades [ 'duration' ] ]
sns . distplot ( trade_holding_times , kde = False , ax = ax_holding_time )
ax_holding_time . set ( xlabel = 'Holding time in days' )
sns . distplot ( trades . pnl , kde = False , ax = ax_pnl_per_round_trip_dollars )
ax_pnl_per_round_trip_dollars . set ( xlabel = 'PnL per round-trip trade in $' )
sns . distplot ( trades . returns . dropna ( ) * 100 , kde = False , ax = ax_pnl_per_round_trip_pct )
ax_pnl_per_round_trip_pct . set ( xlabel = 'Round-trip returns in %' )
gs . tight_layout ( fig )
if return_fig :
    return fig


signature:
def create_interesting_times_tear_sheet ( returns , benchmark_rets = None , legend_loc = 'best' , return_fig = False ) :
    """Generate a number of returns plots around interesting points in time ,
 like the flash crash and 9/11.
 Plots : returns around the dotcom bubble burst , Lehmann Brothers ' failure ,
 9/11 , US downgrade and EU debt crisis , Fukushima meltdown , US housing
 bubble burst , EZB IR , Great Recession ( August 2007 , March and September
 of 2008 , Q1 & Q2 2009 ) , flash crash , April and October 2014.
 benchmark _ rets must be passed , as it is meaningless to analyze performance
 during interesting times without some benchmark to refer to .
 Parameters
 returns : pd . Series
 Daily returns of the strategy , noncumulative .
 - See full explanation in create _ full _ tear _ sheet .
 benchmark _ rets : pd . Series
 Daily noncumulative returns of the benchmark .
 - This is in the same style as returns .
 legend _ loc : plt . legend _ loc , optional
 The legend ' s location .
 return _ fig : boolean , optional
 If True , returns the figure that was plotted on ."""

implementation:
rets_interesting = timeseries . extract_interesting_date_ranges ( returns )
if not rets_interesting :
    warnings . warn ( 'Passed returns do not overlap with any' 'interesting times.' , UserWarning )
    return
utils . print_table ( pd . DataFrame ( rets_interesting ) . describe ( ) . transpose ( ) . loc [ : , [ 'mean' , 'min' , 'max' ] ] * 100 , name = 'Stress Events' , float_format = '{0:.2f}%' . format )
if benchmark_rets is not None :
    returns = utils . clip_returns_to_benchmark ( returns , benchmark_rets )
    bmark_interesting = timeseries . extract_interesting_date_ranges ( benchmark_rets )
num_plots = len ( rets_interesting )
# 2 plots , 1 row ; 3 plots , 2 rows ; 4 plots , 2 rows ; etc .
num_rows = int ( ( num_plots + 1 ) / 2.0 )
fig = plt . figure ( figsize = ( 14 , num_rows * 6.0 ) )
gs = gridspec . GridSpec ( num_rows , 2 , wspace = 0.5 , hspace = 0.5 )
for i , ( name , rets_period ) in enumerate ( rets_interesting . items ( ) ) : # i = 0 - > 0 , i = 1 - > 0 , i = 2 - > 1 ; ; i = 0 - > 0 , i = 1 - > 1 , i = 2 - > 0
    ax = plt . subplot ( gs [ int ( i / 2.0 ) , i % 2 ] )
    ep . cum_returns ( rets_period ) . plot ( ax = ax , color = 'forestgreen' , label = 'algo' , alpha = 0.7 , lw = 2 )
    if benchmark_rets is not None :
        ep . cum_returns ( bmark_interesting [ name ] ) . plot ( ax = ax , color = 'gray' , label = 'benchmark' , alpha = 0.6 )
        ax . legend ( [ 'Algo' , 'benchmark' ] , loc = legend_loc , frameon = True , framealpha = 0.5 )
    else :
        ax . legend ( [ 'Algo' ] , loc = legend_loc , frameon = True , framealpha = 0.5 )
    ax . set_title ( name )
    ax . set_ylabel ( 'Returns' )
    ax . set_xlabel ( '' )
if return_fig :
    return fig


signature:
def create_capacity_tear_sheet ( returns , positions , transactions , market_data , liquidation_daily_vol_limit = 0.2 , trade_daily_vol_limit = 0.05 , last_n_days = utils . APPROX_BDAYS_PER_MONTH * 6 , days_to_liquidate_limit = 1 , estimate_intraday = 'infer' ) :
    """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 ."""

implementation:
positions = utils . check_intraday ( estimate_intraday , returns , positions , transactions )
print ( "Max days to liquidation is computed for each traded name " "assuming a 20% limit on daily bar consumption \n" "and trailing 5 day mean volume as the available bar volume.\n\n" "Tickers with >1 day liquidation time at a" " constant $1m capital base:" )
max_days_by_ticker = capacity . get_max_days_to_liquidate_by_ticker ( positions , market_data , max_bar_consumption = liquidation_daily_vol_limit , capital_base = 1e6 , mean_volume_window = 5 )
max_days_by_ticker . index = ( max_days_by_ticker . index . map ( utils . format_asset ) )
print ( "Whole backtest:" )
utils . print_table ( max_days_by_ticker [ max_days_by_ticker . days_to_liquidate > days_to_liquidate_limit ] )
max_days_by_ticker_lnd = capacity . get_max_days_to_liquidate_by_ticker ( positions , market_data , max_bar_consumption = liquidation_daily_vol_limit , capital_base = 1e6 , mean_volume_window = 5 , last_n_days = last_n_days )
max_days_by_ticker_lnd . index = ( max_days_by_ticker_lnd . index . map ( utils . format_asset ) )
print ( "Last {} trading days:" . format ( last_n_days ) )
utils . print_table ( max_days_by_ticker_lnd [ max_days_by_ticker_lnd . days_to_liquidate > 1 ] )
llt = capacity . get_low_liquidity_transactions ( transactions , market_data )
llt . index = llt . index . map ( utils . format_asset )
print ( 'Tickers with daily transactions consuming >{}% of daily bar \n' 'all backtest:' . format ( trade_daily_vol_limit * 100 ) )
utils . print_table ( llt [ llt [ 'max_pct_bar_consumed' ] > trade_daily_vol_limit * 100 ] )
llt = capacity . get_low_liquidity_transactions ( transactions , market_data , last_n_days = last_n_days )
print ( "Last {} trading days:" . format ( last_n_days ) )
utils . print_table ( llt [ llt [ 'max_pct_bar_consumed' ] > trade_daily_vol_limit * 100 ] )
bt_starting_capital = positions . iloc [ 0 ] . sum ( ) / ( 1 + returns . iloc [ 0 ] )
fig , ax_capacity_sweep = plt . subplots ( figsize = ( 14 , 6 ) )
plotting . plot_capacity_sweep ( returns , transactions , market_data , bt_starting_capital , min_pv = 100000 , max_pv = 300000000 , step_size = 1000000 , ax = ax_capacity_sweep )


signature:
def create_bayesian_tear_sheet ( returns , benchmark_rets = None , live_start_date = None , samples = 2000 , return_fig = False , stoch_vol = False , progressbar = True ) :
    """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"""

implementation:
if not have_bayesian :
    raise NotImplementedError ( "Bayesian tear sheet requirements not found.\n" "Run 'pip install pyfolio[bayesian]' to install " "bayesian requirements." )
if live_start_date is None :
    raise NotImplementedError ( 'Bayesian tear sheet requires setting of live_start_date' )
live_start_date = ep . utils . get_utc_timestamp ( live_start_date )
df_train = returns . loc [ returns . index < live_start_date ]
df_test = returns . loc [ returns . index >= live_start_date ]
# Run T model with missing data
print ( "Running T model" )
previous_time = time ( )
# track the total run time of the Bayesian tear sheet
start_time = previous_time
trace_t , ppc_t = bayesian . run_model ( 't' , df_train , returns_test = df_test , samples = samples , ppc = True , progressbar = progressbar )
previous_time = timer ( "T model" , previous_time )
# Compute BEST model
print ( "\nRunning BEST model" )
trace_best = bayesian . run_model ( 'best' , df_train , returns_test = df_test , samples = samples , progressbar = progressbar )
previous_time = timer ( "BEST model" , previous_time )
# Plot results
fig = plt . figure ( figsize = ( 14 , 10 * 2 ) )
gs = gridspec . GridSpec ( 9 , 2 , wspace = 0.3 , hspace = 0.3 )
axs = [ ]
row = 0
# Plot Bayesian cone
ax_cone = plt . subplot ( gs [ row , : ] )
bayesian . plot_bayes_cone ( df_train , df_test , ppc_t , ax = ax_cone )
previous_time = timer ( "plotting Bayesian cone" , previous_time )
# Plot BEST results
row += 1
axs . append ( plt . subplot ( gs [ row , 0 ] ) )
axs . append ( plt . subplot ( gs [ row , 1 ] ) )
row += 1
axs . append ( plt . subplot ( gs [ row , 0 ] ) )
axs . append ( plt . subplot ( gs [ row , 1 ] ) )
row += 1
axs . append ( plt . subplot ( gs [ row , 0 ] ) )
axs . append ( plt . subplot ( gs [ row , 1 ] ) )
row += 1
# Effect size across two
axs . append ( plt . subplot ( gs [ row , : ] ) )
bayesian . plot_best ( trace = trace_best , axs = axs )
previous_time = timer ( "plotting BEST results" , previous_time )
# Compute Bayesian predictions
row += 1
ax_ret_pred_day = plt . subplot ( gs [ row , 0 ] )
ax_ret_pred_week = plt . subplot ( gs [ row , 1 ] )
day_pred = ppc_t [ : , 0 ]
p5 = scipy . stats . scoreatpercentile ( day_pred , 5 )
sns . distplot ( day_pred , ax = ax_ret_pred_day )
ax_ret_pred_day . axvline ( p5 , linestyle = '--' , linewidth = 3. )
ax_ret_pred_day . set_xlabel ( 'Predicted returns 1 day' )
ax_ret_pred_day . set_ylabel ( 'Frequency' )
ax_ret_pred_day . text ( 0.4 , 0.9 , 'Bayesian VaR = %.2f' % p5 , verticalalignment = 'bottom' , horizontalalignment = 'right' , transform = ax_ret_pred_day . transAxes )
previous_time = timer ( "computing Bayesian predictions" , previous_time )
# Plot Bayesian VaRs
week_pred = ( np . cumprod ( ppc_t [ : , : 5 ] + 1 , 1 ) - 1 ) [ : , - 1 ]
p5 = scipy . stats . scoreatpercentile ( week_pred , 5 )
sns . distplot ( week_pred , ax = ax_ret_pred_week )
ax_ret_pred_week . axvline ( p5 , linestyle = '--' , linewidth = 3. )
ax_ret_pred_week . set_xlabel ( 'Predicted cum returns 5 days' )
ax_ret_pred_week . set_ylabel ( 'Frequency' )
ax_ret_pred_week . text ( 0.4 , 0.9 , 'Bayesian VaR = %.2f' % p5 , verticalalignment = 'bottom' , horizontalalignment = 'right' , transform = ax_ret_pred_week . transAxes )
previous_time = timer ( "plotting Bayesian VaRs estimate" , previous_time )
# Run alpha beta model
if benchmark_rets is not None :
    print ( "\nRunning alpha beta model" )
    benchmark_rets = benchmark_rets . loc [ df_train . index ]
    trace_alpha_beta = bayesian . run_model ( 'alpha_beta' , df_train , bmark = benchmark_rets , samples = samples , progressbar = progressbar )
    previous_time = timer ( "running alpha beta model" , previous_time )
    # Plot alpha and beta
    row += 1
    ax_alpha = plt . subplot ( gs [ row , 0 ] )
    ax_beta = plt . subplot ( gs [ row , 1 ] )
    sns . distplot ( ( 1 + trace_alpha_beta [ 'alpha' ] [ 100 : ] ) ** 252 - 1 , ax = ax_alpha )
    sns . distplot ( trace_alpha_beta [ 'beta' ] [ 100 : ] , ax = ax_beta )
    ax_alpha . set_xlabel ( 'Annual Alpha' )
    ax_alpha . set_ylabel ( 'Belief' )
    ax_beta . set_xlabel ( 'Beta' )
    ax_beta . set_ylabel ( 'Belief' )
    previous_time = timer ( "plotting alpha beta model" , previous_time )
if stoch_vol : # run stochastic volatility model
    returns_cutoff = 400
    print ( "\nRunning stochastic volatility model on " "most recent {} days of returns." . format ( returns_cutoff ) )
    if df_train . size > returns_cutoff :
        df_train_truncated = df_train [ - returns_cutoff : ]
    _ , trace_stoch_vol = bayesian . model_stoch_vol ( df_train_truncated )
    previous_time = timer ( "running stochastic volatility model" , previous_time )
    # plot latent volatility
    row += 1
    ax_volatility = plt . subplot ( gs [ row , : ] )
    bayesian . plot_stoch_vol ( df_train_truncated , trace = trace_stoch_vol , ax = ax_volatility )
    previous_time = timer ( "plotting stochastic volatility model" , previous_time )
total_time = time ( ) - start_time
print ( "\nTotal runtime was {:.2f} seconds." . format ( total_time ) )
gs . tight_layout ( fig )
if return_fig :
    return fig


signature:
def create_risk_tear_sheet ( positions , style_factor_panel = None , sectors = None , caps = None , shares_held = None , volumes = None , percentile = None , returns = None , transactions = None , estimate_intraday = 'infer' , return_fig = False ) :
    '''Creates risk tear sheet : computes and plots style factor exposures , sector
 exposures , market cap exposures and volume exposures .
 Parameters
 positions : pd . DataFrame
 Daily equity positions of algorithm , in dollars .
 - DataFrame with dates as index , equities as columns
 - Last column is cash held
 - Example :
 Equity ( 24 Equity ( 62
 [ AAPL ] ) [ ABT ] ) cash
 2017-04-03-108062.40 4401.540 2.247757e + 07
 2017-04-04-108852.00 4373.820 2.540999e + 07
 2017-04-05-119968.66 4336.200 2.839812e + 07
 style _ factor _ panel : pd . Panel
 Panel where each item is a DataFrame that tabulates style factor per
 equity per day .
 - Each item has dates as index , equities as columns
 - Example item :
 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
 sectors : pd . DataFrame
 Daily Morningstar sector code per asset
 - DataFrame with dates as index and equities as columns
 - Example :
 Equity ( 24 Equity ( 62
 [ AAPL ] ) [ ABT ] )
 2017-04-03 311.0 206.0
 2017-04-04 311.0 206.0
 2017-04-05 311.0 206.0
 caps : pd . DataFrame
 Daily market cap per asset
 - DataFrame with dates as index and equities as columns
 - Example :
 Equity ( 24 Equity ( 62
 [ AAPL ] ) [ ABT ] )
 2017-04-03 1.327160e + 10 6.402460e + 10
 2017-04-04 1.329620e + 10 6.403694e + 10
 2017-04-05 1.297464e + 10 6.397187e + 10
 shares _ held : pd . DataFrame
 Daily number of shares held by an algorithm .
 - Example :
 Equity ( 24 Equity ( 62
 [ AAPL ] ) [ ABT ] )
 2017-04-03 1915 - 2595
 2017-04-04 1968 - 3272
 2017-04-05 2104 - 3917
 volumes : pd . DataFrame
 Daily volume per asset
 - DataFrame with dates as index and equities as columns
 - Example :
 Equity ( 24 Equity ( 62
 [ AAPL ] ) [ ABT ] )
 2017-04-03 34940859.00 4665573.80
 2017-04-04 35603329.10 4818463.90
 2017-04-05 41846731.75 4129153.10
 percentile : float
 Percentile to use when computing and plotting volume exposures .
 - Defaults to 10th percentile'''

implementation:
positions = utils . check_intraday ( estimate_intraday , returns , positions , transactions )
idx = positions . index & style_factor_panel . iloc [ 0 ] . index & sectors . index & caps . index & shares_held . index & volumes . index
positions = positions . loc [ idx ]
vertical_sections = 0
if style_factor_panel is not None :
    vertical_sections += len ( style_factor_panel . items )
    new_style_dict = { }
    for item in style_factor_panel . items :
        new_style_dict . update ( { item : style_factor_panel . loc [ item ] . loc [ idx ] } )
    style_factor_panel = pd . Panel ( )
    style_factor_panel = style_factor_panel . from_dict ( new_style_dict )
if sectors is not None :
    vertical_sections += 4
    sectors = sectors . loc [ idx ]
if caps is not None :
    vertical_sections += 4
    caps = caps . loc [ idx ]
if ( shares_held is not None ) & ( volumes is not None ) & ( percentile is not None ) :
    vertical_sections += 3
    shares_held = shares_held . loc [ idx ]
    volumes = volumes . loc [ idx ]
if percentile is None :
    percentile = 0.1
fig = plt . figure ( figsize = [ 14 , vertical_sections * 6 ] )
gs = gridspec . GridSpec ( vertical_sections , 3 , wspace = 0.5 , hspace = 0.5 )
if style_factor_panel is not None :
    style_axes = [ ]
    style_axes . append ( plt . subplot ( gs [ 0 , : ] ) )
    for i in range ( 1 , len ( style_factor_panel . items ) ) :
        style_axes . append ( plt . subplot ( gs [ i , : ] , sharex = style_axes [ 0 ] ) )
    j = 0
    for name , df in style_factor_panel . iteritems ( ) :
        sfe = risk . compute_style_factor_exposures ( positions , df )
        risk . plot_style_factor_exposures ( sfe , name , style_axes [ j ] )
        j += 1
if sectors is not None :
    i += 1
    ax_sector_longshort = plt . subplot ( gs [ i : i + 2 , : ] , sharex = style_axes [ 0 ] )
    i += 2
    ax_sector_gross = plt . subplot ( gs [ i , : ] , sharex = style_axes [ 0 ] )
    i += 1
    ax_sector_net = plt . subplot ( gs [ i , : ] , sharex = style_axes [ 0 ] )
    long_exposures , short_exposures , gross_exposures , net_exposures = risk . compute_sector_exposures ( positions , sectors )
    risk . plot_sector_exposures_longshort ( long_exposures , short_exposures , ax = ax_sector_longshort )
    risk . plot_sector_exposures_gross ( gross_exposures , ax = ax_sector_gross )
    risk . plot_sector_exposures_net ( net_exposures , ax = ax_sector_net )
if caps is not None :
    i += 1
    ax_cap_longshort = plt . subplot ( gs [ i : i + 2 , : ] , sharex = style_axes [ 0 ] )
    i += 2
    ax_cap_gross = plt . subplot ( gs [ i , : ] , sharex = style_axes [ 0 ] )
    i += 1
    ax_cap_net = plt . subplot ( gs [ i , : ] , sharex = style_axes [ 0 ] )
    long_exposures , short_exposures , gross_exposures , net_exposures = risk . compute_cap_exposures ( positions , caps )
    risk . plot_cap_exposures_longshort ( long_exposures , short_exposures , ax_cap_longshort )
    risk . plot_cap_exposures_gross ( gross_exposures , ax_cap_gross )
    risk . plot_cap_exposures_net ( net_exposures , ax_cap_net )
if volumes is not None :
    i += 1
    ax_vol_longshort = plt . subplot ( gs [ i : i + 2 , : ] , sharex = style_axes [ 0 ] )
    i += 2
    ax_vol_gross = plt . subplot ( gs [ i , : ] , sharex = style_axes [ 0 ] )
    longed_threshold , shorted_threshold , grossed_threshold = risk . compute_volume_exposures ( positions , volumes , percentile )
    risk . plot_volume_exposures_longshort ( longed_threshold , shorted_threshold , percentile , ax_vol_longshort )
    risk . plot_volume_exposures_gross ( grossed_threshold , percentile , ax_vol_gross )
for ax in fig . axes :
    plt . setp ( ax . get_xticklabels ( ) , visible = True )
if return_fig :
    return fig


signature:
def create_perf_attrib_tear_sheet ( returns , positions , factor_returns , factor_loadings , transactions = None , pos_in_dollars = True , return_fig = False , factor_partitions = FACTOR_PARTITIONS ) :
    """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 ' , . . . ] }"""

implementation:
portfolio_exposures , perf_attrib_data = perf_attrib . perf_attrib ( returns , positions , factor_returns , factor_loadings , transactions , pos_in_dollars = pos_in_dollars )
display ( Markdown ( "## Performance Relative to Common Risk Factors" ) )
# aggregate perf attrib stats and show summary table
perf_attrib . show_perf_attrib_stats ( returns , positions , factor_returns , factor_loadings , transactions , pos_in_dollars )
# one section for the returns plot , and for each factor grouping
# one section for factor returns , and one for risk exposures
vertical_sections = 1 + 2 * max ( len ( factor_partitions ) , 1 )
current_section = 0
fig = plt . figure ( figsize = [ 14 , vertical_sections * 6 ] )
gs = gridspec . GridSpec ( vertical_sections , 1 , wspace = 0.5 , hspace = 0.5 )
perf_attrib . plot_returns ( perf_attrib_data , ax = plt . subplot ( gs [ current_section ] ) )
current_section += 1
if factor_partitions is not None :
    for factor_type , partitions in factor_partitions . iteritems ( ) :
        columns_to_select = perf_attrib_data . columns . intersection ( partitions )
        perf_attrib . plot_factor_contribution_to_perf ( perf_attrib_data [ columns_to_select ] , ax = plt . subplot ( gs [ current_section ] ) , title = ( 'Cumulative common {} returns attribution' ) . format ( factor_type ) )
        current_section += 1
    for factor_type , partitions in factor_partitions . iteritems ( ) :
        perf_attrib . plot_risk_exposures ( portfolio_exposures [ portfolio_exposures . columns . intersection ( partitions ) ] , ax = plt . subplot ( gs [ current_section ] ) , title = 'Daily {} factor exposures' . format ( factor_type ) )
        current_section += 1
else :
    perf_attrib . plot_factor_contribution_to_perf ( perf_attrib_data , ax = plt . subplot ( gs [ current_section ] ) )
    current_section += 1
    perf_attrib . plot_risk_exposures ( portfolio_exposures , ax = plt . subplot ( gs [ current_section ] ) )
gs . tight_layout ( fig )
if return_fig :
    return fig


signature:
def daily_txns_with_bar_data ( transactions , market_data ) :
    """Sums the absolute value of shares traded in each name on each day .
 Adds columns containing the closing price and total daily volume for
 each day - ticker combination .
 Parameters
 transactions : pd . DataFrame
 Prices and amounts of executed trades . One row per trade .
 - See full explanation in tears . create _ full _ tear _ sheet
 market _ data : pd . Panel
 Contains " volume " and " price " DataFrames for the tickers
 in the passed positions DataFrames
 Returns
 txn _ daily : pd . DataFrame
 Daily totals for transacted shares in each traded name .
 price and volume columns for close price and daily volume for
 the corresponding ticker , respectively ."""

implementation:
transactions . index . name = 'date'
txn_daily = pd . DataFrame ( transactions . assign ( amount = abs ( transactions . amount ) ) . groupby ( [ 'symbol' , pd . TimeGrouper ( 'D' ) ] ) . sum ( ) [ 'amount' ] )
txn_daily [ 'price' ] = market_data [ 'price' ] . unstack ( )
txn_daily [ 'volume' ] = market_data [ 'volume' ] . unstack ( )
txn_daily = txn_daily . reset_index ( ) . set_index ( 'date' )
return txn_daily