
    .i^F                       d Z ddlmZ ddlZddlmZmZ ddlmZm	Z	m
Z
mZmZmZ ddlZddlmZ ddlZddlZddlmZmZmZmZmZmZ ddlZddlmZ dd	lmZ dd
l m!Z!m"Z" ddl#m$Z$m%Z%m&Z&m'Z'm(Z( ddl)m*Z* ddl+m,Z, erddl-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3 ddl4m5Z5 d Z6d Z7dAdZ8d Z9d Z:dBdZ;dBdZ<dBdZ=dBdZ>dCdZ?e	 dD	 	 	 	 	 dEd       Z@edDdFd       Z@dGdFdZ@	 dG	 	 	 	 	 dHdZAd ZBdIdZCdBd ZDdBd!ZEdJd"ZFdKd#ZGd$ ZHd% ZId& ZJedLd'       ZKe	 	 	 	 dMd(       ZKdGdNd)ZK ed*      ZLe	 	 	 	 	 	 	 	 	 	 dOd+       ZMe	 	 	 	 	 	 	 	 	 	 dPd,       ZM	 	 	 	 	 	 	 	 	 	 dQd-ZMd. ZN	 	 	 	 dRd/ZOej                  dSdTd0       ZQdUd1ZRi ej                  d2ej                  d3ej                  d4ej                  d5ej                  d6ej                  d2ej                  d2ej                  d7ej                  d7ej                  d8ej                  d8ej                  d9ej                  d9ej                  d:ej                  d:ej                  d;ej                  d;ej                  d3ej                  d3ej                  d4ej                  d4ej                  d<ej                  d<ej                  d=ej                  d=iZidVd>ZjdWd?Zkd@ Zly)Xzh
Misc tools for implementing data structures

Note: pandas.core.common is *not* part of the public API.
    )annotationsN)abcdefaultdict)Callable
Collection	GeneratorHashableIterableSequence)partial)TYPE_CHECKINGAnyConcatenateTypeVarcastoverload)lib)'construct_1d_object_array_from_listlike)is_bool_dtype
is_integer)ABCExtensionArrayABCIndexABCMultiIndexABCNumpyExtensionArray	ABCSeries)iterable_not_string)
Expression)AnyArrayLike	ArrayLikeNpDtypePRandomStateT)Indexc              #  d   K   | D ]%  }t        |      rt        |      E d{    "| ' y7 w)a  
    Flatten an arbitrarily nested sequence.

    Parameters
    ----------
    line : sequence
        The non string sequence to flatten

    Notes
    -----
    This doesn't consider strings sequences.

    Returns
    -------
    flattened : generator
    N)r   flatten)lineelements     P/var/www/app/trading-bot/venv/lib/python3.12/site-packages/pandas/core/common.pyr&   r&   D   s5     "  w'w'''M	's   0.0c                    | d   j                   }| dd  D ]  }	 |j                   |k7  rd } |S  |S # t        $ r d }Y  |S w xY w)Nr      )name
ValueError)objsr,   objs      r)   consensus_name_attrr0   \   sn    7<<DABx 	xx4 K   K  	DK	s   1A Ac                (   t        | t        t        j                  t        t
        t        f      rt        | t              s| j                  t        j                  k(  rPt        j                  |       }t        j                  |      s%d}t        j                  |d      rt        |      yyt        | j                        ryyt        | t              r?t!        |       dkD  r1t#        |       t        urt        |       } t        j$                  |       S y)a  
    Check whether `key` is a valid boolean indexer.

    Parameters
    ----------
    key : Any
        Only list-likes may be considered boolean indexers.
        All other types are not considered a boolean indexer.
        For array-like input, boolean ndarrays or ExtensionArrays
        with ``_is_boolean`` set are considered boolean indexers.

    Returns
    -------
    bool
        Whether `key` is a valid boolean indexer.

    Raises
    ------
    ValueError
        When the array is an object-dtype ndarray or ExtensionArray
        and contains missing values.

    See Also
    --------
    check_array_indexer : Check that `key` is a valid array to index,
        and convert to an ndarray.
    z=Cannot mask with non-boolean array containing NA / NaN valuesT)skipnaFr   )
isinstancer   npndarrayr   r   r   r   dtypeobject_asarrayr   is_bool_arrayr-   r   listlentypeis_bool_list)key	key_arrayna_msgs      r)   is_bool_indexerrA   i   s    8 	BJJ*;=ST m,99

"

3I$$Y/X$$Yt< %V,,399%  
C	s8a<Cy$3i##C((    c                f    t        j                  |       r| j                         rt        d      | S )z
    Disallow indexing with a float key, even if that key is a round number.

    Parameters
    ----------
    val : scalar

    Returns
    -------
    outval : scalar
    zYIndexing with a float is no longer supported. Manually convert to an integer key instead.)r   is_floatr   
IndexError)vals    r)   cast_scalar_indexerrG      s2     ||CS^^-)
 	

 JrB   c                     d | D        S )zL
    Returns a generator consisting of the arguments that are not None.
    c              3  &   K   | ]	  }||  y wN .0args     r)   	<genexpr>znot_none.<locals>.<genexpr>   s     3C3?C3s   rK   argss    r)   not_nonerR      s     4433rB   c                 &    t        d | D              S )z?
    Returns a boolean indicating if any argument is None.
    c              3  $   K   | ]  }|d u  
 y wrJ   rK   rL   s     r)   rO   zany_none.<locals>.<genexpr>        +ssd{+   anyrP   s    r)   any_nonerY           +d+++rB   c                 &    t        d | D              S )zA
    Returns a boolean indicating if all arguments are None.
    c              3  $   K   | ]  }|d u  
 y wrJ   rK   rL   s     r)   rO   zall_none.<locals>.<genexpr>   rU   rV   allrP   s    r)   all_noner_      rZ   rB   c                 &    t        d | D              S )zC
    Returns a boolean indicating if any argument is not None.
    c              3  $   K   | ]  }|d u 
 y wrJ   rK   rL   s     r)   rO   zany_not_none.<locals>.<genexpr>        /3s$/rV   rW   rP   s    r)   any_not_nonerc           /$///rB   c                 &    t        d | D              S )zE
    Returns a boolean indicating if all arguments are not None.
    c              3  $   K   | ]  }|d u 
 y wrJ   rK   rL   s     r)   rO   zall_not_none.<locals>.<genexpr>   rb   rV   r]   rP   s    r)   all_not_nonerg      rd   rB   c                 &    t        d | D              S )z;
    Returns the count of arguments that are not None.
    c              3  $   K   | ]  }|d u 
 y wrJ   rK   )rM   xs     r)   rO   z!count_not_none.<locals>.<genexpr>   s     +q}+rV   )sumrP   s    r)   count_not_nonerl      rZ   rB   c                     y rJ   rK   valuesr6   s     r)   asarray_tuplesaferp      s     rB   c                     y rJ   rK   rn   s     r)   rp   rp      s    SVrB   c                   t        | t        t        f      st        | d      st        |       } n8t        | t              r| j
                  S t        | t              r| j
                  S t        | t              r#|t        j                  t        fv rt        |       S 	 t        j                  | |      }t        |j                  j                  t               rt        j                  | t              }|j"                  dk(  r#| D cg c]  }t        |       } }t        |       }|S # t        $ r t        |       cY S w xY wc c}w )N	__array__r6      )r3   r:   tuplehasattrr   _valuesr   r4   r7   objectr   r8   r-   
issubclassr6   r<   strndim)ro   r6   resultrj   s       r)   rp   rp      s    ve}-1Mf	FH	%~~	FI	&~~&$Ebjj&-A$A6v>>?F%0 &,,##S)F&1{{a$*+q%(++8@M  ?
 7v>>? ,s   D% D?%D<;D<c                    t        | t        t        f      r| g} t        | t        t        j
                  f      s	 t        |       } t        | |      }|S # t        $ r | g} Y w xY w)z
    Transform label or iterable of labels to array, for use in Index.

    Parameters
    ----------
    dtype : dtype
        If specified, use as dtype of the resulting array, otherwise infer.

    Returns
    -------
    array
    rt   )r3   r{   rv   r:   r4   r5   	TypeErrorrp   )labelsr6   rlabelss      r)   index_labels_to_arrayr     se     &3,'ftRZZ01	&\F  e4GN  	XF	s   A A$#A$c                <    | t        | t        t        f      s| gS | S rJ   )r3   rv   r:   r/   s    r)   maybe_make_listr   +  s     
z#t}=uJrB   c                    t        | t        j                        r%t        | t        j                        st	        |       S t        t        |       } | S )zB
    If obj is Iterable but not list-like, consume into list.
    )r3   r   r
   Sizedr:   r   r   r   s    r)   maybe_iterable_to_listr   1  s:     #s||$ZSYY-GCy
z3
CJrB   c                    t        | t              xr. | j                  du xr | j                  du xr | j                  du S )z
    We have a null slice.
    Nr3   slicestartstopstepr   s    r)   is_null_slicer   ;  sH    
 	3 	II	HH	 HH	rB   c                    t        | t              xr9 | j                  duxr) | j                  duxr | j                  | j                  k(  S )z>
    We have an empty slice, e.g. no values are selected.
    N)r3   r   r   r   r   s    r)   is_empty_slicer   G  sL    
 	3 	"IIT!	"HHD 	" II!	rB   c              #  Z   K   | D ]"  }t        |t              xr t        |        $ yw)z;
    Find non-trivial slices in "line": yields a bool.
    N)r3   r   r   )r'   ks     r)   is_true_slicesr   S  s1       <E";=+;';;<s   )+c                    t        | t              xr0 | j                  dk(  xr | j                  |k(  xr | j                  du S )z&
    We have a full length slice.
    r   Nr   )r/   r'   s     r)   is_full_slicer   \  sG    
 	3 	IIN	HH	 HH	rB   c                    t        | d      r| j                  S t        | t              rt	        | j
                        S t        |       rt        |       j                  S y )N__name__)rw   r   r3   r   get_callable_namefunccallabler<   r   s    r)   r   r   h  sK    sJ||#w **}Cy!!!
 rB   c                t    t        | t              r | j                  |fi |S t        |       r	 | |fi |S | S )z
    Evaluate possibly callable input using obj and kwargs if it is callable,
    otherwise return as it is.

    Parameters
    ----------
    maybe_callable : possibly a callable
    obj : NDFrame
    **kwargs
    )r3   r   _eval_expressionr   )maybe_callabler/   kwargss      r)   apply_if_callabler   y  sD     .*-.~..s=f==	.	!c,V,,rB   c                   t        j                  |       s5t        | t              rt	        t        | j
                        S t        |       } t        | t        j                        st        d|        | t        k(  rt        d      | S )a  
    Helper function to standardize a supplied mapping.

    Parameters
    ----------
    into : instance or subclass of collections.abc.Mapping
        Must be a class, an initialized collections.defaultdict,
        or an instance of a collections.abc.Mapping subclass.

    Returns
    -------
    mapping : a collections.abc.Mapping subclass or other constructor
        a callable object that can accept an iterator to create
        the desired Mapping.

    See Also
    --------
    DataFrame.to_dict
    Series.to_dict
    zunsupported type: z/to_dict() only accepts initialized defaultdicts)inspectisclassr3   r   r   default_factoryr<   rz   r   Mappingr   )intos    r)   standardize_mappingr     sp    * ??4 dK(;(<(<==DzdCKK(,TF344{IJJKrB   c                     y rJ   rK   states    r)   random_stater     s    EHrB   c                     y rJ   rK   r   s    r)   r   r     s      rB   c                   t        |       s4t        | t        j                  t        j                  j
                  f      rt        j                  j                  |       S t        | t        j                  j                        r| S t        | t        j                  j                        r| S | t        j                  S t        d      )aq  
    Helper function for processing random_state arguments.

    Parameters
    ----------
    state : int, array-like, BitGenerator, Generator, np.random.RandomState, None.
        If receives an int, array-like, or BitGenerator, passes to
        np.random.RandomState() as seed.
        If receives an np.random RandomState or Generator, just returns that unchanged.
        If receives `None`, returns np.random.
        If receives anything else, raises an informative ValueError.

        Default None.

    Returns
    -------
    np.random.RandomState or np.random.Generator. If state is None, returns np.random

    zdrandom_state must be an integer, array-like, a BitGenerator, Generator, a numpy RandomState, or None)	r   r3   r4   r5   randomBitGeneratorr"   r   r-   r   s    r)   r   r     s    ( %Jurzz299;Q;Q.RSyy$$U++	E29900	1	E299..	/	yy+
 	
rB   _Tc                     y rJ   rK   r/   r   rQ   r   s       r)   piper          	rB   c                     y rJ   rK   r   s       r)   r   r     r   rB   c                    t        |t              r&|\  }}||v r| d}t        |      | ||<    ||i |S  || g|i |S )as  
    Apply a function ``func`` to object ``obj`` either by passing obj as the
    first argument to the function or, in the case that the func is a tuple,
    interpret the first element of the tuple as a function and pass the obj to
    that function as a keyword argument whose key is the value of the second
    element of the tuple.

    Parameters
    ----------
    func : callable or tuple of (callable, str)
        Function to apply to this object or, alternatively, a
        ``(callable, data_keyword)`` tuple where ``data_keyword`` is a
        string indicating the keyword of ``callable`` that expects the
        object.
    *args : iterable, optional
        Positional arguments passed into ``func``.
    **kwargs : dict, optional
        A dictionary of keyword arguments passed into ``func``.

    Returns
    -------
    object : the return type of ``func``.
    z/ is both the pipe target and a keyword argument)r3   rv   r-   )r/   r   rQ   r   func_targetmsgs          r)   r   r     sd    : $vVHKLCS/!vd%f%%C)$)&))rB   c                V      fd}t         t        j                  t        f      r|S  S )zv
    Returns a function that will map names/labels, dependent if mapper
    is a dict, Series or just a function.
    c                    | v r|    S | S rJ   rK   )rj   mappers    r)   fzget_rename_function.<locals>.f  s    ;!9HrB   )r3   r   r   r   )r   r   s   ` r)   get_rename_functionr     s'     6CKK#;<1H&HrB   c                    t        | t        t        j                  t        t
        t        f      r| S t        | t        j                        rt        | t              st        |       S | gS )z
    Convert list-like or scalar input to list-like. List, numpy and pandas array-like
    inputs are returned unmodified whereas others are converted to list.
    )
r3   r:   r4   r5   r   r   r   r   r
   r{   )ro   s    r)   convert_to_list_liker   &  sK     &4XyBSTU	FCLL	)*VS2IF|8OrB   c              #     K   |rt        | |      }t        | ||       	 |  |rt        | |       yy# |rt        | |       w w xY ww)a  
    Temporarily set attribute on an object.

    Parameters
    ----------
    obj : object
        Object whose attribute will be modified.
    attr : str
        Attribute to modify.
    value : Any
        Value to temporarily set attribute to.
    condition : bool, default True
        Whether to set the attribute. Provided in order to not have to
        conditionally use this context manager.

    Yields
    ------
    object : obj with modified attribute.
    N)getattrsetattr)r/   attrvalue	condition	old_values        r)   temp_setattrr   5  sU     * C&	T5!*	Cy) 9Cy) s   A	4 A	AA	c                z    t        |       t        |      k7  r$t        dt        |        dt        |       d      y)zC
    Check the length of data matches the length of the index.
    zLength of values (z") does not match length of index ()N)r;   r-   )dataindexs     r)   require_length_matchr   T  sI     4yCJD	{ E
|1
 	
 rB   rk   maxminr^   rX   meanprodstdvarmediancumprodcumsumc                ,    t         j                  |       S )zH
    if we define an internal function for this argument, return it
    )_cython_tableget)rN   s    r)   get_cython_funcr   ~  s     S!!rB   c                X    t        |       D cg c]  \  }}|d| n| c}}S c c}}w )a  
    If a name is missing then replace it by level_n, where n is the count

    Parameters
    ----------
    names : list-like
        list of column names or None values.

    Returns
    -------
    list
        list of column names with the None values replaced.
    level_)	enumerate)namesir,   s      r)   fill_missing_namesr     s2     CLEBRSwq$DLfQCLd2SSSs   &c                x    t        j                  d      }|j                  j                         D ]  }|| u s y y)a  
    Helper function used in detecting chained assignment.

    If the pandas object (DataFrame/Series) is a local variable
    in the caller's frame, it should not be a case of chained
    assignment or method call.

    For example:

    def test():
        df = pd.DataFrame(...)
        df["a"] = 1  # not chained assignment

    Inside ``df.__setitem__``, we call this function to check whether `df`
    (`self`) is a local variable in `test` frame (the frame calling setitem). If
    so, we know it is not a case of chained assignment (even when the refcount
    of `df` is below the threshold due to optimization of local variables).
    ru   TF)sys	_getframef_localsro   )r/   framevs      r)   is_local_in_caller_framer     s=    & MM!E^^""$ 8 rB   )r>   r   returnbool)r   r   )r   int).)ro   zArrayLike | list | tuple | zipr6   NpDtype | Noner   
np.ndarray)ro   r
   r6   r   r   r   rJ   )r   znp.ndarray | Iterabler6   r   r   r   )r/   zIterable[T] | Tr   zCollection[T] | T)r'   zabc.Iterabler   zabc.Generator[bool, None, None])r'   r   r   r   )r   np.random.Generatorr   r   )r   zHint | np.ndarray | np.random.BitGenerator | np.random.RandomState | Noner   znp.random.RandomState)r   zRandomState | None)
r/   r   r   zCallable[Concatenate[_T, P], T]rQ   zP.argsr   zP.kwargsr   r#   )
r/   r   r   ztuple[Callable[..., T], str]rQ   r   r   r   r   r#   )
r/   r   r   z>Callable[Concatenate[_T, P], T] | tuple[Callable[..., T], str]rQ   r   r   r   r   r#   )ro   z"Hashable | Iterable | AnyArrayLiker   zlist | AnyArrayLike)T)r   r{   r   r   r   zGenerator[None])r   r$   r   None)rN   r   r   z
str | None)r   zSequence[Hashable | None]r   zlist[Hashable])m__doc__
__future__r   builtinscollectionsr   r   collections.abcr   r   r   r	   r
   r   
contextlib	functoolsr   r   r   typingr   r   r   r   r   r   numpyr4   pandas._libsr   pandas.core.dtypes.castr   pandas.core.dtypes.commonr   r   pandas.core.dtypes.genericr   r   r   r   r   pandas.core.dtypes.inferencer   pandas.core.colr   pandas._typingr   r   r    r!   r"   r#   pandasr$   r&   r0   rA   rG   rR   rY   r_   rc   rg   rl   rp   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   contextmanagerr   r   rk   r   r   r^   rX   nansumr   nanmeanr   nanprodr   nanstdr   nanvarr   	nanmediannanmaxnanminr   
nancumprodr   	nancumsumr   r   r   r   rK   rB   r)   <module>r     s   #      
    K  = &  0
5p,4,,00, 
DG*3A 
 
 V 
 V@ <@!*8:		<	"&@ 
 H 
 H 
 S   
 
 
F T] 
	
)  	
  
 
	
&  	
  
&*	&*
H&* &* 	&*
 &*RI. * *<

LL%LL% LL% FFE	
 FFE FFE IIu GGV JJ GGV JJ FFE IIu FFE IIu  IIx!" LL(#$ FFEIIuFFEIIuJJ	MM9IIxLL(3:"T"rB   