-
-
Notifications
You must be signed in to change notification settings - Fork 397
/
time_series.pyx
2733 lines (2125 loc) · 85.1 KB
/
time_series.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Time Series
This is a module for working with discrete floating 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 range(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
"""
#*****************************************************************************
# Copyright (C) 2008 William Stein <wstein@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
cimport cython
from cpython.bytes cimport PyBytes_FromStringAndSize, PyBytes_AsString
from libc.math cimport exp, floor, log, pow, sqrt
from libc.string cimport memcpy
from cysignals.memory cimport sig_malloc, sig_free
from sage.structure.richcmp cimport rich_to_bool
cimport numpy as cnumpy
from sage.misc.randstate cimport randstate, current_randstate
from sage.rings.integer import Integer
from sage.rings.real_double import RDF
from sage.modules.vector_real_double_dense cimport Vector_real_double_dense
max_print = 10
digits = 4
cdef class TimeSeries:
def __cinit__(self):
"""
Create new empty uninitialized time series.
EXAMPLES:
This implicitly calls new::
sage: finance.TimeSeries([1,3,-4,5])
[1.0000, 3.0000, -4.0000, 5.0000]
"""
self._values = NULL
def __init__(self, values, bint initialize=True):
"""
Initialize new time series.
INPUT:
- ``values`` -- integer (number of values) or an iterable of
floats.
- ``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 fill in,
this can be way faster.
EXAMPLES:
This implicitly calls init::
sage: finance.TimeSeries([pi, 3, 18.2])
[3.1416, 3.0000, 18.2000]
Conversion from a NumPy 1-D array, which is very fast::
sage: v = finance.TimeSeries([1..5])
sage: w = v.numpy()
sage: finance.TimeSeries(w)
[1.0000, 2.0000, 3.0000, 4.0000, 5.0000]
Conversion from an n-dimensional NumPy array also works::
sage: import numpy
sage: v = numpy.array([[1,2], [3,4]], dtype=float); v
array([[1., 2.],
[3., 4.]])
sage: finance.TimeSeries(v)
[1.0000, 2.0000, 3.0000, 4.0000]
sage: finance.TimeSeries(v[:,0])
[1.0000, 3.0000]
sage: u = numpy.array([[1,2],[3,4]])
sage: finance.TimeSeries(u)
[1.0000, 2.0000, 3.0000, 4.0000]
For speed purposes we don't initialize (so value is garbage)::
sage: t = finance.TimeSeries(10, initialize=False)
"""
cdef Vector_real_double_dense z
cdef cnumpy.ndarray np
cdef double *np_data
cdef unsigned int j
if isinstance(values, (int, long, Integer)):
self._length = values
values = None
elif isinstance(values, Vector_real_double_dense) or isinstance(values, cnumpy.ndarray):
if isinstance(values, Vector_real_double_dense):
np = values._vector_numpy
else:
np = values
if np.ndim != 1:
np = np.reshape([np.size])
# Make the array be the correct type and have a C array
# for a data structure. If the array already is the
# correct type and has a C array, nothing is done, so this
# should be fast in the common case.
np = np.astype('double')
np = cnumpy.PyArray_GETCONTIGUOUS(np)
np_data = <double*> cnumpy.PyArray_DATA(np)
self._length = np.shape[0]
self._values = <double*> sig_malloc(sizeof(double) * self._length)
if self._values == NULL:
raise MemoryError
memcpy(self._values, np_data, sizeof(double)*self._length)
return
else:
values = [float(x) for x in values]
self._length = len(values)
self._values = <double*> sig_malloc(sizeof(double) * self._length)
if self._values == NULL:
raise MemoryError
if not initialize: return
cdef Py_ssize_t i
if values is not None:
for i from 0 <= i < self._length:
self._values[i] = values[i]
else:
for i from 0 <= i < self._length:
self._values[i] = 0
def __reduce__(self):
"""
Used in pickling time series.
EXAMPLES::
sage: v = finance.TimeSeries([1,-3.5])
sage: v.__reduce__()
(<cyfunction unpickle_time_series_v1 at ...>, (..., 2))
sage: loads(dumps(v)) == v
True
Note that dumping and loading with compress ``False`` is much faster,
though dumping with compress ``True`` can save a lot of space::
sage: v = finance.TimeSeries([1..10^5])
sage: loads(dumps(v, compress=False),compress=False) == v
True
"""
buf = PyBytes_FromStringAndSize(<char*>self._values, self._length*sizeof(double)/sizeof(char))
return unpickle_time_series_v1, (buf, self._length)
def __richcmp__(TimeSeries self, other, int op):
"""
Compare ``self`` and ``other``. This has the same semantics
as list comparison.
EXAMPLES::
sage: v = finance.TimeSeries([1,2,3]); w = finance.TimeSeries([1,2])
sage: v < w
False
sage: w < v
True
sage: v == v
True
sage: w == w
True
"""
cdef Py_ssize_t i
cdef double d
if not isinstance(other, TimeSeries):
return NotImplemented
_other = <TimeSeries>other
for i in range(min(self._length, _other._length)):
d = self._values[i] - _other._values[i]
if d:
return rich_to_bool(op, -1 if d < 0 else 1)
c = self._length - _other._length
if c:
return rich_to_bool(op, -1 if c < 0 else 1)
return rich_to_bool(op, 0)
def __dealloc__(self):
"""
Free up memory used by a time series.
EXAMPLES:
This tests ``__dealloc__`` implicitly::
sage: v = finance.TimeSeries([1,3,-4,5])
sage: del v
"""
sig_free(self._values)
def vector(self):
"""
Return real double vector whose entries are the values of this
time series. This is useful since vectors have standard
algebraic structure and play well with matrices.
OUTPUT:
A real double vector.
EXAMPLES::
sage: v = finance.TimeSeries([1..10])
sage: v.vector()
(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
"""
V = RDF**self._length
# A copy of the numpy array is made in the vector constructor
cdef Vector_real_double_dense x = Vector_real_double_dense(V, self.numpy(copy=False))
return x
def __repr__(self):
"""
Return string representation of ``self``.
EXAMPLES::
sage: v = finance.TimeSeries([1,3.1908439,-4,5.93932])
sage: v.__repr__()
'[1.0000, 3.1908, -4.0000, 5.9393]'
By default 4 digits after the decimal point are displayed. To
change this, change ``self.finance.time_series.digits``. ::
sage: sage.finance.time_series.digits = 2
sage: v.__repr__()
'[1.00, 3.19, -4.00, 5.94]'
sage: v
[1.00, 3.19, -4.00, 5.94]
sage: sage.finance.time_series.digits = 4
sage: v
[1.0000, 3.1908, -4.0000, 5.9393]
"""
return self._repr()
def _repr(self, prec=None):
"""
Print representation of a time series.
INPUT:
- ``prec`` -- (default: ``None``) number of digits of precision or
``None``. If ``None`` use the default
``sage.finance.time_series.digits``.
OUTPUT:
A string.
EXAMPLES::
sage: v = finance.TimeSeries([1,3.1908439,-4,5.93932])
sage: v._repr()
'[1.0000, 3.1908, -4.0000, 5.9393]'
sage: v._repr(10)
'[1.0000000000, 3.1908439000, -4.0000000000, 5.9393200000]'
sage: v._repr(2)
'[1.00, 3.19, -4.00, 5.94]'
"""
if prec is None: prec = digits
format = '%.' + str(prec) + 'f'
if len(self) > max_print:
v0 = self[:max_print//2]
v1 = self[-max_print//2:]
return '[' + ', '.join([format%x for x in v0]) + ' ... ' + \
', '.join([format%x for x in v1]) + ']'
else:
return '[' + ', '.join([format%x for x in self]) + ']'
def __len__(self):
"""
Return the number of entries in this time series.
OUTPUT:
Python integer.
EXAMPLES::
sage: v = finance.TimeSeries([1,3.1908439,-4,5.93932])
sage: v.__len__()
4
sage: len(v)
4
"""
return self._length
def __getitem__(self, i):
"""
Return i-th entry or slice of ``self``.
EXAMPLES::
sage: v = finance.TimeSeries([1,-4,3,-2.5,-4,3])
sage: v[2]
3.0
sage: v[-1]
3.0
sage: v[-10]
Traceback (most recent call last):
...
IndexError: TimeSeries index out of range
sage: v[5]
3.0
sage: v[6]
Traceback (most recent call last):
...
IndexError: TimeSeries index out of range
Some slice examples::
sage: v[-3:]
[-2.5000, -4.0000, 3.0000]
sage: v[-3:-1]
[-2.5000, -4.0000]
sage: v[::2]
[1.0000, 3.0000, -4.0000]
sage: v[3:20]
[-2.5000, -4.0000, 3.0000]
sage: v[3:2]
[]
Make a copy::
sage: v[:]
[1.0000, -4.0000, 3.0000, -2.5000, -4.0000, 3.0000]
Reverse the time series::
sage: v[::-1]
[3.0000, -4.0000, -2.5000, 3.0000, -4.0000, 1.0000]
"""
cdef Py_ssize_t start, stop, step, j
cdef TimeSeries t
if isinstance(i, slice):
start = 0 if (i.start is None) else i.start
stop = self._length if (i.stop is None) else i.stop
step = 1 if (i.step is None) else i.step
if start < 0:
start += self._length
if start < 0: start = 0
elif start >= self._length:
start = self._length - 1
if stop < 0:
stop += self._length
if stop < 0: stop = 0
elif stop > self._length:
stop = self._length
if start >= stop:
return new_time_series(0)
if step < 0:
step = -step
t = new_time_series((stop-start)/step)
for j from 0 <= j < (stop-start)/step:
t._values[j] = self._values[stop-1 - j*step]
elif step > 1:
t = new_time_series((stop-start)/step)
for j from 0 <= j < (stop-start)/step:
t._values[j] = self._values[j*step+start]
else:
t = new_time_series(stop-start)
memcpy(t._values, self._values + start, sizeof(double)*t._length)
return t
else:
j = i
if j < 0:
j += self._length
if j < 0:
raise IndexError("TimeSeries index out of range")
elif j >= self._length:
raise IndexError("TimeSeries index out of range")
return self._values[j]
def __setitem__(self, Py_ssize_t i, double x):
"""
Set the i-th entry of ``self`` to ``x``.
INPUT:
- i -- a nonnegative integer.
- x -- a float.
EXAMPLES::
sage: v = finance.TimeSeries([1,3,-4,5.93932]); v
[1.0000, 3.0000, -4.0000, 5.9393]
sage: v[0] = -5.5; v
[-5.5000, 3.0000, -4.0000, 5.9393]
sage: v[-1] = 3.2; v
[-5.5000, 3.0000, -4.0000, 3.2000]
sage: v[10]
Traceback (most recent call last):
...
IndexError: TimeSeries index out of range
sage: v[-5]
Traceback (most recent call last):
...
IndexError: TimeSeries index out of range
"""
if i < 0:
i += self._length
if i < 0:
raise IndexError("TimeSeries index out of range")
elif i >= self._length:
raise IndexError("TimeSeries index out of range")
self._values[i] = x
def __copy__(self):
"""
Return a copy of ``self``.
EXAMPLES::
sage: v = finance.TimeSeries([1,-4,3,-2.5,-4,3])
sage: v.__copy__()
[1.0000, -4.0000, 3.0000, -2.5000, -4.0000, 3.0000]
sage: copy(v)
[1.0000, -4.0000, 3.0000, -2.5000, -4.0000, 3.0000]
sage: copy(v) is v
False
"""
cdef Py_ssize_t i
cdef TimeSeries t = new_time_series(self._length)
memcpy(t._values, self._values , sizeof(double)*self._length)
return t
def __add__(left, right):
"""
Concatenate the time series ``self`` and ``right``.
.. NOTE::
To add a single number to the entries of a time series,
use the ``add_scalar`` method, and to add componentwise use
the ``add_entries`` method.
INPUT:
- ``right`` -- a time series.
OUTPUT:
A time series.
EXAMPLES::
sage: v = finance.TimeSeries([1,2,3]); w = finance.TimeSeries([1,2])
sage: v + w
[1.0000, 2.0000, 3.0000, 1.0000, 2.0000]
sage: v = finance.TimeSeries([1,2,-5]); v
[1.0000, 2.0000, -5.0000]
Note that both summands must be a time series::
sage: v + list(range(4))
Traceback (most recent call last):
...
TypeError: right operand must be a time series
sage: [1,5] + v
Traceback (most recent call last):
...
TypeError: left operand must be a time series
"""
if not isinstance(right, TimeSeries):
raise TypeError("right operand must be a time series")
if not isinstance(left, TimeSeries):
raise TypeError("left operand must be a time series")
cdef TimeSeries R = right
cdef TimeSeries L = left
cdef TimeSeries t = new_time_series(L._length + R._length)
memcpy(t._values, L._values, sizeof(double)*L._length)
memcpy(t._values + L._length, R._values, sizeof(double)*R._length)
return t
def __mul__(left, right):
"""
Multiply a time series by an integer n, which (like for lists)
results in the time series concatenated with itself n times.
.. NOTE::
To multiply all the entries of a time series by a single
scalar, use the ``scale`` method.
INPUT:
- ``left``, ``right`` -- an integer and a time series.
OUTPUT:
A time series.
EXAMPLES::
sage: v = finance.TimeSeries([1,2,-5]); v
[1.0000, 2.0000, -5.0000]
sage: v*3
[1.0000, 2.0000, -5.0000, 1.0000, 2.0000, -5.0000, 1.0000, 2.0000, -5.0000]
sage: 3*v
[1.0000, 2.0000, -5.0000, 1.0000, 2.0000, -5.0000, 1.0000, 2.0000, -5.0000]
sage: v*v # py2
Traceback (most recent call last):
...
TypeError: 'sage.finance.time_series.TimeSeries' object cannot be interpreted as an index
sage: v*v # py3
Traceback (most recent call last):
...
TypeError: 'sage.finance.time_series.TimeSeries' object cannot be interpreted as an integer
"""
cdef Py_ssize_t n, i
cdef TimeSeries T
if isinstance(left, TimeSeries):
T = left
n = right
else:
T = right
n = left
# Make n copies of T concatenated together
cdef TimeSeries v = new_time_series(T._length * n)
for i from 0 <= i < n:
memcpy(v._values + i*T._length, T._values, sizeof(double)*T._length)
return v
def autoregressive_fit(self,M):
r"""
This method fits the time series to an autoregressive process
of order ``M``. That is, we assume the process is given by
`X_t-\mu=a_1(X_{t-1}-\mu)+a_2(X_{t-1}-\mu)+\cdots+a_M(X_{t-M}-\mu)+Z_t`
where `\mu` is the mean of the process and `Z_t` is noise.
This method returns estimates for `a_1,\dots,a_M`.
The method works by solving the Yule-Walker equations
`\Gamma a =\gamma`, where `\gamma=(\gamma(1),\dots,\gamma(M))`,
`a=(a_1,\dots,a_M)` with `\gamma(i)` the autocovariance of lag `i`
and `\Gamma_{ij}=\gamma(i-j)`.
.. WARNING::
The input sequence is assumed to be stationary, which
means that the autocovariance `\langle y_j y_k \rangle` depends
only on the difference `|j-k|`.
INPUT:
- ``M`` -- an integer.
OUTPUT:
A time series -- the coefficients of the autoregressive process.
EXAMPLES::
sage: set_random_seed(0)
sage: v = finance.TimeSeries(10^4).randomize('normal').sums()
sage: F = v.autoregressive_fit(100)
sage: v
[0.6767, 0.2756, 0.6332, 0.0469, -0.8897 ... 87.6759, 87.6825, 87.4120, 87.6639, 86.3194]
sage: v.autoregressive_forecast(F)
86.0177285042...
sage: F
[1.0148, -0.0029, -0.0105, 0.0067, -0.0232 ... -0.0106, -0.0068, 0.0085, -0.0131, 0.0092]
sage: set_random_seed(0)
sage: t=finance.TimeSeries(2000)
sage: z=finance.TimeSeries(2000)
sage: z.randomize('normal',1)
[1.6767, 0.5989, 1.3576, 0.4136, 0.0635 ... 1.0057, -1.1467, 1.2809, 1.5705, 1.1095]
sage: t[0]=1
sage: t[1]=2
sage: for i in range(2,2000):
....: t[i]=t[i-1]-0.5*t[i-2]+z[i]
sage: c=t[0:-1].autoregressive_fit(2) #recovers recurrence relation
sage: c #should be close to [1,-0.5]
[1.0371, -0.5199]
"""
acvs = [self.autocovariance(i) for i in range(M+1)]
return autoregressive_fit(acvs)
def autoregressive_forecast(self, filter):
"""
Given the autoregression coefficients as outputted by the
``autoregressive_fit`` command, compute the forecast for the next
term in the series.
INPUT:
- ``filter`` -- a time series outputted by the ``autoregressive_fit``
command.
EXAMPLES::
sage: set_random_seed(0)
sage: v = finance.TimeSeries(100).randomize('normal').sums()
sage: F = v[:-1].autoregressive_fit(5); F
[1.0019, -0.0524, -0.0643, 0.1323, -0.0539]
sage: v.autoregressive_forecast(F)
11.7820298611...
sage: v
[0.6767, 0.2756, 0.6332, 0.0469, -0.8897 ... 9.2447, 9.6709, 10.4037, 10.4836, 12.1960]
"""
cdef TimeSeries filt
if isinstance(filter, TimeSeries):
filt = filter
else:
filt = TimeSeries(filter)
cdef double f = 0
cdef Py_ssize_t i
for i from 0 <= i < min(self._length, filt._length):
f += self._values[self._length - i - 1] * filt._values[i]
return f
def reversed(self):
"""
Return new time series obtain from this time series by
reversing the order of the entries in this time series.
OUTPUT:
A time series.
EXAMPLES::
sage: v = finance.TimeSeries([1..5])
sage: v.reversed()
[5.0000, 4.0000, 3.0000, 2.0000, 1.0000]
"""
cdef Py_ssize_t i, n = self._length-1
cdef TimeSeries t = new_time_series(self._length)
for i from 0 <= i < self._length:
t._values[i] = self._values[n - i]
return t
def extend(self, right):
"""
Extend this time series by appending elements from the iterable
``right``.
INPUT:
- ``right`` -- iterable that can be converted to a time series.
EXAMPLES::
sage: v = finance.TimeSeries([1,2,-5]); v
[1.0000, 2.0000, -5.0000]
sage: v.extend([-3.5, 2])
sage: v
[1.0000, 2.0000, -5.0000, -3.5000, 2.0000]
"""
if not isinstance(right, TimeSeries):
right = TimeSeries(right)
if not right:
return
cdef TimeSeries T = right
cdef double* z = <double*> sig_malloc(sizeof(double)*(self._length + T._length))
if z == NULL:
raise MemoryError
memcpy(z, self._values, sizeof(double)*self._length)
memcpy(z + self._length, T._values, sizeof(double)*T._length)
sig_free(self._values)
self._values = z
self._length = self._length + T._length
def list(self):
"""
Return list of elements of ``self``.
EXAMPLES::
sage: v = finance.TimeSeries([1,-4,3,-2.5,-4,3])
sage: v.list()
[1.0, -4.0, 3.0, -2.5, -4.0, 3.0]
"""
cdef Py_ssize_t i
return [self._values[i] for i in range(self._length)]
def log(self):
"""
Return new time series got by taking the logarithms of all the
terms in the time series.
OUTPUT:
A new time series.
EXAMPLES:
We exponentiate then log a time series and get back
the original series::
sage: v = finance.TimeSeries([1,-4,3,-2.5,-4,3]); v
[1.0000, -4.0000, 3.0000, -2.5000, -4.0000, 3.0000]
sage: v.exp()
[2.7183, 0.0183, 20.0855, 0.0821, 0.0183, 20.0855]
sage: v.exp().log()
[1.0000, -4.0000, 3.0000, -2.5000, -4.0000, 3.0000]
Log of 0 gives ``-inf``::
sage: finance.TimeSeries([1,0,3]).log()[1]
-inf
"""
cdef Py_ssize_t i
cdef TimeSeries t = new_time_series(self._length)
for i from 0 <= i < self._length:
t._values[i] = log(self._values[i])
return t
def exp(self):
"""
Return new time series got by applying the exponential map to
all the terms in the time series.
OUTPUT:
A new time series.
EXAMPLES::
sage: v = finance.TimeSeries([1..5]); v
[1.0000, 2.0000, 3.0000, 4.0000, 5.0000]
sage: v.exp()
[2.7183, 7.3891, 20.0855, 54.5982, 148.4132]
sage: v.exp().log()
[1.0000, 2.0000, 3.0000, 4.0000, 5.0000]
"""
cdef Py_ssize_t i
cdef TimeSeries t = new_time_series(self._length)
for i from 0 <= i < self._length:
t._values[i] = exp(self._values[i])
return t
def abs(self):
"""
Return new time series got by replacing all entries
of ``self`` by their absolute value.
OUTPUT:
A new time series.
EXAMPLES::
sage: v = finance.TimeSeries([1,3.1908439,-4,5.93932])
sage: v
[1.0000, 3.1908, -4.0000, 5.9393]
sage: v.abs()
[1.0000, 3.1908, 4.0000, 5.9393]
"""
cdef Py_ssize_t i
cdef TimeSeries t = new_time_series(self._length)
for i from 0 <= i < self._length:
t._values[i] = self._values[i] if self._values[i] >= 0 else -self._values[i]
return t
def diffs(self, Py_ssize_t k = 1):
r"""
Return the new time series got by taking the differences of
successive terms in the time series. So if ``self`` is the time
series `X_0, X_1, X_2, \dots`, then this function outputs the
series `X_1 - X_0, X_2 - X_1, \dots`. The output series has one
less term than the input series. If the optional parameter
`k` is given, return `X_k - X_0, X_{2k} - X_k, \dots`.
INPUT:
- ``k`` -- positive integer (default: 1)
OUTPUT:
A new time series.
EXAMPLES::
sage: v = finance.TimeSeries([5,4,1.3,2,8]); v
[5.0000, 4.0000, 1.3000, 2.0000, 8.0000]
sage: v.diffs()
[-1.0000, -2.7000, 0.7000, 6.0000]
"""
if k != 1:
return self.scale_time(k).diffs()
cdef Py_ssize_t i
cdef TimeSeries t = new_time_series(self._length - 1)
for i from 1 <= i < self._length:
t._values[i-1] = self._values[i] - self._values[i-1]
return t
def scale_time(self, Py_ssize_t k):
r"""
Return the new time series at scale ``k``. If the input
time series is `X_0, X_1, X_2, \dots`, then this function
returns the shorter time series `X_0, X_k, X_{2k}, \dots`.
INPUT:
- ``k`` -- a positive integer.
OUTPUT:
A new time series.
EXAMPLES::
sage: v = finance.TimeSeries([5,4,1.3,2,8,10,3,-5]); v
[5.0000, 4.0000, 1.3000, 2.0000, 8.0000, 10.0000, 3.0000, -5.0000]
sage: v.scale_time(1)
[5.0000, 4.0000, 1.3000, 2.0000, 8.0000, 10.0000, 3.0000, -5.0000]
sage: v.scale_time(2)
[5.0000, 1.3000, 8.0000, 3.0000]
sage: v.scale_time(3)
[5.0000, 2.0000]
sage: v.scale_time(10)
[]
A series of odd length::
sage: v = finance.TimeSeries([1..5]); v
[1.0000, 2.0000, 3.0000, 4.0000, 5.0000]
sage: v.scale_time(2)
[1.0000, 3.0000, 5.0000]
TESTS::
sage: v.scale_time(0)
Traceback (most recent call last):
...
ValueError: k must be positive
sage: v.scale_time(-1)
Traceback (most recent call last):
...
ValueError: k must be positive
"""
if k <= 0:
raise ValueError("k must be positive")
cdef Py_ssize_t i, n
n = self._length/k
if self._length % 2:
n += 1
cdef TimeSeries t = new_time_series(n) # in C / is floor division.
for i from 0 <= i < n:
t._values[i] = self._values[i*k]
return t
cpdef rescale(self, double s):
"""
Change ``self`` by multiplying every value in the series by ``s``.
INPUT:
- ``s`` -- a float.
EXAMPLES::
sage: v = finance.TimeSeries([5,4,1.3,2,8,10,3,-5]); v
[5.0000, 4.0000, 1.3000, 2.0000, 8.0000, 10.0000, 3.0000, -5.0000]
sage: v.rescale(0.5)
sage: v
[2.5000, 2.0000, 0.6500, 1.0000, 4.0000, 5.0000, 1.5000, -2.5000]
"""
for i from 0 <= i < self._length:
self._values[i] = self._values[i] * s
def scale(self, double s):
"""
Return new time series obtained by multiplying every value in the
series by ``s``.
INPUT:
- ``s`` -- a float.
OUTPUT:
A new time series with all values multiplied by ``s``.
EXAMPLES::
sage: v = finance.TimeSeries([5,4,1.3,2,8,10,3,-5]); v
[5.0000, 4.0000, 1.3000, 2.0000, 8.0000, 10.0000, 3.0000, -5.0000]
sage: v.scale(0.5)
[2.5000, 2.0000, 0.6500, 1.0000, 4.0000, 5.0000, 1.5000, -2.5000]
"""
cdef TimeSeries t = new_time_series(self._length)
for i from 0 <= i < self._length:
t._values[i] = self._values[i] * s
return t
def add_scalar(self, double s):
"""
Return new time series obtained by adding a scalar to every
value in the series.
.. NOTE::
To add componentwise, use the ``add_entries`` method.
INPUT:
- ``s`` -- a float.
OUTPUT:
A new time series with ``s`` added to all values.
EXAMPLES::
sage: v = finance.TimeSeries([5,4,1.3,2,8,10,3,-5]); v
[5.0000, 4.0000, 1.3000, 2.0000, 8.0000, 10.0000, 3.0000, -5.0000]
sage: v.add_scalar(0.5)
[5.5000, 4.5000, 1.8000, 2.5000, 8.5000, 10.5000, 3.5000, -4.5000]
"""
cdef TimeSeries t = new_time_series(self._length)
for i from 0 <= i < self._length:
t._values[i] = self._values[i] + s
return t
def add_entries(self, t):
"""
Add corresponding entries of ``self`` and ``t`` together,
extending either ``self`` or ``t`` by 0's if they do
not have the same length.
.. NOTE::
To add a single number to the entries of a time series,
use the ``add_scalar`` method.
INPUT:
- ``t`` -- a time series.
OUTPUT:
A time series with length the maxima of the lengths of
``self`` and ``t``.
EXAMPLES::
sage: v = finance.TimeSeries([1,2,-5]); v
[1.0000, 2.0000, -5.0000]
sage: v.add_entries([3,4])
[4.0000, 6.0000, -5.0000]
sage: v.add_entries(v)
[2.0000, 4.0000, -10.0000]
sage: v.add_entries([3,4,7,18.5])
[4.0000, 6.0000, 2.0000, 18.5000]
"""