forked from jamsix/ib-edavki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ib_edavki.py
executable file
·1354 lines (1269 loc) · 58 KB
/
ib_edavki.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
#!/usr/bin/python
import argparse
import copy
import datetime
import glob
import os
import re
import sys
import urllib.request
import xml.etree.ElementTree
from collections import defaultdict
from difflib import SequenceMatcher
from xml.dom import minidom
from generators import doh_obr
bsRateXmlUrl = "https://www.bsi.si/_data/tecajnice/dtecbs-l.xml"
normalAssets = ["STK"]
derivateAssets = ["CFD", "FXCFD", "OPT", "FUT", "FOP", "WAR"]
ignoreAssets = ["CASH", "CMDTY"]
stockSplits = defaultdict(list)
def getSplitMultiplier(symbol, conid, date):
multiplier = 1
key = f"{symbol}:{conid}"
if key not in stockSplits:
return multiplier
for splitData in stockSplits[key]:
if datetime.datetime.strptime(date, "%Y%m%d") < splitData["date"]:
multiplier *= splitData["multiplier"]
return multiplier
def addStockSplits(corporateActions):
for action in corporateActions:
description = action.attrib["description"]
descriptionSearch = re.search(r"SPLIT (.+) FOR (.+) \(", description)
if descriptionSearch is not None:
# we have to extract split information from description since IB does not provide
# any information on what the corporate action is
multiplier = float(descriptionSearch.group(1)) / float(
descriptionSearch.group(2)
)
symbol = action.attrib["symbol"]
conid = action.attrib["conid"]
key = f"{symbol}:{conid}"
date = datetime.datetime.strptime(action.attrib["reportDate"], "%Y%m%d")
# check if the same split was added from a different report
for split in stockSplits[key]:
if split["date"] == date and split["multiplier"] == multiplier:
continue
stockSplits[key].append({"date": date, "multiplier": multiplier})
""" Gets the currency rate for a given date and currency. If no rate exists for a given
date, it returns the last value on the last previous day on which the rate exists
"""
def getCurrencyRate(dateStr, currency, rates):
if currency == "CNH":
currency = "CNY"
if dateStr in rates and currency in rates[dateStr]:
rate = float(rates[dateStr][currency])
else:
date = datetime.datetime.strptime(dateStr, "%Y%m%d")
for i in range(1, 10):
lastWorkingDate = date - datetime.timedelta(days=i)
lastWorkingDateStr = lastWorkingDate.strftime("%Y%m%d")
if lastWorkingDateStr in rates and currency in rates[lastWorkingDateStr]:
rate = float(rates[lastWorkingDateStr][currency])
print(
"There is no exchange rate for "
+ str(dateStr)
+ ", using "
+ str(lastWorkingDateStr)
)
break
if i >= 9:
sys.exit("Error: There is no exchange rate for " + str(dateStr))
return rate
def main():
if not os.path.isfile("taxpayer.xml"):
print("Modify taxpayer.xml and add your data first!")
f = open("taxpayer.xml", "w+", encoding="utf-8")
f.write(
"<taxpayer>\n"
" <taxNumber>12345678</taxNumber>\n"
" <taxpayerType>FO</taxpayerType>\n"
" <name>Janez Novak</name>\n"
" <address1>Slovenska 1</address1>\n"
" <city>Ljubljana</city>\n"
" <postNumber>1000</postNumber>\n"
" <postName>Ljubljana</postName>\n"
" <email>[email protected]</email>\n"
" <telephoneNumber>01 123 45 67</telephoneNumber>\n"
" <residentCountry>SI</residentCountry>\n"
" <isResident>true</isResident>\n"
"</taxpayer>"
)
exit(0)
parser = argparse.ArgumentParser()
parser.add_argument(
"ibXmlFiles",
metavar="ib-xml-file",
help="InteractiveBrokers XML ouput file(s) (see README.md on how to generate one)",
nargs="+",
)
parser.add_argument(
"-y",
metavar="report-year",
type=int,
default=0,
help="Report will be generated for the provided calendar year (defaults to "
+ str(datetime.date.today().year - 1)
+ ")",
)
parser.add_argument(
"-t",
help="Change trade dates to previous year (see README.md)",
action="store_true",
)
args = parser.parse_args()
ibXmlFilenames = args.ibXmlFiles
test = args.t
if args.y == 0:
if test == True:
reportYear = datetime.date.today().year
else:
reportYear = datetime.date.today().year - 1
else:
reportYear = int(args.y)
if test == True:
testYearDiff = reportYear - datetime.date.today().year - 1
else:
testYearDiff = 0
""" Parse taxpayer information from the local taxpayer.xml file """
taxpayer = xml.etree.ElementTree.parse("taxpayer.xml").getroot()
taxpayerConfig = {
"taxNumber": taxpayer.find("taxNumber").text,
"taxpayerType": "FO",
"name": taxpayer.find("name").text,
"address1": taxpayer.find("address1").text,
"city": taxpayer.find("city").text,
"postNumber": taxpayer.find("postNumber").text,
"postName": taxpayer.find("postName").text,
"email": taxpayer.find("email").text,
"telephoneNumber": taxpayer.find("telephoneNumber").text,
"residentCountry": taxpayer.find("residentCountry").text,
"isResident": taxpayer.find("isResident").text,
}
""" Fetch companies.xml from GitHub if it doesn't exist and use the data for Doh-Div.xml """
companies = {}
if not os.path.isfile("companies.xml"):
urllib.request.urlretrieve(
"https://github.com/jamsix/ib-edavki/raw/master/companies.xml",
"companies.xml",
)
if os.path.isfile("companies.xml"):
cmpns = xml.etree.ElementTree.parse("companies.xml").getroot()
for company in cmpns:
c = {
"symbol": company.find("symbol").text,
"name": company.find("name").text,
"taxNumber": company.find("taxNumber").text,
"address": company.find("address").text,
"country": company.find("country").text,
}
companies[c["symbol"]] = c
""" Fetch relief-statements.xml from GitHub if it doesn't exist and use the data for Doh-Div.xml """
if not os.path.isfile("relief-statements.xml"):
urllib.request.urlretrieve(
"https://github.com/jamsix/ib-edavki/raw/master/relief-statements.xml",
"relief-statements.xml",
)
if os.path.isfile("relief-statements.xml"):
statements = xml.etree.ElementTree.parse("relief-statements.xml").getroot()
for statement in statements:
for symbol in companies:
if companies[symbol]["country"] == statement.find("country").text:
companies[symbol]["reliefStatement"] = statement.find(
"statement"
).text
""" Creating daily exchange rates object """
bsRateXmlFilename = (
"bsrate-"
+ str(datetime.date.today().year)
+ str(datetime.date.today().month)
+ str(datetime.date.today().day)
+ ".xml"
)
if not os.path.isfile(bsRateXmlFilename):
for file in glob.glob("bsrate-*.xml"):
os.remove(file)
urllib.request.urlretrieve(bsRateXmlUrl, bsRateXmlFilename)
bsRateXml = xml.etree.ElementTree.parse(bsRateXmlFilename).getroot()
rates = {}
for d in bsRateXml:
date = d.attrib["datum"].replace("-", "")
rates[date] = {}
for r in d:
currency = r.attrib["oznaka"]
rates[date][currency] = r.text
""" Parsing IB XMLs """
ibTradesList = []
ibCashTransactionsList = []
ibSecuritiesInfoList = []
ibEntities = []
for ibXmlFilename in ibXmlFilenames:
ibXml = xml.etree.ElementTree.parse(ibXmlFilename).getroot()
ibFlexStatements = ibXml[0]
for ibFlexStatement in ibFlexStatements:
ibTradesList.append(ibFlexStatement.find("Trades"))
ibCashTransactionsList.append(ibFlexStatement.find("CashTransactions"))
ibSecuritiesInfoList.append(ibFlexStatement.find("SecuritiesInfo"))
if ibFlexStatement.find("AccountInformation") is not None:
for entity in ibEntities:
if entity["accountId"] == ibFlexStatement.find(
"AccountInformation"
).get("accountId"):
break
else:
ibEntity = {
"accountId": ibFlexStatement.find("AccountInformation").get(
"accountId"
),
"ibEntity": ibFlexStatement.find("AccountInformation").get(
"ibEntity"
),
}
ibEntities.append(ibEntity)
else:
print(
"Account Information section of flex report is missing for account "
+ ibFlexStatement.get("accountId")
+ " in file "
+ ibXmlFilename
)
corporateActions = ibFlexStatement.find("CorporateActions")
if corporateActions is not None:
addStockSplits(corporateActions)
if test == True:
statementStartDate = str(reportYear + testYearDiff) + "0101"
statementEndDate = str(reportYear + testYearDiff) + "1231"
else:
statementStartDate = str(reportYear) + "0101"
statementEndDate = str(reportYear) + "1231"
"""
IB is PITA in terms of unique security ID, old outputs and some asset types only have conid,
same assets have ISIN but had none in the past, euro ETFs can have different symbols but same ISIN.
Code below merges trades based on these IDs in the order of ISIN > CUSIP > securityID > CONID > Symbol
"""
tradesByIsin = {}
tradesByCusip = {}
tradesBySecurityId = {}
tradesByConid = {}
tradesBySymbol = {}
""" Get trades from IB XML and sort them by securityID """
for ibTrades in ibTradesList:
if ibTrades is None:
continue
for ibTrade in ibTrades:
if ibTrade.attrib["assetCategory"] in ignoreAssets:
continue
""" dateTime is now the primary parameter, but old reports only have tradeDate and sometimes tradeTime """
try:
dateTime = ibTrade.attrib["dateTime"].split(";")
date = dateTime[0]
time = dateTime[1]
except:
date = ibTrade.attrib["tradeDate"]
try:
time = ibTrade.attrib["tradeTime"]
except KeyError:
time = "0"
if ibTrade.tag == "Trade":
trade = {
"conid": ibTrade.attrib["conid"],
"symbol": ibTrade.attrib["symbol"],
"currency": ibTrade.attrib["currency"],
"assetCategory": ibTrade.attrib["assetCategory"],
"tradePrice": float(ibTrade.attrib["tradePrice"]),
"quantity": float(ibTrade.attrib["quantity"]),
"buySell": ibTrade.attrib["buySell"],
"tradeDate": date,
"tradeTime": time,
"transactionID": ibTrade.attrib["transactionID"],
"ibOrderID": ibTrade.attrib["ibOrderID"],
"openCloseIndicator": ibTrade.attrib["openCloseIndicator"],
}
if len(ibTrade.attrib["isin"]) > 0:
trade["isin"] = ibTrade.attrib["isin"]
if len(ibTrade.attrib["cusip"]) > 0:
trade["cusip"] = ibTrade.attrib["cusip"]
if len(ibTrade.attrib["securityID"]) > 0:
trade["securityID"] = ibTrade.attrib["securityID"]
splitMultiplier = getSplitMultiplier(
trade["symbol"], trade["conid"], trade["tradeDate"]
)
trade["quantity"] *= splitMultiplier
trade["tradePrice"] /= splitMultiplier
if ibTrade.attrib["securityID"] != "":
trade["securityID"] = ibTrade.attrib["securityID"]
if ibTrade.attrib["isin"] != "":
trade["isin"] = ibTrade.attrib["isin"]
if ibTrade.attrib["cusip"] != "":
trade["cusip"] = ibTrade.attrib["cusip"]
if ibTrade.attrib["description"] != "":
trade["description"] = ibTrade.attrib["description"]
""" Futures and options have multipliers, i.e. a quantity of 1 with tradePrice 3 and multiplier 100 is actually a future/option for 100 stocks, worth 100 x 3 = 300 """
if "multiplier" in ibTrade.attrib:
trade["tradePrice"] = trade["tradePrice"] * float(
ibTrade.attrib["multiplier"]
)
lastTrade = trade
if "isin" in trade:
if trade["isin"] not in tradesByIsin:
tradesByIsin[trade["isin"]] = []
tradesByIsin[trade["isin"]].append(trade)
elif "cusip" in trade:
if trade["cusip"] not in tradesByCusip:
tradesByCusip[trade["cusip"]] = []
tradesByCusip[trade["cusip"]].append(trade)
elif "securityID" in trade:
if trade["securityID"] not in tradesBySecurityId:
tradesBySecurityId[trade["securityID"]] = []
tradesBySecurityId[trade["securityID"]].append(trade)
elif "conid" in trade:
if trade["conid"] not in tradesByConid:
tradesByConid[trade["conid"]] = []
tradesByConid[trade["conid"]].append(trade)
elif "symbol" in trade:
if trade["symbol"] not in tradesBySymbol:
tradesBySymbol[trade["symbol"]] = []
tradesBySymbol[trade["symbol"]].append(trade)
elif ibTrade.tag == "Lot" and lastTrade != None:
if "openTransactionIds" not in lastTrade:
lastTrade["openTransactionIds"] = {}
tid = ibTrade.attrib["transactionID"]
splitMultiplier = getSplitMultiplier(
ibTrade.attrib["symbol"], ibTrade.attrib["conid"], date
)
if tid not in lastTrade["openTransactionIds"]:
lastTrade["openTransactionIds"][tid] = (
float(ibTrade.attrib["quantity"]) * splitMultiplier
)
else:
lastTrade["openTransactionIds"][tid] += (
float(ibTrade.attrib["quantity"]) * splitMultiplier
)
"""
Merge tradesByIsin, tradesByCusip, tradesBySecurityId, tradesByConid and tradesBySymbol
into a single trades Dict with keys in the following order of precedence:
ISIN > CUSIP > securityID > CONID > Symbol
"""
trades = tradesByIsin
for cusip in tradesByCusip:
match = False
for id in trades:
for trade in trades[id]:
if "cusip" in trade and cusip == trade["cusip"]:
trades[id] += tradesByCusip[cusip]
match = True
break
if match == True:
break
if match == False:
trades[cusip] = tradesByCusip[cusip]
for securityID in tradesBySecurityId:
match = False
for id in trades:
for trade in trades[id]:
if "securityID" in trade and securityID == trade["securityID"]:
trades[id] += tradesBySecurityId[securityID]
match = True
break
if match == True:
break
if match == False:
trades[securityID] = tradesBySecurityId[securityID]
for conid in tradesByConid:
match = False
for id in trades:
for trade in trades[id]:
if "conid" in trade and conid == trade["conid"]:
trades[id] += tradesByConid[conid]
match = True
break
if match == True:
break
if match == False:
trades[conid] = tradesByConid[conid]
for symbol in tradesBySymbol:
match = False
for id in trades:
for trade in trades[id]:
if "symbol" in trade and symbol == trade["symbol"]:
trades[id] += tradesBySymbol[symbol]
match = True
break
if match == True:
break
if match == False:
trades[symbol] = tradesBySymbol[symbol]
""" If a trade is both closing and opening, i.e. it goes from negative into positive
balance or vice versa, split it into one closing and one opening trade """
for securityID in trades:
xtrades = []
for trade in trades[securityID]:
if trade["openCloseIndicator"] != "C;O":
xtrades.append(trade)
else:
openSum = 0
for openTransactionId in trade["openTransactionIds"]:
openSum += trade["openTransactionIds"][openTransactionId]
if abs(trade["quantity"]) == abs(openSum):
xtrades.append(trade)
else:
closeTrade = trade.copy()
openTrade = trade.copy()
closeTrade["openCloseIndicator"] = "C"
openTrade["openCloseIndicator"] = "O"
closeTrade["quantity"] = -openSum
openTrade["quantity"] = trade["quantity"] - closeTrade["quantity"]
del openTrade["openTransactionIds"]
xtrades.append(closeTrade)
xtrades.append(openTrade)
trades[securityID] = xtrades
""" Detect if trades are Normal or Derivates and if they are Opening or Closing positions
Convert the price to EUR """
for securityID in trades:
for trade in trades[securityID]:
if trade["currency"] == "EUR":
trade["tradePriceEUR"] = trade["tradePrice"]
else:
trade["tradePriceEUR"] = trade["tradePrice"] / getCurrencyRate(
trade["tradeDate"], trade["currency"], rates
)
if (trade["openCloseIndicator"] == "O" and trade["quantity"] > 0) or (
trade["openCloseIndicator"] == "C" and trade["quantity"] < 0
):
trade["positionType"] = "long"
else:
trade["positionType"] = "short"
if trade["assetCategory"] in normalAssets:
trade["assetType"] = "normal"
elif trade["assetCategory"] in derivateAssets:
trade["assetType"] = "derivate"
else:
sys.exit("Error: unknown asset type: %s" % trade["assetCategory"])
""" Filter trades to only include those that closed in the parameter year and trades that opened the closing position """
yearTrades = {}
for securityID in trades:
for trade in trades[securityID]:
if (
trade["tradeDate"][0:4] == str(reportYear)
and trade["openCloseIndicator"] == "C"
):
if securityID not in yearTrades:
yearTrades[securityID] = []
for xtrade in trades[securityID]:
if (
xtrade["openCloseIndicator"] == "O"
and xtrade["transactionID"] in trade["openTransactionIds"]
):
ctrade = copy.copy(xtrade)
tid = ctrade["transactionID"]
ctrade["quantity"] = trade["openTransactionIds"][tid]
yearTrades[securityID].append(ctrade)
yearTrades[securityID].append(trade)
""" Logical trade order can be executed as multiple suborders at different price. Merge suborders in a single logical order. """
mergedTrades = {}
for securityID in yearTrades:
for trade in yearTrades[securityID]:
tradeExists = False
if securityID in mergedTrades:
for previousTrade in mergedTrades[securityID]:
if (
previousTrade["ibOrderID"] == trade["ibOrderID"]
and previousTrade["openCloseIndicator"]
== trade["openCloseIndicator"]
):
previousTrade["tradePrice"] = (
previousTrade["quantity"] * previousTrade["tradePrice"]
+ trade["quantity"] * trade["tradePrice"]
) / (previousTrade["quantity"] + trade["quantity"])
previousTrade["tradePriceEUR"] = (
previousTrade["quantity"] * previousTrade["tradePriceEUR"]
+ trade["quantity"] * trade["tradePriceEUR"]
) / (previousTrade["quantity"] + trade["quantity"])
previousTrade["quantity"] = (
previousTrade["quantity"] + trade["quantity"]
)
tradeExists = True
break
if tradeExists == False:
if securityID not in mergedTrades:
mergedTrades[securityID] = []
mergedTrades[securityID].append(trade)
""" Sort the trades by time """
for securityID in mergedTrades:
l = sorted(
mergedTrades[securityID],
key=lambda k: "%s%s" % (k["tradeDate"], k["tradeTime"]),
)
mergedTrades[securityID] = l
""" Sort the trades in 4 categories """
longNormalTrades = {}
shortNormalTrades = {}
longDerivateTrades = {}
shortDerivateTrades = {}
for securityID in mergedTrades:
for trade in mergedTrades[securityID]:
if trade["assetType"] == "normal" and trade["positionType"] == "long":
if securityID not in longNormalTrades:
longNormalTrades[securityID] = []
longNormalTrades[securityID].append(trade)
elif trade["assetType"] == "normal" and trade["positionType"] == "short":
if securityID not in shortNormalTrades:
shortNormalTrades[securityID] = []
shortNormalTrades[securityID].append(trade)
elif trade["assetType"] == "derivate" and trade["positionType"] == "long":
if securityID not in longDerivateTrades:
longDerivateTrades[securityID] = []
longDerivateTrades[securityID].append(trade)
elif trade["assetType"] == "derivate" and trade["positionType"] == "short":
if securityID not in shortDerivateTrades:
shortDerivateTrades[securityID] = []
shortDerivateTrades[securityID].append(trade)
else:
sys.exit(
"Error: cannot figure out if trade is Normal or Derivate, Long or Short"
)
""" Generate the files for Normal """
envelope = xml.etree.ElementTree.Element(
"Envelope", xmlns="http://edavki.durs.si/Documents/Schemas/Doh_KDVP_9.xsd"
)
envelope.set(
"xmlns:edp", "http://edavki.durs.si/Documents/Schemas/EDP-Common-1.xsd"
)
header = xml.etree.ElementTree.SubElement(envelope, "edp:Header")
taxpayer = xml.etree.ElementTree.SubElement(header, "edp:taxpayer")
xml.etree.ElementTree.SubElement(taxpayer, "edp:taxNumber").text = taxpayerConfig[
"taxNumber"
]
xml.etree.ElementTree.SubElement(
taxpayer, "edp:taxpayerType"
).text = taxpayerConfig["taxpayerType"]
xml.etree.ElementTree.SubElement(taxpayer, "edp:name").text = taxpayerConfig["name"]
xml.etree.ElementTree.SubElement(taxpayer, "edp:address1").text = taxpayerConfig[
"address1"
]
xml.etree.ElementTree.SubElement(taxpayer, "edp:city").text = taxpayerConfig["city"]
xml.etree.ElementTree.SubElement(taxpayer, "edp:postNumber").text = taxpayerConfig[
"postNumber"
]
xml.etree.ElementTree.SubElement(taxpayer, "edp:postName").text = taxpayerConfig[
"postName"
]
xml.etree.ElementTree.SubElement(envelope, "edp:AttachmentList")
xml.etree.ElementTree.SubElement(envelope, "edp:Signatures")
body = xml.etree.ElementTree.SubElement(envelope, "body")
xml.etree.ElementTree.SubElement(body, "edp:bodyContent")
Doh_KDVP = xml.etree.ElementTree.SubElement(body, "Doh_KDVP")
KDVP = xml.etree.ElementTree.SubElement(Doh_KDVP, "KDVP")
if test == True:
xml.etree.ElementTree.SubElement(KDVP, "DocumentWorkflowID").text = "I"
else:
xml.etree.ElementTree.SubElement(KDVP, "DocumentWorkflowID").text = "O"
xml.etree.ElementTree.SubElement(KDVP, "Year").text = statementEndDate[0:4]
xml.etree.ElementTree.SubElement(KDVP, "PeriodStart").text = (
statementStartDate[0:4]
+ "-"
+ statementStartDate[4:6]
+ "-"
+ statementStartDate[6:8]
)
xml.etree.ElementTree.SubElement(KDVP, "PeriodEnd").text = (
statementEndDate[0:4]
+ "-"
+ statementEndDate[4:6]
+ "-"
+ statementEndDate[6:8]
)
xml.etree.ElementTree.SubElement(KDVP, "IsResident").text = "true"
xml.etree.ElementTree.SubElement(KDVP, "TelephoneNumber").text = taxpayerConfig[
"telephoneNumber"
]
xml.etree.ElementTree.SubElement(KDVP, "SecurityCount").text = str(
len(longNormalTrades)
)
xml.etree.ElementTree.SubElement(KDVP, "SecurityShortCount").text = str(
len(shortNormalTrades)
)
xml.etree.ElementTree.SubElement(KDVP, "SecurityWithContractCount").text = "0"
xml.etree.ElementTree.SubElement(KDVP, "SecurityWithContractShortCount").text = "0"
xml.etree.ElementTree.SubElement(KDVP, "ShareCount").text = "0"
xml.etree.ElementTree.SubElement(KDVP, "Email").text = taxpayerConfig["email"]
tradeYearsInNormalReport = set()
for securityID in longNormalTrades:
trades = longNormalTrades[securityID]
KDVPItem = xml.etree.ElementTree.SubElement(Doh_KDVP, "KDVPItem")
InventoryListType = xml.etree.ElementTree.SubElement(
KDVPItem, "InventoryListType"
).text = "PLVP"
Name = xml.etree.ElementTree.SubElement(KDVPItem, "Name").text = trades[0][
"description"
]
HasForeignTax = xml.etree.ElementTree.SubElement(
KDVPItem, "HasForeignTax"
).text = "false"
HasLossTransfer = xml.etree.ElementTree.SubElement(
KDVPItem, "HasLossTransfer"
).text = "false"
ForeignTransfer = xml.etree.ElementTree.SubElement(
KDVPItem, "ForeignTransfer"
).text = "false"
TaxDecreaseConformance = xml.etree.ElementTree.SubElement(
KDVPItem, "TaxDecreaseConformance"
).text = "false"
Securities = xml.etree.ElementTree.SubElement(KDVPItem, "Securities")
if len(trades) > 0 and "isin" in trades[0]:
ISIN = xml.etree.ElementTree.SubElement(Securities, "ISIN").text = trades[
0
]["isin"]
Code = xml.etree.ElementTree.SubElement(Securities, "Code").text = trades[0][
"symbol"
][:10]
if len(trades) > 0 and "description" in trades[0]:
Name = xml.etree.ElementTree.SubElement(Securities, "Name").text = trades[
0
]["description"]
IsFond = xml.etree.ElementTree.SubElement(Securities, "IsFond").text = "false"
F8Value = 0
n = -1
for trade in trades:
n += 1
if test == True:
tradeYear = int(trade["tradeDate"][0:4]) + testYearDiff
else:
tradeYear = int(trade["tradeDate"][0:4])
tradeYearsInNormalReport.add(str(tradeYear))
Row = xml.etree.ElementTree.SubElement(Securities, "Row")
ID = xml.etree.ElementTree.SubElement(Row, "ID").text = str(n)
if trade["quantity"] > 0:
PurchaseSale = xml.etree.ElementTree.SubElement(Row, "Purchase")
F1 = xml.etree.ElementTree.SubElement(PurchaseSale, "F1").text = (
str(tradeYear)
+ "-"
+ trade["tradeDate"][4:6]
+ "-"
+ trade["tradeDate"][6:8]
)
F2 = xml.etree.ElementTree.SubElement(PurchaseSale, "F2").text = "B"
F3 = xml.etree.ElementTree.SubElement(
PurchaseSale, "F3"
).text = "{0:.4f}".format(trade["quantity"])
F4 = xml.etree.ElementTree.SubElement(
PurchaseSale, "F4"
).text = "{0:.4f}".format(trade["tradePriceEUR"])
F5 = xml.etree.ElementTree.SubElement(
PurchaseSale, "F5"
).text = "0.0000"
else:
PurchaseSale = xml.etree.ElementTree.SubElement(Row, "Sale")
F6 = xml.etree.ElementTree.SubElement(PurchaseSale, "F6").text = (
str(tradeYear)
+ "-"
+ trade["tradeDate"][4:6]
+ "-"
+ trade["tradeDate"][6:8]
)
F7 = xml.etree.ElementTree.SubElement(
PurchaseSale, "F7"
).text = "{0:.4f}".format(-trade["quantity"])
F9 = xml.etree.ElementTree.SubElement(
PurchaseSale, "F9"
).text = "{0:.4f}".format(trade["tradePriceEUR"])
F8Value += trade["quantity"]
F8 = xml.etree.ElementTree.SubElement(Row, "F8").text = "{0:.4f}".format(
F8Value
)
for securityID in shortNormalTrades:
trades = shortNormalTrades[securityID]
KDVPItem = xml.etree.ElementTree.SubElement(Doh_KDVP, "KDVPItem")
InventoryListType = xml.etree.ElementTree.SubElement(
KDVPItem, "InventoryListType"
).text = "PLVPSHORT"
Name = xml.etree.ElementTree.SubElement(KDVPItem, "Name").text = trades[0][
"description"
]
HasForeignTax = xml.etree.ElementTree.SubElement(
KDVPItem, "HasForeignTax"
).text = "false"
HasLossTransfer = xml.etree.ElementTree.SubElement(
KDVPItem, "HasLossTransfer"
).text = "false"
ForeignTransfer = xml.etree.ElementTree.SubElement(
KDVPItem, "ForeignTransfer"
).text = "false"
TaxDecreaseConformance = xml.etree.ElementTree.SubElement(
KDVPItem, "TaxDecreaseConformance"
).text = "false"
SecuritiesShort = xml.etree.ElementTree.SubElement(KDVPItem, "SecuritiesShort")
if len(trades) > 0 and "isin" in trades[0]:
ISIN = xml.etree.ElementTree.SubElement(
SecuritiesShort, "ISIN"
).text = trades[0]["isin"]
Code = xml.etree.ElementTree.SubElement(SecuritiesShort, "Code").text = trades[
0
]["symbol"][:10]
if len(trades) > 0 and "description" in trades[0]:
Name = xml.etree.ElementTree.SubElement(
SecuritiesShort, "Name"
).text = trades[0]["description"]
IsFond = xml.etree.ElementTree.SubElement(
SecuritiesShort, "IsFond"
).text = "false"
F8Value = 0
n = -1
for trade in trades:
n += 1
if test == True:
tradeYear = int(trade["tradeDate"][0:4]) + testYearDiff
else:
tradeYear = int(trade["tradeDate"][0:4])
tradeYearsInNormalReport.add(str(tradeYear))
Row = xml.etree.ElementTree.SubElement(SecuritiesShort, "Row")
ID = xml.etree.ElementTree.SubElement(Row, "ID").text = str(n)
if trade["quantity"] > 0:
PurchaseSale = xml.etree.ElementTree.SubElement(Row, "Purchase")
F1 = xml.etree.ElementTree.SubElement(PurchaseSale, "F1").text = (
str(tradeYear)
+ "-"
+ trade["tradeDate"][4:6]
+ "-"
+ trade["tradeDate"][6:8]
)
F2 = xml.etree.ElementTree.SubElement(PurchaseSale, "F2").text = "A"
F3 = xml.etree.ElementTree.SubElement(
PurchaseSale, "F3"
).text = "{0:.4f}".format(trade["quantity"])
F4 = xml.etree.ElementTree.SubElement(
PurchaseSale, "F4"
).text = "{0:.4f}".format(trade["tradePriceEUR"])
F5 = xml.etree.ElementTree.SubElement(
PurchaseSale, "F5"
).text = "0.0000"
else:
PurchaseSale = xml.etree.ElementTree.SubElement(Row, "Sale")
F6 = xml.etree.ElementTree.SubElement(PurchaseSale, "F6").text = (
str(tradeYear)
+ "-"
+ trade["tradeDate"][4:6]
+ "-"
+ trade["tradeDate"][6:8]
)
F7 = xml.etree.ElementTree.SubElement(
PurchaseSale, "F7"
).text = "{0:.4f}".format(-trade["quantity"])
F9 = xml.etree.ElementTree.SubElement(
PurchaseSale, "F9"
).text = "{0:.4f}".format(trade["tradePriceEUR"])
F8Value += trade["quantity"]
F8 = xml.etree.ElementTree.SubElement(Row, "F8").text = "{0:.4f}".format(
F8Value
)
xmlString = xml.etree.ElementTree.tostring(envelope)
prettyXmlString = minidom.parseString(xmlString).toprettyxml(indent="\t")
with open("Doh-KDVP.xml", "w", encoding="utf-8") as f:
f.write(prettyXmlString)
if tradeYearsInNormalReport:
print(
"Doh-KDVP.xml created (includes trades from years %s)"
% ", ".join(sorted(tradeYearsInNormalReport))
)
else:
print("Doh-KDVP.xml created (includes no trades)")
""" Generate the files for Derivates """
envelope = xml.etree.ElementTree.Element(
"Envelope", xmlns="http://edavki.durs.si/Documents/Schemas/D_IFI_4.xsd"
)
envelope.set(
"xmlns:edp", "http://edavki.durs.si/Documents/Schemas/EDP-Common-1.xsd"
)
header = xml.etree.ElementTree.SubElement(envelope, "edp:Header")
taxpayer = xml.etree.ElementTree.SubElement(header, "edp:taxpayer")
xml.etree.ElementTree.SubElement(taxpayer, "edp:taxNumber").text = taxpayerConfig[
"taxNumber"
]
xml.etree.ElementTree.SubElement(
taxpayer, "edp:taxpayerType"
).text = taxpayerConfig["taxpayerType"]
xml.etree.ElementTree.SubElement(taxpayer, "edp:name").text = taxpayerConfig["name"]
xml.etree.ElementTree.SubElement(taxpayer, "edp:address1").text = taxpayerConfig[
"address1"
]
xml.etree.ElementTree.SubElement(taxpayer, "edp:city").text = taxpayerConfig["city"]
xml.etree.ElementTree.SubElement(taxpayer, "edp:postNumber").text = taxpayerConfig[
"postNumber"
]
xml.etree.ElementTree.SubElement(taxpayer, "edp:postName").text = taxpayerConfig[
"postName"
]
workflow = xml.etree.ElementTree.SubElement(header, "edp:Workflow")
if test == True:
xml.etree.ElementTree.SubElement(workflow, "edp:DocumentWorkflowID").text = "I"
else:
xml.etree.ElementTree.SubElement(workflow, "edp:DocumentWorkflowID").text = "O"
xml.etree.ElementTree.SubElement(envelope, "edp:AttachmentList")
xml.etree.ElementTree.SubElement(envelope, "edp:Signatures")
body = xml.etree.ElementTree.SubElement(envelope, "body")
xml.etree.ElementTree.SubElement(body, "edp:bodyContent")
difi = xml.etree.ElementTree.SubElement(body, "D_IFI")
xml.etree.ElementTree.SubElement(difi, "PeriodStart").text = (
statementStartDate[0:4]
+ "-"
+ statementStartDate[4:6]
+ "-"
+ statementStartDate[6:8]
)
xml.etree.ElementTree.SubElement(difi, "PeriodEnd").text = (
statementEndDate[0:4]
+ "-"
+ statementEndDate[4:6]
+ "-"
+ statementEndDate[6:8]
)
xml.etree.ElementTree.SubElement(difi, "TelephoneNumber").text = taxpayerConfig[
"telephoneNumber"
]
xml.etree.ElementTree.SubElement(difi, "Email").text = taxpayerConfig["email"]
tradeYearsInDerivateReport = set()
n = 0
for securityID in longDerivateTrades:
trades = longDerivateTrades[securityID]
n += 1
TItem = xml.etree.ElementTree.SubElement(difi, "TItem")
TypeId = xml.etree.ElementTree.SubElement(TItem, "TypeId").text = "PLIFI"
if trades[0]["assetCategory"] == "FUT":
Type = xml.etree.ElementTree.SubElement(TItem, "Type").text = "01"
TypeName = xml.etree.ElementTree.SubElement(
TItem, "TypeName"
).text = "terminska pogodba"
elif trades[0]["assetCategory"] in ["CFD", "FXCFD"]:
Type = xml.etree.ElementTree.SubElement(TItem, "Type").text = "02"
TypeName = xml.etree.ElementTree.SubElement(
TItem, "TypeName"
).text = "finančne pogodbe na razliko"
elif trades[0]["assetCategory"] in ["OPT", "FOP"]:
Type = xml.etree.ElementTree.SubElement(TItem, "Type").text = "03"
TypeName = xml.etree.ElementTree.SubElement(
TItem, "TypeName"
).text = "opcija in certifikat"
else:
Type = xml.etree.ElementTree.SubElement(TItem, "Type").text = "04"
TypeName = xml.etree.ElementTree.SubElement(
TItem, "TypeName"
).text = "drugo"
if len(trades) > 0 and "description" in trades[0]:
Name = xml.etree.ElementTree.SubElement(TItem, "Name").text = trades[0][
"description"
]
if trades[0]["assetCategory"] != "OPT" and trades[0]["assetCategory"] != "WAR":
"""Option descriptions are to long and not accepted by eDavki"""
Code = xml.etree.ElementTree.SubElement(TItem, "Code").text = trades[0][
"symbol"
][:10]
if len(trades) > 0 and "isin" in trades[0]:
ISIN = xml.etree.ElementTree.SubElement(TItem, "ISIN").text = trades[0][
"isin"
]
HasForeignTax = xml.etree.ElementTree.SubElement(
TItem, "HasForeignTax"
).text = "false"
F8Value = 0
for trade in trades:
if test == True:
tradeYear = int(trade["tradeDate"][0:4]) + testYearDiff
else:
tradeYear = int(trade["tradeDate"][0:4])
tradeYearsInDerivateReport.add(str(tradeYear))
TSubItem = xml.etree.ElementTree.SubElement(TItem, "TSubItem")
if trade["quantity"] > 0:
PurchaseSale = xml.etree.ElementTree.SubElement(TSubItem, "Purchase")
F1 = xml.etree.ElementTree.SubElement(PurchaseSale, "F1").text = (
str(tradeYear)
+ "-"
+ trade["tradeDate"][4:6]
+ "-"
+ trade["tradeDate"][6:8]
)
F2 = xml.etree.ElementTree.SubElement(PurchaseSale, "F2").text = "A"
F3 = xml.etree.ElementTree.SubElement(
PurchaseSale, "F3"
).text = "{0:.4f}".format(trade["quantity"])
F4 = xml.etree.ElementTree.SubElement(
PurchaseSale, "F4"
).text = "{0:.4f}".format(trade["tradePriceEUR"])
F9 = xml.etree.ElementTree.SubElement(PurchaseSale, "F9").text = "false"
# TODO: kako ugotovit iz reporta F9 = Trgovanje z vzvodom
else:
PurchaseSale = xml.etree.ElementTree.SubElement(TSubItem, "Sale")
F5 = xml.etree.ElementTree.SubElement(PurchaseSale, "F5").text = (
str(tradeYear)
+ "-"
+ trade["tradeDate"][4:6]
+ "-"
+ trade["tradeDate"][6:8]
)
F6 = xml.etree.ElementTree.SubElement(
PurchaseSale, "F6"
).text = "{0:.4f}".format(-trade["quantity"])
F7 = xml.etree.ElementTree.SubElement(
PurchaseSale, "F7"
).text = "{0:.4f}".format(trade["tradePriceEUR"])
F8Value += trade["quantity"]
F8 = xml.etree.ElementTree.SubElement(
TSubItem, "F8"
).text = "{0:.4f}".format(F8Value)
for securityID in shortDerivateTrades:
trades = shortDerivateTrades[securityID]
n += 1
TItem = xml.etree.ElementTree.SubElement(difi, "TItem")
TypeId = xml.etree.ElementTree.SubElement(TItem, "TypeId").text = "PLIFIShort"
if trades[0]["assetCategory"] == "FUT":
Type = xml.etree.ElementTree.SubElement(TItem, "Type").text = "01"
TypeName = xml.etree.ElementTree.SubElement(
TItem, "TypeName"
).text = "terminska pogodba"
elif trades[0]["assetCategory"] in ["CFD", "FXCFD"]:
Type = xml.etree.ElementTree.SubElement(TItem, "Type").text = "02"
TypeName = xml.etree.ElementTree.SubElement(
TItem, "TypeName"
).text = "finančne pogodbe na razliko"
elif trades[0]["assetCategory"] == "OPT":
Type = xml.etree.ElementTree.SubElement(TItem, "Type").text = "03"
TypeName = xml.etree.ElementTree.SubElement(
TItem, "TypeName"
).text = "opcija in certifikat"
else:
Type = xml.etree.ElementTree.SubElement(TItem, "Type").text = "04"
TypeName = xml.etree.ElementTree.SubElement(