-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpjb-bourse.el
1412 lines (1181 loc) · 51.2 KB
/
pjb-bourse.el
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
;;;; -*- mode:emacs-lisp;coding:utf-8 -*-
;;;;******************************************************************************
;;;;FILE: pjb-bourse.el
;;;;LANGUAGE: emacs lisp
;;;;SYSTEM: emacs
;;;;USER-INTERFACE: emacs
;;;;DESCRIPTION
;;;;
;;;; This module exports
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon
;;;;MODIFICATIONS
;;;; 199?/??/?? <PJB> Creation.
;;;;BUGS
;;;;LEGAL
;;;; LGPL
;;;;
;;;; Copyright Pascal J. Bourguignon 1990 - 2011
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 2 of the License, or (at your option) any later version.
;;;;
;;;; This library is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
;;;;
;;;;******************************************************************************
(require 'pjb-cl)
(require 'pjb-list)
(require 'pjb-utilities)
(require 'pjb-euro)
(require 'pjb-strings)
(require 'pjb-object)
(provide 'pjb-bourse)
(defun debug-tag () nil)
(defun percent (num denum)
(if (or (null denum) (= denum 0.0))
0.0
(* 100.0 (/ num (+ 0.0 denum)))))
(defun class-attributes (c)
(aref (get c 'eieio-class-definition) class-public-a))
;;------------------------------------------------------------------------------
;;
;; +-----------+ +-----------+ +----------------+
;; | Portfolio |---------------| Line |---------------| Position |
;; +-----------+ 0,1 0,n +-----------+ 0,1 0,n +----------------+
;; | | symbol | | buy-quantity |
;; | | devise | | sell-quantity |
;; | +-----------+ | buy-amount |
;; | | sell-ammount |
;; | | comissions |
;; | | nb-operations |
;; | n | open-date |
;; +----------------+ +---------------+ | last-date |
;; | DeviseAccount | | BuySellOp | | /state |
;; +----------------+ +---------------+ +----------------+
;; |
;; / \
;; +------+---+------+
;; | |
;; +----------+ +-----------+
;; | BuyOp | | SellOp |
;; +----------+ +-----------+
;;
;;------------------------------------------------------------------------------
;;
;;
;; +-------------------------------------------+
;; | Position |
;; +-------------------------------------------+
;; | buy-amount |
;; | buy-quantity |
;; | sell-ammount |
;; | sell-quantity |
;; | comissions |
;; | nb-operations |
;; | open-date |
;; | last-date |
;; +-------------------------------------------+
;; | state |
;; | is-closed |
;; | is-running |
;; | update-with-operation(operation) |
;; | amount-invested |
;; | quantity |
;; | gain |
;; | paid-per-share |
;; | owner-line |
;; +-------------------------------------------+
;; 1,n | positions {ordered}
;; |
;; |
;; |
;; |
;; 0,1 | owner-line
;; +-------------------------------------------+
;; | Line |
;; +-------------------------------------------+
;; | symbol |
;; | devise |
;; +-------------------------------------------+
;; | buy-amount --> |
;; | buy-quantity --> |
;; | sell-amount --> |
;; | sell-quantity --> |
;; | comission --> |
;; | nb-operations --> |
;; | |
;; | amount-invested --> |
;; | quantity --> |
;; | gain --> |
;; | paid-per-share --> |
;; | |
;; | last-position |
;; | open-new-position |
;; | |
;; | average-comission |
;; | total-buy-amount |
;; | total-gain |
;; | update-with-operation |
;; +-------------------------------------------+
;; 1,1 [ symbol ] lines
;; |
;; |
;; |
;; |
;; 0,1 |
;; +-------------------------------------------+
;; | Portfolio |
;; +-------------------------------------------+
;; | operations |
;; | lines |
;; | total-credit |
;; | total-debit |
;; | total-comissions |
;; | total-operations |
;; +-------------------------------------------+
;; | add-line(line) |
;; | add-operation(operation) |
;; | line-with-symbol(symbol) |
;; | sort-portfolio-lines |
;; | total-liquidite |
;; | total-opcom |
;; +-------------------------------------------+
;;;---------------------------------------------------------------------
;;;--- DeviseAccount ---------------------------------------------------
;;;---------------------------------------------------------------------
(defclass DeviseAccount (PjbObject)
((amounts
:initform nil
:accessor amounts
:type list
:documentation
"The alist where the (devise . amount) are stored."))
(:documentation
"A DeviseAccount is an account where the amount is stored separately
for each devise [See: pjb-euro]."))
(defmethod* amount-at-devise ((self DeviseAccount) devise)
"Retourne le montant de la devise indiquée dans le devise-account.
Voir account-valuation pour la valeur totale du devise-account."
(cdr (assoc devise (amounts self))))
(defmethod* devises ((self DeviseAccount))
"Retourne la liste des devises dans le compte."
(mapcar 'car (amounts self)))
(defmethod* account-valuation ((self DeviseAccount) devise)
"Retourne la valeur du devise-account dans la devise indiquée.
Utilise pjb-euro, et nécessite pour les devises flottantes, des cours à jour."
(let ((total-euro 0.0))
(mapc (lambda (a)
(setq total-euro (+ total-euro
(euro-from-value (cdr a) (car a)))))
(amounts self))
(euro-to-value devise total-euro)))
(defmethod* account-add ((self DeviseAccount) devise montant)
"Additionne au devise-account le montant indiqué dans la devise indiquée.
Pour additionner deux comptes, utiliser account-add-account.
Return: self."
(let ((ligne (assoc devise (amounts self))))
(if ligne
(setcdr ligne (+ (cdr ligne) montant))
(setf (slot-value self 'amounts)
(cons (cons devise montant) (amounts self)))))
self)
(defmethod* account-sub ((self DeviseAccount) devise montant)
"Soustrait du devise-account le montant indiqué dans la devise indiquée.
Pour soustraire deux comptes, utiliser account-sub-account.
Return: self."
(let ((ligne (assoc devise (amounts self))))
(if ligne
(setcdr ligne (- (cdr ligne) montant))
(setf (slot-value self 'amounts)
(cons (cons devise (- 0 montant)) (amounts self)))))
self)
(defmethod* account-mul ((self DeviseAccount) facteur)
"Multiplie le devise-account par le facteur.
RETURN: self"
(mapc (lambda (devise-amount)
(setcdr devise-amount (* (cdr devise-amount) facteur)))
(amounts self))
self)
(defun compare-sequal-sn-c (a b)
"Interne DeviseAccount."
(string-equal (symbol-name (car a))
(symbol-name (car b))))
(defun compare-slessp-sn-c (a b)
"Interne DeviseAccount."
(string-lessp (symbol-name (car a))
(symbol-name (car b))))
(defun compare-slessp-sn (a b)
"Interne DeviseAccount."
(string-lessp (symbol-name a)
(symbol-name b)))
(defmethod* sorted-accounts ((self DeviseAccount))
"Returns a list of assoc (devise . amount) sorted on the devise."
(sort (copy-sequence (slot-value self 'amounts)) 'compare-slessp-sn-c))
(defmethod* account-operation-account ((self DeviseAccount)
(other DeviseAccount) op-lambda)
"Retourne un devise-account résultat de l'opération op-lambda sur
les paires de montants de même devise, et ajoute les montants-devise
restants."
(let ((sort-a (sorted-accounts self))
(sort-b (sorted-accounts other))
(result nil)
(oresult (make-instance DeviseAccount)))
(while (or sort-a sort-b)
(let ((a (car sort-a)) (b (car sort-b)))
(setq result
(cons
(cond
((and a b (compare-sequal-sn-c a b)) ;; les deux sont égaux
(setq sort-a (cdr sort-a) ;; on les passe
sort-b (cdr sort-b))
;; resultat : l'operation appliquee sur eux.
(cons (car a) (funcall op-lambda (cdr a) (cdr b))))
((or (null b)
(compare-slessp-sn-c a b)) ;; lequel est le plus petit ?
(setq sort-a (cdr sort-a)) ;; on le passe.
;; resultat : l'operation appliquee sur lui.
(cons (car a) (funcall op-lambda (cdr a) 0.0)))
(t ;; lequel reste ?
(setq sort-b (cdr sort-b)) ;; on le passe.
;; resultat : l'operation appliquee sur lui.
(cons (car b) (funcall op-lambda 0.0 (cdr b)))))
result))))
(setf (slot-value oresult 'amounts) result)
oresult))
(defmethod* account-add-account ((self DeviseAccount) (other DeviseAccount))
"Additionne les deux comptes-devises."
(account-operation-account self other '+))
(defmethod* account-sub-account ((self DeviseAccount) (other DeviseAccount))
"Soustrait le devise-account compte-b du devise-account compte-a."
(account-operation-account self other '-))
;;;END DeviseAccount ---------------------------------------------------
;;;---------------------------------------------------------------------
;;;---------------------------------------------------------------------
;;;--- Operation -------------------------------------------------------
;;;---------------------------------------------------------------------
(defclass Operation (PjbObject)
((date
:initform nil
:initarg :date
:accessor date
:type symbol
:documentation "Date of the Operation.
This is a symbol with the format: YYYY-MM-DD.")
(symbol
:initform nil
:initarg :symbol
:accessor symbol
:type symbol
:documentation "The ticker symbol of the shares handled in this operation."))
(:documentation "
Reification of a single operation.
This is an abstract class. Concrete subclasses may be buy or sell operations
or split operations.
Instances of theses subclasses are made by make-operation.
"))
;; ---------- --- ---------- ---- -------- ------ ------ ------------
;; DATE DEV MONTANT QUTE COURS FRAIS FRAIS% SYMBOL
;; YYYY-MM-DD --ERROR: OPERATION CLASS CANNOT DISPLAY-- SSSSSSSSSSSS
;; YYYY-MM-DD DEV 0000000.00 0000 00000.00 000.00 00.00% SSSSSSSSSSSS
;; YYYY-MM-DD SPLIT 0000 NEW SHARES FOR 0000 OLD SHARES SSSSSSSSSSSS
(defconstant operation-format-bad
"%-10s --ERROR: OPERATION CLASS CANNOT DISPLAY-- %s"
"Format to print an abstract operation.")
(defconstant operation-format-buy-sell
"%-10s %-3s %10.2f %4d %8.2f %6.2f %5.2f%% %s"
"Format to print a buy or sell operation.")
(defconstant operation-format-split
"%-10s SPLIT %4d NEW SHARES FOR %4d OLD SHARES %s"
"Format to print a split operation.")
(defmethod* as-string ((self Operation))
"RETURN: A human readable string representing the operation."
(format operation-format-bad (date self) (symbol self)))
;;;END Operation -------------------------------------------------------
;;;---------------------------------------------------------------------
;;;---------------------------------------------------------------------
;;;--- Position --------------------------------------------------------
;;;---------------------------------------------------------------------
(defclass Position (PjbObject)
((buy-quantity
:initform 0
:initarg :buy-quantity
:accessor buy-quantity
:type number
:documentation "Total number of share bought.
buy-quantity>=0.")
(buy-amount
:initform 0.0
:initarg :buy-amount
:accessor buy-amount
:type number
:documentation "Total amount paid.
This includes the comission paid for the buys.
(Expressed in the devise of the line).")
(sell-quantity
:initform 0
:initarg :sell-quantity
:accessor sell-quantity
:type number
:documentation "Total number of share sold.
sell-quantity>=0.")
(sell-amount
:initform 0.0
:initarg :sell-amount
:accessor sell-amount
:type number
:documentation "Total amount received for sells.
This includes the deducted comission paid for the sells.
(Expressed in the devise of the line).")
(comission
:initform 0.0
:initarg :comission
:accessor comission
:type number
:documentation "Total comissions paid.
(Expressed in the devise of the line).")
(nb-operations
:initform 0
:initarg :nb-operations
:accessor nb-operations
:type number
:documentation "Number of operations done.")
(open-date
:initform '0000-00-00
:initarg :open-date
:accessor open-date
:type symbol
:documentation "Date of the first operation.")
(last-date
:initform '0000-00-00
:initarg :last-date
:accessor last-date
:type symbol
:documentation "Date of the last operation.")
(owner-line
:initform nil
:initarg :owner-line
:accessor owner-line
:documentation "The Line instance that owns this position."))
(:documentation "
Reification of a position. This is the summary of a range of
operations where the number of posseded shares only comes to 0 when
the position is closed. A Line posses several successive Position
instances, of which all but the last must be closed.
"))
(defmethod* apply-to-position ((self Operation) (position Position))
"NOTE: This method must be overriden by subclasses.
PRE: (equal (symbol self) (symbol (owner-line position)))
DO: Apply self operation onto the position."
(error "Method apply-to-line must be overriden by subclasses."))
(defmethod* as-string ((self Position))
"RETURN: a human readable string describing the position."
;; (insert (apply 'concat
;; (mapcar (lambda (x) (format "(format \" %-20s=%%S\\n\" (%s self))\n"
;; (symbol-name x) (symbol-name x)))
;; (class-attributes Position))))
(concat
"Position {\n"
(format " buy-quantity =%S\n" (buy-quantity self))
(format " buy-amount =%S\n" (buy-amount self))
(format " sell-quantity =%S\n" (sell-quantity self))
(format " sell-amount =%S\n" (sell-amount self))
(format " comission =%S\n" (comission self))
(format " nb-operations =%S\n" (nb-operations self))
;; (format " open-date =%S\n" (open-date self))
;; (format " last-date =%S\n" (last-date self))
;; (format " owner-line =%S\n" (owner-line self))
"}\n"))
(defmethod* state ((self Position))
"RETURN: the state of the Position.
Either: 'newborn when no operation has been included;
'running when operations have been included,
but (quantity self) never has been 0;
'closed once (quantity self) reach 0."
(cond
((= 0 (nb-operations self)) 'newborn)
((= 0 (quantity self)) 'closed)
(t 'running)))
(defmethod* is-closed ((self Position))
"RETURN: Whether (equal (state self) 'closed)."
(equal (state self) 'closed))
(defmethod* is-running ((self Position))
"RETURN: Whether (equal (state self) 'running)."
(equal (state self) 'running))
(defmethod* update-with-operation ((self Position) (operation Operation))
"PRE: (not (is-closed self))
DO: Updates this position with the given operation.
RETURN: self."
(if (equal 'closed (state self))
(let ((msg (format "POSITION FOR %s IS CLOSED.\n"
(symbol (owner-line self)))))
(printf msg)
(error msg)))
(if (equal (state self) 'newborn)
(setf (slot-value self 'open-date) (date operation)))
(setf (slot-value self 'last-date) (date operation))
(apply-to-position operation self)
(setf (slot-value self 'nb-operations) (1+ (nb-operations self)))
self)
(defmethod* amount-invested ((self Position))
"RETURN: The amount mobilized on this position.
amount-invested = (- (buy-amount self) (sell-amount self)).
When is-closed, this is the lost (if positive)
or the gain (if negative)."
(- (buy-amount self) (sell-amount self)))
(defmethod* quantity ((self Position))
"RETURN: The number of share remaining in the position.
quantity = (- (buy-quantity self) (sell-quantity self))"
(- (buy-quantity self) (sell-quantity self)))
(defmethod* gain ((self Position))
"RETURN: The gain on this position, negative if there's a loss.
This is valid only when the position is closed:
is-closed => gain = (- sell-amount buy-amount)
(not is-closed) => gain = 0.0"
(if (is-closed self)
(- (sell-amount self) (buy-amount self))
0.0))
(defmethod* paid-per-share ((self Position))
"RETURN: The cost of the remaining shares.
This is valid only when running.
when the position is not running, or if the amount-invested is negative,
then paid-per-share = 0.0
else paid-per-share = (/ (amount-invested self) quantity)."
(if (equal 'running (state self))
(if (<= (amount-invested self) 0.0)
;; We already have a gain.
0.0
(/ (amount-invested self) (quantity self)))
0.0))
;;;END Position --------------------------------------------------------
;;;---------------------------------------------------------------------
;;;---------------------------------------------------------------------
;;;--- SplitOp ---------------------------------------------------------
;;;---------------------------------------------------------------------
(defclass SplitOp (Operation)
(
(oldQuantity
:initform 0
:initarg :oldQuantity
:accessor oldQuantity
:type number
:documentation "Number of old shares.
oldQuantity>=0")
(newQuantity
:initform 0
:initarg :newQuantity
:accessor newQuantity
:type number
:documentation "Number of new shares.
newQuantity>=0")
)
(:documentation "
A split operation.
This kind of operation replaces oldQuantity shares by newQuantity shares.
An allocation of new (free) shares can be modelized by a split from the
oldQuantity required to the newQuantity = number of new share + oldQuantity.
"))
(defmethod* apply-to-position ((self SplitOp) (position Position))
"NOTE: This method must be overriden by subclasses.
PRE: (equal (symbol self) (symbol (owner-line position)))
DO: Apply this split operation onto the position."
;;DEBUG;; (message (format "SplitOp::apply-to-position \n split=%S \n%s" self (as-string position)))
;; TODO: This should go into a Position::split method.
(setf (slot-value position 'sell-quantity)
(/ (* (sell-quantity position) (newQuantity self)) (oldQuantity self)))
(setf (slot-value position 'buy-quantity)
(/ (* (buy-quantity position) (newQuantity self)) (oldQuantity self)))
;;DEBUG;; (message (format "%s\n" (as-string position)))
)
(defmethod* as-string ((self SplitOp))
"RETURN: A human readable string representing the operation."
(format operation-format-split
(date self) (newQuantity self) (oldQuantity self) (symbol self)))
;;;END SplitOp ---------------------------------------------------------
;;;---------------------------------------------------------------------
;;;---------------------------------------------------------------------
;;;--- BuySellOp -------------------------------------------------------
;;;---------------------------------------------------------------------
(defclass BuySellOp (Operation)
(
(quantity
:initform 0
:initarg :quantity
:accessor quantity
:type number
:documentation "Number of share bought or sold.
quantity>=0")
(devise
:initform nil
:initarg :devise
:accessor devise
:type symbol
:documentation "The devise symbol (see package pjb-euro).")
(price
:initform 0.0
:initarg :price
:accessor price
:type number
:documentation "The price for one share on this operation.
The price is expressed in the devise of the operation.
price>0.0")
(comission
:initform 0.0
:initarg :comission
:accessor comission
:type number
:documentation "The comission value for this operation.
The comission is expressed in the devise of the operation.
comission>=0.0")
)
(:documentation "
Reification of a single buy or sell operation.
This is an abstract class. Concrete subclasses are BuyOp and SellOp.
Instances of theses subclasses are made by make-operation.
"))
(defmethod* amount-base ((self BuySellOp))
"RETURN: The total amount of this operation, excluding the comission."
(* (quantity self) (price self)))
(defmethod* comission-percent ((self BuySellOp))
"RETURN: The percentage the comission represents relatively to the share value."
(percent (comission self) (amount-base self)))
(defmethod* amount-paid ((self BuySellOp))
"RETURN: The amount paid for the operation. Negative when it's a sell operation."
(+ (* (signed-quantity self) (price self)) (comission self)))
(defmethod* signed-quantity ((self BuySellOp))
"RETURN: The quantity.
NOTE: Should be overriden by sell operation to return the opposite."
(quantity self))
(defmethod* as-string ((self BuySellOp))
"RETURN: A human readable string representing the operation."
(format operation-format-buy-sell
(date self) (devise self)
(amount-paid self) (signed-quantity self) (price self)
(comission self) (comission-percent self) (symbol self)))
;;;END SellBuyOp -------------------------------------------------------
;;;---------------------------------------------------------------------
;;;---------------------------------------------------------------------
;;;--- BuyOp -----------------------------------------------------------
;;;---------------------------------------------------------------------
(defclass BuyOp (BuySellOp) ()
(:documentation "
Reification of a buy operation.
"))
(defmethod* amount ((self BuySellOp))
"RETURN: The total amount aid of this operation, including the comission.
For buys, it's quantity*price+comission."
(+ (* (quantity self) (price self)) (comission self)))
(defmethod* apply-to-position ((self BuyOp) (position Position))
"PRE: (equal (symbol self) (symbol (owner-line position))),
(equal (devise self) (devise (owner-line position)))
DO: Apply this buy operation onto the position."
(if (not (equal (devise (owner-line position)) (devise self)))
(let ((msg (format "DEVISE MISMATCH WITH LINE FOR %s: %s %s\n"
(symbol self)
(devise (owner-line position)) (devise self))))
(printf msg)
(error msg)))
;;DEBUG;; (message (format "BuyOp::apply-to-position \n buy=%S \n%s" self (as-string position)))
;; TODO: This should go into a Position::buy method.
(setf (slot-value position 'buy-quantity) (+ (buy-quantity position) (quantity self)))
(setf (slot-value position 'buy-amount) (+ (buy-amount position) (amount-paid self)))
(setf (slot-value position 'comission) (+ (comission position) (comission self)))
;;DEBUG;; (message (format "%s\n" (as-string position)))
)
;;;END BuyOp -----------------------------------------------------------
;;;---------------------------------------------------------------------
;;;---------------------------------------------------------------------
;;;--- SellOp ----------------------------------------------------------
;;;---------------------------------------------------------------------
(defclass SellOp (BuySellOp) ()
(:documentation "
Reification of a sell operation.
"))
(defmethod* amount ((self BuySellOp))
"RETURN: The total amount paid for this operation, including the comission.
For sells, it's quantity*price-comission"
(- (* (quantity self) (price self)) (comission self)))
(defmethod* signed-quantity ((self SellOp))
"RETURN: The opposite of the quantity, to denote a sell."
(- 0 (quantity self)))
(defmethod* apply-to-position ((self SellOp) (position Position))
"PRE: (equal (symbol self) (symbol (owner-line position))),
(equal (devise self) (devise (owner-line position)))
DO: Apply this sell operation onto the position."
(if (not (equal (devise (owner-line position)) (devise self)))
(let ((msg (format "DEVISE MISMATCH WITH LINE FOR %s: %s %s\n"
(symbol self)
(devise (owner-line position)) (devise self))))
(printf msg)
(error msg)))
;;DEBUG;; (message (format "Sell::apply-to-position \n buy=%S \n%s" self (as-string position)))
;; TODO: This should go into a Position::sell method.
(setf (slot-value position 'sell-quantity) (+ (sell-quantity position) (quantity self)))
(setf (slot-value position 'sell-amount) (- (sell-amount position) (amount-paid self)))
;; amount-paid < 0 == sell-amount is incremented.
;; (Note if quantity*price < commission then amount-paid > 0)
(setf (slot-value position 'comission) (+ (comission position) (comission self)))
;;DEBUG;; (message (format "%s\n" (as-string position)))
)
;;;END SellOp ----------------------------------------------------------
;;;---------------------------------------------------------------------
(defun make-operation (attributes)
"RETURN: either a new BuyOp (quantity>=0)
or a new SellOp (quantity<0) instance built from the given attributes."
(if (eq 'SPLIT (nth 1 attributes))
(let ((date (nth 0 attributes))
(newQuantity (nth 2 attributes))
(oldQuantity (nth 3 attributes))
(symbol (nth 4 attributes)))
(make-instance (class-constructor SplitOp)
(format "%s-%s" symbol date)
'date date
'newQuantity newQuantity
'oldQuantity oldQuantity
'symbol symbol))
(let ((date (nth 0 attributes))
(quantity (nth 1 attributes))
(devise (nth 2 attributes))
(price (nth 3 attributes))
(comission (nth 4 attributes))
(symbol (nth 5 attributes)))
(make-instance
(if (< 0 quantity) (class-constructor BuyOp) (class-constructor SellOp))
(format "%s-%s" symbol date)
:date date
:quantity (abs quantity)
:devise devise
:price price
:comission comission
:symbol symbol))))
;;;---------------------------------------------------------------------
;;;--- Line ------------------------------------------------------------
;;;---------------------------------------------------------------------
(defclass Line (PjbObject)
((symbol
:initform nil
:initarg :symbol
:accessor symbol
:type symbol
:documentation
"The ticker symbol of this line (stored as a lisp symbol).")
(devise
:initform nil
:initarg :devise
:accessor devise
:type symbol
:documentation
"The devise in which the shares of this line are dealt.
(See: pjb-euro).")
(positions
:initform nil
:accessor positions
:type list
:documentation
"The list of successive positions for this line.
They're stored the last one first."))
(:documentation "
Reification of a Portfolio Line, where all the operations regarding a share
are accumulated.
"))
(defmethod* update-with-operation ((self Line) (operation BuySellOp))
"PRE: (and (or (null (devise self)) (equal (devise self) (devise operation)))
(or (null (symbol self)) (equal (symbol self) (symbol operation))))
POST: (and (equal (devise self) (devise operation))
(equal (symbol self) (symbol operation)))
DO: Updates this line with the given operation.
RETURN: self."
(if (null (devise self))
(setf (slot-value self 'devise) (devise operation)))
(if (null (symbol self))
(setf (slot-value self 'symbol) (symbol operation)))
(if (not (equal (symbol self) (symbol operation)))
(let ((msg (format "SYMBOL MISMATCH WITH LINE FOR %s: %s\n"
(symbol self) (symbol operation))))
(printf msg)
(error msg)))
(if (is-closed (last-position self))
(open-new-position self))
(update-with-operation (last-position self) operation))
(defmethod* open-new-position ((self Line))
"PRE: (is-closed (last-position self))
POST: self has a new newbord position ready to be filled with operations.
RETURN: self"
(let ((p (car (slot-value self 'positions))))
(if (and p (not (is-closed p)))
(error "The last position is not closed."))
(setf (slot-value self 'positions)
(cons (make-instance Position
(format "%s-%d" (symbol self) (length p))
:owner-line self)
(slot-value self 'positions))))
self)
(defmethod* last-position ((self Line))
"RETURN: The last position of the line."
(if (null (slot-value self 'positions))
(open-new-position self))
(car (slot-value self 'positions)))
;; Last position data:
(defmethod* quantity ((self Line))
"RETURN: The number of share of the last postion.
(All the previous positions have a number of 0 share remaining...)."
(quantity (last-position self)))
(defmethod* amount-invested ((self Line))
"RETURN: The amount-invested of the last position."
(if (is-running (last-position self))
(amount-invested (last-position self))
0.0))
(defmethod* comission ((self Line))
"RETURN: The comission paid for the last position."
(if (is-running (last-position self))
(comission (last-position self))
0.0))
(defmethod* nb-operations ((self Line))
"RETURN: The number of operation of the last position.
(used for average-comission)"
(nb-operations (last-position self)))
(defmethod* average-comission ((self Line))
"RETURN: The average comission paid for the last position."
(/ (comission self) (nb-operations self)))
(defmethod* paid-per-share ((self Line))
"RETURN: The price paid per share for the last position."
(paid-per-share (last-position self)))
(defmethod* gain ((self Line))
"RETURN: The gain of the last position."
(gain (last-position self)))
(defmethod* buy-amount ((self Line))
"RETURN: The buy amount of the last position of the line."
(buy-amount (last-position self)))
(defmethod* sell-amount ((self Line))
"RETURN: The sell amount of the last position of the line."
(sell-amount (last-position self)))
(defmethod* buy-quantity ((self Line))
"RETURN: The buy quantity of the last position of the line."
(buy-quantity (last-position self)))
(defmethod* sell-quantity ((self Line))
"RETURN: The sell quantity of the last position of the line."
(sell-quantity (last-position self)))
;; Totals over closed positions:
(defmethod* closed-buy-amount ((self Line))
"RETURN: The sum over closed positions of (amount-base position).
(used to compute the percentage gain)."
(apply '+ (mapcar (lambda (pos) (buy-amount pos))
(if (is-closed (last-position self))
(positions self)
(cdr (positions self))))))
(defmethod* closed-gain ((self Line))
"RETURN: The sum over closed positions of (gain position)."
(apply '+ (mapcar (lambda (pos) (gain pos))
(if (is-closed (last-position self))
(positions self)
(cdr (positions self))))))
;;;END Line ------------------------------------------------------------
;;;---------------------------------------------------------------------
;;------------------------------------------------------------------------
;;--- Portfolio ----------------------------------------------------------
;;------------------------------------------------------------------------
(defclass Portfolio (PjbObject)
((operations
:initform nil
:accessor operations
:type list
:documentation
"The list of operations applied to this portfolio.")
(lines
:initform nil
:accessor lines
:type list
:documentation "The alist of (symbol . Line).")
;; BuySellOp totals:
;; -----------------
;; total-opcom total-comissions total-comissions/total-amount-base (%)
;; total-credit total-debit
(total-opcom
:initform (lambda () (make-instance DeviseAccount))
:accessor total-opcom
:documentation
"The sum over operations of (amount operation).")
(total-amount-base
:initform (lambda () (make-instance DeviseAccount))
:accessor total-amount-base