forked from jscherer26/Icarra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
portfolio.py
4519 lines (3876 loc) · 148 KB
/
portfolio.py
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
# Copyright (c) 2006-2010, Jesse Liesch
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE IMPLIED
# DISCLAIMED. IN NO EVENT SHALL JESSE LIESCH BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from db import *
from ofxToolkit import *
from fileFormats import *
from userprice import *
from positionCheck import *
from twrr import *
import irr
import prefs
try:
import autoUpdater
haveAutoUpdater = True
except:
haveAutoUpdater = False
import chart
import time
import datetime
import os
import copy
import operator
import uuid
def floatCompare(a, b):
'''Return the ratio of two floating point numbers. Return value is always greater than 0 unless both numbers are 0 in which case this function returns 0.'''
if a > b:
num = a
den = b
else:
num = b
den = a
if num == 0 and den == 0:
return 0
elif den == 0:
return 1e9
else:
return num / den
class TransactionErrorCheck:
'''Implements a detected error for one transaction'''
def __init__(self, id, ticker, type, oldDate = False, newDate = False, oldTotal = False, newTotal = False, delete = False):
self.id = id
self.ticker = ticker
self.type = type
self.newDate = newDate
self.oldDate = oldDate
self.newTotal = newTotal
self.oldTotal = oldTotal
self.delete = delete
def formatErrorText(self):
'''Format the error text as suitable for display'''
if self.id:
errorText = "An error occurred with the " + self.ticker + " " + Transaction.getTypeString(self.type) + " transaction on " + Transaction.formatDateStatic(self.oldDate) + ".\n"
if self.delete:
errorText += "There is no record of this transaction having occurred.\nIt may have been added to your portfolio on accident.\n\nDelete it?"
if self.oldTotal != self.newTotal:
if self.type == Transaction.split:
errorText += "\nThe split value is " + Transaction.splitValueToString(self.oldTotal) + " but should be " + Transaction.splitValueToString(self.newTotal) + "."
else:
errorText += "Unknown error."
if self.newDate != self.oldDate:
errorText += "\nThe date is " + Transaction.formatDateStatic(self.oldDate) + " but should be " + Transaction.formatDateStatic(self.newDate) + "."
else:
errorText = "This portfolio is missing a "
if self.type == Transaction.split:
errorText += Transaction.splitValueToString(self.newTotal) + " " + Transaction.getTypeString(self.type) + " transaction for " + self.ticker + " on " + Transaction.formatDateStatic(self.newDate) + "?"
errorText += "\n\nWould you like to fix this error by adding this transaction?"
return errorText
class PortfolioPrefs(prefs.Prefs):
'''Implements portfolio specific preferences'''
def __init__(self, db):
prefs.Prefs.__init__(self, db)
self.checkDefaults("dirty", "True")
self.checkDefaults("positionIncSplits", "False")
self.checkDefaults("positionIncDividends", "True")
self.checkDefaults("positionIncFees", "False")
self.checkDefaults("positionIncBenchmark", "True")
self.checkDefaults("chartType", "Value")
self.checkDefaults("positionPeriod", "Since Inception")
self.checkDefaults("performanceCurrent", "False")
self.checkDefaults("performanceDividends", "True")
self.checkDefaults("lastImport", "ofx")
self.checkDefaults("combinedComponents", "")
self.checkDefaults("brokerage", "False")
self.checkDefaults("sync", "")
self.checkDefaults("autoAdjust", "True")
self.checkDefaults("autoSplit", "False")
self.checkDefaults("autoDividend", "False")
self.checkDefaults("autoDividendReinvest", "False")
def getTransactionId(self):
'''Return a random transaction id'''
return uuid.uuid4().hex
def getDirty(self):
'''Return True if this portfolio is dirty (needs to be rebuilt)'''
return self.getPreference("dirty") == "True"
def getPositionIncSplits(self):
'''Return True if the chart should include split adjusted returns'''
return self.getPreference("positionIncSplits") == "True"
def getPositionIncDividends(self):
'''Return True if the chart should include dividend adjusted returns'''
return self.getPreference("positionIncDividends") == "True"
def getPositionIncFees(self):
'''Return True if the chart should include dividend and fee adjusted returns'''
return self.getPreference("positionIncFees") == "True"
def getPositionIncBenchmark(self):
'''Return True if the chart should include the benchmark'''
return self.getPreference("positionIncBenchmark") == "True"
def getChartType(self):
'''Return the active chart type'''
return self.getPreference("chartType")
def getPositionPeriod(self):
'''Return the charting period'''
return self.getPreference("positionPeriod")
def getPerformanceCurrent(self):
'''Return True if the performance tool should include only current positions'''
return self.getPreference("performanceCurrent") == "True"
def getPerformanceDividends(self):
'''Return True if the performance tool should include dividends'''
return self.getPreference("performanceDividends") == "True"
def getLastImport(self):
'''Return the datetime of the last transaction import'''
return self.getPreference("lastImport")
def getCombinedComponents(self):
'''Return the sub-portfolios for a combined portfolio'''
if not self.getPreference("combinedComponents"):
return []
return self.getPreference("combinedComponents").split(",")
def getBrokerage(self):
'''Return this portfolio's brokerage name'''
return self.getPreference("brokerage")
def getUrl(self):
'''Return the last URL used for importing transactions via the web'''
return self.getPreference("url")
def getSync(self):
'''Return a list of online services with which to sync this portfolio'''
if not self.getPreference("sync"):
return []
return self.getPreference("sync").split(",")
def getAutoAdjust(self):
'''Return True if this portfolio should automatically adjust to position checks'''
return self.getPreference("autoAdjust") == "True"
def getAutoSplit(self):
'''Return True if this portfolio should automatically include splits'''
return self.getPreference("autoSplit") == "True"
def getAutoDividend(self):
'''Return True if this portfolio should automatically include dividends'''
return self.getPreference("autoDividend") == "True"
def getAutoDividendReinvest(self):
'''Return True if this portfolio should automatically reinvest dividends'''
return self.getPreference("autoDividendReinvest") == "True"
def setDirty(self, dirty):
self.db.beginTransaction()
self.db.update("prefs", {"value": dirty}, {"name": "dirty"})
self.db.commitTransaction()
def setPositionIncSplits(self, inc):
self.db.beginTransaction()
self.db.update("prefs", {"value": inc}, {"name": "positionIncSplits"})
self.db.commitTransaction()
def setPositionIncDividends(self, inc):
self.db.beginTransaction()
self.db.update("prefs", {"value": inc}, {"name": "positionIncDividends"})
self.db.commitTransaction()
def setPositionIncFees(self, inc):
self.db.beginTransaction()
self.db.update("prefs", {"value": inc}, {"name": "positionIncFees"})
self.db.commitTransaction()
def setPositionIncBenchmark(self, inc):
self.db.beginTransaction()
self.db.update("prefs", {"value": inc}, {"name": "positionIncBenchmark"})
self.db.commitTransaction()
def setChartType(self, type):
self.db.beginTransaction()
self.db.update("prefs", {"value": type}, {"name": "chartType"})
self.db.commitTransaction()
def setPositionPeriod(self, period):
self.db.beginTransaction()
self.db.update("prefs", {"value": period}, {"name": "positionPeriod"})
self.db.commitTransaction()
def setPerformanceCurrent(self, value):
self.db.beginTransaction()
self.db.update("prefs", {"value": value}, {"name": "performanceCurrent"})
self.db.commitTransaction()
def setPerformanceDividends(self, value):
self.db.beginTransaction()
self.db.update("prefs", {"value": value}, {"name": "performanceDividends"})
self.db.commitTransaction()
def setLastImport(self, value):
self.db.beginTransaction()
self.db.update("prefs", {"value": value}, {"name": "lastImport"})
self.db.commitTransaction()
def setCombinedComponents(self, value):
self.db.beginTransaction()
self.db.update("prefs", {"value": value}, {"name": "combinedComponents"})
self.db.commitTransaction()
def setBrokerage(self, value):
self.db.beginTransaction()
self.db.update("prefs", {"value": value}, {"name": "brokerage"})
self.db.commitTransaction()
def setUrl(self, value):
self.db.beginTransaction()
self.db.update("prefs", {"value": value}, {"name": "url"})
self.db.commitTransaction()
def setSync(self, value):
self.db.beginTransaction()
self.db.update("prefs", {"value": value}, {"name": "sync"})
self.db.commitTransaction()
def setAutoAdjust(self, value):
self.db.beginTransaction()
self.db.update("prefs", {"value": value}, {"name": "autoAdjust"})
self.db.commitTransaction()
def setAutoSplit(self, value):
self.db.beginTransaction()
self.db.update("prefs", {"value": value}, {"name": "autoSplit"})
self.db.commitTransaction()
def setAutoDividend(self, value):
self.db.beginTransaction()
self.db.update("prefs", {"value": value}, {"name": "autoDividend"})
self.db.commitTransaction()
def setAutoDividendReinvest(self, value):
self.db.beginTransaction()
self.db.update("prefs", {"value": value}, {"name": "autoDividendReinvest"})
self.db.commitTransaction()
class Portfolio:
'''Implements all functions needed for managing portfolios.
Also implements many functions that are used for generating tool output.
'''
def __init__(self, name = False, brokerage = "", username = "", account = "", customDb = False):
self.open(name, customDb)
def open(self, name, customDb = False):
'''Initialize this portfolio and open it's database'''
self.name = name
if prefs.prefs:
info = prefs.prefs.getPortfolioInfo(name)
if not info:
raise Exception("No portfolio " + name)
self.brokerage = info["brokerage"]
self.username = info["username"]
self.account = info["account"]
if customDb:
self.db = Db(customDb)
else:
self.db = Db(appGlobal.getApp().prefs.getPortfolioPath(name))
self.db.beginTransaction()
self.portPrefs = PortfolioPrefs(self.db)
self.portPrefs.checkDefaults("nextTransactionId", "1")
self.portPrefs.checkDefaults("lastTicker", "__COMBINED__")
self.portPrefs.checkDefaults("benchmark", "S&P 500")
self.portPrefs.checkDefaults("isBrokerage", "True")
self.portPrefs.checkDefaults("isBank", "False")
self.portPrefs.checkDefaults("isBenchmark", "False")
self.portPrefs.checkDefaults("isCombined", "False")
self.portPrefs.checkDefaults("url", "")
self.portPrefs.checkDefaults("summaryYears", "lastYear")
self.portPrefs.checkDefaults("summaryChart1", chart.oneYearVsBenchmarkCash)
if self.isBank():
self.portPrefs.checkDefaults("summaryChart2", chart.oneMonthSpending)
else:
self.portPrefs.checkDefaults("summaryChart2", chart.oneMonthMovers)
self.db.checkTable("stockInfo", [
{"name": "uniqueId", "type": "text"},
{"name": "uniqueIdType", "type": "text"},
{"name": "secName", "type": "text"},
{"name": "ticker", "type": "text"}])
self.db.checkTable("transactions", [
{"name": "uniqueId", "type": "text"},
{"name": "date", "type": "text"},
{"name": "ticker", "type": "text"},
{"name": "ticker2", "type": "text"},
{"name": "type", "type": "integer"},
{"name": "subType", "type": "integer"},
{"name": "shares", "type": "float"},
{"name": "pricePerShare", "type": "float"},
{"name": "fee", "type": "float"},
{"name": "total", "type": "float"},
{"name": "optionStrike", "type": "float"},
{"name": "optionExpire", "type": "text"},
{"name": "edited", "type": "text not null default False"},
{"name": "deleted", "type": "bool not null default False"},
{"name": "auto", "type": "bool not null default False"}], index = [
{"name": "tickerDate", "cols": ["ticker", "date"]}])
self.db.checkTable("userPrices", [
{"name": "date", "type": "datetime"},
{"name": "ticker", "type": "text"},
{"name": "price", "type": "float"}])
self.db.checkTable("positionCheck", [
{"name": "date", "type": "datetime"},
{"name": "ticker", "type": "text"},
{"name": "shares", "type": "float"},
{"name": "value", "type": "float"}])
self.db.checkTable("positionHistory", [
{"name": "date", "type": "datetime"},
{"name": "ticker", "type": "text"},
{"name": "shares", "type": "float"},
{"name": "options", "type": "float"},
{"name": "value", "type": "float"},
{"name": "normSplit", "type": "float"},
{"name": "normDividend", "type": "float"},
{"name": "normFee", "type": "float"},
{"name": "profitSplit", "type": "float"},
{"name": "profitDividend", "type": "float"},
{"name": "profitFee", "type": "float"}],
index = [{"name": "positionHistoryIndex", "cols": ["ticker, date"]}])
self.db.checkTable("allocation", [
{"name": "ticker", "type": "text"},
{"name": "percentage", "type": "float"}],
unique = [{"name": "tickerIndex", "cols": ["ticker"]}])
self.db.checkTable("categories", [
{"name": "ticker", "type": "text"},
{"name": "category", "type": "text"}],
unique = [{"name": "tickerIndex", "cols": ["ticker"]}])
self.db.checkTable("rules", [
{"name": "rule", "type": "text"},
{"name": "category", "type": "text"}],
unique = [{"name": "ruleIndex", "cols": ["rule"]}])
self.db.checkTable("availCategories", [
{"name": "category", "type": "text"}],
unique = [{"name": "categoryIndex", "cols": ["category"]}])
self.db.checkTable("availCategories", [
{"name": "category", "type": "text"}],
unique = [{"name": "categoryIndex", "cols": ["category"]}])
self.db.checkTable("ignoreTransactionChecks", [
{"name": "ticker", "type": "text"},
{"name": "date", "type": "datetime"},
{"name": "type", "type": "integer"}],
unique = [{"name": "tickerIndex", "cols": ["ticker"]}])
self.db.commitTransaction()
# List of transactions
self.transactions = []
# List of user prices
self.userPrices = []
def close(self):
'''Close this portfolio's database'''
self.db.close()
def strToDatetime(self, date, zeroHMS = False):
'''Convert a string to a datetime value. If zeroHMS is true then the hours, minutes and seconds will be zeroed out.'''
# Remove HMS if specified
if zeroHMS:
date = str(date)
date = date[0:10] + " 00:00:00"
return Transaction.parseDate(date)
def delete(self, prefs):
'''Delete this portfolio (remove from Icarra)'''
self.db.close()
os.remove(prefs.getPortfolioPath(self.name))
prefs.deletePortfolio(self.name)
def updateFromFile(self, data, app, status = False):
'''Import transactions from a file. This is the main call for importing transactions.
A StatusUpdate class may be passed in the status argument to show the import status to the user.
Returns a tuple of (number of new transactions, number of old transactions, number of new tickers added to the portfolio)
'''
if status:
status.setSubTask(50)
status.setStatus("Parsing transactions", 10)
found = False
format = False
for format in getFileFormats():
if format.Guess(data):
found = True
break
if not found:
if status:
status.addError("Unknown file format")
status.finishSubTask()
status.setStatus("Aborted", 100)
return (False, False, False)
try:
app.beginBigTask('importing transactions', status)
(numNew, numOld, newTickers) = format.StartParse(data, self, status)
if status:
status.setStatus("Parsing transactions")
status.finishSubTask()
# Download new stock data
# NOTE: This function may be called by auto-updater when rebuilding portfolios
# We know this is the case if status is false
if haveAutoUpdater and not appGlobal.getFailConnected() and self.isBrokerage():
# Temporarily end big task so autoUpdater can run
app.endBigTask()
autoUpdater.wakeUp()
if status:
if autoUpdater.percentDone() == 100:
status.setStatus(level = 99)
else:
status.setSubTask(99)
status.setStatus("Downloading stock data\nWarning: This operation may take a while")
# Wait for downloading to finish
autoUpdater.wakeUp()
while not autoUpdater.sleeping():
status.setStatus(level = autoUpdater.percentDone())
# Sleep for 1 second
app.processEvents(QEventLoop.AllEvents, 1000)
status.finishSubTask()
# Resume big task
app.beginBigTask('importing transactions', status)
# Check for new positions not in stockData
if newTickers and self.isBrokerage():
notFound = []
for ticker in newTickers:
if ticker == "__CASH__":
continue
p = app.stockData.getPrices(ticker)
if not p:
notFound.append(ticker)
if notFound:
message = "No stock data was found for the following tickers: " + ", ".join(notFound)
message += ". You can fix this problem by going to the \"Stock Data\" page, choosing a position from the list, then clicking the \"Suggest\" button."
if status:
status.addMessage(message)
self.portPrefs.setDirty(True)
if status:
status.setStatus("Finished\nImported %d new transactions.\n%d transactions had already been imported." % (numNew, numOld), 100)
status.setFinished()
app.endBigTask()
return (numNew, numOld, newTickers)
except:
app.endBigTask()
raise
def readFromDb(self):
'''Read cached transactions from the database. This function must be called before any other function that uses transactions, and should be called after transactions have been modified.'''
res = self.db.select("transactions")
self.transactions = []
for row in res.fetchall():
t = Transaction(
uniqueId = row["uniqueId"],
ticker = row["ticker"].upper(),
date = row["date"],
transactionType = row["type"],
amount = row["total"],
shares = row["shares"],
pricePerShare = row["pricePerShare"],
fee = row["fee"],
optionStrike = row["optionStrike"],
optionExpire = row["optionExpire"],
edited = row["edited"],
deleted = row["deleted"],
ticker2 = row["ticker2"],
subType = row["subType"],
auto = row["auto"])
self.transactions.append(t)
# Sort transactions
self.transactions.sort()
res = self.db.select("userPrices")
for row in res.fetchall():
ticker = row["ticker"]
p = UserPrice(
row["date"],
ticker,
row["price"])
self.userPrices.append(p)
def getTickers(self, includeAllocation = False):
'''Return a list of all tickers in this portfolio. If includeAllocation is true then values from the allocation table will be included. Otherwise tickers will be taken strictly from transactions. This list includes __CASH__ but does not include __COMBINED__ and __BENCHMARK__.'''
if self.isCombined():
# Combined portfolio
tickers = {}
components = self.portPrefs.getCombinedComponents()
for name in components:
if not name:
continue
p = Portfolio(name)
p.readFromDb()
pTickers = p.getTickers(includeAllocation)
for ticker in pTickers:
tickers[ticker] = ticker
else:
# Regular portfolio
tickers = {}
for t in self.transactions:
if t.ticker and not t.deleted and not t.ticker in tickers:
tickers[t.ticker] = t.ticker
if t.ticker2 and not t.deleted and not t.ticker2 in tickers:
tickers[t.ticker2] = t.ticker2
# Add in positionCheck
# Do not include options (ends in " call" or " put")
cursor = self.db.select("positionCheck", what = "distinct(ticker) as ticker")
for row in cursor.fetchall():
if not row["ticker"] in tickers and not row["ticker"].endswith(" call") and not row["ticker"].endswith(" put"):
tickers[row["ticker"]] = row["ticker"]
# Optionally add allocation
if includeAllocation:
allocation = self.getAllocation()
for a in allocation:
tickers[a] = a
if not "__CASH__" in tickers:
tickers["__CASH__"] = "__CASH__"
return sorted(tickers.keys())
def getLastTicker(self):
'''Return the last active ticker for this portfolio used by a toolset'''
return self.portPrefs.getPreference("lastTicker")
def isBrokerage(self):
'''Return True if this portfolio is a brokerage portfolio'''
return self.portPrefs.getPreference("isBrokerage") == "True"
def isBank(self):
'''Return True if this portfolio is a bank portfolio'''
return self.portPrefs.getPreference("isBank") == "True"
def isBenchmark(self):
'''Return True if this portfolio is a benchmark portfolio'''
return self.portPrefs.getPreference("isBenchmark") == "True"
def isCombined(self):
'''Return True if this portfolio is a combined portfolio'''
return self.portPrefs.getPreference("isCombined") == "True"
def makeBenchmark(self):
'''Turn this portfolio into a benchmark portfolio'''
self.db.update("prefs", {"value": "True"}, {"name": "isBenchmark"})
self.db.update("prefs", {"value": "False"}, {"name": "isBrokerage"})
self.db.update("prefs", {"value": "False"}, {"name": "isBank"})
self.db.update("prefs", {"value": "False"}, {"name": "isCombined"})
def makeCombined(self):
'''Turn this portfolio into a combined portfolio'''
self.db.update("prefs", {"value": "True"}, {"name": "isCombined"})
self.db.update("prefs", {"value": "False"}, {"name": "isBrokerage"})
self.db.update("prefs", {"value": "False"}, {"name": "isBank"})
self.db.update("prefs", {"value": "False"}, {"name": "isBenchmark"})
def makeBank(self):
'''Turn this portfolio into a bank portfolio'''
self.db.update("prefs", {"value": "True"}, {"name": "isBank"})
self.db.update("prefs", {"value": "False"}, {"name": "isBrokerage"})
self.db.update("prefs", {"value": "False"}, {"name": "isCombined"})
self.db.update("prefs", {"value": "False"}, {"name": "isBenchmark"})
def getCategories(self):
'''Return a list of spending categories for this portfolio. Used by bank portfolios.'''
# Read categories from DB
categories = []
cursor = self.db.select("availCategories")
for row in cursor.fetchall():
categories.append(row["category"])
if len(categories) > 0:
return sorted(categories)
else:
# If no categories (first time called) insert
defaultCategories = ["Charity", "Childcare", "Clothing", "Debt Repayment", "Eating Out", "Entertainment", "Fees & Interest", "Groceries", "Health & Fitness", "Hobbies", "Housing", "Luxuries & Gifts", "Medical & Dental", "Miscellaneous", "Pets", "Savings & Investmentments", "Transportation", "Uncategorized", "Utilities", "Vacations"]
self.db.beginTransaction()
for c in defaultCategories:
self.db.insert("availCategories", {"category": c})
self.db.commitTransaction()
return sorted(defaultCategories)
def getRules(self):
'''Return a list of rules for this portfolio. Used to automatically assign spending categories by bank portfolios.'''
# Read rules from DB
rules = []
cursor = self.db.select("rules")
for row in cursor.fetchall():
rules.append((row["rule"], row["category"]))
return rules
def addCategory(self, category):
'''Add a spending category for a bank portfolio'''
self.db.beginTransaction()
self.db.insert("availCategories", {"category": category})
self.db.commitTransaction()
def addRule(self, rule, category):
'''Add a rule for a bank portfolio'''
self.db.beginTransaction()
self.db.insert("rules", {"rule": rule, "category": category})
self.db.commitTransaction()
def removeCategory(self, category):
'''Remove a category for a bank portfolio'''
self.db.beginTransaction()
self.db.delete("availCategories", {"category": category})
self.db.delete("categories", {"category": category})
self.db.delete("rules", {"category": category})
self.db.commitTransaction()
def removeRule(self, rule):
'''Remove a category for a bank portfolio'''
self.db.beginTransaction()
self.db.delete("rules", {"rule": rule})
self.db.commitTransaction()
def getCategory(self, ticker):
'''Return a category for a bank portfolio'''
cursor = self.db.select("categories", where = {"ticker": ticker})
for row in cursor.fetchall():
return row["category"]
return "Uncategorized"
def setCategory(self, ticker, category):
'''Update a spending category'''
self.db.beginTransaction()
self.db.insertOrUpdate("categories", {"ticker": ticker, "category": category}, {"ticker": ticker})
self.db.commitTransaction()
def ignoreTransactionCheck(self, error):
'''Ignore a transaction check'''
self.db.beginTransaction()
self.db.insert("ignoreTransactionChecks", {"ticker": error.ticker, "date": error.oldDate, "type": error.type})
self.db.commitTransaction()
def isTransactionCheckIgnored(self, error):
'''Check if a transaction check is ignored'''
cursor = self.db.select("ignoreTransactionChecks", where = {"ticker": error.ticker, "date": error.oldDate, "type": error.type})
if cursor.fetchone():
return True
else:
return False
def getBenchmark(self):
'''Return the portfolio name of this portfolio's benchmark'''
return self.portPrefs.getPreference("benchmark")
def setBenchmark(self, benchmark):
'''Change this portfolio's benchmark'''
self.db.update("prefs", {"value": benchmark}, {"name": "benchmark"})
def getSummaryYears(self):
'''Return the number of years to show summary data. Value may be thisYear, lastYear or allYears.'''
return self.portPrefs.getPreference("summaryYears")
def getSummaryChart1(self):
'''Get the first type of chart to show for the summary tool'''
return int(self.portPrefs.getPreference("summaryChart1"))
def getSummaryChart2(self):
'''Get the second type of chart to show for the summary tool'''
return int(self.portPrefs.getPreference("summaryChart2"))
def setSummaryYears(self, all):
'''Set the number of years to show summary data. All may be thisYear, lastYear or allYears.'''
self.db.update("prefs", {"value": all}, {"name": "summaryYears"})
def setSummaryChart1(self, type):
'''Set the first type of chart to show for the summary tool'''
self.db.update("prefs", {"value": type}, {"name": "summaryChart1"})
def setSummaryChart2(self, type):
'''Set the second type of chart to show for the summary tool'''
self.db.update("prefs", {"value": type}, {"name": "summaryChart2"})
def setLastTicker(self, last):
'''Set the active ticker for this portfolio'''
self.db.update("prefs", {"value": last}, {"name": "lastTicker"})
def getStartDate(self):
'''Return the starting date of this portfolio'''
cursor = self.db.select("transactions", orderBy = "date asc", limit = 1)
row = cursor.fetchone()
if row:
return Transaction.parseDate(row["date"])
return False
def getEndDate(self):
'''Return the ending date of this portfolio (last date of position history)'''
cursor = self.db.select("positionHistory", orderBy = "date desc", limit = 1)
row = cursor.fetchone()
if row:
return Transaction.parseDate(row["date"])
return False
def getLastTransactionDate(self):
'''Return the date of the last transaction in the portfolio'''
cursor = self.db.select("transactions", orderBy = "date desc", limit = 1)
row = cursor.fetchone()
if row:
return Transaction.parseDate(row["date"])
return False
def getFirstTransactionDate(self):
'''Return the date of the first transaction in the portfolio'''
cursor = self.db.select("transactions", orderBy = "date asc", limit = 1)
row = cursor.fetchone()
if row:
return Transaction.parseDate(row["date"])
return False
def getTransaction(self, id):
'''Return a transaction with uniqueId equal to id. Returns False if not found.'''
for t in self.transactions:
if t.uniqueId == id:
return t
return False
def getTransactions(self, ticker = False, ascending = False, getDeleted = False, deletedOnly = False, buysToCash = True, limit = False, transType = False):
'''Return a list of all transactions.
Parameters:
* ticker: The ticker to search for. False to return all transactions. Default is False.
* ascending: If transactions should be returned in ascending order (by date). Default is False.
* getDeleted: If deleted transactions should be returned. Default is False.
* deletedOnly: If only deleted transactions should be returned. Default is False.
* buysToCash: If buy/sell transactions should be converted to cash deposits/withdrawals. Mainly useful when rebuilding the cash position of a portfolio. Default is True.
* limit: If only a certain number of transactions should be returned. Pass in an integer value. Default is False (no limit).
* transType: Reurn transactions of a specific type. Default is False (return all transaction types).
'''
retTrans = []
if ticker:
ticker = ticker.upper()
for t in self.transactions:
# Ignore type if type is specified and it doesn't match
if type(transType) == int and t.type != transType:
continue
# Ignore deleted transactions
if not getDeleted and not deletedOnly and t.deleted:
continue
if deletedOnly and not t.deleted:
continue
if buysToCash and ticker == "__CASH__":
if t.ticker == "__CASH__":
# Don't modify cash transactions
retTrans.append(t)
elif t.getCashMod() != 0:
# Transaction modifies cash, create copy
t2 = copy.deepcopy(t)
t2.ticker = "__CASH__"
t2.fee = 0.0
if t.getCashMod() > 0:
# Deposit if cashMod > 0
t2.type = Transaction.deposit
t2.total = t.getCashMod()
else:
# Withdrawal if cashMod < 0
t2.type = Transaction.withdrawal
t2.total = -t.getCashMod()
retTrans.append(t2)
elif ticker == "__CASH__" and t.type == Transaction.transferIn:
# Tranfser in must get a deposit to signify that value was added to the account
t2 = copy.deepcopy(t)
t2.type = Transaction.deposit
t2.total = abs(t2.total)
t2.fee = 0.0
retTrans.append(t2)
elif ticker == "__CASH__" and t.type == Transaction.transferOut:
# Tranfser out must get a withdrawal to signify that value was removed from the account
t2 = copy.deepcopy(t)
t2.type = Transaction.withdrawal
t2.total = abs(t2.total)
t2.fee = 0.0
retTrans.append(t2)
elif not ticker or t.ticker.upper() == ticker or (t.ticker2 and t.ticker2 != "False" and t.ticker2.upper() == ticker):
# Append if we are getting all tickers
# or the requested ticker matches ticker or ticker2
retTrans.append(t)
else:
for t in self.transactions:
if type(transType) == int and t.type != transType:
continue
# Ignore deleted transactions
if not getDeleted and not deletedOnly and t.deleted:
continue
if deletedOnly and not t.deleted:
continue
retTrans.append(t)
if limit and len(retTrans) == limit:
break
if ascending:
retTrans.reverse()
if limit and len(retTrans) > limit:
del retTrans[limit:]
return retTrans
def getDividendForDate(self, ticker, date):
'''Get a dividend nearest to the given ticker and date'''
query = "select * From transactions where ticker='%s' and type='%s' order by abs(julianday('%s') - julianday(date)) limit 1;" % (ticker, Transaction.dividend, date.strftime("%Y-%m-%d"))
res = self.db.query(query)
row = res.fetchone()
if row:
return Transaction(
row["uniqueId"],
row["ticker"].upper(),
row["date"],
row["type"],
row["total"],
row["shares"],
row["pricePerShare"],
row["fee"],
row["edited"],
row["deleted"],
row["ticker2"],
row["auto"])
else:
return False
def getUserPrices(self, ticker):
'''Return the user prices for this ticker. User prices are zzz'''
retPrices = []
ticker = ticker.upper()
for p in self.userPrices:
if p.ticker.upper() == ticker:
retPrices.append(p)
return retPrices
def addUserAndTransactionPrices(self, ticker, prices, optionPrices, transactions):
'''Add user prices and prices based on transactions to existing stock data'''
userPrices = self.getUserPrices(ticker)
# Use buys/sells to add to user price
for t in transactions:
if t.type in [Transaction.buy, Transaction.sell, Transaction.transferIn, Transaction.transferOut, Transaction.short, Transaction.cover, Transaction.buyToOpen, Transaction.sellToClose, Transaction.sellToOpen, Transaction.buyToClose]:
# Add to user prices
# Note there may already be a user price for this date
price = False
if t.pricePerShare:
price = t.pricePerShare
elif t.shares > 0:
price = abs(t.total / t.shares)
# Add user price if we found pricing information
if price:
if t.isOption():
if not t.formatTicker() in optionPrices:
optionPrices[t.formatTicker()] = []
optionPrices[t.formatTicker()].append({'volume': 0, 'high': price, 'low': price, 'date': t.date, 'close': price, 'open': price})
else:
userPrices.append(UserPrice(t.date, t.ticker, price))
# Add user prices and transaction prices to prices array
appended = False
for p in userPrices:
date = self.strToDatetime(p.date, zeroHMS = True)
# Check if date is already there
found = False
for p2 in prices:
if p2["date"] == date:
found = True
break
if not found:
appended = True
prices.append({'volume': 0, 'high': p.price, 'low': p.price, 'date': date, 'close': p.price, 'open': p.price})
# If we added prices, sort by date
if appended:
prices.sort(key = lambda p: p['date'])
def getPositionCheck(self, ticker):
'''Return position checks for this ticker'''
checks = []
cursor = self.db.select("positionCheck", where = {"ticker": ticker})
for row in cursor.fetchall():
check = PositionCheck(
self.strToDatetime(row["date"]),
row["ticker"],
float(row["shares"]),
float(row["value"]))
checks.append(check)
return checks
def getPositionForCheck(self, ticker, check):
'''Check the closest position history for a given position check'''
# Check position on 3 closest days
d = datetime.datetime(check.date.year, check.date.month, check.date.day, 0, 0, 0)
# Check if same day matches
same = self.getPositionOnDate(ticker, d)
if same and abs(check.shares - same["shares"]) < 1.0e-6 and floatCompare(check.value, same["value"]):
return same
# Check 1 day before
pos = self.getPositionOnDate(ticker, d - datetime.timedelta(days = 1))
if pos and abs(check.shares - pos["shares"]) < 1.0e-6 and floatCompare(check.value, pos["value"]):
return pos
# Check 1 day after
pos = self.getPositionOnDate(ticker, d + datetime.timedelta(days = 1))
if pos and abs(check.shares - pos["shares"]) < 1.0e-6 and floatCompare(check.value, pos["value"]):