
    EjM                       d dl mZ d dlZd dlmZmZmZmZmZ d dl	Z	d dl
Zd dlmZmZmZ d dlZd dlmZmZmZ ddlmZ ddlmZmZmZ dd	lmZ dd
lmZ ddlmZ  G d d          Z e dZ!dZ"dg dg ddgdddddddg dg dg ddddiddg d g d!d"gd#d$d%d&d'd(ddg d)g d*gdd+d,idd-Z# G d. d/          Z$dS )0    )annotationsN)AnyOptionalListUnionDict)SessionResponse
exceptions)datetimedate	timedelta   )_QUERY1_URL_)log_indent_decoratorget_yf_logger_parse_user_dt)screen)YfData)YFExceptionc                  B    e Zd ZdZddZdd
Zedd            ZddZdS )CalendarQuerya  
    Simple CalendarQuery class for calendar queries, similar to yf.screener.query.QueryBase.

    Simple operand accepted by YF is of the form:
        `{ "operator": operator, "operands": [field, ...values] }`

    Nested operand accepted by YF:
        `{ "operator": operator, "operands": [ ...CalendarQuery ] }`

    ### Simple example:
    ```python
    op = CalendarQuery('eq', ['ticker', 'AAPL'])
    print(op.to_dict())
    ```
    operatorstroperand'Union[List[Any], List['CalendarQuery']]c                J    |                                 }|| _        || _        dS )z
        :param operator: Operator string, e.g., 'eq', 'gte', 'and', 'or'.
        :param operand: List of operands: can be values (str, int), or other Operands instances (nested).
        N)upperr   operands)selfr   r   s      N/var/www/html/bolsaweb/venv/lib/python3.11/site-packages/yfinance/calendars.py__init__zCalendarQuery.__init__"   s%    
 >>##     r   returnNonec                :    | j                             |           dS )z
        Append an operand to the operands list.

        :param operand: CalendarQuery to append (can be value or CalendarQuery instance).
        N)r   append)r    r   s     r!   r'   zCalendarQuery.append+   s      	W%%%%%r#   boolc                2    t          | j                  dk    S )zy
        Check if the operands list is empty.

        :return: True if operands list is empty, False otherwise.
        r   )lenr   r    s    r!   is_emptyzCalendarQuery.is_empty3   s     4=!!Q&&r#   dictc                <    | j         }| j        }|d |D             dS )a  
        Query-ready dict for YF.

        Simple operand accepted by YF is of the form:
            `{ "operator": operator, "operands": [field, ...values] }`

        Nested operand accepted by YF:
            `{ "operator": operator, "operands": [ ...CalendarQuery ] }`
        c                d    g | ]-}t          |t                    r|                                n|.S  )
isinstancer   to_dict).0os     r!   
<listcomp>z)CalendarQuery.to_dict.<locals>.<listcomp>J   s4    YYYPQ
1m(D(DK!YYYr#   r   r   r6   )r    opopss      r!   r2   zCalendarQuery.to_dict<   s6     ]mYYUXYYY
 
 	
r#   N)r   r   r   r   )r   r   r$   r%   )r$   r(   )r$   r-   )	__name__
__module____qualname____doc__r"   r'   propertyr,   r2   r0   r#   r!   r   r      sz                 & & & & ' ' ' X'
 
 
 
 
 
r#   r   z/v1/finance/visualizationz%Y-%m-%dintradaymarketcap)	tickercompanyshortnamer>   	eventnamestartdatetimestartdatetimetypeepsestimate	epsactualepssurprisepct)Surprise (%)zEPS EstimatezReported EPSEvent Start DateSymbolzSurprise(%)Company	Marketcap)rG   zCompany NamezMarket Cap (Intraday))	sortFieldincludeFieldsnan_colsdatetime_colsdf_indexrenamesrB   )r?   r@   exchange_short_name
filingdaterB   amendeddate	pricefrompriceto
offerpricecurrencynamesharesdealtype)z
Price FromzPrice ToPriceShares)zFiling DateDatezAmended DatezExchange Short NameExchange)econ_releasecountry_coderB   periodafter_release_actualconsensus_estimateprior_release_actualoriginally_reported_actual)ActualMarket ExpectationPrior to ThisRevised fromz
Event TimeEventRegionExpectedLastRevised)zCountry Coderg   rh   ri   )r?   r@   rB   
optionableold_share_worthshare_worthz
Payable OnzOptionable?
Optionable)sp_earningsipo_infoeconomic_eventsplitsc                  H   e Zd ZdZ	 	 	 d*d+dZd,dZ	 d-d.dZd/dZd0dZe		 d1d2d            Z
d3d4dZe		 	 	 	 	 	 	 d5d6d"            Ze		 d7d8d#            Ze		 d7d8d$            Ze		 d7d8d%            Zed8d&            Zed8d'            Zed8d(            Zed8d)            ZdS )9	Calendarsa&  
    Get economic calendars, for example, Earnings, IPO, Economic Events, Splits

    ### Simple example default params:
    ```python
    import yfinance as yf
    calendars = yf.Calendars()
    earnings_calendar = calendars.get_earnings_calendar(limit=50)
    print(earnings_calendar)
    ```Nstart$Optional[Union[str, datetime, date]]endsessionOptional[Session]c                   t                      | _        |pt                      | _        t	          |          | _        |                     |          }|                     |          }|p*t          j                    	                    t                    | _        |pGt          j        | j        t                    t          d          z   	                    t                    | _        |s-|r+| j                            d| j        d| j                   n/|r-|s+| j                            d| j        d| j        d           t!          dg           | _        i | _        i | _        d	S )
a  
        :param str | datetime | date start: start date (default today)             eg. start="2025-11-08"
        :param str | datetime | date end: end date (default `start + 7 days`)             eg. end="2025-11-08"
        :param session: requests.Session object, optional
        )r|      )dayszFIncomplete boundary: did not provide `start`, using today self._start=z to self._end=z>Incomplete boundary: did not provide `end`, using self._start=z: +7 days from self._startorN)r   _loggerr	   r|   r   _data_parse_date_paramr   nowstrftimeDATE_STR_FORMAT_startstrptimer   _enddebugr   _most_active_qy_cache_request_body	calendars)r    ry   r{   r|   r   r   s         r!   r"   zCalendars.__init__   sx    %+'))#G444
''..%%c**H 7 7 H H{X.t{OLLy^_O`O`O``jjkz{{	 	N 	NLz\`\gzznrnwzz{{{{ 	N3 	NL   MTXT_   M   Mfjfo   M   M   M  N  N  N.;D".E.E#% 24r#   _date)Optional[Union[str, datetime, date, int]]r$   r   c                X    |sdS t          |                              t                    S )N )r   r   r   )r    r   s     r!   r   zCalendars._parse_date_param   s,     	C2!%((11/BBBr#      r   Fcalendar_typequeryr   pd.DataFramec                   |t           vrt          d|           ddd}d|t           |         d         t           |         d         t          |d          ||                                d	}| j                            |d           rI|sG| j        |         }||k    r4|| j        v r+| j                            d
|d           | j        |         S || j        |<   | j                            d|d|           | j	        
                    t          ||          }		 |	                                }
n4# t          j        $ r" | j                            | d           i }
Y nw xY w|
                    di                               di           r7t          |
                    di                               di                     |                     |
          | j        |<   |                     |          S )NzUnknown calendar type: zen-USUS)langregionDESCrL   rM   d   )sortTypeentityIdTyperL   rM   sizeoffsetr   zGetting calendar_type=z from local cachezFetching calendar_type=z with limit=)paramsbodyz: Failed to retrieve calendar.financeerror)PREDEFINED_CALENDARSr   minr2   r   getr   r   r   r   post_CALENDAR_URL_jsonJSONDecodeErrorr   
_create_df_cleanup_df)r    r   r   limitr   forcer   r   
cache_bodyresponse	json_datas              r!   	_get_datazCalendars._get_data   s     444GGGHHH!T22)-m<[I1-@QsOO]]__
 
 #''t<< 	5U 	51-@JT!!mt~&E&E""#Om#O#O#OPPP~m4426 /E}EEUEEFFF!Z__^FQU_VV	 II# 	 	 	L-OOOPPPIII	
 ==B''++GR88 	MimmIr::>>wKKLLL(,	(B(B}%...s   D3 3.E$#E$r   r-   c                @   g }|d         d         d         d         d         d         D ]:}|                     |d                    |d         dk    r|d         d	k    rd
|d<   ;|d         d         d         d         d         d         }t          j        ||          S )Nr   resultr   	documentscolumnslabelrH   typeSTRINGTimingrows)r   )r'   pd	DataFrame)r    r   r   colr   s        r!   r   zCalendars._create_df  s    Y'1!4[A!DYO 	' 	'CNN3w<(((7|111c&kX6M6M&#H-a0=a@H|D'2222r#   c                   t           |         }| j        |         }|j        r|S |d         }|r<||                             d                              dt
          j                  ||<   |                    |d         d           |d                                         D ]\  }}|	                    ||id           |d	         D ]}t          j        ||                   ||<    |S )
NrN   float64g        rP   T)inplacerQ   )r   r   rO   )r   r   emptyastypereplacenpnan	set_indexitemsrenamer   to_datetime)r    r   
predef_caldfrN   rename_from	rename_todatetime_cols           r!   r   zCalendars._cleanup_df  s   />
>-88 	I $J/ 	Oh<..y99AA#rvNNBxL 	Z
+T:::&0&;&A&A&C&C 	F 	F"KII{I6IEEEE&7 	@ 	@L!~b.>??B|	r#   _market_capOptional[float]c                P   | j         j        s	|s| j         S | j                            d           	 t	          dd          }n6# t
          j        $ r$ | j                            d           | j         cY S w xY w|                    di g          }t          dg           | _         |D ]y}t          |          t          ur|                    dd	          }|                    d
d          }|r2|||k    r*| j                             t          dd|g                     z| j         S )ax  
        Retrieve tickers from YF, converts them into operands accepted by YF.
        Saves the operands in self._most_active_qy.
        Will not re-query if already populated.

        Used for earnings calendar optional filter.

        :param force: if True, will re-query even if operands already exist
        :return: list of operands for active traded stocks
        z.Fetching 200 most_active for earnings calendarMOST_ACTIVES   )r   countz&Failed to retrieve most active stocks.quotesr   symbolr   	marketCapr   Neqr?   )r   r,   r   r   r   r   	HTTPErrorr   r   r   r   r-   r'   )r    r   r   json_rawrawstockr?   t_market_caps           r!   _get_most_active_operandsz#Calendars._get_most_active_operands&  sR    #, 	(U 	(''KLLL	(#.DDDHH# 	( 	( 	(LGHHH''''	( ll8bT**,T266 	U 	UEE{{$&&YYx,,F 99[!44L U;.,+2M2M$++M$6@R,S,STTT##s   A 0A65A6c           	        |                      |          }|                      |          }|r|r|r|st          j        dt          d           t	          dt	          dd|p| j        g          t	          dd|p| j        g          g          S )z
        Get startdatetime operands for start/end dates.
        If no dates passed, defaults to internal date set on initialization.
        pWhen prividing custom `start` and `end` parameters, you may want to specify both, to avoid unexpected behaviour.   
stacklevelandgterB   lte)r   warningswarnUserWarningr   r   r   )r    ry   r{   r   r   s        r!   _get_startdatetime_operatorsz&Calendars._get_startdatetime_operatorsN  s    
 ''..%%c** 	# 	3 	u 	M C    eov7L%MNNeot7Hty%IJJ
 
 	
r#   T
market_capfilter_most_activer(   c                   |                      |          }|                      |          }	|r|r|r|st          j        dt          d           t	          dt	          dddg          t	          dt	          dd	d
g          t	          dd	dg          g          t	          dd|p| j        g          t	          dd|	p| j        g          g          }
|K|dk     r t          j        d| dt          d           |
                    t	          dd|g                     |r*|s(|
                    |                     |                     | 	                    d|
|||          S )a/  
        Retrieve earnings calendar from YF as a DataFrame.
        Will re-query every time it is called, overwriting previous data.

        :param market_cap: market cap cutoff in USD, default None
        :param filter_most_active: will filter for actively traded stocks (default True)
        :param str | datetime | date start: overwrite start date (default set by __init__)             eg. start="2025-11-08"
        :param str | datetime | date end: overwrite end date (default set by __init__)             eg. end="2025-11-08"
        :param limit: maximum number of results to return (YF caps at 100)
        :param offset: offsets the results for pagination. YF default 0
        :param force: if True, will re-query even if cache already exists
        :return: DataFrame with earnings calendar
        r   r   r   r   r   r   usr   	eventtypeEADERAr   rB   r   Ni zmarket_cap z, is very low, did you mean to set it higher?r>   rs   r   r   r   r   r   )
r   r   r   r   r   r   r   r'   r   r   )r    r   r   ry   r{   r   r   r   r   r   r   s              r!   get_earnings_calendarzCalendars.get_earnings_calendarf  s   4 ''..%%c** 	# 	3 	u 	M C    dXt$455%d[%,@AA%d[%,@AA  eov7L%MNNeot7Hty%IJJ
 
  !J&&Z*ZZZ    
 LLu/BJ.OPPQQQ 	Ef 	ELL77
CCDDD~~'  
 
 	
r#   c                   |                      |          }|                      |          }|r|r|r|st          j        dt          d           t	          dt	          dd|p| j        |p| j        g          t	          dd|p| j        |p| j        g          t	          dd|p| j        |p| j        g          g          }|                     d	||||
          S )aB  
        Retrieve IPOs calendar from YF as a Dataframe.

        :param str | datetime | date start: overwrite start date (default set by __init__)             eg. start="2025-11-08"
        :param str | datetime | date end: overwrite end date (default set by __init__)             eg. end="2025-11-08"
        :param limit: maximum number of results to return (YF caps at 100)
        :param offset: offsets the results for pagination. YF default 0
        :param force: if True, will re-query even if cache already exists
        :return: DataFrame with IPOs calendar
        r   r   r   r   gteltrB   rS   rT   rt   r   )r   r   r   r   r   r   r   r   )	r    ry   r{   r   r   r   r   r   r   s	            r!   get_ipo_info_calendarzCalendars.get_ipo_info_calendar  s     ''..%%c** 	# 	3 	u 	M C    g9N4;PTPaX\Xa'bccgf6KTM^UYU^'_``gv7LdN_VZV_'`aa
 
 ~~$  
 
 	
r#   c                ^    |                      d|                     ||          |||          S )aX  
        Retrieve Economic Events calendar from YF as a DataFrame.

        :param str | datetime | date start: overwrite start date (default set by __init__)             eg. start="2025-11-08"
        :param str | datetime | date end: overwrite end date (default set by __init__)             eg. end="2025-11-08"
        :param limit: maximum number of results to return (YF caps at 100)
        :param offset: offsets the results for pagination. YF default 0
        :param force: if True, will re-query even if cache already exists
        :return: DataFrame with Economic Events calendar
        ru   r   r   r   r    ry   r{   r   r   r   s         r!   get_economic_events_calendarz&Calendars.get_economic_events_calendar  s>      ~~*33E3??  
 
 	
r#   c                ^    |                      d|                     ||          |||          S )aF  
        Retrieve Splits calendar from YF as a DataFrame.

        :param str | datetime | date start: overwrite start date (default set by __init__)             eg. start="2025-11-08"
        :param str | datetime | date end: overwrite end date (default set by __init__)             eg. end="2025-11-08"
        :param limit: maximum number of results to return (YF caps at 100)
        :param offset: offsets the results for pagination. YF default 0
        :param force: if True, will re-query even if cache already exists
        :return: DataFrame with Splits calendar
        rv   r   r   r   s         r!   get_splits_calendarzCalendars.get_splits_calendar  s>      ~~"33E3??  
 
 	
r#   c                V    d| j         v r| j         d         S |                                 S )z(Earnings calendar with default settings.rs   )r   r   r+   s    r!   earnings_calendarzCalendars.earnings_calendar	  s0     DN**>-00))+++r#   c                V    d| j         v r| j         d         S |                                 S )z$IPOs calendar with default settings.rt   )r   r   r+   s    r!   ipo_info_calendarzCalendars.ipo_info_calendar  s0     ''>*--))+++r#   c                V    d| j         v r| j         d         S |                                 S )z/Economic events calendar with default settings.ru   )r   r   r+   s    r!   economic_events_calendarz"Calendars.economic_events_calendar  s1     t~-->"23300222r#   c                V    d| j         v r| j         d         S |                                 S )z&Splits calendar with default settings.rv   )r   r   r+   s    r!   splits_calendarzCalendars.splits_calendar  s0     t~%%>(++'')))r#   )NNN)ry   rz   r{   rz   r|   r}   )r   r   r$   r   )r   r   F)r   r   r   r   r$   r   )r   r-   r$   r   )r   r   r$   r   )F)r   r   r$   r   )NN)r$   r   )NTNNr   r   F)r   r   r   r(   r$   r   )NNr   r   F)r$   r   )r9   r:   r;   r<   r"   r   r   r   r   r   r   r   r   r   r   r   r=   r  r  r  r  r0   r#   r!   rx   rx      s&       	 	 7;48%)	5 5 5 5 5BC C C C SX'/ '/ '/ '/ '/R
3 
3 
3 
3   * 27%$ %$ %$ %$ %$N
 
 
 
 
0  '+#'D
 D
 D
 D
 D
L >C'
 '
 '
 '
 '
R >C
 
 
 
 
. >C
 
 
 
 
2 , , , X, , , , X, 3 3 3 X3 * * * X* * *r#   rx   )%
__future__r   r   typingr   r   r   r   r   r   numpyr   requestsr	   r
   r   pandasr   r   r   r   constr   utilsr   r   r   screenerr   datar   r   r   r   r   r   rx   r0   r#   r!   <module>r     s   " " " " " "  3 3 3 3 3 3 3 3 3 3 3 3 3 3      2 2 2 2 2 2 2 2 2 2     . . . . . . . . . .       F F F F F F F F F F             # # # # # #:
 :
 :
 :
 :
 :
 :
 :
z !;;; )

 

 

 EDD,-)%%0
 
! . %
 
 
 BAA@@@!:
' 0 %	
 	
 	
 VUU&$",#%	
 
 . %
 
 
 &<
 IU U pz* z* z* z* z* z* z* z* z* z*r#   