
    'i                         d dl mZmZmZmZ d dlZd dlmZ d dlm	Z	m
Z
 d dlmZmZ d dlmZmZ  G d de	      Z G d	 d
e      Zy)    )absolute_importdivisionprint_functionunicode_literalsN)
itervalues)Analyzer	TimeFrame)averagestandarddev)
TimeReturnAnnualReturnc            
            e Zd ZdZdej
                  fddddddd	d
df
Zej                  dej                  dej                  dej
                  diZ
d Z fdZ xZS )SharpeRatioaB
  This analyzer calculates the SharpeRatio of a strategy using a risk free
    asset which is simply an interest rate

    See also:

      - https://en.wikipedia.org/wiki/Sharpe_ratio

    Params:

      - ``timeframe``: (default: ``TimeFrame.Years``)

      - ``compression`` (default: ``1``)

        Only used for sub-day timeframes to for example work on an hourly
        timeframe by specifying "TimeFrame.Minutes" and 60 as compression

      - ``riskfreerate`` (default: 0.01 -> 1%)

        Expressed in annual terms (see ``convertrate`` below)

      - ``convertrate`` (default: ``True``)

        Convert the ``riskfreerate`` from annual to monthly, weekly or daily
        rate. Sub-day conversions are not supported

      - ``factor`` (default: ``None``)

        If ``None``, the conversion factor for the riskfree rate from *annual*
        to the chosen timeframe will be chosen from a predefined table

          Days: 252, Weeks: 52, Months: 12, Years: 1

        Else the specified value will be used

      - ``annualize`` (default: ``False``)

        If ``convertrate`` is ``True``, the *SharpeRatio* will be delivered in
        the ``timeframe`` of choice.

        In most occasions the SharpeRatio is delivered in annualized form.
        Convert the ``riskfreerate`` from annual to monthly, weekly or daily
        rate. Sub-day conversions are not supported

      - ``stddev_sample`` (default: ``False``)

        If this is set to ``True`` the *standard deviation* will be calculated
        decreasing the denominator in the mean by ``1``. This is used when
        calculating the *standard deviation* if it's considered that not all
        samples are used for the calculation. This is known as the *Bessels'
        correction*

      - ``daysfactor`` (default: ``None``)

        Old naming for ``factor``. If set to anything else than ``None`` and
        the ``timeframe`` is ``TimeFrame.Days`` it will be assumed this is old
        code and the value will be used

      - ``legacyannual`` (default: ``False``)

        Use the ``AnnualReturn`` return analyzer, which as the name implies
        only works on years

      - ``fund`` (default: ``None``)

        If ``None`` the actual mode of the broker (fundmode - True/False) will
        be autodetected to decide if the returns are based on the total net
        asset value or on the fund value. See ``set_fundmode`` in the broker
        documentation

        Set it to ``True`` or ``False`` for a specific behavior

    Methods:

      - get_analysis

        Returns a dictionary with key "sharperatio" holding the ratio

    	timeframe)compression   )riskfreerateg{Gz?)factorN)convertrateT)	annualizeF)stddev_sampleF)
daysfactorN)legacyannualF)fundN   4      r   c                     | j                   j                  rt               | _        y t	        | j                   j
                  | j                   j                  | j                   j                        | _        y )N)r   r   r   )	pr   r   anretr   r   r   r   
timereturn)selfs    Y/var/www/app/trading-bot/venv/lib/python3.12/site-packages/backtrader/analyzers/sharpe.py__init__zSharpeRatio.__init__   sI    66%DJ(&&** FF..VV[["DO    c                    t         t        |           | j                  j                  rq| j                  j
                  }t        | j                  j                  D cg c]  }||z
  	 c}      }t        | j                  j                        }||z  | _
        nt        t        | j                  j                                     }| j                  j
                  }d }| j                  j                  t         j"                  k(  r-| j                  j$                  | j                  j$                  }nr| j                  j&                  | j                  j&                  }nE| j                  j                  | j(                  v r#| j(                  | j                  j                     }|K| j                  j*                  rt-        d|z   d|z        dz
  }n|D cg c]  }t-        d|z   |      dz
   }}t/        |      | j                  j0                  z
  }|r|D cg c]  }||z
  	 }	}t        |	      }
t        |	|
| j                  j0                        }	 |
|z  }|D| j                  j*                  r.| j                  j2                  rt5        j6                  |      |z  }nd }|| _
        | j                  | j                  d<   y c c}w c c}w c c}w # t8        t:        t<        f$ r d }Y Hw xY w)Ng      ?)avgxbesselsharperatio)superr   stopr   r   r   r
   r    retsr   ratiolistr   r!   get_analysisr   r	   Daysr   r   RATEFACTORSr   powlenr   r   mathsqrt
ValueError	TypeErrorZeroDivisionError)r"   raterretavgretdevreturnsr   xlretsret_freeret_free_avgr-   	__class__s               r#   r+   zSharpeRatio.stop   sb   k4%'6666&&D

@1a$h@AF 1F&DJ :doo&B&B&DEFG66&&DF vv9>>1vv  ,** 66==,!VV]]FVV%%)9)99!--dff.>.>?F! 66%%sTz3<83>D DKKas37F3c9KGKL466#7#77E.56AH66&x0$XL,0FF,@,@B!(61E)vv))dff.>.> $		& 1E 9
 DJ#'::		- w AB L 7 #I/@A ! E!s%   KK
KAK K-,K-)__name__
__module____qualname____doc__r	   Yearsparamsr0   WeeksMonthsr1   r$   r+   __classcell__)rB   s   @r#   r   r   !   sz    M^ 
ioo&  	F  	"	K"?. ?.r%   r   c                       e Zd ZdZdZy)SharpeRatio_AzExtension of the SharpeRatio which returns the Sharpe Ratio directly in
    annualized form

    The following param has been changed from ``SharpeRatio``

      - ``annualize`` (default: ``True``)

    ))r   TN)rC   rD   rE   rF   rH    r%   r#   rM   rM      s    Fr%   rM   )
__future__r   r   r   r   r4   backtrader.utils.py3r   
backtraderr   r	   backtrader.mathsupportr
   r   backtrader.analyzersr   r   r   rM   rN   r%   r#   <module>rT      s;   ** *  + * 7 9m.( m.`K r%   