/
funds.py
1171 lines (936 loc) · 42.1 KB
/
funds.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 2018-2021 Alvaro Bartolome, alvarobartt @ GitHub
# See LICENSE for details.
import json
from datetime import date, datetime, timedelta
from random import randint
import pandas as pd
import pkg_resources
import pytz
import requests
from lxml.html import fromstring
from unidecode import unidecode
from .data.funds_data import (
fund_countries_as_list,
funds_as_df,
funds_as_dict,
funds_as_list,
)
from .utils.data import Data
from .utils.extra import random_user_agent
def get_funds(country=None):
"""
This function retrieves all the available `funds` from Investing.com and returns them as a :obj:`pandas.DataFrame`,
which contains not just the fund names, but all the fields contained on the `funds.csv` file.
All the available funds can be found at: https://www.investing.com/funds/
Args:
country (:obj:`str`, optional): name of the country to retrieve all its available funds from.
Returns:
:obj:`pandas.DataFrame` - funds_df:
The resulting :obj:`pandas.DataFrame` contains all the funds basic information retrieved from Investing.com,
some of which is not useful for the user, but for the inner package functions, such as the `id` field,
for example.
In case the information was successfully retrieved, the :obj:`pandas.DataFrame` will look like::
country | name | symbol | issuer | isin | asset_class | currency | underlying
--------|------|--------|--------|------|-------------|----------|------------
xxxxxxx | xxxx | xxxxxx | xxxxxx | xxxx | xxxxxxxxxxx | xxxxxxxx | xxxxxxxxxx
Raises:
ValueError: raised whenever any of the introduced arguments is not valid or errored.
FileNotFoundError: raised when the `funds.csv` file was not found.
IOError: raised if the `funds.csv` file is missing or errored.
"""
return funds_as_df(country=country)
def get_funds_list(country=None):
"""
This function retrieves all the available funds and returns a list of each one of them.
All the available funds can be found at: https://www.investing.com/funds/
Args:
country (:obj:`str`, optional): name of the country to retrieve all its available funds from.
Returns:
:obj:`list` - funds_list:
The resulting list contains the retrieved data, which corresponds to the fund names of
every fund listed on Investing.com.
In case the information was successfully retrieved from the CSV file, the :obj:`list` will look like::
funds = [
'Blackrock Global Funds - Global Allocation Fund E2',
'Quality Inversión Conservadora Fi',
'Nordea 1 - Stable Return Fund E Eur',
...
]
Raises:
ValueError: raised whenever any of the introduced arguments is not valid or errored.
FileNotFoundError: raised when the `funds.csv` file was not found.
IOError: raised if the `funds.csv` file is missing or errored.
"""
return funds_as_list(country=country)
def get_funds_dict(country=None, columns=None, as_json=False):
"""
This function retrieves all the available funds on Investing.com and returns them as a :obj:`dict` containing
the country, name, symbol, tag, id, issuer, isin, asset_class, currency and underlying data. All the available
funds can be found at: https://www.investing.com/funds/
Args:
country (:obj:`str`, optional): name of the country to retrieve all its available funds from.
columns (:obj:`list` of :obj:`str`, optional): description
a :obj:`list` containing the column names from which the data is going to be retrieved.
as_json (:obj:`bool`, optional): description
value to determine the format of the output data (:obj:`dict` or :obj:`json`).
Returns:
:obj:`dict` or :obj:`json` - funds_dict:
The resulting :obj:`dict` contains the retrieved data if found, if not, the corresponding
fields are filled with `None` values.
In case the information was successfully retrieved, the :obj:`dict` will look like::
{
'country': country,
'name': name,
'symbol': symbol,
'issuer': issuer,
'isin': isin,
'asset_class': asset_class,
'currency': currency,
'underlying': underlying
}
Raises:
ValueError: raised whenever any of the introduced arguments is not valid or errored.
FileNotFoundError: raised when the `funds.csv` file was not found.
IOError: raised if the `funds.csv` file is missing or errored.
"""
return funds_as_dict(country=country, columns=columns, as_json=as_json)
def get_fund_countries():
"""
This function retrieves all the country names indexed in Investing.com with available funds to retrieve data
from, via reading the `fund_countries.csv` file from the resources directory. So on, this function will display a
listing containing a set of countries, in order to let the user know which countries are taken into account and also
the return listing from this function can be used for country param check if needed.
Returns:
:obj:`list` - countries:
The resulting :obj:`list` contains all the available countries with funds as indexed in Investing.com
Raises:
FileNotFoundError: raised when the `fund_countries.csv` file was not found.
IndexError: raised if `fund_countries.csv` file was unavailable or not found.
"""
return fund_countries_as_list()
def get_fund_recent_data(
fund, country, as_json=False, order="ascending", interval="Daily"
):
"""
This function retrieves recent historical data from the introduced `fund` from Investing
via Web Scraping. The resulting data can it either be stored in a :obj:`pandas.DataFrame` or in a
:obj:`json` file, with `ascending` or `descending` order.
Args:
fund (:obj:`str`): name of the fund to retrieve recent historical data from.
country (:obj:`str`): name of the country from where the introduced fund is.
as_json (:obj:`bool`, optional):
optional argument to determine the format of the output data (:obj:`pandas.DataFrame` or :obj:`json`).
order (:obj:`str`, optional):
optional argument to define the order of the retrieved data (`ascending`, `asc` or `descending`, `desc`).
interval (:obj:`str`, optional):
value to define the historical data interval to retrieve, by default `Daily`, but it can also be `Weekly` or `Monthly`.
Returns:
:obj:`pandas.DataFrame` or :obj:`json`:
The function returns a either a :obj:`pandas.DataFrame` or a :obj:`json` file containing the retrieved
recent data from the specified fund via argument. The dataset contains the open, high, low and close
values for the selected fund on market days.
The returned data is case we use default arguments will look like::
Date || Open | High | Low | Close | Currency
-----||------|------|-----|-------|----------
xxxx || xxxx | xxxx | xxx | xxxxx | xxxxxxxx
but if we define `as_json=True`, then the output will be::
{
name: name,
recent: [
{
date: dd/mm/yyyy,
open: x,
high: x,
low: x,
close: x,
currency: x
},
...
]
}
Raises:
ValueError: argument error.
IOError: funds object/file not found or unable to retrieve.
RuntimeError: introduced fund does not match any of the indexed ones.
ConnectionError: if GET requests does not return 200 status code.
IndexError: if fund information was unavailable or not found.
Examples:
>>> data = investpy.get_fund_recent_data(fund='bbva multiactivo conservador pp', country='spain')
>>> data.head()
Open High Low Close Currency
Date
2019-08-13 1.110 1.110 1.110 1.110 EUR
2019-08-16 1.109 1.109 1.109 1.109 EUR
2019-08-19 1.114 1.114 1.114 1.114 EUR
2019-08-20 1.112 1.112 1.112 1.112 EUR
2019-08-21 1.115 1.115 1.115 1.115 EUR
"""
if not fund:
raise ValueError(
"ERR#0029: fund parameter is mandatory and must be a valid fund name."
)
if not isinstance(fund, str):
raise ValueError("ERR#0028: fund argument needs to be a str.")
if country is None:
raise ValueError("ERR#0039: country can not be None, it should be a str.")
if country is not None and not isinstance(country, str):
raise ValueError("ERR#0025: specified country value not valid.")
if not isinstance(as_json, bool):
raise ValueError(
"ERR#0002: as_json argument can just be True or False, bool type."
)
if order not in ["ascending", "asc", "descending", "desc"]:
raise ValueError(
"ERR#0003: order argument can just be ascending (asc) or descending (desc),"
" str type."
)
if not interval:
raise ValueError(
"ERR#0073: interval value should be a str type and it can just be either"
" 'Daily', 'Weekly' or 'Monthly'."
)
if not isinstance(interval, str):
raise ValueError(
"ERR#0073: interval value should be a str type and it can just be either"
" 'Daily', 'Weekly' or 'Monthly'."
)
interval = interval.lower()
if interval not in ["daily", "weekly", "monthly"]:
raise ValueError(
"ERR#0073: interval value should be a str type and it can just be either"
" 'Daily', 'Weekly' or 'Monthly'."
)
resource_package = "investpy"
resource_path = "/".join(("resources", "funds.csv"))
if pkg_resources.resource_exists(resource_package, resource_path):
funds = pd.read_csv(
pkg_resources.resource_filename(resource_package, resource_path),
keep_default_na=False,
)
else:
raise FileNotFoundError("ERR#0057: funds file not found or errored.")
if funds is None:
raise IOError("ERR#0005: funds object not found or unable to retrieve.")
country = unidecode(country.strip().lower())
if country not in get_fund_countries():
raise RuntimeError(
"ERR#0034: country " + country + " not found, check if it is correct."
)
funds = funds[funds["country"].str.lower() == country]
fund = unidecode(fund.strip().lower())
if fund not in list(funds["name"].apply(unidecode).str.lower()):
raise RuntimeError(
"ERR#0019: fund " + fund + " not found, check if it is correct."
)
symbol = funds.loc[
(funds["name"].apply(unidecode).str.lower() == fund).idxmax(), "symbol"
]
id_ = funds.loc[(funds["name"].apply(unidecode).str.lower() == fund).idxmax(), "id"]
name = funds.loc[
(funds["name"].apply(unidecode).str.lower() == fund).idxmax(), "name"
]
fund_currency = funds.loc[
(funds["name"].apply(unidecode).str.lower() == fund).idxmax(), "currency"
]
header = symbol + " Historical Data"
params = {
"curr_id": id_,
"smlID": str(randint(1000000, 99999999)),
"header": header,
"interval_sec": interval.capitalize(),
"sort_col": "date",
"sort_ord": "DESC",
"action": "historical_data",
}
head = {
"User-Agent": random_user_agent(),
"X-Requested-With": "XMLHttpRequest",
"Accept": "text/html",
"Accept-Encoding": "gzip, deflate",
"Connection": "keep-alive",
}
url = "https://www.investing.com/instruments/HistoricalDataAjax"
req = requests.post(url, headers=head, data=params)
if req.status_code != 200:
raise ConnectionError(
"ERR#0015: error " + str(req.status_code) + ", try again later."
)
root_ = fromstring(req.text)
path_ = root_.xpath(".//table[@id='curr_table']/tbody/tr")
result = list()
if path_:
for elements_ in path_:
if elements_.xpath(".//td")[0].text_content() == "No results found":
raise IndexError("ERR#0008: fund information unavailable or not found.")
info = []
for nested_ in elements_.xpath(".//td"):
info.append(nested_.get("data-real-value"))
fund_date = datetime.strptime(
str(
datetime.fromtimestamp(int(info[0]), tz=pytz.timezone("GMT")).date()
),
"%Y-%m-%d",
)
fund_close = float(info[1].replace(",", ""))
fund_open = float(info[2].replace(",", ""))
fund_high = float(info[3].replace(",", ""))
fund_low = float(info[4].replace(",", ""))
result.insert(
len(result),
Data(
fund_date,
fund_open,
fund_high,
fund_low,
fund_close,
None,
fund_currency,
None,
),
)
if order in ["ascending", "asc"]:
result = result[::-1]
elif order in ["descending", "desc"]:
result = result
if as_json is True:
json_ = {"name": name, "recent": [value.fund_as_json() for value in result]}
return json.dumps(json_, sort_keys=False)
elif as_json is False:
df = pd.DataFrame.from_records([value.fund_to_dict() for value in result])
df.set_index("Date", inplace=True)
return df
else:
raise RuntimeError("ERR#0004: data retrieval error while scraping.")
def get_fund_historical_data(
fund,
country,
from_date,
to_date,
as_json=False,
order="ascending",
interval="Daily",
):
"""
This function retrieves historical data from the introduced `fund` from Investing
via Web Scraping on the introduced date range. The resulting data can it either be
stored in a :obj:`pandas.DataFrame` or in a :obj:`json` object with `ascending` or `descending` order.
Args:
fund (:obj:`str`): name of the fund to retrieve recent historical data from.
country (:obj:`str`): name of the country from where the introduced fund is.
from_date (:obj:`str`): date as `str` formatted as `dd/mm/yyyy`, from where data is going to be retrieved.
to_date (:obj:`str`): date as `str` formatted as `dd/mm/yyyy`, until where data is going to be retrieved.
as_json (:obj:`bool`, optional):
to determine the format of the output data (:obj:`pandas.DataFrame` or :obj:`json`).
order (:obj:`str`, optional):
optional argument to define the order of the retrieved data (`ascending`, `asc` or `descending`, `desc`).
interval (:obj:`str`, optional):
value to define the historical data interval to retrieve, by default `Daily`, but it can also be `Weekly` or `Monthly`.
Returns:
:obj:`pandas.DataFrame` or :obj:`json`:
The function returns a either a :obj:`pandas.DataFrame` or a :obj:`json` file containing the retrieved
recent data from the specified fund via argument. The dataset contains the open, high, low and close
values for the selected fund on market days.
The returned data is case we use default arguments will look like::
Date || Open | High | Low | Close | Currency
-----||------|------|-----|-------|----------
xxxx || xxxx | xxxx | xxx | xxxxx | xxxxxxxx
but if we define `as_json=True`, then the output will be::
{
name: name,
historical: [
{
date: dd/mm/yyyy,
open: x,
high: x,
low: x,
close: x,
currency: x
},
...
]
}
Raises:
ValueError: argument error.
IOError: funds object/file not found or unable to retrieve.
RuntimeError: introduced fund does not match any of the indexed ones.
ConnectionError: if GET requests does not return 200 status code.
IndexError: if fund information was unavailable or not found.
Examples:
>>> data = investpy.get_fund_historical_data(fund='bbva multiactivo conservador pp', country='spain', from_date='01/01/2010', to_date='01/01/2019')
>>> data.head()
Open High Low Close Currency
Date
2018-02-15 1.105 1.105 1.105 1.105 EUR
2018-02-16 1.113 1.113 1.113 1.113 EUR
2018-02-17 1.113 1.113 1.113 1.113 EUR
2018-02-18 1.113 1.113 1.113 1.113 EUR
2018-02-19 1.111 1.111 1.111 1.111 EUR
"""
if not fund:
raise ValueError(
"ERR#0029: fund parameter is mandatory and must be a valid fund name."
)
if not isinstance(fund, str):
raise ValueError("ERR#0028: fund argument needs to be a str.")
if country is None:
raise ValueError("ERR#0039: country can not be None, it should be a str.")
if country is not None and not isinstance(country, str):
raise ValueError("ERR#0025: specified country value not valid.")
if not isinstance(as_json, bool):
raise ValueError(
"ERR#0002: as_json argument can just be True or False, bool type."
)
if order not in ["ascending", "asc", "descending", "desc"]:
raise ValueError(
"ERR#0003: order argument can just be ascending (asc) or descending (desc),"
" str type."
)
if not interval:
raise ValueError(
"ERR#0073: interval value should be a str type and it can just be either"
" 'Daily', 'Weekly' or 'Monthly'."
)
if not isinstance(interval, str):
raise ValueError(
"ERR#0073: interval value should be a str type and it can just be either"
" 'Daily', 'Weekly' or 'Monthly'."
)
interval = interval.lower()
if interval not in ["daily", "weekly", "monthly"]:
raise ValueError(
"ERR#0073: interval value should be a str type and it can just be either"
" 'Daily', 'Weekly' or 'Monthly'."
)
try:
datetime.strptime(from_date, "%d/%m/%Y")
except ValueError:
raise ValueError(
"ERR#0011: incorrect start date format, it should be 'dd/mm/yyyy'."
)
try:
datetime.strptime(to_date, "%d/%m/%Y")
except ValueError:
raise ValueError(
"ERR#0012: incorrect to_date format, it should be 'dd/mm/yyyy'."
)
start_date = datetime.strptime(from_date, "%d/%m/%Y")
end_date = datetime.strptime(to_date, "%d/%m/%Y")
if start_date >= end_date:
raise ValueError(
"ERR#0032: to_date should be greater than from_date, both formatted as"
" 'dd/mm/yyyy'."
)
date_interval = {
"intervals": [],
}
flag = True
while flag is True:
diff = end_date.year - start_date.year
if diff > 19:
obj = {
"start": start_date.strftime("%m/%d/%Y"),
"end": start_date.replace(year=start_date.year + 19).strftime(
"%m/%d/%Y"
),
}
date_interval["intervals"].append(obj)
start_date = start_date.replace(year=start_date.year + 19) + timedelta(
days=1
)
else:
obj = {
"start": start_date.strftime("%m/%d/%Y"),
"end": end_date.strftime("%m/%d/%Y"),
}
date_interval["intervals"].append(obj)
flag = False
interval_limit = len(date_interval["intervals"])
interval_counter = 0
data_flag = False
resource_package = "investpy"
resource_path = "/".join(("resources", "funds.csv"))
if pkg_resources.resource_exists(resource_package, resource_path):
funds = pd.read_csv(
pkg_resources.resource_filename(resource_package, resource_path),
keep_default_na=False,
)
else:
raise FileNotFoundError("ERR#0057: funds file not found or errored.")
if funds is None:
raise IOError("ERR#0005: funds object not found or unable to retrieve.")
country = unidecode(country.strip().lower())
if country not in get_fund_countries():
raise RuntimeError(
"ERR#0034: country " + country + " not found, check if it is correct."
)
funds = funds[funds["country"].str.lower() == country]
fund = unidecode(fund.strip().lower())
if fund not in list(funds["name"].apply(unidecode).str.lower()):
raise RuntimeError(
"ERR#0019: fund " + fund + " not found, check if it is correct."
)
symbol = funds.loc[
(funds["name"].apply(unidecode).str.lower() == fund).idxmax(), "symbol"
]
id_ = funds.loc[(funds["name"].apply(unidecode).str.lower() == fund).idxmax(), "id"]
name = funds.loc[
(funds["name"].apply(unidecode).str.lower() == fund).idxmax(), "name"
]
fund_currency = funds.loc[
(funds["name"].apply(unidecode).str.lower() == fund).idxmax(), "currency"
]
final = list()
header = symbol + " Historical Data"
for index in range(len(date_interval["intervals"])):
params = {
"curr_id": id_,
"smlID": str(randint(1000000, 99999999)),
"header": header,
"st_date": date_interval["intervals"][index]["start"],
"end_date": date_interval["intervals"][index]["end"],
"interval_sec": interval.capitalize(),
"sort_col": "date",
"sort_ord": "DESC",
"action": "historical_data",
}
head = {
"User-Agent": random_user_agent(),
"X-Requested-With": "XMLHttpRequest",
"Accept": "text/html",
"Accept-Encoding": "gzip, deflate",
"Connection": "keep-alive",
}
url = "https://www.investing.com/instruments/HistoricalDataAjax"
req = requests.post(url, headers=head, data=params)
if req.status_code != 200:
raise ConnectionError(
"ERR#0015: error " + str(req.status_code) + ", try again later."
)
if not req.text:
continue
root_ = fromstring(req.text)
path_ = root_.xpath(".//table[@id='curr_table']/tbody/tr")
result = list()
if path_:
for elements_ in path_:
if elements_.xpath(".//td")[0].text_content() == "No results found":
if interval_counter < interval_limit:
data_flag = False
else:
raise IndexError(
"ERR#0008: fund information unavailable or not found."
)
else:
data_flag = True
info = []
for nested_ in elements_.xpath(".//td"):
info.append(nested_.get("data-real-value"))
if data_flag is True:
fund_date = datetime.strptime(
str(
datetime.fromtimestamp(
int(info[0]), tz=pytz.timezone("GMT")
).date()
),
"%Y-%m-%d",
)
fund_close = float(info[1].replace(",", ""))
fund_open = float(info[2].replace(",", ""))
fund_high = float(info[3].replace(",", ""))
fund_low = float(info[4].replace(",", ""))
result.insert(
len(result),
Data(
fund_date,
fund_open,
fund_high,
fund_low,
fund_close,
None,
fund_currency,
None,
),
)
if data_flag is True:
if order in ["ascending", "asc"]:
result = result[::-1]
elif order in ["descending", "desc"]:
result = result
if as_json is True:
json_list = [value.fund_as_json() for value in result]
final.append(json_list)
elif as_json is False:
df = pd.DataFrame.from_records(
[value.fund_to_dict() for value in result]
)
df.set_index("Date", inplace=True)
final.append(df)
else:
raise RuntimeError("ERR#0004: data retrieval error while scraping.")
if order in ["descending", "desc"]:
final.reverse()
if as_json is True:
json_ = {
"name": name,
"historical": [value for json_list in final for value in json_list],
}
return json.dumps(json_, sort_keys=False)
elif as_json is False:
return pd.concat(final)
def get_fund_information(fund, country, as_json=False):
"""
This function retrieves basic financial information from the specified fund. Retrieved information
from the fund can be valuable as it is additional information that can be used combined with OHLC
values, so to determine financial insights from the company which holds the specified fund.
Args:
fund (:obj:`str`): name of the fund to retrieve the financial information from.
country (:obj:`str`): name of the country from where the introduced fund is.
as_json (:obj:`bool`, optional):
optional argument to determine the format of the output data (:obj:`dict` or :obj:`json`).
Returns:
:obj:`pandas.DataFrame` or :obj:`dict`- fund_information:
The resulting :obj:`pandas.DataFrame` contains the information fields retrieved from Investing.com
from the specified fund; it can also be returned as a :obj:`dict`, if argument `as_json=True`.
If any of the information fields could not be retrieved, that field/s will be filled with
None values. If the retrieval process succeeded, the resulting :obj:`dict` will look like::
fund_information = {
'Fund Name': fund_name,
'Rating': rating,
'1-Year Change': year_change,
'Previous Close': prev_close,
'Risk Rating': risk_rating,
'TTM Yield': ttm_yield,
'ROE': roe,
'Issuer': issuer,
'Turnover': turnover,
'ROA': row,
'Inception Date': inception_date,
'Total Assets': total_assets,
'Expenses': expenses,
'Min Investment': min_investment,
'Market Cap': market_cap,
'Category': category
}
"""
if not fund:
raise ValueError(
"ERR#0029: fund parameter is mandatory and must be a valid fund name."
)
if not isinstance(fund, str):
raise ValueError("ERR#0028: fund argument needs to be a str.")
if country is None:
raise ValueError("ERR#0039: country can not be None, it should be a str.")
if country is not None and not isinstance(country, str):
raise ValueError("ERR#0025: specified country value not valid.")
if not isinstance(as_json, bool):
raise ValueError(
"ERR#0002: as_json argument can just be True or False, bool type."
)
resource_package = "investpy"
resource_path = "/".join(("resources", "funds.csv"))
if pkg_resources.resource_exists(resource_package, resource_path):
funds = pd.read_csv(
pkg_resources.resource_filename(resource_package, resource_path),
keep_default_na=False,
)
else:
raise FileNotFoundError("ERR#0057: funds file not found or errored.")
if funds is None:
raise IOError("ERR#0005: funds object not found or unable to retrieve.")
country = unidecode(country.strip().lower())
if country not in get_fund_countries():
raise RuntimeError(
"ERR#0034: country " + country + " not found, check if it is correct."
)
funds = funds[funds["country"] == country]
fund = unidecode(fund.strip().lower())
if fund not in list(funds["name"].apply(unidecode).str.lower()):
raise RuntimeError(
"ERR#0019: fund " + fund + " not found, check if it is correct."
)
tag = funds.loc[
(funds["name"].apply(unidecode).str.lower() == fund).idxmax(), "tag"
]
url = "https://www.investing.com/funds/" + tag
head = {
"User-Agent": random_user_agent(),
"X-Requested-With": "XMLHttpRequest",
"Accept": "text/html",
"Accept-Encoding": "gzip, deflate",
"Connection": "keep-alive",
}
req = requests.get(url, headers=head)
if req.status_code != 200:
raise ConnectionError(
"ERR#0015: error " + str(req.status_code) + ", try again later."
)
root_ = fromstring(req.text)
path_ = root_.xpath("//div[contains(@class, 'overviewDataTable')]/div")
result = pd.DataFrame(
columns=[
"Fund Name",
"Rating",
"1-Year Change",
"Previous Close",
"Risk Rating",
"TTM Yield",
"ROE",
"Issuer",
"Turnover",
"ROA",
"Inception Date",
"Total Assets",
"Expenses",
"Min Investment",
"Market Cap",
"Category",
]
)
result.at[0, "Fund Name"] = fund
if path_:
for elements_ in path_:
element = elements_.xpath(".//span[@class='float_lang_base_1']")[0]
title_ = element.text_content()
if title_ == "Day's Range":
title_ = "Todays Range"
if title_ in result.columns.tolist():
try:
result.at[0, title_] = float(
element.getnext().text_content().replace(",", "")
)
continue
except:
pass
try:
text = element.getnext().text_content().strip()
result.at[0, title_] = datetime.strptime(
text, "%b %d, %Y"
).strftime("%d/%m/%Y")
continue
except:
pass
try:
value = element.getnext().text_content().strip()
if value.__contains__("K"):
value = float(value.replace("K", "").replace(",", "")) * 1e3
elif value.__contains__("M"):
value = float(value.replace("M", "").replace(",", "")) * 1e6
elif value.__contains__("B"):
value = float(value.replace("B", "").replace(",", "")) * 1e9
elif value.__contains__("T"):
value = float(value.replace("T", "").replace(",", "")) * 1e12
result.at[0, title_] = value
continue
except:
pass
result.replace({"N/A": None}, inplace=True)
if as_json is True:
json_ = result.iloc[0].to_dict()
return json_
elif as_json is False:
return result
else:
raise RuntimeError("ERR#0004: data retrieval error while scraping.")
def get_funds_overview(country, as_json=False, n_results=100):
"""
This function retrieves an overview containing all the real time data available for the main funds from a country,
such as the names, symbols, current value, etc. as indexed in Investing.com. So on, the main usage of this
function is to get an overview on the main funds from a country, so to get a general view. Note that since
this function is retrieving a lot of information at once, by default just the overview of the Top 100 funds
is being retrieved, but an additional parameter called n_results can be specified so to retrieve N results.
Args:
country (:obj:`str`): name of the country to retrieve the funds overview from.
as_json (:obj:`bool`, optional):
optional argument to determine the format of the output data (:obj:`pandas.DataFrame` or :obj:`json`).
n_results (:obj:`int`, optional): number of results to be displayed on the overview table (0-1000).
Returns:
:obj:`pandas.DataFrame` - funds_overview:
The resulting :obj:`pandas.DataFrame` contains all the data available in Investing.com of the main ETFs
from a country in order to get an overview of it.
If the retrieval process succeeded, the resulting :obj:`pandas.DataFrame` should look like::
country | name | symbol | last | change | total_assets
--------|------|--------|------|--------|--------------
xxxxxxx | xxxx | xxxxxx | xxxx | xxxxxx | xxxxxxxxxxxx
Raises:
ValueError: raised if there was any argument error.
FileNotFoundError: raised when `funds.csv` file is missing.
IOError: raised if data could not be retrieved due to file error.
RuntimeError:
raised either if the introduced country does not match any of the listed ones or if no overview results could be
retrieved from Investing.com.
ConnectionError: raised if GET requests does not return 200 status code.
"""
if country is None:
raise ValueError("ERR#0039: country can not be None, it should be a str.")
if country is not None and not isinstance(country, str):
raise ValueError("ERR#0025: specified country value not valid.")
if not isinstance(as_json, bool):
raise ValueError(
"ERR#0002: as_json argument can just be True or False, bool type."
)
if not isinstance(n_results, int):
raise ValueError(
"ERR#0089: n_results argument should be an integer between 1 and 1000."
)
if 1 > n_results or n_results > 1000:
raise ValueError(
"ERR#0089: n_results argument should be an integer between 1 and 1000."
)
resource_package = "investpy"
resource_path = "/".join(("resources", "funds.csv"))
if pkg_resources.resource_exists(resource_package, resource_path):
funds = pd.read_csv(
pkg_resources.resource_filename(resource_package, resource_path),
keep_default_na=False,
)
else:
raise FileNotFoundError("ERR#0057: funds file not found or errored.")
if funds is None:
raise IOError("ERR#0005: funds object not found or unable to retrieve.")
country = unidecode(country.strip().lower())
if country not in get_fund_countries():
raise RuntimeError("ERR#0025: specified country value is not valid.")
funds = funds[funds["country"] == country]
if country.lower() == "united states":
country = "usa"
elif country.lower() == "united kingdom":
country = "uk"
head = {
"User-Agent": random_user_agent(),
"X-Requested-With": "XMLHttpRequest",
"Accept": "text/html",
"Accept-Encoding": "gzip, deflate",