# Sage Reference Manual: Quantitative Finance

Release 5.12

The Sage Development Team

October 10, 2013

CONTENTS

1 2 3 4 5 6

Time Series Stock Market Price Series Tools for working with ﬁnancial options Multifractal Random Walk Markov Switching Multifractal model Indices and Tables

1 23 29 31 35 39 41

Bibliography

i

ii

CHAPTER

ONE

TIME SERIES
Time Series This is a module for working with discrete ﬂoating point time series. It is designed so that every operation is very fast, typically much faster than with other generic code, e.g., Python lists of doubles or even NumPy arrays. The semantics of time series is more similar to Python lists of doubles than Sage real double vectors or NumPy 1-D arrays. In particular, time series are not endowed with much algebraic structure and are always mutable. Note: NumPy arrays are faster at slicing, since slices return references, and NumPy arrays have strides. However, this speed at slicing makes NumPy slower at certain other operations. EXAMPLES:
sage: set_random_seed(1) sage: t = finance.TimeSeries([random()-0.5 for _ in xrange(10)]); t [0.3294, 0.0959, -0.0706, -0.4646, 0.4311, 0.2275, -0.3840, -0.3528, -0.4119, -0.2933] sage: t.sums() [0.3294, 0.4253, 0.3547, -0.1099, 0.3212, 0.5487, 0.1647, -0.1882, -0.6001, -0.8933] sage: t.exponential_moving_average(0.7) [0.0000, 0.3294, 0.1660, 0.0003, -0.3251, 0.2042, 0.2205, -0.2027, -0.3078, -0.3807] sage: t.standard_deviation() 0.33729638212891383 sage: t.mean() -0.08933425506929439 sage: t.variance() 0.1137688493972542...

AUTHOR: • William Stein class sage.finance.time_series.TimeSeries Bases: object Initialize new time series. INPUT: •values – integer (number of values) or an iterable of ﬂoats. •initialize – bool (default: True); if False, do not bother to zero out the entries of the new time series. For large series that you are going to just ﬁll in, this can be way faster. EXAMPLES: This implicitly calls init:

1

3.0000.0000] Conversion from an n-dimensional NumPy array also works: sage: import numpy sage: v = numpy. Release 5.TimeSeries(w) [1. extending either self or t by 0’s if they do not have the same length. 2. 4.array([[1.0000] sage: finance.3.. 4.2].0000.0000. 3.1908.0000.0]) [1. dtype=float).[3. 4. [ 3.0000. INPUT: •t – a time series. 3.TimeSeries([pi. EXAMPLES: 2 Chapter 1.-4.TimeSeries([1.0000.1908. OUTPUT: A new time series. initialize=False) abs() Return new time series got by replacing all entries of self by their absolute value. EXAMPLES: sage: v = finance. -4.93932]) sage: v [1.0000.numpy() sage: finance. [3.0000.0000.0000.9393] sage: v. v array([[ 1.]. 2..TimeSeries(v[:.]]) sage: finance.TimeSeries(10.TimeSeries(v) [1.2000] Conversion from a NumPy 1-D array. 2.array([[1. 18.4]]) sage: finance.Sage Reference Manual: Quantitative Finance.0000.0000.0000. 3. use the add_scalar method.1416.9393] add_entries(t) Add corresponding entries of self and t together. 3.TimeSeries(u) [1.0000] sage: u = numpy.2]) [3. Note: To add a single number to the entries of a time series.1908439.TimeSeries([1.. 5.abs() [1.12 sage: finance.5. Time Series . 3.2]. 5.4]].0000.0000. 18. 3. OUTPUT: A time series with length the maxima of the lengths of self and t.0000] For speed purposes we don’t initialize (so value is garbage): sage: t = finance. 2.0000. 4.5]) sage: w = v. 4. 3. which is very fast: sage: v = finance. 5.

v [5.8. -5.3000. 8.1875 sage: v. -5.add_entries([3.4]) [4. -10. 6.8000.2. 3. -4.0 sage: v.4.7.5000. 4.autocorrelation(0) 1.2.20138888888888887 sage: v.0000.5) [5. 2. INPUT: •k – a nonnegative integer (default: 1) OUTPUT: A time series.1875 sage: v. OUTPUT: A new time series with s added to all values.7.0000] sage: v.0000.0000.TimeSeries([5. Then the sample autocorrelation function is n−k −1 (xt − µ)(xt+k t=0 n−1 2 t=0 (xt − µ) − µ) .12. 8.autocorrelation() -0.4. 2.0000. 4. 4.0000.-5]).Sage Reference Manual: Quantitative Finance.0000.0000.0000] sage: v.3.12 sage: v = finance.18055555555555555 3 .4.0000] sage: v. 1.0000. 3. 2. 2.0000.14.-5]).5000.autocorrelation(2) -0.8.12]) sage: v. 1. -5.0000.5000.5]) [4. Note that the variance must be nonzero or you will get a ZeroDivisionError.10. EXAMPLES: sage: v = finance.5000. Note: To add componentwise. v [1. INPUT: •s – a ﬂoat.4. Release 5.add_scalar(0.0000] sage: v. use the add_entries method. 18.18.5000.autocorrelation(1) -0. 10.TimeSeries([13.0000.5000] add_scalar(s) Return new time series obtained by adding a scalar to every value in the series.11.TimeSeries([1.5000] autocorrelation(k=1) Return the k-th sample autocorrelation of this time series xi . Let µ be the sample mean.0000. 6. EXAMPLE: sage: v = finance.add_entries([3.15.autocorrelation(3) 0.0000.5000.0000.1.3.add_entries(v) [2. 10.0000.

1. sage: v. That is. we assume the process is given by Xt − µ = a1 (Xt−1 − µ) + a2 (Xt−1 − µ) + · · · + aM (Xt−M − µ) + Zt where µ is the mean of the process and Zt is noise.TimeSeries([1. sage: set_random_seed(0) sage: v = finance.autocovariance(2) 0. -4. aM . 4 Chapter 1. . This is the covariance of self with self shifted by k .autocovariance(1) We illustrate with a random sample that an independently and identically distributed distribution with zero mean and variance σ 2 has autocovariance function γ (h) with γ (0) = σ 2 and γ (h) = 0 for h = 0. -6.TimeSeries(10^6) sage: v.1000])..7. ... γ (M )). 0.TimeSeries([13.00508390.11. Time Series .randomize(’normal’.autocorrelation() 0.e. 9. n−k−1 (xt − µ)(xt+k − µ) t=0 n. .. .7882. a = (a1 . .autocovariance(1) -0. sage: v. sum([(a-mu)^2 for a in v])/len(v) v.7 v = finance.01902000...autocovariance(3) -0. INPUT: •k – a nonnegative integer (default: 0) OUTPUT: A ﬂoat..Sage Reference Manual: Quantitative Finance.022056325..9319.12]) v. .15.mean(). autoregressive_fit(M ) This method ﬁts the time series to an autoregressive process of order M.. -2.2282.. . . i. where γ = (γ (1).4.4 sage: -2. This method returns estimates for a1 .95410689.12 sage: finance. Note the denominator of n. -2.1868.8. .4. The method works by solving the Yule-Walker equations Γa = γ .3835. where n is the length of self. .0055.12.997 autocovariance(k=0) Return the k-th autocovariance function γ (k ) of self.. . EXAMPLES: sage: sage: 14. 5) [3.7652] sage: v.7 sage: -2. which gives a “better” sample estimator. -8. Release 5. .9274.4 sage: 14.. sage: v. aM ) with γ (i) the autocovariance of lag i and Γij = γ (i − j ).autocovariance(1) mu = v. 0.mean().autocovariance(0) 24.7 sage: -2.14. sum([(v[i]-mu)*(v[i+1]-mu) for i in range(len(v)-1)])/len(v) v.6827 .2613. -5.autocovariance(0) mu = v.

-0. Release 5. 0.0019. -1.6709. sage: c=t[0:-1]..2447. sage: F [1.4836. 0. 1. 1.0057.5705.2809. 12.6639. 1.0177285042. 87.5*t[i-2]+z[i] . -0.6759.0232 . F [1. -0.0092] sage: set_random_seed(0) sage: t=finance..3576. 87. 87.0635 .autoregressive_fit(5). 0. compute the forecast for the next term in the series.6767.Sage Reference Manual: Quantitative Finance.TimeSeries(2000) sage: z.5989.-0. 87. -0.randomize(’normal’).. 1. 86.2756.. which is just the mean of the k-th powers of the differences self[i] . INPUT: •M – an integer. -0.sums() sage: F = v[:-1]. INPUT: •filter – a time series outputted by the autoregressive_fit command. -0.. 0.2756. 0. 9. 0.6332..0106.0105.sums() sage: F = v.0469. 0.autoregressive_forecast(F) 11.6825.mu.0539] sage: v.4136. 9. 0.1) [1.1095] sage: t[0]=1 sage: t[1]=2 sage: for i in range(2.randomize(’normal’. 10.0067.0643.6767...2000): . EXAMPLES: sage: set_random_seed(0) sage: v = finance. EXAMPLES: sage: set_random_seed(0) sage: v = finance.TimeSeries(2000) sage: z=finance.8897 .TimeSeries(100).0068. -0. 0.. which means that the autocovariance yj yk depends only on the difference |j − k |.. t[i]=t[i-1]-0... OUTPUT: A time series – the coefﬁcients of the autoregressive process. -0.0371. sage: v [0.0148. -0.0085. where mu is the mean of self.1960] central_moment(k) Return the k-th central moment of self. 0..12 Warning: The input sequence is assumed to be stationary. 0..autoregressive_fit(2) #recovers recurrence relation sage: c #should be close to [1..8897 .6332. 0. 1.5] [1.0131.4037.3194] sage: v. 10. -0. 0. -0.1323.5199] autoregressive_forecast(ﬁlter) Given the autoregression coefﬁcients as outputted by the autoregressive_fit command.4120.6767..0524.TimeSeries(10^4).autoregressive_fit(100) sage: v [0. -0.0469. INPUT: 5 .1467.randomize(’normal’).0029.7820298611.autoregressive_forecast(F) 86.

12 •k – a positive integer.0000. 7.0000.TimeSeries([4.0000] correlation(other) Return the correlation of self and other. 8. which is the covariance of self and other divided by the product of their standard deviation. 7. 9.. Whichever time series has more terms is truncated. 5..moment(2) 4. 6.covariance(w)/(v.0 sage: ((1-mu)^2 + (2-mu)^2 + (3-mu)^2) / 3 0. Release 5.0000] sage: v.0000.Sage Reference Manual: Quantitative Finance.7) [3.5. max=None) Return new time series obtained from self by removing all values that are less than or equal to a certain minimum value or greater than or equal to a certain maximum.0000.0000. •max – (default: None) None or double.0000.2. Time Series .0000.6666666666666666 clip_remove(min=None.0000. EXAMPLES: sage: v = finance. w = finance.standard_deviation() * w. 10. 3...TimeSeries([1. other – time series.6666666666666666 Note that the central moment is different from the moment here.correlation(w) -0.0000. since the mean is not 0: sage: v.mean().3]) sage: v.0000.-10]) sage: v. OUTPUT: A double.0000.clip_remove(3) [3.0000.10]) sage: v.3]).TimeSeries([1.standard_deviation()) -0.0000. 4.0000] sage: v. 4. OUTPUT: A time series.666666666666667 # doesn’t subtract off mean We compute the central moment directly: sage: mu = v.. 4.558041609.clip_remove(3. 5. 7. 6. 6.0000. EXAMPLES: sage: v = finance. EXAMPLES: sage: v = finance.558041609. mu 2.clip_remove(max=7) [1. sage: v.0000.0000.central_moment(2) 0. 2.TimeSeries([1.0000.-2. 5. INPUT: •self. 6 Chapter 1. INPUT: •min – (default: None) None or double.

Release 5. w = finance. .0000] exponential_moving_average(alpha) Return the exponential moving average time series. .7183. EXAMPLES: sage: v = finance.-10]) sage: v.5. 2. other – time series.1.0000. 5. . X1 . The 0-th term is formally undeﬁned..0000.0000. . 0.3. 3. return Xk − X0 .0000. -2. The output series has one less term than the input series. 54. .covariance(w) -11.TimeSeries([5. v [5.2. then this function outputs the series X1 − X0 .777777777777779 diffs(k=1) Return the new time series got by taking the differences of successive terms in the time series. The t-th step of the output is the sum of the previous k-1 steps of self and the k-th step divided by k. 1.diffs() [-1.4. 8. OUTPUT: A new time series.-2.TimeSeries([1.log() [1.0000. .0000. . EXAMPLES: sage: v = finance.5982.TimeSeries([4. a smoothing factor with 0 <= alpha <= 1. 148.0000. .0000] sage: v.exp().0000.0000. 4. .7000.exp() [2.5]). Whichever time series has more terms is truncated. 7 . 7.0000. X2 − X1 . . . X2 .12 covariance(other) Return the covariance of the time series self and other. 6. EXAMPLES: sage: v = finance. and we deﬁne the ﬁrst term to be self[0]. Assumes the input time series was constant with its starting value for negative time. 2. 4. 20. v [1.4132] sage: v. So if self is the time series X0 .8]).0855.TimeSeries([1.7000. INPUT: •self.Sage Reference Manual: Quantitative Finance. INPUT: •k – positive integer (default: 1) OUTPUT: A new time series. X2k − Xk . . 5.3]).3891. If the optional parameter k is given. so we deﬁne it to be 0.0000. 2. INPUT: •alpha – ﬂoat.0000.3000.0000] exp() Return new time series got by applying the exponential map to all the terms in the time series.0000] sage: v. 4. 3.

0000] sage: w = v.7935] We get just the series of real parts of 8 Chapter 1.5000.-5]). 1.0000.0000.TimeSeries([1. as a real time series: [y (0).0000. 2. 12. 1. -5.3.0000. (y (n/2))] if n is odd where n−1 y (j ) = k=0 √ x[k ] · exp(− −1 · jk · 2π/n) for j = 0.fft().3629. 7. . 2. 1. EXAMPLES: sage: v = finance. (y (1)).0000.0000.0000.0000.0000.5000] Some more examples: sage: v = finance. 1. EXAMPLES: sage: v = finance.0000] extend(right) Extend this time series by appending elements from the iterable right.0000.5. 3. -5.exponential_moving_average(1) [0. Note that y (−j ) = y (n − j ). 9. 1. 4. 6. v [1.0000.TimeSeries([1. 1. .0000.0000] sage: v.0000. (y (1)).exponential_moving_average(1) [0. EXAMPLES: sage: v = finance.0000.0000. -3. .0000.4.0000] sage: v. .0000.3]).Sage Reference Manual: Quantitative Finance. w [45. -4.9]).0000. 3.exponential_moving_average(0.12 OUTPUT: A time series with the same number of steps as self.5000.3636. .0000.1.0000. 4.0000.0000] fft(overwrite=False) Return the real discrete fast Fourier transform of self.0000. (y (1)). v [1.0000.exponential_moving_average(0) [0. 1. .0000. .2. (y (n/2)). -4. . . 5. INPUT: •right – iterable that can be converted to a time series.0000.0000. 1.extend([-3. (y (1)).0000] sage: v. . 2.2.5000. -4.5]) sage: v. 1. .5) [0.0000. 1. 1. 2.0000.exponential_moving_average(0) [0.0000.0000.0000.TimeSeries([1.TimeSeries([1. 2. (y (n/2))] if n is even [y (0). 2..0000.0000] sage: v.0000.0000.5000. Time Series . 1.5981. 2]) sage: v [1.0000.2. v [1. 1.0000. 5. 1.0000.0000] sage: v. 8.5000.1. 0. n − 1. -4.0000. Release 5. 3. 2. 2. 1. 1. . 1. 1.

0000.0000] sage: w = v.0.fft(). This function estimates the Hurst exponent as 0.7..0469. -5. -4. We use the algorithm from pages 61 – 63 of [Peteres.Sage Reference Manual: Quantitative Finance. 4.0000] sage: v.908 sage: bm. EXAMPLES: sage: v = finance. v [5.1)[0] sage: fbm.0000.scale_time(2) [45.8.0000] sage: v.0000. 6. 6.hurst_exponent() 0.0000. -4.fft(). 10.12 sage: finance.0000.randomize(’normal’).0000.0000. 7.10]).0000. (5. 152.0000. sage: set_random_seed(0) sage: bm = finance. 2. Release 5. 10. EXAMPLES: The Hurst exponent of Brownian motion is 1/2. -5.0000..0000.TimeSeries([w[0]]) + w[1:].8819.527450972..706511951. 0. -5.5000.. 0. 9 . 152. 4. We compute the Hurst exponent of a simulated fractional Brownian motion with Hurst parameter 0.0000. -4. -5. 152. normalize=False) Return the frequency histogram of the values in this time series divided up into the given number of bins. 8.TimeSeries([1. 3. 151. OUTPUT: •counts – list of counts of numbers of elements in each bin. 6.0000. •endpoints – list of 2-tuples (a. 9. 2. 15.0000.3.. We deﬁne the Hurst exponent of a constant time series to be 1.1. 4. see Google Books]. (0.sums().fractional_brownian_motion_simulation(0.histogram(3) ([1.0).3884. Note that the estimator is biased and slightly overestimates. Another example with small Hurst exponent (notice the overestimation)...7629. 2.-5]).10. v [1.2437.0000.5000.0000.5000. Fractal Market Analysis (1994). 9.hurst_exponent() 0.0000.b) that give the endpoints of the bins. 3].0000.0000. -5. [(-5.1.0000.6332. -5.2756.5000] An example with an even number of terms: sage: v = finance. -4.0000. 10.0000] histogram(bins=50.0000. bm [0. 1.ifft() [1.4.TimeSeries(10^5). 5. 5. 152.0)]) hurst_exponent() Returns an estimate of the Hurst exponent of this time series.7. 8. INPUT: •bins – a positive integer (default: 50) •normalize – (default: False) whether to normalize so the total area in the bars of the histogram is 1. 3.2.0000.0000. 8.0).TimeSeries([5. w [55.0000.706511951. 0. 10.9169.6327.0.0000. sage: set_random_seed(0) sage: fbm = finance.0000. 0.6246. We approximate it with some speciﬁc samples.5327.. 7.10^5. 3.8897 .6767. 4.0. -0.0000.0000. 3. 1.0000.0.. 5.3000.3.

4249.1)[0] sage: fbm.57984822577934. Release 5. 1.5.0000.2249.-4. . Time Series .hurst_exponent() 0.4. 2. -1.hurst_exponent() for z in y]).mean() 0.100) sage: finance. -1.2764.02.. -5.0. 2. 9.0000.c..6663.01. The returned real array contains [y (0).c.simulations(1000. -0. 0.0000. v [1.0000. ifft(overwrite=False) Return the real discrete inverse fast Fourier transform of self.0000.0. denotes complex conjugate of preceding expression. 7.5. 10.0000. + x[0] where c. 7.0000] list() Return list of elements of self. EXAMPLES: sage: v = finance. -0.0.MarkovSwitchingMultifractal(8.0000. + x[0] + (−1)j x[n − 1] and for n is odd  y (j ) = 1/n  k=1 (n−1)/2 (x[2k − 1] + √  √ −1 · x[2k ]) · exp( −1 · jk · 2pi/n) + c. We compute the mean Hurst exponent of 100 simulated Markov switching multifractal time series.1000.0000.10^5.0000.0. 6.hurst_exponent() for z in y]). 4.0] 10 Chapter 1. .mean() 0. 5. sage: set_random_seed(0) sage: msm = finance. 0.c. 8.-4.01.0.0000.TimeSeries([z. The Hurst exponent is quite small.0.95. y (n − 1)] where for n is even  y (j ) = 1/n  k=1 n/2−1 (x[2k − 1] + √  √ −1 · x[2k ]) · exp( −1 · jk · 2pi/n) + c.ifft(). 4.fft() [1.6876. .. -4.1.0000] sage: v. 3.0000...0000. -2. 3.1000.4764. -4.286102325623705.ifft() [5. .0000.-2. EXAMPLES: sage: v = finance.3]) sage: v.0774.0000.Sage Reference Manual: Quantitative Finance. 9. 3.6988] sage: v.0..10]). 5.3.fractional_brownian_motion_simulation(0.0..0000.12 sage: fbm = finance.0000.1000.list() [1.0000.TimeSeries([1. 3. 8. y (1).3) sage: y = msm. This is the inverse of fft(). 6.0000.TimeSeries([z.2. 1.100) sage: finance.0.1. We compute the mean Hurst exponent of 100 simulated multifractal cascade random walks: sage: set_random_seed(0) sage: y = finance.TimeSeries([1. which is also a real time series.0.5.278997441.multifractal_cascade_random_walk_simulation(3700. 10.

v = finance.0000. EXAMPLES: sage: v = finance.0000.TimeSeries([1.0000] sage: v.0000.3.mean() 1. 3. INPUT: •index – bool (default: False).0000. -4. 3. -2. 3.0000. EXAMPLES: sage: sage: 3. OUTPUT: 11 .3]). only returned if index=True. also return index of minimal entry.0855.-4. 20. OUTPUT: A double.0000.0855] sage: v.5000. 0.-2.0000] sage: v.7183. 1. -4.0.-2. OUTPUT: •ﬂoat – largest value. OUTPUT: A new time series. v [1.log() [1. 20. 1.TimeSeries([1. -2.0.-4.max(index=True) 2) mean() Return the mean (average) of the elements of self.6 min(index=False) Return the smallest value in this time series. 3.5. 0.0821.0183. 3.-4.12 log() Return new time series got by taking the logarithms of all the terms in the time series. INPUT: •index – bool (default: False).exp().Sage Reference Manual: Quantitative Finance.0000.3]).0000.1. also return index of maximum entry. If this series has length 0 we raise a ValueError.exp() [2.-4. 0. if True.5000.0000. -4.0000.0000] Log of 0 gives -inf: sage: finance.5.log()[1] -inf max(index=False) Return the largest value in this time series.3]).0 sage: (3.max() v.TimeSeries([1.0183. If this series has length 0 we raise a ValueError. EXAMPLES: We exponentiate then log a time series and get back the original series: sage: v = finance. v [1. 2. -4. Release 5.1. if True.0000.3]) v. •integer – index of largest value.2.TimeSeries([1.3.0000.

However. OUTPUT: A double. -2.min() -4.numpy(copy=False). EXAMPLES: sage: v = finance.Sage Reference Manual: Quantitative Finance.TimeSeries([1. 1. return a NumPy 1-D array reference to exactly the same block of memory as this time series. This is very.0000] sage: v.2 numpy(copy=True) Return a NumPy version of this time series.0000.-4. EXAMPLES: sage: v = finance. -3. it is dangerous because when this time series goes out of scope and is garbage collected. Release 5.-2. .moment(1) 1.0000. •integer – index of smallest value.0. Time Series .moment(2) 3. the corresponding NumPy reference object will point to garbage.ndarray’> sage: w. v [1. w array([ 1.5.min(index=True) (-4.) Notice that changing w also changes v too! sage: w[0] = 20 sage: w 12 Chapter 1. 1) moment(k) Return the k-th moment of self.TimeSeries([1.shape (4.1. ]) sage: type(w) <type ’numpy. 3. INPUT: •copy – bool (default: True) OUTPUT: A numpy 1-D array. Note: If copy is False.3.-3.0000.-2]) sage: w = v. EXAMPLES: sage: v = finance.4.TimeSeries([1.5. only returned if index=True.3]).5.12 •ﬂoat – smallest value. INPUT: •k – a positive integer. .0000.1. 2. very fast and makes it easy to quickly use all NumPy/SciPy functionality on self. 1. 4.0 sage: v.-4]) sage: v. which is just the mean of the k-th powers of the elements of self.2.6 sage: v.

0000. rgbcolor=’red’.-5]).2.plot() + v. •**kwds – passed to the line or point command.0000. Only plot the given number of equally spaced points in the time series. EXAMPLES: Here we look at the candlestick plot for Brownian motion: sage: v = finance.5000. The bar represents the open / close range.10.0000.plot() sage: v. 4.numpy().5.randomize() sage: v. -2. T (i)).4. rgbcolor=’red’) sage: v. EXAMPLES: sage: v = finance.TimeSeries(1000). .0000. high. -3. 4. .5000. 4. INPUT: •bins – positive integer (default: 30). The interval is colored blue if the open for that bin is less than the close.0000. -2.3. v [5.Sage Reference Manual: Quantitative Finance.3. Release 5.plot(points=True) sage: v. 4.0000] plot(plot_points=1000. ]) sage: z[0] = -10 sage: v [20.0000.plot_candlestick(bins=20) plot_histogram(bins=50. If 0. -3.0000] sage: v.TimeSeries([5. where i ranges over nonnegative integers up to the length of self.plot() + v.3000. -3. If True. 8. INPUT: •bins – positive integer (default: 50) 13 . sage: z = v. INPUT: •plot_points – (default: 1000) 0 or positive integer. **kwds) Return histogram plot of this time series with given number of bins.12 array([ 20. 2. plot all points. 1. the number of bins or candles. z array([ 20. -5. **kwds) Return a plot of this time series as a line or points through (i. ]) sage: v [20.plot(points=True.plot(points=True. points=False.8.0000. . -2. the line represents the high / low range.5.0000] If you want a separate copy do not give the copy=False option.0000. normalize=True. return just the points of the time series. -3. 10. •points – bool (default: False). and close stock data. A candlestick plot is a style of bar-chart used to view open.1. pointsize=50) plot_candlestick(bins=30) Return a candlestick plot of this time series with the given number of bins. low. 4. OUTPUT: A candlestick plot. then that bin is colored red instead. At each bin. . -2.0000. If the close is less than the open.0000. 3.

3. 1.TimeSeries([1. supported values are: –’uniform’ – from loc to loc + scale –’normal’ – mean loc and standard deviation scale –’semicircle’ – with center at loc (scale is ignored) –’lognormal’ – mean loc and standard deviation scale •loc – ﬂoat (default: 0) •scale – ﬂoat (default: 1) 14 Chapter 1.0000.0000. 1.0000] sage: v. Thus this function both changes self in place. 2.0000. **kwds) Randomize the entries in this time series.0000. 1.plot_histogram(bins=10) sage: v. returns 1.0000. OUTPUT: A time series. v [1. Time Series .1. 9.2.0000.2. loc=0.prod() 6. 1.1. EXAMPLES: sage: v = finance.TimeSeries([1. EXAMPLES: sage: v = finance.3]).0000. v [1.0000.aspect_ratio=1) pow(k) Return a new time series with every elements of self raised to the k-th power. OUTPUT: A histogram plot.50]) sage: v. INPUT: •k – a ﬂoat. for convenience. INPUT: •distribution – (default: "uniform")..0000] prod() Return the product of all the entries of self. Release 5.0000.0 randomize(distribution=’uniform’.1.normalize=False.0000. 2.plot_histogram(bins=3.1. scale=1.12 •normalize – (default: True) whether to normalize so the total area in the bars of the histogram is 1. 1. 4. and return a reference to self.0000. and returns a copy of self.0000] sage: v.0000. OUTPUT: A double.3]). If self has length 0.pow(2) [1. EXAMPLES: sage: v = finance.TimeSeries([1. 3. 1.Sage Reference Manual: Quantitative Finance.

5813. 5.8986.2412. sage: set_random_seed(0) sage: a = finance.4011. sage: set_random_seed(0) sage: finance.683094 sage: len(a.9541.TimeSeries(5). 1311. 2) [6.TimeSeries(10).3576. Release 5.randomize(’semicircle’) [0.7153.TimeSeries(10^6). but is of course much better quality.clip_remove(-5*s. It’s not quite as fast as the C library random number generator. 4. 130699. -0.2911.4628. Thus this function fully respects the Sage set_random_state command.1978.7472.6271] We generate 5 values using the semicircle distribution. 5. 5.randomize(’uniform’.8685. 5.TimeSeries(10).2816. 4. 5. -0.Sage Reference Manual: Quantitative Finance. -0. 21290.7990. 0. 35] We take the above values. 1148. 3.9598. 5.7369.1456. and is platform independent.7369. -0.TimeSeries(5).7484.randomize(’normal’) [0. 2) [6. 340054. 2.3534. 5.standard_deviation() sage: len(a.9365] We generate 10 normal random values with mean 5 and variance 2.3*s))/float(len(a)) 0. 5. 5.0459.2*s))/float(len(a)) 0.4187] We generate 1 million normal random values and create a frequency histogram.clip_remove(-s.2010. 0. 2.2761. -0.clip_remove(-3*s. and 6 standard deviations of the mean (0): sage: s = a.8273. 6. 5.1269.s))/float(len(a)) 0.clip_remove(-2*s. 0.0229.histogram(10)[0] [36.997228 sage: len(a.1]: sage: set_random_seed(0) sage: finance. -0.999998 There were no “six sigma events”: 15 .4628. 0. and compute the proportion that lie within 1.7314] We generate 5 uniform random numbers from 5 to 5 + 2 = 7: sage: set_random_seed(0) sage: finance.randomize(’normal’) sage: a. 5.5632. 137953. 19604. sage: set_random_seed(0) sage: finance. 347870. 3. 0. 3. 6. 5.5439] We generate 5 normal random values with mean 0 and variance 1.randomize() [0.12 Note: All random numbers are generated using algorithms that build on the high quality GMP random number function gmp_urandomb_ui.5864.954559 sage: len(a. 3. 3.randomize(’normal’.5*s))/float(len(a)) 0.6767. 0. EXAMPLES: We generate 5 uniform random numbers in the interval [0.TimeSeries(5). sage: set_random_seed(0) sage: finance.

clip_remove(-6*s..6*s))/float(len(a)) 1.0000.TimeSeries(10^6). •b – integer (default: None).0000.Sage Reference Manual: Quantitative Finance.0000.4. 4.0000] sage: v. rescale(s) Change self by multiplying every value in the series by s.randomize(’normal’). and set Zk = Yk − ((k + 1)/n) · Yn .-5])..range_statisti 1897.3.0.10. EXAMPLES: sage: v = finance.8. Time Series . EXAMPLES: sage: v = finance. and return the average of those R/S statistics. 4..0000.5000. If the optional parameter b is given.5]) sage: v.. Release 5. Then R/S = max(Zk ) − min(Zk ) /σ where the max and min are over all Zk . 1.1. 4.0000.TimeSeries(10^6).0000.sums(). INPUT: •self – a time series (not the series of differences).0000.0 range_statistic(b=None) Return the rescaled range statistic R/S of self.0000. INPUT: •s – a ﬂoat.0000. Basically replacing Yk by Zk allows us to measure the difference from the line from the origin to (n. compute the R/S statistic for each block. 2.0000.3. finance.0000.sums().8392602.0000.0000] 16 Chapter 1. 0.6500.0000. OUTPUT: A ﬂoat. sage: set_random_seed(0).range_st 1897.. OUTPUT: A time series. v [5. and let Yk be the k-th term of self. 10.2.100).3000.randomize(’normal’. EXAMPLES: Notice that if we make a Brownian motion random walk.TimeSeries([1.rescale(0. Let n be the number of terms of self. finance. if given instead divide the input time series up into j = floor(n/b) disjoint blocks. 2. 5. 8. 2.8392602. -5. 1. 3. return the average of R/S range statistics of disjoint blocks of size b. sage: set_random_seed(0).5000] reversed() Return new time series obtain from this time series by reversing the order of the entries in this time series. there is no difference if we change the standard deviation.TimeSeries([5. Let σ be the standard deviation of the sequence of differences of self.12 sage: len(a. 1. which is deﬁned as follows (see Hurst 1951).0000. 3.reversed() [5. 1.5) sage: v [2.5000. -2. Yn ).

1. This is thus just an alias for plot. 17 . 10.TimeSeries([5. .3000.Sage Reference Manual: Quantitative Finance.8.0000.-5]).5000.4.scale_time(10) [] A series of odd length: sage: v = finance. 4. .3.0000.0000.0000.0000.0000. v [5.0000. INPUT: •k – a positive integer.0000. Xk . ValueError: k must be positive sage: v.scale(0.scale_time(2) [1.2.0000.0000. -5.0000.0000.0000. 3. 2.. 2. 2. 5. then this function returns the shorter time series X0 . 1.5000.0000. . -5. 2.0000. .. 1.12 scale(s) Return new time series obtained by multiplying every value in the series by s.10.0000. 3.0000] sage: v.0000] sage: v.0000.5) [2.0000. 8.0000. 5.TimeSeries([5.0000.. 8.0000.2.scale_time(3) [5.0000. 5.8. EXAMPLES: sage: v = finance.0000] sage: v.0000. If the input time series is X0 .0000] TESTS: sage: v.0000] sage: v. OUTPUT: A new time series with all values multiplied by s.TimeSeries([1. 1.3000. -5. 2.scale_time(2) [5. 10.0000.scale_time(0) Traceback (most recent call last): .3000. 8.6500. **kwds) Calls plot and passes all arguments onto the plot function. v [1. EXAMPLES: sage: v = finance. . 0.0000. X1 . 4.5000] scale_time(k) Return the new time series at scale k. 3.4. 3.scale_time(1) [5.. 4. 1.3.10. 3.0000.1. 4. X2 . Release 5. X2k .-5]).3.5]). 1.0000] sage: v.scale_time(-1) Traceback (most recent call last): .0000.0000. -2.0000. . ValueError: k must be positive show(*args. . .0000] sage: v. 8. 4. v [5.0000. 10. INPUT: •s – a ﬂoat. OUTPUT: A new time series. 1.0000. 3.3000..3. 2.

0000.12 EXAMPLES: Draw a plot of a time series: sage: finance. divide by self.0000.1.0000.1. OUTPUT: A double.3333. INPUT: •bias – bool (default: False).standard_deviation(bias=True) 0. if False.length() to give a less biased estimator for the variance. Thus k values are averaged at each point. OUTPUT: 18 Chapter 1. 1.TimeSeries([]).0000.1 instead of self.show() simple_moving_average(k) Return the moving average time series over the last k time units. 1.3]).standard_deviation() 0. 3. v [1.0000. 1. v [1.2.0000.0000. 2. returns 0. 2.0000.0000.0000.0000.standard_deviation() 0. 1.simple_moving_average(3) [1..1. 1.1 steps of self and the k-th step divided by k.TimeSeries([1]). 3. 2. 1. EXAMPLES: sage: v = finance.0000. 3.0000. 1. Assumes the input time series was constant with its starting value for negative time.5000] sage: v. 1.0000.simple_moving_average(2) [1. 3.TimeSeries([1. OUTPUT: A time series with the same number of steps as self.8 TESTS: sage: finance.10]).TimeSeries([1.5000. If self has length 0.0000.8944271909.standard_deviation() 0.0000] standard_deviation(bias=False) Return the standard deviation of the entries of self.0000] sage: v. sage: v.0000] sage: v. Time Series .simple_moving_average(0) [1.Sage Reference Manual: Quantitative Finance. 2. 1.length() .0000.0000] sage: v.0 sage: finance.0 sum() Return the sum of all the entries of self.0000. 2.0000.simple_moving_average(1) [1. EXAMPLES: sage: v = finance. 1.1.0000.TimeSeries([1. Release 5.. 1.3]). The t-th step of the output is the sum of the previous k . 2.0000..0000] sage: v. 1. 1.0000.0000.2. INPUT: •k – positive integer. 1.

2.0 vector() Return real double vector whose entries are the values of this time series.0 sums(s=0) Return the new time series got by taking the running partial sums of the terms of this time series. divide by self. v [1.3]).12 A double. 2.0000.1 instead of self.2.sums() [1. 1. INPUT: •bias – bool (default: False).3]). 2. This is useful since vectors have standard algebraic structure and play well with matrices.0000] sage: v.8 sage: v.0000. 8.variance() 0. 3.1.variance() 0.sum() 8.3]).0000] sage: v. Release 5.TimeSeries([1.0000.variance(bias=True) 0.0000.0000.0000.0 sage: finance.0000.0000.1. EXAMPLES: 19 . 1. 3. if False.length() to give a less biased estimator for the variance.2.length() .1. v [1. 1. 2. EXAMPLES: sage: v = finance. EXAMPLES: sage: v = finance.TimeSeries([1]).0000. 1.0000.1.TimeSeries([1. which is the mean of the squares of the differences from the mean. 3.0000] sage: v.TimeSeries([]).TimeSeries([1. OUTPUT: A double.1.variance() 0. 1. 1.Sage Reference Manual: Quantitative Finance.2.0000. 3. INPUT: •s – starting value for partial sums.0000. OUTPUT: A time series.1. EXAMPLE: sage: v = finance.0000.0000.64 TESTS: sage: finance.0000. OUTPUT: A real double vector. 5.0000] variance(bias=False) Return the variance of the elements of self. v [1.0000.

abs().. 3.diffs().6701] Note: ac looks like a line – one could best ﬁt it to yield a lot more approximate autocovariances.7836741372407. 0.autoregressive_fit(ac). and use simulations to estimate the expected ﬁrst few autocovariance parameters for this model. . -0. This models the logarithms of a stock price sequence.0.01.autoregressive_forecast(F) 6. 9.0002. 3.9982.12 sage: v = finance. 20 Chapter 1.vector() (1. -0. . 1. To predict k time steps into the future would require using a similar technique but would require scaling time by k. .1000.0014] Note that the sum is close to 1: sage: sum(F) 0.multifractal_cascade_random_walk_simulation(3700.Sage Reference Manual: Quantitative Finance. F [0.8004.7033. .7144.9601.02. 0.0013.0002.9962. -0.TimeSeries([1. 6.. .. the forecast is close: sage: y2[:-1].0066. 8.99593284089454.multifractal_cascade_random_walk_simulation(3700. a = (a1 .0059.finance.01.0002.8063. We compute the ﬁrst 200 autocovariance values for every random walk: sage: c = [[a.0000.9481 .time_series.10]) sage: v.0001 . -0.mean() for z in c]) sage: ac [3.0. . 1.0..9722.. ap so that the ﬁrst M autocovariance coefﬁcients of the autoregressive processes Xt = a1 Xt1 + · · · + ap Xt−p + Zt are the same as the input sequence. which is only a model for predicting volatility.0. . 3. . 6. We create 100 simulations of a multifractal random walk.0002. 1.0) sage.0. 2.0.6812.di sage: y2 [0. 4. sage: set_random_seed(0) sage: y = finance.8009. aM ). 5.0.8090.0002. 6..0. 6.0068.02. -0. Time Series . 6. 1.0.9842..0184 . 0.6922.0. γ (M )). We compute the autoregression coefﬁcients matching the above autocovariances: sage: F = finance. 0. 0.0. .1)[0].1000.01.0003. then use them to construct a linear ﬁlter that works vastly better than a linear ﬁlter constructed from the same data but not using this model.autocovariance(i) for a in y] for i in range(200)] We make a time series out of the expected values of the autocovariances: sage: ac = finance. The MonteCarlo method illustrated below should work for predicting one “time step” into the future for any model that can be simulated.01.autoregressive_fit(acvs) Given a sequence of lagged autocovariances of length M produce a1 . 0. -0. The function works by solving the Yule-Walker equations Γa = γ .0. where γ = (γ (1).TimeSeries(z). .100) For each walk below we replace the walk by the walk but where each step size is replaced by its absolute value – this is what we expect to be able to predict given the model. . 1.TimeSeries([finance.0. 3. 3. 10.0. with γ (i) the autocovariance of lag i and Γij = γ (i − j ).8339] And we forecast the very last value using our linear ﬁlter. .. EXAMPLES: In this example we consider the multifractal cascade random walk of length 1000... 0. 6.. Now we make up an ‘out of sample’ sequence: sage: y2 = finance. Release 5. 7.0.sums().

always using all correct values up to the one we are forecasting: sage: s1 = sum([(y2[:-i]. s2 = [] sage: for v in y_out: . How does it compare overall? To ﬁnd out we do 100 simulations and for each we compute the percent that our model beats naively using the autocovariances of the sample: sage: y_out = finance.autoregressive_forecast(y2[:-1].12 In fact it is closer than we would get by forecasting using a linear ﬁlter made from all the autocovariances of our sequence: sage: y2[:-1]. INPUT: •v – a raw char buffer EXAMPLES: sage: v = finance.. 3.TimeSeries([s2[i]/s1[i] for i in range(len(s1))]) sage: s.0000] sage: sage..unpickle_time_series_v1(s+s.3]) sage: s = v..20)]) We do the same.100) sage: s1 = []. 2.0000] sage: sage.354073591877. but using the autocovariances of the sample sequence: sage: F2 = y2[:-100].0.unpickle_time_series_v1(v.. F2 = v[:-len(F)].0000.20)])) . 3.0000.6) [1. sage..0000. We ﬁnd that overall the model beats naive linear forecasting by 35 percent! sage: s = finance.01.unpickle_time_series_v1(s.finance.unpickle_time_series_v1(’’.finance.autoregressive_fit(len(F)) .20)])) .autoregressive_fit(len(y2))) 6...15464636102.0..3) [1.autoregressive_forecast(F)-y2[-i])^2 for i in range(1.770168705668.autoregressive_forecast(F)-v[-i])^2 for i in range(1. Release 5.autoregressive_forecast(F2)-y2[-i])^2 for i in range(1.autoregressive_forecast(F2)-v[-i])^2 for i in range(1.01.time_series.02.. We record the last 20 forecasts.2.append(sum([(v[:-i].autoregressive_fit(len(F)) sage: s2 = sum([(y2[:-i]. s2.TimeSeries([1.0000.multifractal_cascade_random_walk_simulation(3700. 1. n) Version 1 unpickle method...finance.Sage Reference Manual: Quantitative Finance.time_series.20)]) Our model gives us something that is 15 percent better in this case: sage: s2/s1 1.append(sum([(v[:-i].mean() 1.0000.. 3.0) [] 21 .0.0000.. 2.finance.time_series.0000.time_series.. s1. 2.1000.__reduce__()[1][0] sage: type(s) <type ’str’> sage: sage.

Time Series .Sage Reference Manual: Quantitative Finance.12 22 Chapter 1. Release 5.

cid=’‘) Class for retrieval of stock market information. (’daily’ or ’weekly’) OUTPUT: A time series – close price data. 100.finance.+1900’) •enddate – string.34.96. 100. **kwds) Return the time series of all historical closing prices for this stock. 2008 TESTS: sage: ohlc = sage. Also stores a timestamp for that data along with the volume.stock. high.finance. high. 95.06 95.stock. (default: current date) •histperiod – string. INPUT: •timestamp – string •open. open.01. 95. and close information for a stock.01. (default: ’Jan+1.finance.06.OHLC(timestamp. 104.34.stock. low. Otherwise.stock.OHLC(’18-Aug-04’. high.finance. close(*args.CHAPTER TWO STOCK MARKET PRICE SERIES AUTHORS: • William Stein. EXAMPLES: 23 .96. data will be gotten from Google Finance. close – ﬂoat •volume – int EXAMPLES: sage: sage.06. volume) Open. 100. close. 22353092) sage: loads(dumps(ohlc)) == ohlc True class sage. INPUT: •startdate – string. 104.01 104. will return last acquired historical data. 2008 • Chris Swierczewski. low. 22353092) 18-Aug-04 100.34 22353092 class sage. low. 2008 • Brett Nakayama.Stock(symbol. If no arguments are given. 100.96 100.OHLC(’18-Aug-04’.

Stock(’vmw’) sage: c. +1900’. Note: Google Finance returns the past year’s ﬁnancial data by default when startdate is set too low from the equity’s date of going public.08 2896600 ] 24 Chapter 2.+yyyy’.85 2473000.close() # optional -.Stock(’vmw’).6700.. 61.91 58..+2008’) [84.e.57 87.6700.12 You can directly obtain close data as so: sage: finance. 1-Feb-08 56.8700. finance.google() will give correct results. +2013’.49 80.4900.7100.87 96.91 93.60 57. 58. 57. However.69 7496000. (’daily’ or ’weekly’) OUTPUT: A sequence. Release 5. self. 72. 84. if you speciﬁed the market during initialization of the stock (i.Stock(’vmw’). 59. 83. 58. enddate=’Oct+10. 56.Stock("OTC:NTDOY")). By default.85 91.9500.8600.3300.67 2591100. 80.google()[:5] # optional -.50 61.39 95.. 60. 57.6700 Otherwise.9900 .0000.. 72.32 62.05 95.9900. 4-Dec-07 92.52 56. 54. 59. 55. you can initialize stock data ﬁrst and then extract the Close data: sage: c = finance.35 55. enddate=’Feb+1.14 55.internet [56. Stock Market Price Series . 83. EXAMPLES: We get the ﬁrst ﬁve days of VMware’s stock history: sage: finance.85 5497600.+1900’) •enddate – string.+2008’. optional -.6000.8500.3000.57 88.Stock(’vmw’). this function only looks at the NASDAQ and NYSE markets.52 2191100 ] sage: c.98 58.google() will be called with the default arguments returning a year’s worth of data: sage: finance. 84.+2008’)[:5] # optional -.8500 Or.26 97.6000.1800.5500.00 88.9900. 3-Dec-07 89. 83. 57. 6-Feb-08 60. 29-Nov-07 90. where ’Mon’ is a three character abbreviation of the month’s name.00 60.30 1709000.9900. 80. 30-Nov-07 95.5200 . 5-Feb-08 57. OHLC data is stored internally as well. (default: ’Jan+1.05 1816500.9500. obtained from Google.60 59. Stock.17 59.4200. 56.9500.60 89. (default: current date) •histperiod – string. 58. returns the past year’s daily OHLC data. INPUT: •startdate – string.internet [ 28-Nov-07 80.37 4750200.97 4401100. 4-Feb-08 58.9900 .06 57..internet [ 31-Jan-08 55.9900 google(startdate=’Jan+1. enddate=’Mar+1.50 90.4900. histperiod=’daily’) Return an immutable sequence of historical price data for this stock.10 92.close() # random. 65.2900. Dates startdate and enddate should be formatted ’Mon+d.00 59.30 57.70 94.close(startdate=’Jan+1. 56.20 89.0500..47 56.+2008’.google(startdate=’Feb+1. By default.Sage Reference Manual: Quantitative Finance. 59.internet [57. 84.

38 9.44 4404000.38 8.+1978’.00 11.05 29.00 11.25 9.internet [ 4-Jan-99 0.Sage Reference Manual: Quantitative Finance.+2007".56 9.Stock(’F’).89 1. 9-Jan-78 0.+2000’)[0:5] # optional -.82 1.+2008")[:5] [ 3-Jan-07 32.44 32. The csv ﬁle must be formatted in the following way. For example.44 48160800. 5-Jan-07 30.00 9.High.00 9.00 1.38 10.15 65670.00 10.69 9.Low.+1990’)[:5] #optional [ 2-Jan-90 0. 5-Jan-90 0.00 11.+2008’)[:5] # optional -. sage: sage.20 31.03 10. ’Jul+7. 8-Jan-07 30. Release 5.50 9. 8-Jan-90 0. Apple’s (AAPL) stock history only dates back to September 7.60 29.00 9.00 9.25 24240000 ] Here is an example where we create and get the history of a stock that is not in NASDAQ or NYSE: sage: finance.00 10.00 1.internet [ 3-Jan-78 0.89 1618200. Note that when using historical.84 2994900.83 3042500. OUTPUT: A sequence – OHLC data.72 11.93 1.50 30.30 32.70 32.31 9.15 30.75 32.53 11.89 1.84 1.25 10.90 103338 ] Here.38 7428400. if a cid is speciﬁed.50 30.41 7911200.70 222643.00 1. 22144).00 1. 5-Jan-99 0. 6-Jan-99 0.finance. EXAMPLES: 25 . just as on Google Finance: Timestamp.88 2482700.25 9.75 9.87 1.40 31. 5-Jan-78 0.google(startdate="Jan+1.98 10.31 34031600.stock.84 1.44 156283.00 1.81 1. 7-Jan-99 0.79 1.Volume INPUT: •file – local ﬁle with Google Finance formatted OHLC data.google(startdate=’Jan+1.90 30.Open. 4-Jan-78 0. 3-Jan-90 0.Stock("OTC:NTDOY"). ’Jan+1.google(’Jan+3.10 30. 9-Jan-07 29.89 1. Note that no symbol data is included in Google Finance’s csv data. 8-Jan-99 0.50 3627600 ] load_from_file(ﬁle) Load historical data from a local csv formatted data ﬁle. 1984: sage: finance.00 30. it will take precedence over the stock’s symbol. and get historical data.15 30.00 10. 4-Jan-07 31. So.50 9. 6-Jan-78 0.00 11. enddate="Jan+1.google(’Sep+1. 4-Jan-90 0. we create a stock by cid.Stock("AAPL".25 51036400.12 sage: finance.Close.27 10. the history based on the contract id will be returned.56 10.+1900’.10 130765.31 6542800.83 50360400. Google Finance defaults to a year’s worth of stock history leading up to the speciﬁed end date.00 9.Stock(’AAPL’).81 3916400 ] Note that when startdate is too far prior to a stock’s actual start date. if the symbol and cid do not match.

80 187.00 188.00 2877.11 188.75 188.00 687.High.187. (’daily’ or ’weekly’) OUTPUT: A time series – close price data.00 188.. (default: current date) •histperiod – string. optional . Stock Market Price Series .market_value() 575.187. called AAPL-minutely.83000000000004 # random. we can initialize a Stock object with the symbol ’goog’.00 188.Close. 1212408000 188.00 188.Stock(’goog’). 1212405780 187. 1212405780 187. If no arguments are given.00 188.00 188. the symbol designated at initialization of Stock need not match the source of the data.00 188.+1900’) •enddate – string.00 1000. **kwds) Return a time series containing historical opening prices for this stock.00 187.80 187.00 188.80 100 ] Note that since the source ﬁle doesn’t contain information on which equity the information comes from.load_from_file(filename)[:5] [ 1212408060 188. Note that the path must be explicit: sage: filename = tmp_filename(ext=’. One can load this information into a Stock object like so. Otherwise.00 188. Release 5.75 188.’w’).80.80 187. (default: ’Jan+1.80 187.80. For example. IOError: [Errno 2] No such file or directory: ’I am not a file’ market_value() Return the current market value of this stock. but load data from ’aapl’ stock prices: sage: finance.load_from_file("I am not a file") Traceback (most recent call last): . 1212407700 188.. 1212407640 187. data will be gotten from Google Finance.00 188.csv.Stock("AAPL").Open.00 188.csv’) sage: open(filename.load_from_file(filename)[:5] [ 1212408060 188.Volume\n1212405780.Low.80 187.00 188. 1212408000 188.00 188.Sage Reference Manual: Quantitative Finance.00 2877.00 188.write("Date.00 187.75 188.00 687.00 2000. such as that from Google Finance. INPUT: •startdate – string.Stock(’goog’). 1212407640 187.80 187.00 1000.00 188. EXAMPLES: sage: finance.11 188. 1212407700 188.12 Suppose you have a ﬁle in your home directory containing Apple stock OHLC data. 26 Chapter 2.internet open(*args.80 100 ] This tests a ﬁle that doesn’t exist: sage: finance.18 sage: finance.00 188.Stock(’aapl’).00 2000. OUTPUT: A Python ﬂoat. will return last acquired historical data.75 188.

3000. OUTPUT: A dictionary.internet [55. 60.0000. 57.52 2191100 ] sage: c. 59. self.google() will be called with the default arguments returning a year’s worth of data: sage: finance. 58.00 60.internet {’stock_exchange’: ’"NasdaqNM"’. 6-Feb-08 60.98 58. 81.4900.9800 Or.internet [ 31-Jan-08 55.internet [52. 59.47 56.67 2591100.91 58.9000. 58. ’market_cap’: ’181. 81. ’52 27 . EXAMPLES: sage: finance. 1-Feb-08 56.52 56.2500 yahoo() Get Yahoo current price data for this stock.30 1709000.0500. optional -.05 1816500. 84.0000..06 57. 82.17 59.3200 .4900. 5-Feb-08 57.12 EXAMPLES: You can directly obtain Open data as so: sage: finance.Stock(’vmw’). 85.6000.+2008’.50 61.0000. Release 5.9900.0000.1100. 59.open(startdate=’Jan+1.9000. 83. optional -.0500..35 55. 55.5500.Stock(’GOOG’). 57.00 59.0500.2500 .7900. ’200day_moving_avg’: ’564. you can initialize stock data ﬁrst and then extract the Open data: sage: c = finance.60 59.Stock(’vmw’) sage: c..+2008’)[:5] # optional -..14 55.569’. 59. enddate=’Feb+1.open() # random. 56.6000. 56..open() # optional -. 84.+2008’. 82. enddate=’Mar+1. 60. 54.4900.google(startdate=’Feb+1. 4-Feb-08 58.Sage Reference Manual: Quantitative Finance.1B’. 85.0000. 56.Stock(’vmw’).yahoo() # random.2500 .+2008’) [83.2700. 56..60 57.6000. 60.0000.9800.30 57.85 2473000. 82.2600 Otherwise.32 62.

Release 5. Stock Market Price Series .12 28 Chapter 2.Sage Reference Manual: Quantitative Finance.

5.349714381299734 sage: finance.25.CHAPTER THREE TOOLS FOR WORKING WITH FINANCIAL OPTIONS Tools for working with ﬁnancial options AUTHORS: .. 2013: initial version sage.black_scholes(42. 0. 0. 40. 40.0. 0. time_to_maturity. strike_price. vol.2. 0. 0.5. risk_free_rate. ’call’) # abs tol 1e-10 13. The type of option. 520.0236734.1. INPUT: •spot_price – The current underlying asset price •strike_price – The strike of the option •time_to_maturity – The # of years until expiration •risk_free_rate – The risk-free interest-rate •vol – The volatility •opt_type – string.black_scholes(spot_price. EXAMPLES: sage: finance.option.1.25.black_scholes(100. 0. ’put’) # abs tol 1e-10 6. 0. 0. 0.black_scholes(42.5. ValueError: ’whichever makes me more money’ is not a valid string REFERENCES: 29 .finance. 0. ’call’) # abs tol 1e-10 4. 0. ’put’) # abs tol 1e-10 0. 95.’whichever makes me more Traceback (most recent call last): . 0.424563772. 0.1.1.759422392871532 sage: finance.15297..black_scholes(527.black_scholes(100.8085993729000958 sage: finance.695272738608132 sage: finance.2. either ’put’ for put option or ’call’ for call option OUTPUT: The price of an option with the given parameters. 95.5. opt_type) Calculates call/put price of European style options using Black-Scholes formula. 0.Brian Manion.07. See [S] for one of many standard references for this formula.

Release 5.12 30 Chapter 3. Tools for working with ﬁnancial options .Sage Reference Manual: Quantitative Finance.

0 < H < 1.1598.fractional_brownian_motion_simulation(H. 0.01.2541.6267.8. 0. -0.html See also Mandelbrot’s The Misbehavior of Markets for a motivated introduction to the general idea of using a selfsimilar approach to modeling asset returns.6465.0239. Continuous cascade models for asset returns and many other papers by Bacry et al.0754. •n – positive integer (default: 1).ﬂoat.0764.fractional_brownian_motion_simulation(0.2158.1735. 0. 0. 0. 0.1.1982. 0. 0. 0.0. See http://www. 0. •N – positive integer. AUTHOR: • William Stein (2008) sage. 2006.2044. In particular.0363. 0. 0. 0.CHAPTER FOUR MULTIFRACTAL RANDOM WALK Multifractal Random Walk This module implements the fractal approach to understanding ﬁnancial markets that was pioneered by Mandelbrot.8.1600.8.6289]] sage: set_random_seed(0) sage: finance. [0. it implements the multifractal random walk model of asset returns as developed by Bacry.1) [[-0.0125.1009.fractional_brownian_motion_simulation(0. 0.fractional_brownian_motion_simulation(0.8.1692]. Kozhemyak.0153. -0.6824. 0.0.2) [[-0.01. OUTPUT: List of n time series.8.2735. INPUT: •H – ﬂoat.2133]] 31 .8. 0.1874.fr/~bacry/ftpPapers.1989]] sage: finance. 0.1) [[-0.0593.0856. One of the main goals of this implementation is that everything is highly optimized and ready for real world high performance simulation work.1409.fractal.0.0167. 0.0261.0244. 0. 0. sigma2. 0.finance.0342. 0. N. innovation variance (should be close to 0).polytechnique.0865.5059.cmap. n=1) Returns the partial sums of a fractional Gaussian noise simulation with the same input parameters. and Muzy. EXAMPLES: sage: set_random_seed(0) sage: finance. 0. •sigma2 . 0. 0. the Hurst parameter. 0.

-0.7110. sigma2.7025. 0.3538.1252. 2. number of steps in simulation. •N – positive integer.9070.9995. EXAMPLES: We simulate a fractional Gaussian noise: sage: set_random_seed(0) sage: finance.fractional_gaussian_noise_simulation(0. lambda2. 2. N.10.4452. •ell – a small number – time step size.7726. innovation variance.7555.8. 0 < H < 1. sage. 1. 2000. 0. •n – positive integer (default: 1). •n – the number of separate simulations to run. Peter F. -0.2221. OUTPUT: List of time series. 0. 0. •sigma2 – variance of the Gaussian white noise eps[n]. [-0.5947. 1.positive ﬂoat. 0. ell. Release 5. number of simulations.6932.4142. 0. N.multifractal_cascade_random_walk_simulation(T.4090. -0.finance.0077]] The sums deﬁne a fractional Brownian motion process: sage: set_random_seed(0) sage: finance.8500. INPUT: •H – ﬂoat. -1.Sage Reference Manual: Quantitative Finance. -0.3103.0290.5868. n=1) Return n simulations with N steps each of fractional Gaussian noise with Hurst parameter H and innovations variance sigma2.fractional_gaussian_noise_simulation(0. EXAMPLES: 32 Chapter 4. 0. with Application to Long Meoryy Processes. Multifractal Random Walk .sums() [-0.fractal. OUTPUT: List of n time series.3324. Craigmile for a discussion and references for why the algorithm we give – which uses the stationary_gaussian_simulation() function. 0.7248.2) [[-0.4048.1.3465. 2.0818.10.1)[0]. -0.5981. 2.8. •sigma2 . -0. the intermittency coefﬁcient.fractal. -0. 2. INPUT: •T – positive real. the Hurst parameter. •N – number of steps in each simulation. 1.4949. 2. 0.2964]. -1.1157. sigma2. This walk can be interpreted as the sequence of logarithms of a price series.fractional_gaussian_noise_simulation(H. the integral scale.1. •lambda2 – positive real.7054] ALGORITHM: See Simulating a Class of Stationary Gaussian Processes using the Davies-Harte Algorithm.finance.12 sage.1157. n=1) Return a list of n simulations of a multifractal random walk using the log-normal cascade model of BacryKozhemyak-Muzy 2008.

0.exp() [0. if not we pad it with extra 0’s until it has length N+1. •N – a positive integer. this algorithm fails with a NotImplementedError. 0.4]] [0. 0. if it isn’t. where epsn is gaussian white noise of variance σ 2 and ωn is renormalized gaussian magnitude.0078.. 0.0115.0003.0035.4472135954999579] We run the simulation: sage: set_random_seed(0) sage: sim = finance.0746.0563.0067.0005. 1.9987.0047. 0.10. 0.multifractal_cascade_random_walk_simulation(3770. 0.01.0377.56234006792017. INPUT: •s – a list of real numbers that deﬁnes the ACVS.98665816086255. -0..02.0749. 0.0078.N]] s[:5] 0.0116.0051. 0.. 0. [-0. 0. 0.autocovariance(i) for i in [0.0003. 0. EXAMPLES: We deﬁne an autocovariance sequence: sage: sage: sage: [1. 0. 0.0096. We assume that a certain Fourier transform associated to s is nonnegative. -0. 0.0257.0066.3) sage: a [[-0.. 0. Optimally s should have length N+1. 0... 0. 1. n=1) Implementation of the Davies-Harte algorithm which given an autocovariance sequence (ACVS) s and an integer N. 33 .0358. OUTPUT: A list of n time series. 0.. which is given by a stationary gaussian simulation associated to a certain autocovariance sequence.0018... simulates N steps of the corresponding stationary Gaussian process with mean 0. 0.0. N)[0] Note that indeed the autocovariance sequence approximates s well: sage: [sim.0012.0003. 0. 0. 0. 0.9905. 1.0060]] The corresponding price series: sage: a[0]. Kozhemyak. 0..0120. It is summarized nicely with many applications at the beginning of Simulating a Class of Stationary Gaussian Processes Using the Davies-Harte Algorithm. 2006.0.0.0085. sage. Release 5. 0.Sage Reference Manual: Quantitative Finance.stationary_gaussian_simulation(s. N = 2^15 s = [1/math.fractal.0043].0016... 0. See Bacry..0013. -0. 1.stationary_gaussian_simulation(s.69201577095377. 0.01.sqrt(k+1) for k in [0. 0. 1.0025.5773502691896258.12 sage: set_random_seed(0) sage: a = finance..48647965409871.0078.7071067811865475. 0. then the autocovariance sequence would not approximate s very well. Continuous cascade models for asset returns for details.9957] MORE DETAILS: The random walk has n-th step epsn eωn . Muzy. 1.0025. [0. N.0689].0. 0.0043. REFERENCES: This is a standard algorithm that is described in several papers.0661.0051.0016. 0.5.finance. 1.436670433 Warning: If you were to do the above computation with a small value of N.0047.

Sage Reference Manual: Quantitative Finance. The book Wavelet Methods for Time Series Analysis by Percival and Walden also describes this algorithm. but are in the Amazon. Peter F. The description is in Section 7.com preview of the book. Craigmile. This paper also generalizes the algorithm to the case when all elements of s are nonpositive. 34 Chapter 4. which is easily found as a free PDF via a Google search. but has a typo in that they put a 2π instead of π a certain sum. That book describes exactly how to use Fourier transform. Release 5. Multifractal Random Walk .8.12 with Application to Long Memory Processes. Note that these pages are missing from the Google Books version of the book. 2000.

1. b = 3.3) sage: loads(dumps(msm)) == msm True class sage.95 sage: yen_usd = finance. m0.1. Calvet and Fisher.278.76) sage: cad_usd = finance.644.0.0.0.0.0.326.CHAPTER FIVE MARKOV SWITCHING MULTIFRACTAL MODEL REFERENCE: How to Forecast Long-Run Volatility: Regime Switching and the Estimation of Multifractal Processes. and gamma_8 = 0.0.1. gamma_kbar.959. AUTHOR: • William Stein.4.1.262.MarkovSwitchingMultifractal(10.MarkovSwitchingMultifractal(10.finance.MarkovSwitchingMultifractal(8. 2008 TESTS: sage: msm = finance.3.0.markov_multifractal.4. sigma.998.0. msm Markov switching multifractal model with m0 = 1.1.MarkovSwitchingMultifractal(kbar.448.MarkovSwitchingMultifractal(8.95.0.0.1.3). sigma = 0.11) sage: dm = finance.95. b) INPUT: •kbar – positive integer •m0 – ﬂoat with 0 <= m0 <= 2 •sigma – positive ﬂoat •gamma_kbar – ﬂoat with 0 <= gamma_kbar < 1 •b – ﬂoat > 1 EXAMPLES: sage: msm = finance.7) b() Return parameter b of Markov switching multifractal model.4.5.MarkovSwitchingMultifractal(10. EXAMPLES: 35 .2.5.0.2. 2004.461.643.

0.0 simulation(n) Same as self.MarkovSwitchingMultifractal(8.1.4.95.10 gamma_kbar() Return parameter gamma_kbar of Markov switching multifractal model.03630878209190. 0.MarkovSwitchingMultifractal(8. EXAMPLES: sage: msm = finance.kbar() ﬂoats.95 kbar() Return parameter kbar of Markov switching multifractal model.012252436441829.gamma() (0.0.. EXAMPLES: sage: msm = finance.4 sigma() Return parameter sigma of Markov switching multifractal model. EXAMPLES: 36 Chapter 5.004100940201672509.95.1.b() 3. EXAMPLES: sage: msm = finance..12 sage: msm = finance.0. 0.95.01. EXAMPLES: sage: msm = finance.95.3) sage: msm.3) sage: msm. OUTPUT: •gamma – a tuple of self.95..1..Sage Reference Manual: Quantitative Finance. but run only 1 time.1.01.gamma_kbar() 0.1.. 0.001368852970712986.1.4.kbar() 8 m0() Return parameter m0 of Markov switching multifractal model.4.0.MarkovSwitchingMultifractal(8.MarkovSwitchingMultifractal(8.0 gamma() Return the vector of the kbar transitional probabilities.3) sage: msm.0.3) sage: msm.4.sigma() 1.4.m0() 1. Release 5.95. Markov Switching Multifractal model .simulations.MarkovSwitchingMultifractal(8..1.0.1.1.0. and returns a time series instead of a list of time series. 0.0.3) sage: msm. EXAMPLES: sage: msm = finance.3) sage: msm.0.MarkovSwitchingMultifractal(8.1.4. INPUT: •n – a positive integer.

0055.0.0084.1.278. b = 2.95.2. sigma = 0.0097.1. -0.4.12 sage: msm = finance.simulation(3) [0.11.0059. INPUT: •n – positive integer.262. and gamma_10 = 37 .simulation(5) [0.0141] simulations(n. k=1) Return k simulations of length n using this Markov switching multifractal model for n time steps. Release 5. -0.MarkovSwitchingMultifractal(8.3) sage: msm. •k – positive integer (default: 1).0110. -0. 0. OUTPUT: list – a list of TimeSeries objects.0.644. number of simulations.Sage Reference Manual: Quantitative Finance.0067] sage: msm.278. EXAMPLES: sage: cad_usd = finance. number of steps.11).262.0101. -0.0.1.MarkovSwitchingMultifractal(10. -0. cad_usd Markov switching multifractal model with m0 = 1.0.

Markov Switching Multifractal model .Sage Reference Manual: Quantitative Finance.12 38 Chapter 5. Release 5.

CHAPTER SIX INDICES AND TABLES • Index • Module Index • Search Page 39 .

12 40 Chapter 6. Indices and Tables . Release 5.Sage Reference Manual: Quantitative Finance.

New York: Springer. Stochastic Calculus for Finance II: Continuous-Time Models. S.BIBLIOGRAPHY [S] Shreve. 2004 41 .

12 42 Bibliography . Release 5.Sage Reference Manual: Quantitative Finance.

29 sage.stock.finance.fractal.finance.markov_multifractal.finance.option.PYTHON MODULE INDEX f sage. 23 sage.finance. 35 sage. 31 sage. 1 43 .time_series.finance.

12 44 Python Module Index . Release 5.Sage Reference Manual: Quantitative Finance.

6 D diffs() (sage. 6 close() (sage. 4 autoregressive_ﬁt() (in module sage. 8 F fft() (sage.time_series.TimeSeries method).ﬁnance.time_series.ﬁnance.MarkovSwitchingMultifractal method).ﬁnance.TimeSeries method).TimeSeries method).time_series.ﬁnance.ﬁnance.ﬁnance. 23 correlation() (sage.ﬁnance. 35 black_scholes() (in module sage. 3 autocorrelation() (sage.time_series.ﬁnance. 31 G gamma() (sage.TimeSeries method).ﬁnance.time_series.ﬁnance.TimeSeries method).markov_multifractal.ﬁnance. 7 extend() (sage.time_series.fractal). 31 fractional_gaussian_noise_simulation() (in module sage. 2 add_entries() (sage.TimeSeries method).ﬁnance.option).ﬁnance.TimeSeries method). 5 B b() (sage.time_series.TimeSeries method).time_series.TimeSeries method).ﬁnance.TimeSeries method).ﬁnance.TimeSeries method). 2 add_scalar() (sage.ﬁnance.MarkovSwitchingMultifractal method).ﬁnance.time_series.stock. 7 exponential_moving_average() (sage. 7 E exp() (sage.ﬁnance.time_series).markov_multifractal. 4 autoregressive_forecast() (sage. 29 C central_moment() (sage. 6 covariance() (sage. 36 45 . 5 clip_remove() (sage.time_series.time_series.Stock method).ﬁnance. 8 fractional_brownian_motion_simulation() (in module sage.INDEX A abs() (sage.ﬁnance.ﬁnance.TimeSeries method). 20 autoregressive_ﬁt() (sage.TimeSeries method).TimeSeries method).time_series.ﬁnance.TimeSeries method).TimeSeries method).time_series.time_series.time_series.ﬁnance.time_series. 3 autocovariance() (sage.fractal).

36 L list() (sage.Stock method).markov_multifractal.TimeSeries method).ﬁnance. 16 rescale() (sage.TimeSeries method).ﬁnance.TimeSeries method). 10 K kbar() (sage.TimeSeries method). 12 multifractal_cascade_random_walk_simulation() (in module sage.ﬁnance.TimeSeries method). 32 N numpy() (sage.TimeSeries method). 11 moment() (sage.ﬁnance.TimeSeries method).time_series.stock.time_series.fractal (module).TimeSeries method). 11 min() (sage.time_series.TimeSeries method).ﬁnance.time_series.TimeSeries method).time_series.ﬁnance.ﬁnance.TimeSeries method). 23 open() (sage.ﬁnance.ﬁnance. 31 46 Index .TimeSeries method). 36 google() (sage.ﬁnance.stock.Sage Reference Manual: Quantitative Finance.TimeSeries method). 26 MarkovSwitchingMultifractal (class in sage.time_series.Stock method).ﬁnance. 12 O OHLC (class in sage.time_series.ﬁnance.ﬁnance.time_series.TimeSeries method).MarkovSwitchingMultifractal method).ﬁnance.markov_multifractal.time_series.TimeSeries method).ﬁnance. 10 load_from_ﬁle() (sage.TimeSeries method). 11 mean() (sage. 35 max() (sage. 13 plot_histogram() (sage.ﬁnance.stock. 24 H histogram() (sage.fractal).ﬁnance.ﬁnance.markov_multifractal.Stock method). 14 R randomize() (sage.markov_multifractal).TimeSeries method).ﬁnance. 10 M m0() (sage.stock. 13 pow() (sage. 14 prod() (sage.ﬁnance.time_series.ﬁnance.ﬁnance.time_series.ﬁnance.time_series. 25 log() (sage.ﬁnance. 36 market_value() (sage.time_series.TimeSeries method). Release 5.time_series. 26 P plot() (sage.time_series.12 gamma_kbar() (sage.time_series.MarkovSwitchingMultifractal method).ﬁnance.time_series.time_series.ﬁnance. 16 reversed() (sage.stock). 9 hurst_exponent() (sage.ﬁnance. 9 I ifft() (sage.Stock method). 13 plot_candlestick() (sage.MarkovSwitchingMultifractal method).ﬁnance.time_series.ﬁnance. 14 range_statistic() (sage.ﬁnance. 16 S sage.TimeSeries method).

ﬁnance.time_series. 19 vector() (sage.ﬁnance.TimeSeries method).ﬁnance. 16 scale_time() (sage.markov_multifractal.time_series).ﬁnance.MarkovSwitchingMultifractal method).ﬁnance. 1 scale() (sage. 37 standard_deviation() (sage.TimeSeries method).TimeSeries method).time_series. 36 simple_moving_average() (sage. 36 simulations() (sage. 18 stationary_gaussian_simulation() (in module sage. 17 show() (sage.TimeSeries method). 27 Index 47 .TimeSeries method). 17 sigma() (sage. 1 U unpickle_time_series_v1() (in module sage. 19 T TimeSeries (class in sage. 23 sage.markov_multifractal.time_series). 29 sage.ﬁnance.markov_multifractal (module).time_series.MarkovSwitchingMultifractal method).option (module). 35 sage.Sage Reference Manual: Quantitative Finance.12 sage.stock).TimeSeries method).TimeSeries method).ﬁnance.time_series.MarkovSwitchingMultifractal method).ﬁnance. 18 simulation() (sage.ﬁnance.stock (module).ﬁnance.fractal). 18 sums() (sage.ﬁnance.markov_multifractal.Stock method).ﬁnance.ﬁnance. Release 5.time_series. 33 Stock (class in sage.ﬁnance.time_series.ﬁnance.ﬁnance.time_series. 19 Y yahoo() (sage.time_series (module).TimeSeries method).ﬁnance.ﬁnance.TimeSeries method).time_series.ﬁnance.ﬁnance.ﬁnance. 23 sum() (sage. 21 V variance() (sage.stock.time_series.

Sign up to vote on this title