Ticket #9218: trac_9218-reviewer.patch

File trac_9218-reviewer.patch, 100.6 KB (added by mvngu, 11 years ago)
  • sage/finance/fractal.pyx

    # HG changeset patch
    # User Minh Van Nguyen <nguyenminh2@gmail.com>
    # Date 1276379549 25200
    # Node ID 4cd42f8a0d0f56be92c7719d738c5dd2bbcab53f
    # Parent  d7b75546da1f462da27ccc01609266afc3c1c1bf
    #9218: reviewer patch: add a finance chapter to the sage reference manual
    
    diff --git a/sage/finance/fractal.pyx b/sage/finance/fractal.pyx
    a b  
    44This module implements the fractal approach to understanding financial
    55markets that was pioneered by Mandelbrot.  In particular, it implements
    66the multifractal random walk model of asset returns as developed by
    7 Bacry, Kozhemyak, and Muzy, 2006, 'Continuous cascade models for asset
    8 returns' and many other papers by Bacry et al. See
    9    \url{http://www.cmap.polytechnique.fr/~bacry/ftpPapers.html}
     7Bacry, Kozhemyak, and Muzy, 2006, *Continuous cascade models for asset
     8returns* and many other papers by Bacry et al. See
     9http://www.cmap.polytechnique.fr/~bacry/ftpPapers.html
    1010
    11 See also Mandelbrot's 'The Misbehavior of Markets' for a motivated
     11See also Mandelbrot's *The Misbehavior of Markets* for a motivated
    1212introduction to the general idea of using a self-similar approach to
    1313modeling asset returns.
    1414
     
    1717work.
    1818
    1919AUTHOR:
    20      -- William Stein (2008)
     20
     21- William Stein (2008)
    2122"""
    2223
    2324from sage.rings.all import RDF, CDF, Integer
     
    3738##################################################################
    3839
    3940def stationary_gaussian_simulation(s, N, n=1):
    40     """
     41    r"""
    4142    Implementation of the Davies-Harte algorithm which given an
    42     autocovariance sequence (ACVS) s and an integer N, simulates N
     43    autocovariance sequence (ACVS) ``s`` and an integer ``N``, simulates ``N``
    4344    steps of the corresponding stationary Gaussian process with mean
    44     0. We assume that a certain Fourier transform associated to s is
     45    0. We assume that a certain Fourier transform associated to ``s`` is
    4546    nonnegative; if it isn't, this algorithm fails with a
    46     NotImplementedError.
     47    ``NotImplementedError``.
    4748
    4849    INPUT:
    49         s -- a list of real numbers that defines the ACVS.
    50              Optimally s should have length N+1; if not
    51              we pad it with extra 0's until it has length N+1.
    52         N -- a positive integer
     50
     51    - ``s`` -- a list of real numbers that defines the ACVS.
     52      Optimally ``s`` should have length ``N+1``; if not
     53      we pad it with extra 0's until it has length ``N+1``.
     54
     55    - ``N`` -- a positive integer.
    5356       
    5457    OUTPUT:
    55         a list of n time series
     58
     59    A list of ``n`` time series.
    5660       
    5761    EXAMPLES:
    58     We define an autocovariance sequence:
     62
     63    We define an autocovariance sequence::
     64
    5965        sage: N = 2^15
    6066        sage: s = [1/math.sqrt(k+1) for k in [0..N]]
    6167        sage: s[:5]
    6268        [1.0, 0.70710678118654746, 0.57735026918962584, 0.5, 0.44721359549995793]
    6369
    64     We run the simulation:
     70    We run the simulation::
     71
    6572        sage: set_random_seed(0)
    6673        sage: sim = finance.stationary_gaussian_simulation(s, N)[0]
    6774
    68     Note that indeed the autocovariance sequence approximates s well:
     75    Note that indeed the autocovariance sequence approximates ``s`` well::
     76
    6977        sage: [sim.autocovariance(i) for i in [0..4]]
    7078        [0.98665816086255..., 0.69201577095377..., 0.56234006792017..., 0.48647965409871..., 0.43667043322102...]
    7179
    72     WARNING: If you were to do the above computation with a small
    73     value of N, then the autocovariance sequence would not approximate
    74     s very well.
     80    .. WARNING::
     81
     82        If you were to do the above computation with a small
     83        value of ``N``, then the autocovariance sequence would not approximate
     84        ``s`` very well.
    7585
    7686    REFERENCES:
     87
    7788    This is a standard algorithm that is described in several papers.
    7889    It is summarized nicely with many applications at the beginning of
    79     'SIMULATING A CLASS OF STATIONARY GAUSSIAN PROCESSES USING THE
    80     DAVIES-HARTE ALGORITHM, WITH APPLICATION TO LONG MEMORY
    81     PROCESSES', 2000, Peter F. Craigmile, which is easily found as a
     90    *Simulating a Class of Stationary Gaussian Processes Using the
     91    Davies-Harte Algorithm, with Application to Long Memory
     92    Processes*, 2000, Peter F. Craigmile, which is easily found as a
    8293    free PDF via a Google search.  This paper also generalizes the
    83     algorithm to the case when all elements of s are nonpositive.
     94    algorithm to the case when all elements of ``s`` are nonpositive.
    8495
    85     The book 'Wavelet Methods for Time Series Analysis' by Percival
     96    The book *Wavelet Methods for Time Series Analysis* by Percival
    8697    and Walden also describes this algorithm, but has a typo in that
    87     they put a 2*pi instead of pi a certain sum.  That book describes
     98    they put a `2\pi` instead of `\pi` a certain sum.  That book describes
    8899    exactly how to use Fourier transform.  The description is in
    89100    Section 7.8.  Note that these pages are missing from the Google
    90101    Books version of the book, but are in the Amazon.com preview of
     
    136147    return sims
    137148
    138149def fractional_gaussian_noise_simulation(double H, double sigma2, N, n=1):
    139     """
    140     Return $n$ simulations of with N steps each of fractional Gaussian
    141     noise with Hurst parameter $H$ and innovations variance sigma2.
     150    r"""
     151    Return ``n`` simulations with ``N`` steps each of fractional Gaussian
     152    noise with Hurst parameter ``H`` and innovations variance ``sigma2``.
    142153   
    143154    INPUT:
    144         H -- float; 0 < H < 1; the Hurst parameter
    145         sigma2 - positive float; innovation variance
    146         N -- positive integer; number of steps in simulation
    147         n -- positive integer (default: 1) -- number of simulations
     155
     156    - ``H`` -- float; ``0 < H < 1``; the Hurst parameter.
     157
     158    - ``sigma2`` - positive float; innovation variance.
     159
     160    - ``N`` -- positive integer; number of steps in simulation.
     161
     162    - ``n`` -- positive integer (default: 1); number of simulations.
    148163
    149164    OUTPUT:
    150         list of n time series.
     165
     166    List of ``n`` time series.
    151167
    152168    EXAMPLES:
    153     We simulate a fractional Gaussian noise.
     169
     170    We simulate a fractional Gaussian noise::
     171
    154172        sage: set_random_seed(0)
    155173        sage: finance.fractional_gaussian_noise_simulation(0.8,1,10,2)
    156174        [[-0.1157, 0.7025, 0.4949, 0.3324, 0.7110, 0.7248, -0.4048, 0.3103, -0.3465, 0.2964],
    157175         [-0.5981, -0.6932, 0.5947, -0.9995, -0.7726, -0.9070, -1.3538, -1.2221, -0.0290, 1.0077]]
    158176
    159     The sums define a fractional Brownian motion process:
     177    The sums define a fractional Brownian motion process::
     178
    160179        sage: set_random_seed(0)
    161180        sage: finance.fractional_gaussian_noise_simulation(0.8,1,10,1)[0].sums()
    162181        [-0.1157, 0.5868, 1.0818, 1.4142, 2.1252, 2.8500, 2.4452, 2.7555, 2.4090, 2.7054]
    163182
    164     ALGORITHM: See 'SIMULATING A CLASS OF STATIONARY GAUSSIAN
    165     PROCESSES USING THE DAVIES-HARTE ALGORITHM, WITH APPLICATION TO
    166     LONG MEMORY PROCESSES', 2000, Peter F. Craigmile for a discussion
     183    ALGORITHM:
     184
     185    See *Simulating a Class of Stationary Gaussian
     186    Processes using the Davies-Harte Algorithm, with Application to
     187    Long Meoryy Processes*, 2000, Peter F. Craigmile for a discussion
    167188    and references for why the algorithm we give -- which uses
    168     the stationary_gaussian_simulation
     189    the ``stationary_gaussian_simulation()`` function.
    169190    """
    170191    if H <= 0 or H >= 1:
    171192        raise ValueError, "H must satisfy 0 < H < 1"
     
    189210    with the same input parameters.
    190211
    191212    INPUT:
    192         H -- float; 0 < H < 1; the Hurst parameter
    193         sigma2 - float; innovation variance (should be close to 0)
    194         N -- positive integer
    195         n -- positive integer (default: 1)
     213
     214    - ``H`` -- float; ``0 < H < 1``; the Hurst parameter.
     215
     216    - ``sigma2`` - float; innovation variance (should be close to 0).
     217
     218    - ``N`` -- positive integer.
     219
     220    - ``n`` -- positive integer (default: 1).
     221
    196222    OUTPUT:
    197         list of n time series.
    198223
    199     EXAMPLES:
     224    List of ``n`` time series.
     225
     226    EXAMPLES::
     227
    200228        sage: set_random_seed(0)
    201229        sage: finance.fractional_brownian_motion_simulation(0.8,0.1,8,1)
    202230        [[-0.0754, 0.1874, 0.2735, 0.5059, 0.6824, 0.6267, 0.6465, 0.6289]]
     
    216244                                                N,
    217245                                                n=1):
    218246    r"""
    219     Return a list of n simulations of a multifractal random walk using
     247    Return a list of ``n`` simulations of a multifractal random walk using
    220248    the log-normal cascade model of Bacry-Kozhemyak-Muzy 2008.  This
    221249    walk can be interpreted as the sequence of logarithms of a price
    222250    series.
    223251
    224252    INPUT:
    225         T       -- positive real; the integral scale
    226         lambda2 -- positive real; the intermittency coefficient
    227         ell     -- a small number -- time step size.
    228         sigma2  -- variance of the Gaussian white noise eps[n]
    229         N       -- number of steps in each simulation
    230         n       -- the number of separate simulations to run
     253
     254    - ``T`` -- positive real; the integral scale.
     255
     256    - ``lambda2`` -- positive real; the intermittency coefficient.
     257
     258    - ``ell`` -- a small number -- time step size.
     259
     260    - ``sigma2`` -- variance of the Gaussian white noise ``eps[n]``.
     261
     262    - ``N`` -- number of steps in each simulation.
     263
     264    - ``n`` -- the number of separate simulations to run.
    231265       
    232266    OUTPUT:
    233         list of time series
    234267
    235     EXAMPLES:
     268    List of time series.
     269
     270    EXAMPLES::
     271
    236272        sage: set_random_seed(0)
    237273        sage: a = finance.multifractal_cascade_random_walk_simulation(3770,0.02,0.01,0.01,10,3)
    238274        sage: a
     
    240276         [0.0003, 0.0035, 0.0257, 0.0358, 0.0377, 0.0563, 0.0661, 0.0746, 0.0749, 0.0689],
    241277         [-0.0120, -0.0116, 0.0043, 0.0078, 0.0115, 0.0018, 0.0085, 0.0005, 0.0012, 0.0060]]
    242278
    243     The corresponding price series:
     279    The corresponding price series::
     280
    244281        sage: a[0].exp()
    245282        [0.9905, 1.0025, 1.0067, 1.0016, 1.0078, 1.0051, 1.0047, 0.9987, 1.0003, 0.9957]
    246283
    247     MORE DETAILS: The random walk has $n$th step $\eps_n
    248     e^{\omega_n}$, where $\eps_n$ is gaussian white noise of variance
    249     $\sigma^2$ and $\omega_n$ is renormalized gaussian magnitude,
    250     which is given by a stationary gaussian simulation associated to
    251     a certain autocovariance sequence.  See Bacry, Kozhemyak, Muzy,
    252     2006, 'Continuous cascade models for asset returns' for details.
     284    MORE DETAILS:
    253285
     286    The random walk has n-th step `\text{eps}_n e^{\omega_n}`, where
     287    `\text{eps}_n` is gaussian white noise of variance `\sigma^2` and
     288    `\omega_n` is renormalized gaussian magnitude, which is given by a
     289    stationary gaussian simulation associated to a certain autocovariance
     290    sequence.  See Bacry, Kozhemyak, Muzy, 2006,
     291    *Continuous cascade models for asset returns* for details.
    254292    """
    255293    if ell <= 0:
    256294        raise ValueError, "ell must be positive"
  • sage/finance/markov_multifractal.py

    diff --git a/sage/finance/markov_multifractal.py b/sage/finance/markov_multifractal.py
    a b  
    11"""
    22Markov Switching Multifractal model
    33
    4 REFERENCE: How to Forecast Long-Run Volatility: Regime Switching and
    5 the Estimation of Multifractal Processes, Calvet and Fisher, 2004.
     4REFERENCE:
     5
     6*How to Forecast Long-Run Volatility: Regime Switching and
     7the Estimation of Multifractal Processes*, Calvet and Fisher, 2004.
    68
    79AUTHOR:
    8     -- William Stein, 2008
    910
    10 TESTS:
     11- William Stein, 2008
     12
     13TESTS::
     14
    1115    sage: msm = finance.MarkovSwitchingMultifractal(8,1.4,1.0,0.95,3)
    1216    sage: loads(dumps(msm)) == msm
    1317    True
     
    1923    def __init__(self, kbar, m0, sigma, gamma_kbar, b):
    2024        """
    2125        INPUT:
    22             kbar   -- positive integer
    23             m0     -- float with 0 <= m0 <= 2
    24             sigma  -- positive float
    25             gamma_kbar -- float with 0 <= gamma_kbar < 1
    26             b      -- float > 1
    2726
    28         EXAMPLES:
     27        - ``kbar`` -- positive integer
     28
     29        - ``m0`` -- float with ``0 <= m0 <= 2``
     30
     31        - ``sigma`` -- positive float
     32
     33        - ``gamma_kbar`` -- float with ``0 <= gamma_kbar < 1``
     34
     35        - ``b`` -- float > 1
     36
     37        EXAMPLES::
     38
    2939            sage: msm = finance.MarkovSwitchingMultifractal(8,1.4,0.5,0.95,3); msm
    3040            Markov switching multifractal model with m0 = 1.4, sigma = 0.5, b = 3.0, and gamma_8 = 0.95
    3141            sage: yen_usd = finance.MarkovSwitchingMultifractal(10,1.448,0.461,0.998,3.76)
     
    4656
    4757    def __cmp__(self, other):
    4858        """
    49         Compare self and other.
     59        Compare ``self`` and ``other``.
    5060
    51         Comparison is done on the tuple (m0, sigma, b, gamma_kbar, kbar).
     61        Comparison is done on the tuple ``(m0, sigma, b, gamma_kbar, kbar)``.
    5262
    53         EXAMPLES:
     63        EXAMPLES::
     64
    5465            sage: msm = finance.MarkovSwitchingMultifractal(8,1.4,1.0,0.95,3)
    5566            sage: msm.__cmp__(3) # random - depends on memory layout
    5667            -1
     
    7081        """
    7182        Return string representation of Markov switching multifractal model.
    7283
    73         EXAMPLES:
     84        EXAMPLES::
     85
    7486            sage: msm = finance.MarkovSwitchingMultifractal(8,1.4,1,0.95,3)
    7587            sage: msm.__repr__()
    7688            'Markov switching multifractal model with m0 = 1.4, sigma = 1.0, b = 3.0, and gamma_8 = 0.95'
     
    8193        """
    8294        Return parameter m0 of Markov switching multifractal model.
    8395
    84         EXAMPLES:
     96        EXAMPLES::
     97
    8598            sage: msm = finance.MarkovSwitchingMultifractal(8,1.4,1,0.95,3)
    8699            sage: msm.m0()
    87100            1.3999999999999999
     
    92105        """
    93106        Return parameter sigma of Markov switching multifractal model.
    94107
    95         EXAMPLES:
     108        EXAMPLES::
     109
    96110            sage: msm = finance.MarkovSwitchingMultifractal(8,1.4,1,0.95,3)
    97111            sage: msm.sigma()
    98112            1.0
     
    103117        """
    104118        Return parameter b of Markov switching multifractal model.
    105119
    106         EXAMPLES:
     120        EXAMPLES::
     121
    107122            sage: msm = finance.MarkovSwitchingMultifractal(8,1.4,1,0.95,3)
    108123            sage: msm.b()
    109124            3.0
     
    112127   
    113128    def gamma_kbar(self):
    114129        """
    115         Return parameter gamma_kbar of Markov switching multifractal model.
     130        Return parameter ``gamma_kbar`` of Markov switching multifractal model.
    116131
    117         EXAMPLES:
     132        EXAMPLES::
     133
    118134            sage: msm = finance.MarkovSwitchingMultifractal(8,1.4,0.01,0.95,3)
    119135            sage: msm.gamma_kbar()
    120136            0.94999999999999996
     
    123139   
    124140    def kbar(self):
    125141        """
    126         Return parameter kbar of Markov switching multifractal model.
     142        Return parameter ``kbar`` of Markov switching multifractal model.
    127143
    128         EXAMPLES:
     144        EXAMPLES::
     145
    129146            sage: msm = finance.MarkovSwitchingMultifractal(8,1.4,0.01,0.95,3)
    130147            sage: msm.kbar()
    131148            8
     
    137154        Return the vector of the kbar transitional probabilities.
    138155
    139156        OUTPUT:
    140             gamma -- a tuple of self.kbar() floats
    141157
    142         EXAMPLES:
     158        - gamma -- a tuple of ``self.kbar()`` floats.
     159
     160        EXAMPLES::
     161
    143162            sage: msm = finance.MarkovSwitchingMultifractal(8,1.4,1.0,0.95,3)
    144163            sage: msm.gamma()
    145164            (0.001368852970712986, 0.0041009402016725094, 0.012252436441829..., 0.03630878209190..., 0.10501923017634..., 0.28312883556311..., 0.6315968501359..., 0.95000000000000...)
     
    163182
    164183    def simulation(self, n):
    165184        """
    166         Same as self.simulations, but run only 1 time, and returns a time series
    167         instead of a list of time series.
     185        Same as ``self.simulations``, but run only 1 time, and returns a time
     186        series instead of a list of time series.
    168187
    169188        INPUT:
    170             n -- a positive integer
    171189
    172         EXAMPLES:
     190        - ``n`` -- a positive integer.
     191
     192        EXAMPLES::
     193
    173194            sage: msm = finance.MarkovSwitchingMultifractal(8,1.4,1.0,0.95,3)
    174195            sage: msm.simulation(5)
    175196            [0.0059, -0.0097, -0.0101, -0.0110, -0.0067]
     
    180201
    181202    def simulations(self, n, k=1):
    182203        """
    183         Return k simulations of length n using this Markov switching
    184         multifractal model for n time steps.
     204        Return ``k`` simulations of length ``n`` using this Markov switching
     205        multifractal model for ``n`` time steps.
    185206
    186207        INPUT:
    187             n -- positive integer; number of steps
    188             k -- positive integer (default: 1); number of simulations.
     208
     209        - ``n`` -- positive integer; number of steps.
     210
     211        - ``k`` -- positive integer (default: 1); number of simulations.
    189212           
    190213        OUTPUT:
    191             list -- a list of TimeSeries objects.
    192214
    193         EXAMPLES:
     215        list -- a list of TimeSeries objects.
     216
     217        EXAMPLES::
     218
    194219            sage: cad_usd = finance.MarkovSwitchingMultifractal(10,1.278,0.262,0.644,2.11); cad_usd
    195220            Markov switching multifractal model with m0 = 1.278, sigma = 0.262, b = 2.11, and gamma_10 = 0.644
    196221        """
  • sage/finance/stock.py

    diff --git a/sage/finance/stock.py b/sage/finance/stock.py
    a b  
    11"""
    2 Stock market price series
     2Stock Market Price Series
    33
    44AUTHORS:
    5     -- William Stein, 2008
    6     -- Brett Nakayama, 2008
    7     -- Chris Swierczewski, 2008
    85
    9 TESTS:
     6- William Stein, 2008
     7
     8- Brett Nakayama, 2008
     9
     10- Chris Swierczewski, 2008
     11
     12TESTS::
     13
    1014    sage: ohlc = sage.finance.stock.OHLC('18-Aug-04', 100.01, 104.06, 95.96, 100.34, 22353092)
    1115    sage: loads(dumps(ohlc)) == ohlc
    1216    True
     
    2327        a timestamp for that data along with the volume.
    2428
    2529        INPUT:
    26             timestamp -- string
    27             open, high, low, close -- float
    28             volume -- int
    2930
    30         EXAMPLES:
     31        - ``timestamp`` -- string
     32
     33        - ``open``, ``high``, ``low``, ``close`` -- float
     34
     35        - ``volume`` -- int
     36
     37        EXAMPLES::
     38
    3139            sage: sage.finance.stock.OHLC('18-Aug-04', 100.01, 104.06, 95.96, 100.34, 22353092)
    3240             18-Aug-04 100.01 104.06 95.96 100.34   22353092
    3341        """
     
    3947        """
    4048        Return string representation of stock OHLC data.
    4149
    42         EXAMPLES:
     50        EXAMPLES::
     51
    4352            sage: sage.finance.stock.OHLC('18-Aug-04', 100.01, 104.06, 95.96, 100.34, 22353092).__repr__()
    4453            ' 18-Aug-04 100.01 104.06 95.96 100.34   22353092'
    4554        """
     
    4857
    4958    def __cmp__(self, other):
    5059        """
    51         Compare self and other.
     60        Compare ``self`` and ``other``.
    5261
    53         EXAMPLES:
     62        EXAMPLES::
     63
    5464            sage: ohlc = sage.finance.stock.OHLC('18-Aug-04', 100.01, 104.06, 95.96, 100.34, 22353092)
    5565            sage: ohlc2 = sage.finance.stock.OHLC('18-Aug-04', 101.01, 104.06, 95.96, 100.34, 22353092)
    5666            sage: cmp(ohlc, ohlc2)
     
    6777    """
    6878    def __init__(self, symbol, cid=''):
    6979        """
    70         Create a Stock object. Optional initialization by cid: an identifier
    71         for each equity used by Google Finance.
     80        Create a ``Stock`` object. Optional initialization by ``cid``: an
     81        identifier for each equity used by Google Finance.
    7282
    7383        INPUT:
    74             symbol -- string, a ticker symbol (with or without market)
    75                       format: "MARKET:SYMBOL" or "SYMBOL", if you don't
    76                               supply the market, it is assumed to be
    77                               NYSE or NASDAQ.
    78                       eg. "goog" or "OTC:NTDOY"
    79             cid    -- Integer, a Google contract ID (optional)
    8084
    81         LIMITATIONS:
     85        - ``symbol`` -- string, a ticker symbol (with or without market).
     86          Format: ``"MARKET:SYMBOL"`` or ``"SYMBOL"``. If you don't
     87          supply the market, it is assumed to be NYSE or NASDAQ.
     88          e.g. "goog" or "OTC:NTDOY"
     89
     90        - ``cid`` -- Integer, a Google contract ID (optional).
     91
     92
     93        .. NOTE::
     94
    8295            Currently, the symbol and cid do not have to match.  When using
    83             google(), the cid will take precedence.
     96            ``google()``, the cid will take precedence.
    8497
    85         EXAMPLES:
     98        EXAMPLES::
     99
    86100            sage: S = finance.Stock('ibm')
    87101            sage: S        # random; optional -- internet
    88102            IBM (127.48)           
     
    94108        """
    95109        Return string representation of this stock.
    96110
    97         EXAMPLES:
     111        EXAMPLES::
     112
    98113            sage: finance.Stock('ibm').__repr__()     # random; optional -- internet
    99114            'IBM (127.47)'
    100115        """
     
    105120        Return the current market value of this stock.
    106121
    107122        OUTPUT:
    108             Python float
    109123
    110         EXAMPLES:
     124        A Python float.
     125
     126        EXAMPLES::
     127
    111128            sage: finance.Stock('goog').market_value()   # random; optional - internet
    112129            575.83000000000004
    113130        """
     
    118135        Get Yahoo current price data for this stock.
    119136
    120137        OUTPUT:
    121             dict
    122138
    123         EXAMPLES:
     139        A dictionary.
     140
     141        EXAMPLES::
     142
    124143            sage: finance.Stock('GOOG').yahoo()          # random; optional -- internet
    125144            {'stock_exchange': '"NasdaqNM"', 'market_cap': '181.1B', '200day_moving_avg': '564.569', '52_week_high': '747.24', 'price_earnings_growth_ratio': '1.04', 'price_sales_ratio': '10.16', 'price': '576.48', 'earnings_per_share': '14.463', '50day_moving_avg': '549.293', 'avg_daily_volume': '6292480', 'volume': '1613507', '52_week_low': '412.11', 'short_ratio': '1.00', 'price_earnings_ratio': '40.50', 'dividend_yield': 'N/A', 'dividend_per_share': '0.00', 'price_book_ratio': '7.55', 'ebitda': '6.513B', 'change': '-9.32', 'book_value': '77.576'}
    126145        """
     
    156175        internally as well. By default, returns the past year's daily
    157176        OHLC data.
    158177
    159         Dates startdate and enddate should be formatted 'Mon+d,+yyyy' where
    160         'Mon' is a three character abbreviation of the month's name.
     178        Dates ``startdate`` and ``enddate`` should be formatted
     179        ``'Mon+d,+yyyy'``, where ``'Mon'`` is a three character abbreviation
     180        of the month's name.
    161181
    162         NOTE:
     182        .. NOTE::
     183
    163184            Google Finance returns the past year's financial data by default
    164             when startdate is set too low from the equity's date of going
     185            when ``startdate`` is set too low from the equity's date of going
    165186            public.  By default, this function only looks at the NASDAQ and
    166187            NYSE markets.  However, if you specified the market during
    167             initialization of the stock (i.e. "finance.Stock("OTC:NTDOY")"),
    168             Stock.google() will give correct results.
     188            initialization of the stock (i.e. ``finance.Stock("OTC:NTDOY")``),
     189            ``Stock.google()`` will give correct results.
    169190
    170191        INPUT:
    171             startdate -- string, (default: 'Jan+1,+1900')
    172             enddate   -- string, (default: current date )
    173             histperiod -- string, ('daily' or 'weekly')
     192
     193        - ``startdate`` -- string, (default: ``'Jan+1,+1900'``)
     194
     195        - ``enddate`` -- string, (default: current date)
     196
     197        - ``histperiod`` -- string, (``'daily'`` or ``'weekly'``)
    174198
    175199        OUTPUT:
    176             Sequence
     200
     201        A sequence.
    177202
    178203        EXAMPLES:
    179         We get the first five days of VMware's stock history:
     204
     205        We get the first five days of VMware's stock history::
     206
    180207            sage: finance.Stock('vmw').google()[:5]   # optional -- internet
    181208            [
    182209             28-Nov-07 80.57 88.49 80.57 87.69    7496000,
     
    195222              9-Jan-78 0.00 1.81 1.79 1.81    3916400
    196223            ]
    197224           
    198         Note that when startdate is too far prior to a stock's actual start
     225        Note that when ``startdate`` is too far prior to a stock's actual start
    199226        date, Google Finance defaults to a year's worth of stock history
    200         leading up to the specified enddate.  For example, Apple's (AAPL) stock
    201         history only dates back to September 7, 1984
     227        leading up to the specified end date.  For example, Apple's (AAPL)
     228        stock history only dates back to September 7, 1984::
    202229           
    203230            sage: finance.Stock('AAPL').google('Sep+1,+1900', 'Jan+1,+2000')[0:5] # optional -- internet
    204231            [
     
    210237            ]
    211238           
    212239        Here is an example where we create and get the history of a stock
    213         that is not in NASDAQ or NYSE
     240        that is not in NASDAQ or NYSE::
    214241               
    215242            sage: finance.Stock("OTC:NTDOY").google(startdate="Jan+1,+2007", enddate="Jan+1,+2008")[:5]  # optional -- internet
    216243            [
     
    226253        Note that when using historical, if a cid is specified,
    227254        it will take precedence over the stock's symbol.  So, if
    228255        the symbol and cid do not match, the history based on the
    229         contract id will be returned.
     256        contract id will be returned. ::
    230257       
    231258            sage: sage.finance.stock.Stock("AAPL", 22144).google(startdate='Jan+1,+1990')[:5] #optional -- internet
    232259            [
     
    257284
    258285    def open(self, *args, **kwds):
    259286        r"""
    260         Return a TimeSeries containing historical opening prices for this
     287        Return a time series containing historical opening prices for this
    261288        stock. If no arguments are given, will return last acquired historical
    262289        data. Otherwise, data will be gotten from Google Finance.
    263290
    264291        INPUT:
    265             startdate  -- string, (default: 'Jan+1,+1900')
    266             enddate    -- string, (default: current date)
    267             histperiod -- string, ('daily' or 'weekly')
     292
     293        - ``startdate`` -- string, (default: ``'Jan+1,+1900'``)
     294
     295        - ``enddate`` -- string, (default: current date)
     296
     297        - ``histperiod`` -- string, (``'daily'`` or ``'weekly'``)
    268298
    269299        OUTPUT:
    270             TimeSeries -- Close price data
     300
     301        A time series -- close price data.
    271302
    272303        EXAMPLES:
    273         You can directly obtain Open data as so:
     304
     305        You can directly obtain Open data as so::
     306
    274307            sage: finance.Stock('vmw').open(startdate='Jan+1,+2008', enddate='Feb+1,+2008')                 # optional -- internet
    275308            [83.0500, 85.4900, 84.9000, 82.0000, 81.2500 ... 82.0000, 58.2700, 54.4900, 55.6000, 56.9800]
    276309
    277310        Or, you can initialize stock data first and then extract the Open
    278         data:
     311        data::
     312
    279313            sage: c = finance.Stock('vmw')
    280314            sage: c.google(startdate='Feb+1,+2008', enddate='Mar+1,+2008')[:5]    # optional -- internet
    281315            [
     
    288322            sage: c.open()    # optional -- internet
    289323            [55.6000, 56.9800, 58.0000, 57.6000, 60.3200 ... 56.5500, 59.3000, 60.0000, 59.7900, 59.2600]
    290324
    291         Otherwise, \code{self.google()} will be called with the default
    292         arguments returning a year's worth of data:
     325        Otherwise, ``self.google()`` will be called with the default
     326        arguments returning a year's worth of data::
     327
    293328            sage: finance.Stock('vmw').open()   # random; optional -- internet
    294329            [52.1100, 60.9900, 59.0000, 56.0500, 57.2500 ... 83.0500, 85.4900, 84.9000, 82.0000, 81.2500]
    295 
    296330        """
    297331       
    298332        from time_series import TimeSeries
     
    314348        Otherwise, data will be gotten from Google Finance.
    315349
    316350        INPUT:
    317             startdate  -- string, (default: 'Jan+1,+1900')
    318             enddate    -- string, (default: current date)
    319             histperiod -- string, ('daily' or 'weekly')
     351
     352        - ``startdate`` -- string, (default: ``'Jan+1,+1900'``)
     353
     354        - ``enddate`` -- string, (default: current date)
     355
     356        - ``histperiod`` -- string, (``'daily'`` or ``'weekly'``)
    320357
    321358        OUTPUT:
    322             TimeSeries -- Close price data
     359
     360        A time series -- close price data.
    323361
    324362        EXAMPLES:
    325         You can directly obtain close data as so:
     363
     364        You can directly obtain close data as so::
     365
    326366            sage: finance.Stock('vmw').close(startdate='Jan+1,+2008', enddate='Feb+1,+2008')                 # optional -- internet
    327367            [84.9900, 84.6000, 83.9500, 80.4900, 72.9900 ... 83.0000, 54.8700, 56.4200, 56.6700, 57.8500]
    328368
    329369        Or, you can initialize stock data first and then extract the Close
    330         data:
     370        data::
     371
    331372            sage: c = finance.Stock('vmw')
    332373            sage: c.google(startdate='Feb+1,+2008', enddate='Mar+1,+2008')[:5]    # optional -- internet
    333374            [
     
    340381            sage: c.close()    # optional -- internet
    341382            [56.6700, 57.8500, 58.0500, 59.3000, 61.5200 ... 58.2900, 60.1800, 59.8600, 59.9500, 58.6700]
    342383
     384        Otherwise, ``self.google()`` will be called with the default
     385        arguments returning a year's worth of data::
    343386
    344 
    345         Otherwise, \code{self.google()} will be called with the default
    346         arguments returning a year's worth of data:
    347387            sage: finance.Stock('vmw').close()   # random; optional -- internet
    348388            [57.7100, 56.9900, 55.5500, 57.3300, 65.9900 ... 84.9900, 84.6000, 83.9500, 80.4900, 72.9900]
    349389        """
     
    365405        Load historical data from a local csv formatted data file. Note
    366406        that no symbol data is included in Google Finance's csv data.
    367407        The csv file must be formatted in the following way, just as
    368         on Google Finance:
     408        on Google Finance::
    369409
    370         Timestamp,Open,High,Low,Close,Volume
     410            Timestamp,Open,High,Low,Close,Volume
    371411
    372412        INPUT:
    373             file -- local file with Google Finance formatted OHLC data
    374413
    375         OUTPUTS:
    376             Sequence -- OHLC data
     414        - ``file`` -- local file with Google Finance formatted OHLC data.
     415
     416        OUTPUT:
     417
     418        A sequence -- OHLC data.
    377419
    378420        EXAMPLES:
     421
    379422        Suppose you have a file in your home directory containing Apple stock
    380         OHLC data, such as that from Google Finance, called AAPL-minutely.csv.
    381         One can load this information into a Stock object like so. Note that
    382         the path must be explicit:
     423        OHLC data, such as that from Google Finance, called
     424        ``AAPL-minutely.csv``. One can load this information into a Stock
     425        object like so. Note that the path must be explicit::
     426
    383427            sage: finance.Stock('aapl').load_from_file(SAGE_ROOT + '/examples/finance/AAPL-minutely.csv')[:5]
    384428            [
    385429            1212408060 188.00 188.00 188.00 188.00        687,
     
    393437        Note that since the source file doesn't contain information on which
    394438        equity the information comes from, the symbol designated at
    395439        initialization of Stock need not match the source of the data. For
    396         example, we can initialize a Stock object with the symbol 'goog',
    397         but load data from 'aapl' stock prices:
     440        example, we can initialize a Stock object with the symbol ``'goog'``,
     441        but load data from ``'aapl'`` stock prices::
     442
    398443            sage: finance.Stock('goog').load_from_file(SAGE_ROOT + '/examples/finance/AAPL-minutely.csv')[:5]
    399444            [
    400445            1212408060 188.00 188.00 188.00 188.00        687,
     
    404449            1212405780 187.80 187.80 187.80 187.80        100
    405450            ]
    406451
    407         This tests a file that doesn't exist:
     452        This tests a file that doesn't exist::
     453
    408454            sage: finance.Stock("AAPL").load_from_file("I am not a file")
    409455            Bad path or file name
    410 
    411456        """
    412457        try:
    413458            file_obj = open(file, 'r')
     
    421466    def _load_from_csv(self, R):
    422467        """
    423468        EXAMPLES:
    424         This indirectly tests _load_from_csv():
     469
     470        This indirectly tests ``_load_from_csv()``::
     471
    425472            sage: finance.Stock('aapl').load_from_file(SAGE_ROOT + "/examples/finance/AAPL-minutely.csv")
    426473            [
    427474            1212408060 188.00 188.00 188.00 188.00        687,
     
    430477            1212407640 187.75 188.00 187.75 188.00       2000,
    431478            1212405780 187.80 187.80 187.80 187.80        100
    432479            ]
    433 
    434        
    435480        """
    436481        R = R.splitlines()
    437482        headings = R[0].split(',')
     
    451496        This function is used internally.
    452497
    453498        EXAMPLES:
    454         This indirectly tests the use of get_data.
     499
     500        This indirectly tests the use of ``_get_data()``::
     501
    455502            sage: finance.Stock('aapl').google(startdate='Jan+1,+1990')[:2]    # optional -- internet
    456503            [
    457504              2-Jan-90 0.00 9.38 8.75 9.31    6542800,
  • sage/finance/time_series.pyx

    diff --git a/sage/finance/time_series.pyx b/sage/finance/time_series.pyx
    a b  
    55It is designed so that every operation is very fast, typically much
    66faster than with other generic code, e.g., Python lists of doubles or
    77even NumPy arrays.  The semantics of time series is more similar to
    8 Python lists of doubles than Sage real double vectors or NumPy 1d
     8Python lists of doubles than Sage real double vectors or NumPy 1-D
    99arrays.   In particular, time series are not endowed with much
    1010algebraic structure and are always mutable.
    1111
    12 NOTES: NumPy arrays are faster at slicing, since slices return
    13 references, and NumPy arrays have strides.  However, this speed at
    14 slicing makes NumPy slower at certain other operations.
     12.. NOTE::
    1513
    16 EXAMPLES:
     14    NumPy arrays are faster at slicing, since slices return
     15    references, and NumPy arrays have strides.  However, this speed at
     16    slicing makes NumPy slower at certain other operations.
     17
     18EXAMPLES::
     19
    1720    sage: set_random_seed(1)
    1821    sage: t = finance.TimeSeries([random()-0.5 for _ in xrange(10)]); t
    1922    [0.3294, 0.0959, -0.0706, -0.4646, 0.4311, 0.2275, -0.3840, -0.3528, -0.4119, -0.2933]
     
    2932    0.1137688493972542...
    3033
    3134AUTHOR:
    32     -- William Stein
     35
     36- William Stein
    3337"""
    3438
    3539include "../ext/cdefs.pxi"
     
    6266        Create new empty uninitialized time series.
    6367
    6468        EXAMPLES:
    65         This implicitly calls new.
     69
     70        This implicitly calls new::
     71
    6672            sage: finance.TimeSeries([1,3,-4,5])
    6773            [1.0000, 3.0000, -4.0000, 5.0000]
    6874        """
     
    7480       
    7581        INPUT:
    7682
    77             - values -- integer (number of values) or an iterable of
    78               floats
     83        - ``values`` -- integer (number of values) or an iterable of
     84          floats.
    7985           
    80             - initialize -- bool (default: True); if False, do not
    81               bother to zero out the entries of the new time series.
    82               For large series that you are going to just fill in,
    83               this can be way faster.
     86        - ``initialize`` -- bool (default: ``True``); if ``False``, do not
     87          bother to zero out the entries of the new time series.
     88          For large series that you are going to just fill in,
     89          this can be way faster.
    8490
    8591        EXAMPLES:
    8692
    87         This implicitly calls init.::
     93        This implicitly calls init::
    8894       
    8995            sage: finance.TimeSeries([pi, 3, 18.2])
    9096            [3.1416, 3.0000, 18.2000]
    9197
    92         Conversion from a numpy 1d array, which is very fast.::
     98        Conversion from a NumPy 1-D array, which is very fast::
    9399       
    94100            sage: v = finance.TimeSeries([1..5])
    95101            sage: w = v.numpy()
    96102            sage: finance.TimeSeries(w)
    97103            [1.0000, 2.0000, 3.0000, 4.0000, 5.0000]
    98104
    99         Conversion from an n-dimensional numpy array also works::
     105        Conversion from an n-dimensional NumPy array also works::
    100106       
    101107            sage: import numpy
    102108            sage: v = numpy.array([[1,2], [3,4]], dtype=float); v
     
    164170        """
    165171        Used in pickling time series.
    166172
    167         EXAMPLES:
     173        EXAMPLES::
     174
    168175            sage: v = finance.TimeSeries([1,-3.5])
    169176            sage: v.__reduce__()
    170177            (<built-in function unpickle_time_series_v1>, (..., 2))
    171178            sage: loads(dumps(v)) == v
    172179            True
    173180
    174         Note that dumping and loading with compress False is much faster, though
    175         dumping with compress True can save a lot of space.
     181        Note that dumping and loading with compress ``False`` is much faster,
     182        though dumping with compress ``True`` can save a lot of space::
     183
    176184            sage: v = finance.TimeSeries([1..10^5])
    177185            sage: loads(dumps(v, compress=False),compress=False) == v
    178186            True
     
    182190
    183191    def __cmp__(self, _other):
    184192        """
    185         Compare self and other.  This has the same semantics
     193        Compare ``self`` and ``other``.  This has the same semantics
    186194        as list comparison.
    187195
    188         EXAMPLES:
     196        EXAMPLES::
     197
    189198            sage: v = finance.TimeSeries([1,2,3]); w = finance.TimeSeries([1,2])
    190199            sage: v < w
    191200            False
     
    218227        Free up memory used by a time series.
    219228
    220229        EXAMPLES:
    221         This tests __dealloc__ implicitly:
     230
     231        This tests ``__dealloc__`` implicitly::
     232
    222233            sage: v = finance.TimeSeries([1,3,-4,5])
    223234            sage: del v
    224235        """
     
    232243        algebraic structure and play well with matrices.
    233244
    234245        OUTPUT:
    235             a real double vector
    236246
    237         EXAMPLES:
     247        A real double vector.
     248
     249        EXAMPLES::
     250
    238251            sage: v = finance.TimeSeries([1..10])
    239252            sage: v.vector()
    240253            (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
     
    246259
    247260    def __repr__(self):
    248261        """
    249         Return string representation of self.
     262        Return string representation of ``self``.
    250263
    251         EXAMPLES:
     264        EXAMPLES::
     265
    252266            sage: v = finance.TimeSeries([1,3.1908439,-4,5.93932])
    253267            sage: v.__repr__()
    254268            '[1.0000, 3.1908, -4.0000, 5.9393]'
    255269       
    256270        By default 4 digits after the decimal point are displayed.  To
    257         change this change self.finance.time_series.digits.
     271        change this, change ``self.finance.time_series.digits``. ::
     272
    258273            sage: sage.finance.time_series.digits = 2
    259274            sage: v.__repr__()
    260275            '[1.00, 3.19, -4.00, 5.94]'
     
    271286        Print representation of a time series.
    272287
    273288        INPUT:
    274             prec -- number of digits of precision or None; if None
    275                     use the default sage.finance.time_series.digits
     289
     290        - ``prec`` -- (default: ``None``) number of digits of precision or
     291          ``None``. If ``None`` use the default
     292          ``sage.finance.time_series.digits``.
     293
    276294        OUTPUT:
    277              a string
     295
     296        A string.
    278297                     
    279         EXAMPLES:
     298        EXAMPLES::
     299
    280300            sage: v = finance.TimeSeries([1,3.1908439,-4,5.93932])
    281301            sage: v._repr()
    282302            '[1.0000, 3.1908, -4.0000, 5.9393]'
     
    300320        Return the number of entries in this time series.
    301321
    302322        OUTPUT:
    303             Python integer
    304323
    305         EXAMPLES:
     324        Python integer.
     325
     326        EXAMPLES::
     327
    306328            sage: v = finance.TimeSeries([1,3.1908439,-4,5.93932])
    307329            sage: v.__len__()
    308330            4
     
    313335
    314336    def __getitem__(self, i):
    315337        """
    316         Return i-th entry or slice of self.
     338        Return i-th entry or slice of ``self``.
    317339       
    318         EXAMPLES:
     340        EXAMPLES::
     341
    319342            sage: v = finance.TimeSeries([1,-4,3,-2.5,-4,3])
    320343            sage: v[2]
    321344            3.0
     
    332355            ...
    333356            IndexError: TimeSeries index out of range
    334357
    335         Some slice examples:
     358        Some slice examples::
     359
    336360            sage: v[-3:]
    337361            [-2.5000, -4.0000, 3.0000]
    338362            sage: v[-3:-1]
     
    344368            sage: v[3:2]
    345369            []
    346370
    347         Make a copy:
     371        Make a copy::
     372
    348373            sage: v[:]
    349374            [1.0000, -4.0000, 3.0000, -2.5000, -4.0000, 3.0000]
    350375
    351         Reverse the time series:
     376        Reverse the time series::
     377
    352378            sage: v[::-1]
    353379            [3.0000, -4.0000, -2.5000, 3.0000, -4.0000, 1.0000]
    354380        """
     
    395421
    396422    def __setitem__(self, Py_ssize_t i, double x):
    397423        """
    398         Set the i-th entry of self to x.
     424        Set the i-th entry of ``self`` to ``x``.
    399425
    400426        INPUT:
    401             i -- a nonnegative integer
    402             x -- a float
    403427
    404         EXAMPLES:
     428        - i -- a nonnegative integer.
     429
     430        - x -- a float.
     431
     432        EXAMPLES::
     433
    405434            sage: v = finance.TimeSeries([1,3,-4,5.93932]); v
    406435            [1.0000, 3.0000, -4.0000, 5.9393]
    407436            sage: v[0] = -5.5; v
     
    427456
    428457    def __copy__(self):
    429458        """
    430         Return a copy of self.
     459        Return a copy of ``self``.
    431460
    432         EXAMPLES:
     461        EXAMPLES::
     462
    433463            sage: v = finance.TimeSeries([1,-4,3,-2.5,-4,3])
    434464            sage: v.__copy__()
    435465            [1.0000, -4.0000, 3.0000, -2.5000, -4.0000, 3.0000]
     
    445475
    446476    def __add__(left, right):
    447477        """
    448         Concatenate the time series self and right.
     478        Concatenate the time series ``self`` and ``right``.
    449479
    450         NOTE: To add a single number to the entries of a time series,
    451         use the add_scalar method, and to add componentwise use
    452         the add_entries method.
     480        .. NOTE::
     481
     482            To add a single number to the entries of a time series,
     483            use the ``add_scalar`` method, and to add componentwise use
     484            the ``add_entries`` method.
    453485       
    454486        INPUT:
    455             right -- a time series
     487
     488        - ``right`` -- a time series.
     489
    456490        OUTPUT:
    457             a time series
    458491
    459         EXAMPLES:
     492        A time series.
     493
     494        EXAMPLES::
     495
    460496            sage: v = finance.TimeSeries([1,2,3]); w = finance.TimeSeries([1,2])
    461497            sage: v + w
    462498            [1.0000, 2.0000, 3.0000, 1.0000, 2.0000]
    463499            sage: v = finance.TimeSeries([1,2,-5]); v
    464500            [1.0000, 2.0000, -5.0000]
    465501
    466         Note that both summands must be a time series:
     502        Note that both summands must be a time series::
     503
    467504            sage: v + xrange(4)
    468505            Traceback (most recent call last):
    469506            ...
     
    489526        Multiply a time series by an integer n, which (like for lists)
    490527        results in the time series concatenated with itself n times.
    491528
    492         NOTE: To multiply all the entries of a time series by a single
    493         scalar, use the scale method.
     529        .. NOTE::
     530
     531            To multiply all the entries of a time series by a single
     532            scalar, use the ``scale`` method.
    494533       
    495534        INPUT:
    496             left, right -- an integer and a time series
     535
     536        - ``left``, ``right`` -- an integer and a time series.
     537
    497538        OUTPUT:
    498             a time series
    499539
    500         EXAMPLES:
     540        A time series.
     541
     542        EXAMPLES::
     543
    501544            sage: v = finance.TimeSeries([1,2,-5]); v
    502545            [1.0000, 2.0000, -5.0000]
    503546            sage: v*3
     
    525568
    526569
    527570    def autoregressive_fit(self,M):
    528         """
     571        r"""
    529572        This method fits the time series to an autoregressive process
    530         of order M. That is we assume the process is given by
    531         $X_t-\mu=a_1(X_{t-1}-\mu)+a_2(X_{t-1}-\mu)+...+a_M(X_{t-M}-\mu)+Z_t$
    532         where $\mu$ is the mean of the process and $Z_t$ is noise.
    533         This method returns estimates for $a_1,...,a_M$.
     573        of order ``M``. That is, we assume the process is given by
     574        `X_t-\mu=a_1(X_{t-1}-\mu)+a_2(X_{t-1}-\mu)+\cdots+a_M(X_{t-M}-\mu)+Z_t`
     575        where `\mu` is the mean of the process and `Z_t` is noise.
     576        This method returns estimates for `a_1,\dots,a_M`.
    534577
    535578        The method works by solving the Yule-Walker equations
    536         $\Gamma a =\gamma$, where $\gamma=(\gamma(1),...,\gamma(M))$,
    537         $a=(a_1,..,a_M)$  with $\gamma(i)$ the autocovariance of lag i
    538         and $\Gamma_{ij}=\gamma(i-j)$.
     579        `\Gamma a =\gamma`, where `\gamma=(\gamma(1),\dots,\gamma(M))`,
     580        `a=(a_1,\dots,a_M)`  with `\gamma(i)` the autocovariance of lag `i`
     581        and `\Gamma_{ij}=\gamma(i-j)`.
    539582       
    540583       
    541         WARNING: The input sequence is assumed to be stationary, which
    542         means that the autocovariance $\langle y_j y_k \rangle$ depends
    543         only on the difference $|j-k|$.
     584        .. WARNING::
     585
     586            The input sequence is assumed to be stationary, which
     587            means that the autocovariance `\langle y_j y_k \rangle` depends
     588            only on the difference `|j-k|`.
    544589
    545590        INPUT:
    546             M -- integer
     591
     592        - ``M`` -- an integer.
    547593
    548594        OUTPUT:
    549             TimeSeries -- the coefficients of the autoregressive process.
    550595
    551         EXAMPLES:
     596        A time series -- the coefficients of the autoregressive process.
     597
     598        EXAMPLES::
     599
    552600            sage: set_random_seed(0)
    553601            sage: v = finance.TimeSeries(10^4).randomize('normal').sums()
    554602            sage: F = v.autoregressive_fit(100)
     
    572620            sage: c=t[0:-1].autoregressive_fit(2)  #recovers recurrence relation
    573621            sage: c #should be close to [1,-0.5]
    574622            [1.0371, -0.5199]
    575 
    576            
    577623        """
    578624        acvs = [self.autocovariance(i) for i in range(M+1)]
    579625        return autoregressive_fit(acvs)
    580626
    581627    def autoregressive_forecast(self, filter):
    582628        """
    583         Given the autoregression coefficients as outputted by the autoregressive_fit command,
    584         compute the forecast for the next term in the series.
     629        Given the autoregression coefficients as outputted by the
     630        ``autoregressive_fit`` command, compute the forecast for the next
     631        term in the series.
    585632
    586633        INPUT:
    587             autoregression coefficients -- a time series outputted by the autoregressive_fit command.
    588634
    589         EXAMPLES:
     635        - ``filter`` -- a time series outputted by the ``autoregressive_fit``
     636          command.
     637
     638        EXAMPLES::
     639
    590640            sage: set_random_seed(0)
    591641            sage: v = finance.TimeSeries(100).randomize('normal').sums()
    592642            sage: F = v[:-1].autoregressive_fit(5); F
     
    614664        reversing the order of the entries in this time series.
    615665
    616666        OUTPUT:
    617             time series
    618667
    619         EXAMPLES:
     668        A time series.
     669
     670        EXAMPLES::
     671
    620672            sage: v = finance.TimeSeries([1..5])
    621673            sage: v.reversed()
    622674            [5.0000, 4.0000, 3.0000, 2.0000, 1.0000]
     
    630682
    631683    def extend(self, right):
    632684        """
    633         Extend this time series by appending elements from the iterable right.
     685        Extend this time series by appending elements from the iterable
     686        ``right``.
    634687
    635688        INPUT:
    636             right -- iterable that can be converted to a time series
    637689
    638         EXAMPLES:
     690        - ``right`` -- iterable that can be converted to a time series.
     691
     692        EXAMPLES::
     693
    639694            sage: v = finance.TimeSeries([1,2,-5]); v
    640695            [1.0000, 2.0000, -5.0000]
    641696            sage: v.extend([-3.5, 2])
     
    658713
    659714    def list(self):
    660715        """
    661         Return list of elements of self.
     716        Return list of elements of ``self``.
    662717
    663         EXAMPLES:
     718        EXAMPLES::
     719
    664720            sage: v = finance.TimeSeries([1,-4,3,-2.5,-4,3])
    665721            sage: v.list()
    666722            [1.0, -4.0, 3.0, -2.5, -4.0, 3.0]
     
    674730        terms in the time series.
    675731
    676732        OUTPUT:
    677             a new time series.
     733
     734        A new time series.
    678735
    679736        EXAMPLES:
     737
    680738        We exponentiate then log a time series and get back
    681         the original series.
     739        the original series::
     740
    682741            sage: v = finance.TimeSeries([1,-4,3,-2.5,-4,3]); v
    683742            [1.0000, -4.0000, 3.0000, -2.5000, -4.0000, 3.0000]
    684743            sage: v.exp()
     
    686745            sage: v.exp().log()
    687746            [1.0000, -4.0000, 3.0000, -2.5000, -4.0000, 3.0000]
    688747
    689         Log of 0 gives -inf:
     748        Log of 0 gives ``-inf``::
    690749
    691750            sage: finance.TimeSeries([1,0,3]).log()[1]
    692751            -inf
     
    703762        all the terms in the time series.
    704763
    705764        OUTPUT:
    706             a new time series.
    707765
    708         EXAMPLES:
     766        A new time series.
     767
     768        EXAMPLES::
     769
    709770            sage: v = finance.TimeSeries([1..5]); v
    710771            [1.0000, 2.0000, 3.0000, 4.0000, 5.0000]
    711772            sage: v.exp()
     
    722783    def abs(self):
    723784        """
    724785        Return new time series got by replacing all entries
    725         of self by their absolute value.
     786        of ``self`` by their absolute value.
    726787
    727788        OUTPUT:
    728             a new time series
    729789
    730         EXAMPLES:
     790        A new time series.
     791
     792        EXAMPLES::
     793
    731794            sage: v = finance.TimeSeries([1,3.1908439,-4,5.93932])
    732795            sage: v
    733796            [1.0000, 3.1908, -4.0000, 5.9393]
     
    741804        return t
    742805
    743806    def diffs(self, Py_ssize_t k = 1):
    744         """
     807        r"""
    745808        Return the new time series got by taking the differences of
    746         successive terms in the time series.  So if self is the time
    747         series $X_0, X_1, X_2, ...$, then this function outputs the
    748         series $X_1 - X_0, X_2 - X_1, ...$.  The output series has one
     809        successive terms in the time series.  So if ``self`` is the time
     810        series `X_0, X_1, X_2, \dots`, then this function outputs the
     811        series `X_1 - X_0, X_2 - X_1, \dots`.  The output series has one
    749812        less term than the input series.  If the optional parameter
    750         $k$ is given, return $X_k - X_0, X_{2k} - X_k, ...$.
     813        `k` is given, return `X_k - X_0, X_{2k} - X_k, \dots`.
    751814
    752815        INPUT:
    753             k -- positive integer (default: 1)
     816
     817        - ``k`` -- positive integer (default: 1)
    754818
    755819        OUTPUT:
    756             a new time series.
    757820
    758         EXAMPLES:
     821        A new time series.
     822
     823        EXAMPLES::
     824
    759825            sage: v = finance.TimeSeries([5,4,1.3,2,8]); v
    760826            [5.0000, 4.0000, 1.3000, 2.0000, 8.0000]
    761827            sage: v.diffs()
     
    770836        return t
    771837
    772838    def scale_time(self, Py_ssize_t k):
    773         """
    774         Return the new time series at scale k.  If the input
    775         time series is $X_0, X_1, X_2, ...$, then this function
    776         returns the shorter time series $X_0, X_k, X_{2k}, ...$.
     839        r"""
     840        Return the new time series at scale ``k``.  If the input
     841        time series is `X_0, X_1, X_2, \dots`, then this function
     842        returns the shorter time series `X_0, X_k, X_{2k}, \dots`.
    777843
    778844        INPUT:
    779             k -- a positive integer
     845
     846        - ``k`` -- a positive integer.
    780847
    781848        OUTPUT:
    782             a new time series.
    783849
    784         EXAMPLES:
     850        A new time series.
     851
     852        EXAMPLES::
     853
    785854            sage: v = finance.TimeSeries([5,4,1.3,2,8,10,3,-5]); v
    786855            [5.0000, 4.0000, 1.3000, 2.0000, 8.0000, 10.0000, 3.0000, -5.0000]
    787856            sage: v.scale_time(1)
     
    793862            sage: v.scale_time(10)
    794863            []
    795864
    796         A series of odd length:
     865        A series of odd length::
     866
    797867            sage: v = finance.TimeSeries([1..5]); v
    798868            [1.0000, 2.0000, 3.0000, 4.0000, 5.0000]
    799869            sage: v.scale_time(2)
    800870            [1.0000, 3.0000, 5.0000]
    801871
    802         TESTS:
     872        TESTS::
     873
    803874            sage: v.scale_time(0)
    804875            Traceback (most recent call last):
    805876            ...
     
    823894
    824895    cpdef rescale(self, double s):
    825896        """
    826         Change self by multiplying every value in the series by s.
     897        Change ``self`` by multiplying every value in the series by ``s``.
    827898
    828899        INPUT:
    829             s -- float
    830900
    831         EXAMPLES:
     901        - ``s`` -- a float.
     902
     903        EXAMPLES::
     904
    832905            sage: v = finance.TimeSeries([5,4,1.3,2,8,10,3,-5]); v
    833906            [5.0000, 4.0000, 1.3000, 2.0000, 8.0000, 10.0000, 3.0000, -5.0000]
    834907            sage: v.rescale(0.5)
     
    840913
    841914    def scale(self, double s):
    842915        """
    843         Return new time series obtained by multiplying every value in the series by s.
     916        Return new time series obtained by multiplying every value in the
     917        series by ``s``.
    844918
    845919        INPUT:
    846             s -- float
     920
     921        - ``s`` -- a float.
     922
    847923        OUTPUT:
    848             a new time series with all values multiplied by s.
    849924
    850         EXAMPLES:
     925        A new time series with all values multiplied by ``s``.
     926
     927        EXAMPLES::
     928
    851929            sage: v = finance.TimeSeries([5,4,1.3,2,8,10,3,-5]); v
    852930            [5.0000, 4.0000, 1.3000, 2.0000, 8.0000, 10.0000, 3.0000, -5.0000]
    853931            sage: v.scale(0.5)
     
    863941        Return new time series obtained by adding a scalar to every
    864942        value in the series.
    865943
    866         NOTE: To add componentwise use the add_entries method. 
     944        .. NOTE::
     945
     946            To add componentwise, use the ``add_entries`` method. 
    867947
    868948        INPUT:
    869             s -- float
     949
     950        - ``s`` -- a float.
     951
    870952        OUTPUT:
    871             a new time series with s added to all values.
    872953
    873         EXAMPLES:
     954        A new time series with ``s`` added to all values.
     955
     956        EXAMPLES::
     957
    874958            sage: v = finance.TimeSeries([5,4,1.3,2,8,10,3,-5]); v
    875959            [5.0000, 4.0000, 1.3000, 2.0000, 8.0000, 10.0000, 3.0000, -5.0000]
    876960            sage: v.add_scalar(0.5)
     
    883967
    884968    def add_entries(self, t):
    885969        """
    886         Add corresponding entries of self and t together,
    887         extending either self or t by 0's if they do
     970        Add corresponding entries of ``self`` and ``t`` together,
     971        extending either ``self`` or ``t`` by 0's if they do
    888972        not have the same length.
    889973
    890         NOTE: To add a single number to the entries of a time series,
    891         use the add_scalar method.
     974        .. NOTE::
     975
     976            To add a single number to the entries of a time series,
     977            use the ``add_scalar`` method.
    892978
    893979        INPUT:
    894             t -- a time series
     980
     981        - ``t`` -- a time series.
     982
    895983        OUTPUT:
    896             a time series with length the maxima of the lengths of
    897             self and t.
     984
     985        A time series with length the maxima of the lengths of
     986        ``self`` and ``t``.
    898987           
    899         EXAMPLES:
     988        EXAMPLES::
     989
    900990            sage: v = finance.TimeSeries([1,2,-5]); v
    901991            [1.0000, 2.0000, -5.0000]
    902992            sage: v.add_entries([3,4])
     
    9341024
    9351025    def show(self, *args, **kwds):
    9361026        """
    937         Calls plot and passes all arguments onto the plot function.  This is thus
    938         just an alias for plot.
     1027        Calls plot and passes all arguments onto the plot function.  This is
     1028        thus just an alias for plot.
    9391029
    9401030        EXAMPLES:
    941         Draw a plot of a time series:
     1031
     1032        Draw a plot of a time series::
     1033
    9421034            sage: finance.TimeSeries([1..10]).show()
    9431035        """
    9441036        return self.plot(*args, **kwds)
    9451037
    9461038    def plot(self, Py_ssize_t plot_points=1000, points=False, **kwds):
    947         """
     1039        r"""
    9481040        Return a plot of this time series as a line or points through
    949         (i,T(i)), where i ranges over nonnegative integers up to the
    950         length of self.
     1041        `(i,T(i))`, where `i` ranges over nonnegative integers up to the
     1042        length of ``self``.
    9511043
    9521044        INPUT:
    953             plot_points -- (default: 1000) 0 or positive integer; only
    954                            plot the given number of equally spaced
    955                            points in the time series; if 0, plot all points
    956             points -- bool (default: False) -- if True, return just the
    957                       points of the time series
    958             **kwds -- passed to the line or point command
     1045
     1046        - ``plot_points`` -- (default: 1000) 0 or positive integer. Only
     1047          plot the given number of equally spaced points in the time series.
     1048          If 0, plot all points.
     1049
     1050        - ``points`` -- bool (default: ``False``). If ``True``, return just
     1051          the points of the time series.
     1052
     1053        - ``**kwds`` -- passed to the line or point command.
    9591054           
    960         EXAMPLES:
     1055        EXAMPLES::
     1056
    9611057            sage: v = finance.TimeSeries([5,4,1.3,2,8,10,3,-5]); v
    9621058            [5.0000, 4.0000, 1.3000, 2.0000, 8.0000, 10.0000, 3.0000, -5.0000]
    9631059            sage: v.plot()
     
    9891085
    9901086    def simple_moving_average(self, Py_ssize_t k):
    9911087        """
    992         Return the moving average time series over the last k time units.
     1088        Return the moving average time series over the last ``k`` time units.
    9931089        Assumes the input time series was constant with its starting value
    9941090        for negative time.  The t-th step of the output is the sum of
    995         the previous k-1 steps of self and the kth step divided by k.
    996         Thus k values are averaged at each point.
     1091        the previous ``k - 1`` steps of ``self`` and the ``k``-th step
     1092        divided by ``k``. Thus ``k`` values are averaged at each point.
    9971093
    9981094        INPUT:
    999             k -- positive integer
     1095
     1096        - ``k`` -- positive integer.
    10001097
    10011098        OUTPUT:
    1002             a time series with the same number of steps as self.
    10031099
    1004         EXAMPLES:
     1100        A time series with the same number of steps as ``self``.
     1101
     1102        EXAMPLES::
     1103
    10051104            sage: v = finance.TimeSeries([1,1,1,2,3]); v
    10061105            [1.0000, 1.0000, 1.0000, 2.0000, 3.0000]
    10071106            sage: v.simple_moving_average(0)
     
    10391138        Return the exponential moving average time series.  Assumes
    10401139        the input time series was constant with its starting value for
    10411140        negative time.  The t-th step of the output is the sum of the
    1042         previous k-1 steps of self and the kth step divided by k.
     1141        previous k-1 steps of ``self`` and the k-th step divided by k.
    10431142
    1044         The 0th term is formally undefined, so we define it to be 0,
    1045         and we define the first term to be self[0].
     1143        The 0-th term is formally undefined, so we define it to be 0,
     1144        and we define the first term to be ``self[0]``.
    10461145
    10471146        INPUT:
    1048             alpha -- float; a smoothing factor with 0 <= alpha <= 1
     1147
     1148        - ``alpha`` -- float; a smoothing factor with ``0 <= alpha <= 1``.
    10491149
    10501150        OUTPUT:
    1051             a time series with the same number of steps as self.
    10521151
    1053         EXAMPLES:
     1152        A time series with the same number of steps as ``self``.
     1153
     1154        EXAMPLES::
     1155
    10541156            sage: v = finance.TimeSeries([1,1,1,2,3]); v
    10551157            [1.0000, 1.0000, 1.0000, 2.0000, 3.0000]
    10561158            sage: v.exponential_moving_average(0)
     
    10601162            sage: v.exponential_moving_average(0.5)
    10611163            [0.0000, 1.0000, 1.0000, 1.0000, 1.5000]
    10621164
    1063         Some more examples:
     1165        Some more examples::
     1166
    10641167            sage: v = finance.TimeSeries([1,2,3,4,5])
    10651168            sage: v.exponential_moving_average(1)
    10661169            [0.0000, 1.0000, 2.0000, 3.0000, 4.0000]
     
    10871190        sums of the terms of this time series.
    10881191
    10891192        INPUT:
    1090             s -- starting value for partial sums
     1193
     1194        - ``s`` -- starting value for partial sums.
     1195
    10911196        OUTPUT:
    1092             TimeSeries
    10931197
    1094         EXAMPLES:
     1198        A time series.
     1199
     1200        EXAMPLES::
     1201
    10951202            sage: v = finance.TimeSeries([1,1,1,2,3]); v
    10961203            [1.0000, 1.0000, 1.0000, 2.0000, 3.0000]
    10971204            sage: v.sums()
     
    11061213
    11071214    cpdef double sum(self):
    11081215        """
    1109         Return the sum of all the entries of self.  If self has
     1216        Return the sum of all the entries of ``self``.  If ``self`` has
    11101217        length 0, returns 0.
    11111218
    11121219        OUTPUT:
    1113             double
    11141220
    1115         EXAMPLES:
     1221        A double.
     1222
     1223        EXAMPLES::
     1224
    11161225            sage: v = finance.TimeSeries([1,1,1,2,3]); v
    11171226            [1.0000, 1.0000, 1.0000, 2.0000, 3.0000]
    11181227            sage: v.sum()
     
    11261235
    11271236    def prod(self):
    11281237        """
    1129         Return the prod of all the entries of self.  If self has
     1238        Return the product of all the entries of ``self``.  If ``self`` has
    11301239        length 0, returns 1.
    11311240
    11321241        OUTPUT:
    1133             double
    11341242
    1135         EXAMPLES:
     1243        A double.
     1244
     1245        EXAMPLES::
     1246
    11361247            sage: v = finance.TimeSeries([1,1,1,2,3]); v
    11371248            [1.0000, 1.0000, 1.0000, 2.0000, 3.0000]
    11381249            sage: v.prod()
     
    11471258   
    11481259    def mean(self):
    11491260        """
    1150         Return the mean (average) of the elements of self.
     1261        Return the mean (average) of the elements of ``self``.
    11511262
    11521263        OUTPUT:
    1153             double
     1264
     1265        A double.
    11541266           
    1155         EXAMPLES:
     1267        EXAMPLES::
     1268
    11561269            sage: v = finance.TimeSeries([1,1,1,2,3]); v
    11571270            [1.0000, 1.0000, 1.0000, 2.0000, 3.0000]
    11581271            sage: v.mean()
     
    11621275
    11631276    def pow(self, double k):
    11641277        """
    1165         Return new time series with every elements of self raised to the
    1166         kth power.
     1278        Return a new time series with every elements of ``self`` raised to the
     1279        k-th power.
    11671280
    11681281        INPUT:
    1169             k -- float
     1282
     1283        - ``k`` -- a float.
     1284
    11701285        OUTPUT:
    1171             time series
    11721286
    1173         EXAMPLES:
     1287        A time series.
     1288
     1289        EXAMPLES::
     1290
    11741291            sage: v = finance.TimeSeries([1,1,1,2,3]); v
    11751292            [1.0000, 1.0000, 1.0000, 2.0000, 3.0000]
    11761293            sage: v.pow(2)
     
    11841301
    11851302    def moment(self, int k):
    11861303        """
    1187         Return the k-th moment of self, which is just the
    1188         mean of the k-th powers of the elements of self.
     1304        Return the k-th moment of ``self``, which is just the
     1305        mean of the k-th powers of the elements of ``self``.
    11891306
    11901307        INPUT:
    1191             k -- a positive integer
     1308
     1309        - ``k`` -- a positive integer.
    11921310
    11931311        OUTPUT:
    1194             double
     1312
     1313        A double.
    11951314           
    1196         EXAMPLES:
     1315        EXAMPLES::
     1316
    11971317            sage: v = finance.TimeSeries([1,1,1,2,3]); v
    11981318            [1.0000, 1.0000, 1.0000, 2.0000, 3.0000]
    11991319            sage: v.moment(1)
     
    12131333
    12141334    def central_moment(self, int k):
    12151335        """
    1216         Return the k-th central moment of self, which is just the mean
    1217         of the k-th powers of the differences self[i]-mu, where mu is
    1218         the mean of self.
     1336        Return the k-th central moment of ``self``, which is just the mean
     1337        of the k-th powers of the differences ``self[i] - mu``, where ``mu`` is
     1338        the mean of ``self``.
    12191339
    12201340        INPUT:
    1221             k -- a positive integer
     1341
     1342        - ``k`` -- a positive integer.
     1343
    12221344        OUTPUT:
    1223             double
    12241345
    1225         EXAMPLES:
     1346        A double.
     1347
     1348        EXAMPLES::
     1349
    12261350            sage: v = finance.TimeSeries([1,2,3])
    12271351            sage: v.central_moment(2)
    12281352            0.66666666666666663
    12291353
    1230         Note that the central moment is different than the moment
    1231         here, since the mean is not $0$:
     1354        Note that the central moment is different from the moment
     1355        here, since the mean is not `0`::
     1356
    12321357            sage: v.moment(2)     # doesn't subtract off mean
    12331358            4.666666666666667
    12341359
    1235         We compute the central moment directly:
     1360        We compute the central moment directly::
     1361
    12361362            sage: mu = v.mean(); mu
    12371363            2.0
    12381364            sage: ((1-mu)^2 + (2-mu)^2 + (3-mu)^2) / 3
     
    12471373
    12481374    def covariance(self, TimeSeries other):
    12491375        r"""
    1250         Return the covariance of the time series self and other.
     1376        Return the covariance of the time series ``self`` and ``other``.
    12511377
    12521378        INPUT:
    1253             self, other -- time series
     1379
     1380        - ``self``, ``other`` -- time series.
    12541381
    12551382        Whichever time series has more terms is truncated.
    12561383       
    1257         EXAMPLES:
     1384        EXAMPLES::
     1385
    12581386            sage: v = finance.TimeSeries([1,-2,3]); w = finance.TimeSeries([4,5,-10])
    12591387            sage: v.covariance(w)
    12601388            -11.777777777777779
     
    12731401
    12741402    def autocovariance(self, Py_ssize_t k=0):
    12751403        r"""
    1276         Return the k-th autocovariance function $\gamma(k)$ of self.
    1277         This is the covariance of self with self shifted by $k$, i.e.,
    1278         $$
    1279         ( \sum_{t=0}^{n-k-1} (x_t - \mu)(x_{t + k} - \mu) ) / n,
    1280         $$
    1281         where $n$ is the length of self.
     1404        Return the k-th autocovariance function `\gamma(k)` of ``self``.
     1405        This is the covariance of ``self`` with ``self`` shifted by `k`, i.e.,
    12821406
    1283         Note the denominator of $n$, which gives a "better" sample
     1407        .. MATH::
     1408
     1409            \left.
     1410            \left( \sum_{t=0}^{n-k-1} (x_t - \mu)(x_{t + k} - \mu) \right)
     1411            \right/ n,
     1412
     1413        where `n` is the length of ``self``.
     1414
     1415        Note the denominator of `n`, which gives a "better" sample
    12841416        estimator.
    12851417
    12861418        INPUT:
    1287             k -- a nonnegative integer (default: 0)
     1419
     1420        - ``k`` -- a nonnegative integer (default: 0)
    12881421
    12891422        OUTPUT:
    1290             float
    12911423
    1292         EXAMPLES:
     1424        A float.
     1425
     1426        EXAMPLES::
     1427
    12931428            sage: v = finance.TimeSeries([13,8,15,4,4,12,11,7,14,12])
    12941429            sage: v.autocovariance(0)
    12951430            14.4
     
    13041439
    13051440        We illustrate with a random sample that an independently and
    13061441        identically distributed distribution with zero mean and
    1307         variance $\sigma^2$ has autocovariance function $\gamma(h)$
    1308         with $\gamma(0) = \sigma^2$ and $\gamma(h) = 0$ for $h\neq 0$.
     1442        variance `\sigma^2` has autocovariance function `\gamma(h)`
     1443        with `\gamma(0) = \sigma^2` and `\gamma(h) = 0` for `h\neq 0`. ::
     1444
    13091445            sage: set_random_seed(0)
    13101446            sage: v = finance.TimeSeries(10^6)
    13111447            sage: v.randomize('normal', 0, 5)
     
    13291465
    13301466    def correlation(self, TimeSeries other):
    13311467        """
    1332         Return the correlation of self and other, which is the
    1333         covariance of self and other divided by the product of their
     1468        Return the correlation of ``self`` and ``other``, which is the
     1469        covariance of ``self`` and ``other`` divided by the product of their
    13341470        standard deviation.
    13351471
    13361472        INPUT:
    1337             self, other -- time series
     1473
     1474        - ``self``, ``other`` -- time series.
    13381475           
    13391476        Whichever time series has more terms is truncated.
    13401477
    1341         EXAMPLES:
     1478        EXAMPLES::
     1479
    13421480            sage: v = finance.TimeSeries([1,-2,3]); w = finance.TimeSeries([4,5,-10])
    13431481            sage: v.correlation(w)
    13441482            -0.558041609...
     
    13491487
    13501488    def autocorrelation(self, Py_ssize_t k=1):
    13511489        r"""
    1352         Return the $k$th sample autocorrelation of this time series
    1353         $x_i$.
     1490        Return the k-th sample autocorrelation of this time series
     1491        `x_i`.
    13541492
    1355         Let $\mu$ be the sample mean.  Then the sample autocorrelation
     1493        Let `\mu` be the sample mean.  Then the sample autocorrelation
    13561494        function is
    1357            $$
    1358               \frac{\sum_{t=0}^{n-k-1} (x_t - \mu)(x_{t+k} - \mu) }
    1359                    {\sum_{t=0}^{n-1}   (x_t - \mu)^2}
    1360            $$
     1495
     1496        .. MATH::
     1497
     1498            \frac{\sum_{t=0}^{n-k-1} (x_t - \mu)(x_{t+k} - \mu) }
     1499                 {\sum_{t=0}^{n-1}   (x_t - \mu)^2}.
    13611500
    13621501        Note that the variance must be nonzero or you will get a
    1363         ZeroDivisionError.
     1502        ``ZeroDivisionError``.
    13641503
    13651504        INPUT:
    1366             k -- a nonnegative integer (default: 1)
     1505
     1506        - ``k`` -- a nonnegative integer (default: 1)
    13671507       
    13681508        OUTPUT:
    1369             Time series
    13701509
    1371         EXAMPLE:
     1510        A time series.
     1511
     1512        EXAMPLE::
     1513
    13721514            sage: v = finance.TimeSeries([13,8,15,4,4,12,11,7,14,12])
    13731515            sage: v.autocorrelation()
    13741516            -0.1875
     
    13881530
    13891531    def variance(self, bias=False):
    13901532        """
    1391         Return the variance of the elements of self, which is the mean
     1533        Return the variance of the elements of ``self``, which is the mean
    13921534        of the squares of the differences from the mean.
    13931535
    13941536        INPUT:
    1395             bias -- bool (default: False); if False, divide by
    1396                     self.length() - 1 instead of self.length()
    1397                     to give a less biased estimator for the variance
     1537
     1538        - ``bias`` -- bool (default: ``False``); if ``False``, divide by
     1539          ``self.length() - 1`` instead of ``self.length()`` to give a less
     1540          biased estimator for the variance.
     1541
    13981542        OUTPUT:
    1399             double
    14001543
    1401         EXAMPLE:
     1544        A double.
     1545
     1546        EXAMPLE::
     1547
    14021548            sage: v = finance.TimeSeries([1,1,1,2,3]); v
    14031549            [1.0000, 1.0000, 1.0000, 2.0000, 3.0000]
    14041550            sage: v.variance()
     
    14061552            sage: v.variance(bias=True)
    14071553            0.64000000000000001
    14081554
    1409         TESTS:
     1555        TESTS::
     1556
    14101557            sage: finance.TimeSeries([1]).variance()
    14111558            0.0
    14121559            sage: finance.TimeSeries([]).variance()
     
    14281575   
    14291576    def standard_deviation(self, bias=False):
    14301577        """
    1431         Return the standard deviation of the entries of self.
     1578        Return the standard deviation of the entries of ``self``.
    14321579
    14331580        INPUT:
    1434             bias -- bool (default: False); if False, divide by
    1435                     self.length() - 1 instead of self.length()
    1436                     to give a less biased estimator for the variance
     1581
     1582        - ``bias`` -- bool (default: ``False``); if ``False``, divide by
     1583          ``self.length() - 1`` instead of ``self.length()`` to give a less
     1584          biased estimator for the variance.
     1585
    14371586        OUTPUT:
    1438             double
    14391587
    1440         EXAMPLES:
     1588        A double.
     1589
     1590        EXAMPLES::
     1591
    14411592            sage: v = finance.TimeSeries([1,1,1,2,3]); v
    14421593            [1.0000, 1.0000, 1.0000, 2.0000, 3.0000]
    14431594            sage: v.standard_deviation()
     
    14451596            sage: v.standard_deviation(bias=True)
    14461597            0.8000000000...
    14471598
    1448         TESTS:
     1599        TESTS::
     1600
    14491601            sage: finance.TimeSeries([1]).standard_deviation()
    14501602            0.0
    14511603            sage: finance.TimeSeries([]).standard_deviation()
     
    14551607
    14561608    def range_statistic(self, b=None):
    14571609        r"""
    1458         Return the rescaled range statistic $R/S$ of self, which is
     1610        Return the rescaled range statistic `R/S` of ``self``, which is
    14591611        defined as follows (see Hurst 1951).  If the optional
    1460         parameter $b$ is given, return the average of $R/S$ range
    1461         statistics of disjoint blocks of size $b$.
     1612        parameter ``b`` is given, return the average of `R/S` range
     1613        statistics of disjoint blocks of size ``b``.
    14621614
    1463         Let $\sigma$ be the standard deviation of the sequence of
    1464         differences of self, and let $Y_k$ be the $k$th term of self.
    1465         Let $n$ be the number of terms of self, and set
    1466         $Z_k = Y_k - ((k+1)/n)*Y_n$. Then
    1467         $$
    1468            R/S = ( max( Z_k ) - min ( Z_k ) ) / \sigma
    1469         $$
    1470         where the max and min are over all $Z_k$.
    1471         Basically replacing $Y_k$ by $Z_k$ allows us to measure
    1472         the difference from the line from the origin to $(n,Y_n)$.
     1615        Let `\sigma` be the standard deviation of the sequence of
     1616        differences of ``self``, and let `Y_k` be the k-th term of ``self``.
     1617        Let `n` be the number of terms of ``self``, and set
     1618        `Z_k = Y_k - ((k+1)/n) \cdot Y_n`. Then
     1619
     1620        .. MATH::
     1621
     1622            R/S = \big( \max(Z_k) - \min(Z_k) \big) / \sigma
     1623
     1624        where the max and min are over all `Z_k`.
     1625        Basically replacing `Y_k` by `Z_k` allows us to measure
     1626        the difference from the line from the origin to `(n,Y_n)`.
    14731627
    14741628        INPUT:
    1475             self -- a time series  (*not* the series of differences)
    1476             b -- integer (default: None); if given instead divide the
    1477                  input time series up into j = floor(n/b) disjoint
    1478                  blocks, compute the R/S statistic for each block,
    1479                  and return the average of those R/S statistics.
     1629
     1630        - ``self`` -- a time series  (*not* the series of differences).
     1631
     1632        - ``b`` -- integer (default: ``None``); if given instead divide the
     1633          input time series up into ``j = floor(n/b)`` disjoint
     1634          blocks, compute the `R/S` statistic for each block,
     1635          and return the average of those `R/S` statistics.
    14801636
    14811637        OUTPUT:
    1482             float
     1638
     1639        A float.
    14831640
    14841641        EXAMPLES:
     1642
    14851643        Notice that if we make a Brownian motion random walk, there
    1486         is no difference if we change the standard deviation.
     1644        is no difference if we change the standard deviation. ::
     1645
    14871646            sage: set_random_seed(0); finance.TimeSeries(10^6).randomize('normal').sums().range_statistic()
    14881647            1897.8392602...
    14891648            sage: set_random_seed(0); finance.TimeSeries(10^6).randomize('normal',0,100).sums().range_statistic()
     
    15131672        We define the Hurst exponent of a constant time series to be 1.
    15141673
    15151674        EXAMPLES:
     1675
    15161676        The Hurst exponent of Brownian motion is 1/2.  We approximate
    15171677        it with some specific samples.  Note that the estimator is
    1518         biased and slightly overestimates.
     1678        biased and slightly overestimates. ::
     1679
    15191680            sage: set_random_seed(0)
    15201681            sage: bm = finance.TimeSeries(10^5).randomize('normal').sums(); bm
    15211682            [0.6767, 0.2756, 0.6332, 0.0469, -0.8897 ... 152.2437, 151.5327, 152.7629, 152.9169, 152.9084]
     
    15241685
    15251686        We compute the Hurst exponent of a simulated fractional Brownian
    15261687        motion with Hurst parameter 0.7.  This function estimates the
    1527         Hurst exponent as 0.706511951...
     1688        Hurst exponent as 0.706511951... ::
     1689
    15281690            sage: set_random_seed(0)
    15291691            sage: fbm = finance.fractional_brownian_motion_simulation(0.7,0.1,10^5,1)[0]
    15301692            sage: fbm.hurst_exponent()
    15311693            0.706511951...
    15321694
    15331695        Another example with small Hurst exponent (notice the overestimation).
     1696
     1697        ::
     1698
    15341699            sage: fbm = finance.fractional_brownian_motion_simulation(0.2,0.1,10^5,1)[0]
    15351700            sage: fbm.hurst_exponent()
    15361701            0.278997441...
    15371702
    15381703        We compute the mean Hurst exponent of 100 simulated multifractal
    1539         cascade random walks:
     1704        cascade random walks::
     1705
    15401706            sage: set_random_seed(0)
    15411707            sage: y = finance.multifractal_cascade_random_walk_simulation(3700,0.02,0.01,0.01,1000,100)
    15421708            sage: finance.TimeSeries([z.hurst_exponent() for z in y]).mean()
    15431709            0.579848225779347...
    15441710
    15451711        We compute the mean Hurst exponent of 100 simulated Markov switching
    1546         multifractal time series.  The Hurst exponent is quite small.
     1712        multifractal time series.  The Hurst exponent is quite small. ::
     1713
    15471714            sage: set_random_seed(0)
    15481715            sage: msm = finance.MarkovSwitchingMultifractal(8,1.4,0.5,0.95,3)
    15491716            sage: y = msm.simulations(1000,100)
     
    15741741    def min(self, bint index=False):
    15751742        """
    15761743        Return the smallest value in this time series. If this series
    1577         has length 0 we raise a ValueError.
     1744        has length 0 we raise a ``ValueError``.
    15781745
    15791746        INPUT:
    1580             index -- bool (default: False); if True, also return index of
    1581                      minimal entry.
     1747
     1748        - ``index`` -- bool (default: ``False``); if ``True``, also return
     1749          index of minimal entry.
     1750
    15821751        OUTPUT:
    1583             float -- smallest value
    1584             integer -- index of smallest value; only returned if index=True
    15851752
    1586         EXAMPLES:
     1753        - float -- smallest value.
     1754
     1755        - integer -- index of smallest value; only returned if ``index=True``.
     1756
     1757        EXAMPLES::
     1758
    15871759            sage: v = finance.TimeSeries([1,-4,3,-2.5,-4])
    15881760            sage: v.min()
    15891761            -4.0
     
    16071779    def max(self, bint index=False):
    16081780        """
    16091781        Return the largest value in this time series. If this series
    1610         has length 0 we raise a ValueError
     1782        has length 0 we raise a ``ValueError``.
    16111783
    16121784        INPUT:
    1613             index -- bool (default: False); if True, also return index of
    1614                      maximum entry.
     1785
     1786        - ``index`` -- bool (default: ``False``); if ``True``, also return
     1787          index of maximum entry.
     1788
    16151789        OUTPUT:
    1616             float -- largest value
    1617             integer -- index of largest value; only returned if index=True
    16181790
    1619         EXAMPLES:
     1791        - float -- largest value.
     1792
     1793        - integer -- index of largest value; only returned if ``index=True``.
     1794
     1795        EXAMPLES::
     1796
    16201797            sage: v = finance.TimeSeries([1,-4,3,-2.5,-4,3])
    16211798            sage: v.max()
    16221799            3.0
     
    16381815
    16391816    def clip_remove(self, min=None, max=None):
    16401817        """
    1641         Return new time series obtained from self by removing all
     1818        Return new time series obtained from ``self`` by removing all
    16421819        values that are less than or equal to a certain minimum value
    16431820        or greater than or equal to a certain maximum.
    16441821
    16451822        INPUT:
    1646             min -- None or double
    1647             max -- None or double
     1823
     1824        - ``min`` -- (default: ``None``) ``None`` or double.
     1825
     1826        - ``max`` -- (default: ``None``) ``None`` or double.
    16481827
    16491828        OUTPUT:
    1650             time series
    16511829
    1652         EXAMPLES:
     1830        A time series.
     1831
     1832        EXAMPLES::
     1833
    16531834            sage: v = finance.TimeSeries([1..10])
    16541835            sage: v.clip_remove(3,7)
    16551836            [3.0000, 4.0000, 5.0000, 6.0000, 7.0000]
     
    17161897        number of bins.
    17171898
    17181899        INPUT:
    1719             bins -- a positive integer (default: 50)
     1900
     1901        - ``bins`` -- a positive integer (default: 50)
     1902
     1903        - ``normalize`` -- (default: ``False``) whether to normalize so the
     1904          total area in the bars of the histogram is 1.
    17201905
    17211906        OUTPUT:
    1722             counts -- list of counts of numbers of elements in
    1723                       each bin
    1724             endpoints -- list of 2-tuples (a,b) that give the
    1725                       endpoints of the bins
     1907
     1908        - counts -- list of counts of numbers of elements in
     1909          each bin.
     1910
     1911        - endpoints -- list of 2-tuples (a,b) that give the
     1912          endpoints of the bins.
    17261913                     
    1727         EXAMPLES:
     1914        EXAMPLES::
     1915
    17281916            sage: v = finance.TimeSeries([5,4,1.3,2,8,10,3,-5]); v
    17291917            [5.0000, 4.0000, 1.3000, 2.0000, 8.0000, 10.0000, 3.0000, -5.0000]
    17301918            sage: v.histogram(3)
     
    17761964        Return histogram plot of this time series with given number of bins.
    17771965               
    17781966        INPUT:
    1779             bins -- positive integer (default: 50)
    1780             normalize -- (default: True) whether to normalize so the total
    1781                          area in the bars of the histogram is 1.
     1967
     1968        - ``bins`` -- positive integer (default: 50)
     1969
     1970        - ``normalize`` -- (default: ``True``) whether to normalize so the
     1971          total area in the bars of the histogram is 1.
     1972
    17821973        OUTPUT:
    1783             a histogram plot
    17841974
    1785         EXAMPLES:
     1975        A histogram plot.
     1976
     1977        EXAMPLES::
     1978
    17861979            sage: v = finance.TimeSeries([1..50])
    17871980            sage: v.plot_histogram(bins=10)
    17881981        """
     
    18082001        red instead.
    18092002
    18102003        INPUT:
    1811             bins -- positive integer (default: 30), the number of bins
    1812                     or candles
     2004
     2005        - ``bins`` -- positive integer (default: 30), the number of bins
     2006          or candles.
    18132007
    18142008        OUTPUT:
    1815             a candlestick plot
     2009
     2010        A candlestick plot.
    18162011
    18172012        EXAMPLES:
    1818         Here we look at the candlestick plot for Brownian motion:
     2013
     2014        Here we look at the candlestick plot for Brownian motion::
     2015
    18192016            sage: v = finance.TimeSeries(1000).randomize()
    18202017            sage: v.plot_candlestick(bins=20)
    18212018        """
     
    18522049
    18532050    def numpy(self, copy=True):
    18542051        """
    1855         Return version of this time series in numpy.
     2052        Return a NumPy version of this time series.
    18562053       
    1857         NOTE: If copy is False, return a numpy 1d array reference to
    1858         exactly the same block of memory as this time series.  This is
    1859         very very fast, and makes it easy to quickly use all
    1860         numpy/scipy functionality on self.  However, it is dangerous
    1861         because when this time series goes out of scope and is garbage
    1862         collected, the corresponding numpy reference object will point
    1863         to garbage.
     2054        .. NOTE::
     2055
     2056            If copy is ``False``, return a NumPy 1-D array reference to
     2057            exactly the same block of memory as this time series.  This is
     2058            very, very fast and makes it easy to quickly use all
     2059            NumPy/SciPy functionality on ``self``.  However, it is dangerous
     2060            because when this time series goes out of scope and is garbage
     2061            collected, the corresponding NumPy reference object will point
     2062            to garbage.
    18642063
    18652064        INPUT:
    1866             copy -- bool (default: True)
     2065
     2066        - ``copy`` -- bool (default: ``True``)
    18672067
    18682068        OUTPUT:
    1869             a numpy 1-d array
    18702069
    1871         EXAMPLES:
     2070        A numpy 1-D array.
     2071
     2072        EXAMPLES::
     2073
    18722074            sage: v = finance.TimeSeries([1,-3,4.5,-2])
    18732075            sage: w = v.numpy(copy=False); w
    18742076            array([ 1. , -3. ,  4.5, -2. ])
     
    18772079            sage: w.shape
    18782080            (4,)
    18792081
    1880         Notice that changing w also changes v too!
     2082        Notice that changing ``w`` also changes ``v`` too! ::
     2083
    18812084            sage: w[0] = 20
    18822085            sage: w
    18832086            array([ 20. ,  -3. ,   4.5,  -2. ])
    18842087            sage: v
    18852088            [20.0000, -3.0000, 4.5000, -2.0000]
    18862089
    1887         If you want a separate copy do not give the copy=False option.
     2090        If you want a separate copy do not give the ``copy=False`` option. ::
     2091
    18882092            sage: z = v.numpy(); z
    18892093            array([ 20. ,  -3. ,   4.5,  -2. ])
    18902094            sage: z[0] = -10
     
    19032107            return n
    19042108
    19052109    def randomize(self, distribution='uniform', loc=0, scale=1, **kwds):
    1906         """
     2110        r"""
    19072111        Randomize the entries in this time series, and return a reference
    1908         to self.  Thus this function both changes self in place, and returns
    1909         a copy of self, for convenience.
     2112        to ``self``.  Thus this function both changes ``self`` in place, and
     2113        returns a copy of ``self``, for convenience.
    19102114       
    19112115        INPUT:
    1912             distribution -- 'uniform':    from loc to loc + scale
    1913                             'normal':     mean loc and standard deviation scale
    1914                             'semicircle': with center at loc (scale is ignored)
    1915                             'lognormal':  mean loc and standard deviation scale
    1916             loc   -- float (default: 0)
    1917             scale -- float (default: 1)
    19182116
    1919         NOTE: All random numbers are generated using algorithms that
    1920         build on the high quality GMP random number function
    1921         gmp_urandomb_ui.  Thus this function fully respects the Sage
    1922         set_random_state command.  It's not quite as fast at the C
    1923         library random number generator, but is of course much better
    1924         quality, and is platform independent.
     2117        - ``distribution`` -- (default: ``"uniform"``); supported values are:
     2118
     2119          - ``'uniform'`` -- from ``loc`` to ``loc + scale``
     2120
     2121          - ``'normal'`` -- mean ``loc`` and standard deviation ``scale``
     2122
     2123          - ``'semicircle'`` -- with center at ``loc`` (``scale`` is ignored)
     2124
     2125          - ``'lognormal'`` -- mean ``loc`` and standard deviation ``scale``
     2126
     2127        - ``loc`` -- float (default: 0)
     2128
     2129        - ``scale`` -- float (default: 1)
     2130
     2131        .. NOTE::
     2132
     2133            All random numbers are generated using algorithms that
     2134            build on the high quality GMP random number function
     2135            gmp_urandomb_ui.  Thus this function fully respects the Sage
     2136            ``set_random_state`` command.  It's not quite as fast as the C
     2137            library random number generator, but is of course much better
     2138            quality, and is platform independent.
    19252139
    19262140        EXAMPLES:
    1927         We generate 5 uniform random numbers in the interval [0,1]:
     2141
     2142        We generate 5 uniform random numbers in the interval [0,1]::
     2143
    19282144            sage: set_random_seed(0)
    19292145            sage: finance.TimeSeries(5).randomize()
    19302146            [0.8685, 0.2816, 0.0229, 0.1456, 0.7314]
    19312147
    1932         We generate 5 uniform random numbers from 5 to 5+2=7:
     2148        We generate 5 uniform random numbers from 5 to `5+2=7`::
     2149
    19332150            sage: set_random_seed(0)
    19342151            sage: finance.TimeSeries(10).randomize('uniform', 5, 2)
    19352152            [6.7369, 5.5632, 5.0459, 5.2911, 6.4628, 5.2412, 5.2010, 5.2761, 5.5813, 5.5439]
    19362153
    1937         We generate 5 normal random values with mean 0 and variance 1.
     2154        We generate 5 normal random values with mean 0 and variance 1. ::
     2155
    19382156            sage: set_random_seed(0)
    19392157            sage: finance.TimeSeries(5).randomize('normal')
    19402158            [0.6767, -0.4011, 0.3576, -0.5864, -0.9365]
    19412159
    1942         We generate 10 normal random values with mean 5 and variance 2.
     2160        We generate 10 normal random values with mean 5 and variance 2. ::
     2161
    19432162            sage: set_random_seed(0)
    19442163            sage: finance.TimeSeries(10).randomize('normal', 5, 2)
    19452164            [6.3534, 4.1978, 5.7153, 3.8273, 3.1269, 2.9598, 3.7484, 6.7472, 3.8986, 4.6271]
    19462165
    1947         We generate 5 values using the semicircle distribution.
     2166        We generate 5 values using the semicircle distribution. ::
     2167
    19482168            sage: set_random_seed(0)
    19492169            sage: finance.TimeSeries(5).randomize('semicircle')
    19502170            [0.7369, -0.9541, 0.4628, -0.7990, -0.4187]
    19512171
    1952         We generate 1 million normal random values and create a frequency histogram.
     2172        We generate 1 million normal random values and create a frequency
     2173        histogram. ::
     2174
    19532175            sage: set_random_seed(0)
    19542176            sage: a = finance.TimeSeries(10^6).randomize('normal')
    19552177            sage: a.histogram(10)[0]
    19562178            [36, 1148, 19604, 130699, 340054, 347870, 137953, 21290, 1311, 35]
    19572179
    19582180        We take the above values, and compute the proportion that lie within
    1959         1, 2, 3, 5, and 6 standard deviations of the mean (0):
     2181        1, 2, 3, 5, and 6 standard deviations of the mean (0)::
     2182
    19602183            sage: s = a.standard_deviation()
    19612184            sage: len(a.clip_remove(-s,s))/float(len(a))
    19622185            0.68309399999999998
     
    19672190            sage: len(a.clip_remove(-5*s,5*s))/float(len(a))
    19682191            0.99999800000000005
    19692192
    1970         There were no "six sigma events":
     2193        There were no "six sigma events"::
     2194
    19712195            sage: len(a.clip_remove(-6*s,6*s))/float(len(a))
    19722196            1.0
    19732197        """
     
    19852209
    19862210    def _randomize_uniform(self, double left, double right):
    19872211        """
    1988         Generates a uniform random distribution of doubles between left and
    1989         right and stores values in place.
     2212        Generates a uniform random distribution of doubles between ``left`` and
     2213        ``right`` and stores values in place.
    19902214
    19912215        INPUT:
    1992             left -- left bound on random distribution
    1993             right -- right bound on random distribution
     2216
     2217        - ``left`` -- left bound on random distribution.
     2218
     2219        - ``right`` -- right bound on random distribution.
    19942220
    19952221        EXAMPLES:
     2222
    19962223        We generate 5 values distributed with respect to the uniform
    1997         distribution over the interval [0,1].
     2224        distribution over the interval [0,1]::
     2225
    19982226            sage: v = finance.TimeSeries(5)
    19992227            sage: set_random_seed(0)
    20002228            sage: v.randomize('uniform')
    20012229            [0.8685, 0.2816, 0.0229, 0.1456, 0.7314]
    20022230
    2003         We now test that the mean is indeed 0.5.
     2231        We now test that the mean is indeed 0.5::
     2232
    20042233            sage: v = finance.TimeSeries(10^6)
    20052234            sage: set_random_seed(0)
    20062235            sage: v.randomize('uniform').mean()
     
    20172246
    20182247    def _randomize_normal(self, double m, double s):
    20192248        """
    2020         Generates a normal random distribution of doubles with mean m and
    2021         standard deviation s and stores values in place. Uses the
     2249        Generates a normal random distribution of doubles with mean ``m`` and
     2250        standard deviation ``s`` and stores values in place. Uses the
    20222251        Box-Muller algorithm.
    20232252       
    20242253        INPUT:
    2025             m -- mean
    2026             s -- standard deviation
     2254
     2255        - ``m`` -- mean
     2256
     2257        - ``s`` -- standard deviation
    20272258
    20282259        EXAMPLES:
     2260
    20292261        We generate 5 values distributed with respect to the normal
    2030         distribution with mean 0 and standard deviation 1.
     2262        distribution with mean 0 and standard deviation 1::
     2263
    20312264            sage: set_random_seed(0)
    20322265            sage: v = finance.TimeSeries(5)
    20332266            sage: v.randomize('normal')
    20342267            [0.6767, -0.4011, 0.3576, -0.5864, -0.9365]
    20352268
    2036         We now test that the mean is indeed 0.
     2269        We now test that the mean is indeed 0::
     2270
    20372271            sage: set_random_seed(0)
    20382272            sage: v = finance.TimeSeries(10^6)
    20392273            sage: v.randomize('normal').mean()
    20402274            6.2705472723...
    20412275
    20422276        The same test with mean equal to 2 and standard deviation equal
    2043         to 5.
     2277        to 5::
     2278
    20442279            sage: set_random_seed(0)
    20452280            sage: v = finance.TimeSeries(10^6)
    20462281            sage: v.randomize('normal', 2, 5).mean()
     
    20722307        and stores values in place. Uses the acceptance-rejection method.
    20732308
    20742309        INPUT:
    2075             center -- the center of the semicircle distribution
     2310
     2311        - ``center`` -- the center of the semicircle distribution.
    20762312
    20772313        EXAMPLES:
     2314
    20782315        We generate 5 values distributed with respect to the semicircle
    2079         distribution located at center.
     2316        distribution located at center::
     2317
    20802318            sage: v = finance.TimeSeries(5)
    20812319            sage: set_random_seed(0)
    20822320            sage: v.randomize('semicircle')
    20832321            [0.7369, -0.9541, 0.4628, -0.7990, -0.4187]
    20842322
    2085         We now test that the mean is indeed the center.
     2323        We now test that the mean is indeed the center::
     2324
    20862325            sage: v = finance.TimeSeries(10^6)
    20872326            sage: set_random_seed(0)
    20882327            sage: v.randomize('semicircle').mean()
    20892328            0.0007207497...
    20902329
    2091         The same test with center equal to 2.
     2330        The same test with center equal to 2::
     2331
    20922332            sage: v = finance.TimeSeries(10^6)
    20932333            sage: set_random_seed(0)
    20942334            sage: v.randomize('semicircle', 2).mean()
     
    21082348            self._values[k] = x + center
    21092349
    21102350    def _randomize_lognormal(self, double m, double s):
    2111         """
    2112         Generates a log-normal random distribution of doubles with mean m
    2113         and standard deviation s. Uses Box-Muller algorithm and the identity:
    2114         if Y is a random variable with normal distribution then X = exp(Y)
    2115         is a random variable with log-normal distribution.
     2351        r"""
     2352        Generates a log-normal random distribution of doubles with mean ``m``
     2353        and standard deviation ``s``. Uses Box-Muller algorithm and the
     2354        identity: if `Y` is a random variable with normal distribution then
     2355        `X = \exp(Y)` is a random variable with log-normal distribution.
    21162356
    21172357        INPUT:
    2118             m -- mean
    2119             s -- standard deviation
     2358
     2359        - ``m`` -- mean
     2360
     2361        - ``s`` -- standard deviation
    21202362
    21212363        EXAMPLES:
     2364
    21222365        We generate 5 values distributed with respect to the lognormal
    2123         distribution with mean 0 and standard deviation 1.
     2366        distribution with mean 0 and standard deviation 1::
     2367
    21242368            sage: set_random_seed(0)
    21252369            sage: v = finance.TimeSeries(5)
    21262370            sage: v.randomize('lognormal')
    21272371            [1.9674, 0.6696, 1.4299, 0.5563, 0.3920]
    21282372
    2129         We now test that the mean is indeed sqrt(e).
     2373        We now test that the mean is indeed `\sqrt{e}`::
     2374
    21302375            sage: set_random_seed(0)
    21312376            sage: v = finance.TimeSeries(10^6)
    21322377            sage: v.randomize('lognormal').mean()
     
    21372382        A log-normal distribution can be simply thought of as the logarithm
    21382383        of a normally distributed data set. We test that here by generating
    21392384        5 values distributed with respect to the normal distribution with mean
    2140         0 and standard deviation 1.
     2385        0 and standard deviation 1::
     2386
    21412387            sage: set_random_seed(0)
    21422388            sage: w = finance.TimeSeries(5)
    21432389            sage: w.randomize('normal')
     
    21652411                self._values[k] = exp(m + y2*s)
    21662412       
    21672413    def fft(self, bint overwrite=False):
    2168         """
    2169         Return the real discrete fast Fourier transform of self, as a
     2414        r"""
     2415        Return the real discrete fast Fourier transform of ``self``, as a
    21702416        real time series:
    21712417
    2172           [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2))]              if n is even
     2418        .. MATH::
     2419
     2420            [y(0),\Re(y(1)),\Im(y(1)),\dots,\Re(y(n/2))]  \text{ if $n$ is even}
    21732421         
    2174           [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2)),Im(y(n/2))]   if n is odd
     2422            [y(0),\Re(y(1)),\Im(y(1)),\dots,\Re(y(n/2)),\Im(y(n/2))] \text{ if $n$ is odd}
    21752423         
    21762424        where
    2177        
    2178           y(j) = sum[k=0..n-1] x[k] * exp(-sqrt(-1)*j*k* 2*pi/n)
    21792425
    2180         for j = 0..n-1.  Note that y(-j) = y(n-j).
     2426        .. MATH::
     2427
     2428            y(j) = \sum_{k=0}^{n-1} x[k] \cdot \exp(-\sqrt{-1} \cdot jk \cdot 2\pi/n)
     2429
     2430        for `j = 0,\dots,n-1`.  Note that `y(-j) = y(n-j)`.
    21812431   
    2182         EXAMPLES:
     2432        EXAMPLES::
     2433
    21832434            sage: v = finance.TimeSeries([1..9]); v
    21842435            [1.0000, 2.0000, 3.0000, 4.0000, 5.0000, 6.0000, 7.0000, 8.0000, 9.0000]
    21852436            sage: w = v.fft(); w
    21862437            [45.0000, -4.5000, 12.3636, -4.5000, 5.3629, -4.5000, 2.5981, -4.5000, 0.7935]
    21872438
    2188         We get just the series of real parts of
     2439        We get just the series of real parts of ::
     2440
    21892441            sage: finance.TimeSeries([w[0]]) + w[1:].scale_time(2)
    21902442            [45.0000, -4.5000, -4.5000, -4.5000, -4.5000]
    21912443
    2192         An example with an even number of terms.
     2444        An example with an even number of terms::
     2445
    21932446            sage: v = finance.TimeSeries([1..10]); v
    21942447            [1.0000, 2.0000, 3.0000, 4.0000, 5.0000, 6.0000, 7.0000, 8.0000, 9.0000, 10.0000]
    21952448            sage: w = v.fft(); w
     
    22072460        return y
    22082461
    22092462    def ifft(self, bint overwrite=False):
    2210         """
     2463        r"""
    22112464        Return the real discrete inverse fast Fourier transform of
    2212         self, which is also a real time series.
     2465        ``self``, which is also a real time series.
    22132466
    2214         This is the inverse of fft().
     2467        This is the inverse of ``fft()``.
    22152468
    22162469        The returned real array contains
    2217        
    2218                          [y(0),y(1),...,y(n-1)]
     2470
     2471        .. MATH::
     2472
     2473            [y(0),y(1),\dots,y(n-1)]
    22192474                         
    2220         where for n is even
    2221        
    2222           y(j) = 1/n (sum[k=1..n/2-1] (x[2*k-1]+sqrt(-1)*x[2*k])
    2223                                        * exp(sqrt(-1)*j*k* 2*pi/n)
    2224                       + c.c. + x[0] + (-1)**(j) x[n-1])
     2475        where for `n` is even
     2476
     2477        .. MATH::
     2478
     2479            y(j)
     2480            =
     2481            1/n \left(
     2482            \sum_{k=1}^{n/2-1}
     2483            (x[2k-1]+\sqrt{-1} \cdot x[2k])
     2484            \cdot \exp(\sqrt{-1} \cdot jk \cdot 2pi/n)
     2485            + c.c. + x[0] + (-1)^j x[n-1]
     2486            \right)
    22252487                     
    2226         and for n is odd
    2227        
    2228           y(j) = 1/n (sum[k=1..(n-1)/2] (x[2*k-1]+sqrt(-1)*x[2*k])
    2229                                        * exp(sqrt(-1)*j*k* 2*pi/n)
    2230                       + c.c. + x[0])
     2488        and for `n` is odd
     2489
     2490        .. MATH::
     2491
     2492            y(j)
     2493            =
     2494            1/n \left(
     2495            \sum_{k=1}^{(n-1)/2}
     2496            (x[2k-1]+\sqrt{-1} \cdot x[2k])
     2497            \cdot \exp(\sqrt{-1} \cdot jk \cdot 2pi/n)
     2498            + c.c. + x[0]
     2499            \right)
    22312500                     
    2232         c.c. denotes complex conjugate of preceding expression.
     2501        where `c.c.` denotes complex conjugate of preceding expression.
    22332502
    2234         EXAMPLES:
     2503        EXAMPLES::
     2504
    22352505            sage: v = finance.TimeSeries([1..10]); v
    22362506            [1.0000, 2.0000, 3.0000, 4.0000, 5.0000, 6.0000, 7.0000, 8.0000, 9.0000, 10.0000]
    22372507            sage: v.ifft()
     
    22552525    The entries of the time series are garbage.
    22562526
    22572527    INPUT:
    2258         length -- integer
     2528
     2529    - ``length`` -- integer
     2530
    22592531    OUTPUT:
    2260         TimeSeries
     2532
     2533    A time series.
    22612534
    22622535    EXAMPLES:
    2263     This uses new_time_series implicitly:
     2536
     2537    This uses ``new_time_series`` implicitly::
     2538
    22642539        sage: v = finance.TimeSeries([1,-3,4.5,-2])
    22652540        sage: v.__copy__()
    22662541        [1.0000, -3.0000, 4.5000, -2.0000]
     
    22772552    Version 1 unpickle method.
    22782553
    22792554    INPUT:
    2280         v -- a raw char buffer
    22812555
    2282     EXAMPLES:
     2556    - ``v`` -- a raw char buffer
     2557
     2558    EXAMPLES::
     2559
    22832560        sage: v = finance.TimeSeries([1,2,3])
    22842561        sage: s = v.__reduce__()[1][0]
    22852562        sage: type(s)
     
    22992576
    23002577
    23012578def autoregressive_fit(acvs):
    2302     """
    2303     Given a sequence of lagged autocovariances of length $M$ produce
    2304     $a_1,...,a_p$ so that the first $M$ autocovariance coefficients
    2305     of the autoregressive processes $X_t=a_1X_{t_1}+...a_pX_{t-p}+Z_t$
     2579    r"""
     2580    Given a sequence of lagged autocovariances of length `M` produce
     2581    `a_1,\dots,a_p` so that the first `M` autocovariance coefficients
     2582    of the autoregressive processes `X_t=a_1X_{t_1}+\cdots+a_pX_{t-p}+Z_t`
    23062583    are the same as the input sequence.
    23072584   
    23082585    The function works by solving the Yule-Walker equations
    2309     $\Gamma a =\gamma$, where $\gamma=(\gamma(1),...,\gamma(M))$,
    2310     $a=(a_1,..,a_M)$, with $\gamma(i)$ the autocovariance of lag i
    2311     and $\Gamma_{ij}=\gamma(i-j)$.
    2312    
     2586    `\Gamma a =\gamma`, where `\gamma=(\gamma(1),\dots,\gamma(M))`,
     2587    `a=(a_1,\dots,a_M)`, with `\gamma(i)` the autocovariance of lag `i`
     2588    and `\Gamma_{ij}=\gamma(i-j)`.
    23132589   
    23142590    EXAMPLES:
    23152591
     
    23252601    scaling time by k.
    23262602
    23272603    We create 100 simulations of a multifractal random walk.  This
    2328     models the logarithms of a stock price sequence.
     2604    models the logarithms of a stock price sequence. ::
     2605
    23292606        sage: set_random_seed(0)
    23302607        sage: y = finance.multifractal_cascade_random_walk_simulation(3700,0.02,0.01,0.01,1000,100)
    23312608
     
    23332610    step size is replaced by its absolute value -- this is what we
    23342611    expect to be able to predict given the model, which is only a
    23352612    model for predicting volatility.  We compute the first 200
    2336     autocovariance values for every random walk:
     2613    autocovariance values for every random walk::
     2614
    23372615        sage: c = [[a.diffs().abs().sums().autocovariance(i) for a in y] for i in range(200)]
    23382616
    23392617    We make a time series out of the expected values of the
    2340     autocovariances:
     2618    autocovariances::
     2619
    23412620        sage: ac = finance.TimeSeries([finance.TimeSeries(z).mean() for z in c])
    23422621        sage: ac
    23432622        [3.9962, 3.9842, 3.9722, 3.9601, 3.9481 ... 1.7144, 1.7033, 1.6922, 1.6812, 1.6701]
    23442623
    2345     Note: ac looks like a line -- one could best fit it to yield a lot
    2346     more approximate autocovariances.
     2624    .. NOTE::
    23472625
    2348     We compute the autoregression coefficients matching the above autocovariances:
     2626        ``ac`` looks like a line -- one could best fit it to yield a lot
     2627        more approximate autocovariances.
     2628
     2629    We compute the autoregression coefficients matching the above
     2630    autocovariances::
     2631
    23492632        sage: F = finance.autoregressive_fit(ac); F
    23502633        [0.9982, -0.0002, -0.0002, 0.0003, 0.0001 ... 0.0002, -0.0002, -0.0000, -0.0002, -0.0014]
    23512634
    2352     Note that the sum is close to 1.
     2635    Note that the sum is close to 1::
     2636
    23532637        sage: sum(F)
    23542638        0.99593284089454...
    23552639
    2356     Now we make up an 'out of sample' sequence:
     2640    Now we make up an 'out of sample' sequence::
     2641
    23572642        sage: y2 = finance.multifractal_cascade_random_walk_simulation(3700,0.02,0.01,0.01,1000,1)[0].diffs().abs().sums()
    23582643        sage: y2
    23592644        [0.0013, 0.0059, 0.0066, 0.0068, 0.0184 ... 6.8004, 6.8009, 6.8063, 6.8090, 6.8339]
    23602645
    2361     And we forecast the very last value using our linear filter; the forecast is close:
     2646    And we forecast the very last value using our linear filter; the forecast
     2647    is close::
     2648
    23622649        sage: y2[:-1].autoregressive_forecast(F)
    23632650        6.7836741372407...
    23642651
    23652652    In fact it is closer than we would get by forecasting using a
    2366     linear filter made from all the autocovariances of our sequence:
     2653    linear filter made from all the autocovariances of our sequence::
     2654
    23672655        sage: y2[:-1].autoregressive_forecast(y2[:-1].autoregressive_fit(len(y2)))
    23682656        6.770168705668...
    23692657
    23702658    We record the last 20 forecasts, always using all correct values up to the
    2371     one we are forecasting:
     2659    one we are forecasting::
     2660
    23722661        sage: s1 = sum([(y2[:-i].autoregressive_forecast(F)-y2[-i])^2 for i in range(1,20)])
    23732662
    2374     We do the same, but using the autocovariances of the sample sequence:
     2663    We do the same, but using the autocovariances of the sample sequence::
     2664
    23752665        sage: F2 = y2[:-100].autoregressive_fit(len(F))
    23762666        sage: s2 = sum([(y2[:-i].autoregressive_forecast(F2)-y2[-i])^2 for i in range(1,20)])
    23772667
    2378     Our model gives us something that is 15 percent better in this case:
     2668    Our model gives us something that is 15 percent better in this case::
     2669
    23792670        sage: s2/s1
    23802671        1.15464636102...
    23812672
    23822673    How does it compare overall?  To find out we do 100 simulations
    23832674    and for each we compute the percent that our model beats naively
    2384     using the autocovariances of the sample:
     2675    using the autocovariances of the sample::
     2676
    23852677        sage: y_out = finance.multifractal_cascade_random_walk_simulation(3700,0.02,0.01,0.01,1000,100)
    23862678        sage: s1 = []; s2 = []
    23872679        sage: for v in y_out:
     
    23902682        ...       s2.append(sum([(v[:-i].autoregressive_forecast(F2)-v[-i])^2 for i in range(1,20)]))
    23912683        ...
    23922684
    2393     We find that overall the model beats naive linear forecasting by 35 percent!
     2685    We find that overall the model beats naive linear forecasting by 35
     2686    percent! ::
     2687
    23942688        sage: s = finance.TimeSeries([s2[i]/s1[i] for i in range(len(s1))])
    23952689        sage: s.mean()
    23962690        1.354073591877...