forked from OpenBB-finance/LegacyCLI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeys_model.py
2489 lines (1979 loc) · 66.9 KB
/
keys_model.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
"""Keys model"""
__docformat__ = "numpy"
# pylint: disable=too-many-lines
import logging
import sys
from datetime import date
from enum import Enum
from typing import Dict, List, Union
import binance
import pandas as pd
import praw
import quandl
from alpha_vantage.timeseries import TimeSeries
from coinmarketcapapi import CoinMarketCapAPI
from nixtlats import TimeGPT
from prawcore.exceptions import ResponseException
from tokenterminal import TokenTerminal
from openbb_terminal.core.session.current_user import get_current_user, set_credential
from openbb_terminal.core.session.env_handler import write_to_dotenv
from openbb_terminal.cryptocurrency.coinbase_helpers import (
CoinbaseApiException,
CoinbaseProAuth,
make_coinbase_request,
)
from openbb_terminal.helper_funcs import request
from openbb_terminal.rich_config import console
from openbb_terminal.terminal_helper import suppress_stdout
logger = logging.getLogger(__name__)
# README PLEASE:
# The API_DICT keys must match the set and check functions format.
#
# This format is used by the KeysController and get_keys_info().
# E.g. tokenterminal -> set_tokenterminal_key & check_tokenterminal_key
#
# Don't forget to add it to the SDK.
# E.g. `keys.av,keys_model.set_av_key`
# For more info, please refer to the CONTRIBUTING.md file.
API_DICT: Dict = {
"av": "ALPHA_VANTAGE",
"fmp": "FINANCIAL_MODELING_PREP",
"quandl": "QUANDL",
"polygon": "POLYGON",
"intrinio": "INTRINIO",
"databento": "DATABENTO",
"ultima": "ULTIMA",
"fred": "FRED",
"news": "NEWSAPI",
"biztoc": "BIZTOC",
"tradier": "TRADIER",
"cmc": "COINMARKETCAP",
"finnhub": "FINNHUB",
"reddit": "REDDIT",
"binance": "BINANCE",
"bitquery": "BITQUERY",
"coinbase": "COINBASE",
"walert": "WHALE_ALERT",
"glassnode": "GLASSNODE",
"coinglass": "COINGLASS",
"cpanic": "CRYPTO_PANIC",
"ethplorer": "ETHPLORER",
"smartstake": "SMARTSTAKE",
"github": "GITHUB",
"messari": "MESSARI",
"eodhd": "EODHD",
"santiment": "SANTIMENT",
"tokenterminal": "TOKEN_TERMINAL",
"dappradar": "DAPPRADAR",
"companieshouse": "COMPANIES_HOUSE",
"nixtla": "NIXTLA",
}
# sorting api key section by name
API_DICT = dict(sorted(API_DICT.items()))
class KeyStatus(str, Enum):
"""Class to handle status messages and colors"""
DEFINED_TEST_FAILED = "Defined, test failed. Data may still be accessible."
NOT_DEFINED = "Not defined"
DEFINED_TEST_PASSED = "Defined, test passed"
DEFINED_TEST_INCONCLUSIVE = "Defined, test inconclusive"
DEFINED_NOT_TESTED = "Defined, not tested"
def __str__(self):
return self.value
def colorize(self):
c = ""
if self.name == self.DEFINED_TEST_FAILED.name:
c = "red"
elif self.name == self.NOT_DEFINED.name:
c = "grey30"
elif self.name == self.DEFINED_TEST_PASSED.name:
c = "green"
elif self.name in [
self.DEFINED_TEST_INCONCLUSIVE.name,
self.DEFINED_NOT_TESTED.name,
]:
c = "yellow"
return f"[{c}]{self.value}[/{c}]"
def set_keys(
keys_dict: Dict[str, Dict[str, Union[str, bool]]],
persist: bool = False,
show_output: bool = False,
) -> Dict:
"""Set API keys in bundle.
Parameters
----------
keys_dict: Dict[str, Dict[str, Union[str, bool]]]
More info on the required inputs for each API can be found on `keys.get_keys_info()`
persist: bool
If False, api key change will be contained to where it was changed. For example, a Jupyter notebook session.
If True, api key change will be global, i.e. it will affect terminal environment variables.
By default, False.
show_output: bool
Display status string or not. By default, False.
Returns
-------
Dict
Status of each key set.
Examples
--------
>>> from openbb_terminal.sdk import openbb
>>> d = {
"fred": {"key": "XXXXX"},
"binance": {"key": "YYYYY", "secret": "ZZZZZ"},
}
>>> openbb.keys.set_keys(keys_dict=d)
"""
status_dict = {}
for api, kwargs in keys_dict.items():
expected_args_dict = get_keys_info()
if api in expected_args_dict:
received_kwargs_list = list(kwargs.keys())
expected_kwargs_list = expected_args_dict[api]
if received_kwargs_list == expected_kwargs_list:
kwargs["persist"] = persist
kwargs["show_output"] = show_output
status_dict[api] = str(
getattr(sys.modules[__name__], "set_" + str(api) + "_key")(**kwargs)
)
else:
console.print(
f"[red]'{api}' kwargs: {received_kwargs_list} don't match expected: {expected_kwargs_list}.[/red]"
)
else:
console.print(
f"[red]API '{api}' was not recognized. Please check get_keys_info().[/red]"
)
return status_dict
def get_keys_info() -> Dict[str, List[str]]:
"""Get info on available APIs to use in set_keys.
Returns
-------
Dict[str, List[str]]
Dictionary of expected API keys and arguments
"""
args_dict = {}
for api in API_DICT:
arg_list = list(
getattr(
sys.modules[__name__], "set_" + str(api) + "_key"
).__code__.co_varnames
)
arg_list.remove("persist")
arg_list.remove("show_output")
args_dict[api] = arg_list
return args_dict
def get_keys(show: bool = False) -> pd.DataFrame:
"""Get currently set API keys.
Parameters
----------
show: bool, optional
Flag to choose whether to show actual keys or not.
By default, False.
Returns
-------
pd.DataFrame
Currents keys
Examples
--------
>>> from openbb_terminal.sdk import openbb
>>> openbb.keys.mykeys()
Key
API
BITQUERY_KEY *******
CMC_KEY *******
COINGLASS_KEY *******
"""
current_user = get_current_user()
current_keys = {}
for k, _ in current_user.credentials.get_fields().items():
field_value = current_user.credentials.get_value(field=k)
if field_value and field_value != "REPLACE_ME":
current_keys[k] = field_value
if current_keys:
df = pd.DataFrame.from_dict(current_keys, orient="index")
df.index.name = "API"
df = df.rename(columns={0: "Key"})
if show:
return df
df.loc[:, "Key"] = "*******"
return df
return pd.DataFrame()
def handle_credential(name: str, value: str, persist: bool = False):
"""Handle credential: set it for current user and optionally write to .env file.
Parameters
----------
name: str
Name of credential
value: str
Value of credential
persist: bool, optional
Write to .env file. By default, False.
"""
set_credential(name, value)
if persist:
write_to_dotenv("OPENBB_" + name, value)
def set_av_key(key: str, persist: bool = False, show_output: bool = False) -> str:
"""Set Alpha Vantage key
Parameters
----------
key: str
API key
persist: bool, optional
If False, api key change will be contained to where it was changed. For example, a Jupyter notebook session.
If True, api key change will be global, i.e. it will affect terminal environment variables.
By default, False.
show_output: bool, optional
Display status string or not. By default, False.
Returns
-------
str
Status of key set
Examples
--------
>>> from openbb_terminal.sdk import openbb
>>> openbb.keys.av(key="example_key")
"""
handle_credential("API_KEY_ALPHAVANTAGE", key, persist)
return check_av_key(show_output)
def check_av_key(show_output: bool = False) -> str:
"""Check Alpha Vantage key
Parameters
----------
show_output: bool, optional
Display status string or not. By default, False.
Returns
-------
str
Status of key set
"""
if show_output:
console.print("Checking status...")
current_user = get_current_user()
if (
current_user.credentials.API_KEY_ALPHAVANTAGE == "REPLACE_ME"
): # pragma: allowlist secret
status = KeyStatus.NOT_DEFINED
else:
df = TimeSeries(
key=current_user.credentials.API_KEY_ALPHAVANTAGE, output_format="pandas"
).get_intraday(symbol="AAPL")
if df[0].empty: # pylint: disable=no-member
logger.warning("Alpha Vantage key defined, test failed")
status = KeyStatus.DEFINED_TEST_FAILED
else:
status = KeyStatus.DEFINED_TEST_PASSED
if show_output:
console.print(status.colorize())
return str(status)
def set_fmp_key(key: str, persist: bool = False, show_output: bool = False) -> str:
"""Set Financial Modeling Prep key
Parameters
----------
key: str
API key
persist: bool, optional
If False, api key change will be contained to where it was changed. For example, a Jupyter notebook session.
If True, api key change will be global, i.e. it will affect terminal environment variables.
By default, False.
show_output: bool, optional
Display status string or not. By default, False.
Returns
-------
str
Status of key set
Examples
--------
>>> from openbb_terminal.sdk import openbb
>>> openbb.keys.fmp(key="example_key")
"""
handle_credential("API_KEY_FINANCIALMODELINGPREP", key, persist)
return check_fmp_key(show_output)
def check_fmp_key(show_output: bool = False) -> str:
"""Check Financial Modeling Prep key
Parameters
----------
show_output: bool, optional
Display status string or not. By default, False.
Returns
-------
status: str
"""
if show_output:
console.print("Checking status...")
current_user = get_current_user()
if (
current_user.credentials.API_KEY_FINANCIALMODELINGPREP
== "REPLACE_ME" # pragma: allowlist secret
): # pragma: allowlist secret
status = KeyStatus.NOT_DEFINED
else:
r = request(
f"https://financialmodelingprep.com/api/v3/profile/AAPL?apikey="
f"{current_user.credentials.API_KEY_FINANCIALMODELINGPREP}"
)
if r.status_code in [403, 401] or "Error Message" in str(r.content):
logger.warning("Financial Modeling Prep key defined, test failed")
status = KeyStatus.DEFINED_TEST_FAILED
elif r.status_code == 200:
status = KeyStatus.DEFINED_TEST_PASSED
else:
logger.warning("Financial Modeling Prep key defined, test inconclusive")
status = KeyStatus.DEFINED_TEST_INCONCLUSIVE
if show_output:
console.print(status.colorize())
return str(status)
def set_quandl_key(key: str, persist: bool = False, show_output: bool = False) -> str:
"""Set Quandl key
Parameters
----------
key: str
API key
persist: bool, optional
If False, api key change will be contained to where it was changed. For example, a Jupyter notebook session.
If True, api key change will be global, i.e. it will affect terminal environment variables.
By default, False.
show_output: bool, optional
Display status string or not. By default, False.
Returns
-------
str
Status of key set
Examples
--------
>>> from openbb_terminal.sdk import openbb
>>> openbb.keys.quandl(key="example_key")
"""
handle_credential("API_KEY_QUANDL", key, persist)
return check_quandl_key(show_output)
def check_quandl_key(show_output: bool = False) -> str:
"""Check Quandl key
Parameters
----------
show_output: bool, optional
Display status string or not. By default, False.
Returns
-------
str
Status of key set
"""
if show_output:
console.print("Checking status...")
current_user = get_current_user()
if (
current_user.credentials.API_KEY_QUANDL == "REPLACE_ME"
): # pragma: allowlist secret
status = KeyStatus.NOT_DEFINED
else:
try:
quandl.save_key(current_user.credentials.API_KEY_QUANDL)
quandl.get("EIA/PET_RWTC_D")
status = KeyStatus.DEFINED_TEST_PASSED
except Exception as _: # noqa: F841
logger.warning("Quandl key defined, test failed")
status = KeyStatus.DEFINED_TEST_FAILED
if show_output:
console.print(status.colorize())
return str(status)
def set_polygon_key(key: str, persist: bool = False, show_output: bool = False) -> str:
"""Set Polygon key
Parameters
----------
key: str
API key
persist: bool, optional
If False, api key change will be contained to where it was changed. For example, a Jupyter notebook session.
If True, api key change will be global, i.e. it will affect terminal environment variables.
By default, False.
show_output: bool, optional
Display status string or not. By default, False.
Returns
-------
str
Status of key set
Examples
--------
>>> from openbb_terminal.sdk import openbb
>>> openbb.keys.polygon(key="example_key")
"""
handle_credential("API_POLYGON_KEY", key, persist)
return check_polygon_key(show_output)
def check_polygon_key(show_output: bool = False) -> str:
"""Check Polygon key
Parameters
----------
show_output: bool
Display status string or not. By default, False.
Returns
-------
str
Status of key set
"""
if show_output:
console.print("Checking status...")
current_user = get_current_user()
if current_user.credentials.API_POLYGON_KEY == "REPLACE_ME":
status = KeyStatus.NOT_DEFINED
else:
check_date = date(date.today().year, date.today().month, 1).isoformat()
r = request(
f"https://api.polygon.io/v2/aggs/ticker/AAPL/range/1/day/{check_date}"
f"/{check_date}?apiKey={current_user.credentials.API_POLYGON_KEY}"
)
if r.status_code in [403, 401]:
logger.warning("Polygon key defined, test failed")
status = KeyStatus.DEFINED_TEST_FAILED
elif r.status_code == 200:
status = KeyStatus.DEFINED_TEST_PASSED
else:
logger.warning("Polygon key defined, test inconclusive")
status = KeyStatus.DEFINED_TEST_INCONCLUSIVE
if show_output:
console.print(status.colorize())
return str(status)
def set_fred_key(key: str, persist: bool = False, show_output: bool = False) -> str:
"""Set FRED key
Parameters
----------
key: str
API key
persist: bool, optional
If False, api key change will be contained to where it was changed. For example, a Jupyter notebook session.
If True, api key change will be global, i.e. it will affect terminal environment variables.
By default, False.
show_output: bool, optional
Display status string or not. By default, False.
Returns
-------
str
Status of key set
Examples
--------
>>> from openbb_terminal.sdk import openbb
>>> openbb.keys.fred(key="example_key")
"""
handle_credential("API_FRED_KEY", key, persist)
return check_fred_key(show_output)
def check_fred_key(show_output: bool = False) -> str:
"""Check FRED key
Parameters
----------
show_output: bool, optional
Display status string or not. By default, False.
Returns
-------
str
Status of key set
"""
if show_output:
console.print("Checking status...")
current_user = get_current_user()
if current_user.credentials.API_FRED_KEY == "REPLACE_ME":
status = KeyStatus.NOT_DEFINED
else:
r = request(
f"https://api.stlouisfed.org/fred/series?series_id=GNPCA&api_key={current_user.credentials.API_FRED_KEY}"
)
if r.status_code in [403, 401, 400]:
logger.warning("FRED key defined, test failed")
status = KeyStatus.DEFINED_TEST_FAILED
elif r.status_code == 200:
status = KeyStatus.DEFINED_TEST_PASSED
else:
logger.warning("FRED key defined, test inconclusive")
status = KeyStatus.DEFINED_TEST_INCONCLUSIVE
if show_output:
console.print(status.colorize())
return str(status)
def set_news_key(key: str, persist: bool = False, show_output: bool = False) -> str:
"""Set News key
Parameters
----------
key: str
API key
persist: bool, optional
If False, api key change will be contained to where it was changed. For example, a Jupyter notebook session.
If True, api key change will be global, i.e. it will affect terminal environment variables.
By default, False.
show_output: bool, optional
Display status string or not. By default, False.
Returns
-------
str
Status of key set
Examples
--------
>>> from openbb_terminal.sdk import openbb
>>> openbb.keys.news(key="example_key")
"""
handle_credential("API_NEWS_TOKEN", key, persist)
return check_news_key(show_output)
def check_news_key(show_output: bool = False) -> str:
"""Check News key
Parameters
----------
show_output: bool, optional
Display status string or not. By default, False.
Returns
-------
str
Status of key set
"""
if show_output:
console.print("Checking status...")
current_user = get_current_user()
if current_user.credentials.API_NEWS_TOKEN == "REPLACE_ME": # nosec# noqa: S105
status = KeyStatus.NOT_DEFINED
else:
r = request(
f"https://newsapi.org/v2/everything?q=keyword&apiKey={current_user.credentials.API_NEWS_TOKEN}"
)
if r.status_code in [401, 403]:
logger.warning("News API key defined, test failed")
status = KeyStatus.DEFINED_TEST_FAILED
elif r.status_code == 200:
status = KeyStatus.DEFINED_TEST_PASSED
else:
logger.warning("News API key defined, test inconclusive")
status = KeyStatus.DEFINED_TEST_INCONCLUSIVE
if show_output:
console.print(status.colorize())
return str(status)
def set_biztoc_key(key: str, persist: bool = False, show_output: bool = False) -> str:
"""Set BizToc key
Parameters
----------
key: str
API key
persist: bool, optional
If False, api key change will be contained to where it was changed. For example, a Jupyter notebook session.
If True, api key change will be global, i.e. it will affect terminal environment variables.
By default, False.
show_output: bool, optional
Display status string or not. By default, False.
Returns
-------
str
Status of key set
Examples
--------
>>> from openbb_terminal.sdk import openbb
>>> openbb.keys.biztoc(key="example_key")
"""
handle_credential("API_BIZTOC_TOKEN", key, persist)
return check_biztoc_key(show_output)
def check_biztoc_key(show_output: bool = False) -> str:
"""Check BizToc key
Parameters
----------
show_output: bool, optional
Display status string or not. By default, False.
Returns
-------
str
Status of key set
"""
if show_output:
console.print("Checking status...")
current_user = get_current_user()
if current_user.credentials.API_BIZTOC_TOKEN == "REPLACE_ME": # nosec# noqa: S105
status = KeyStatus.NOT_DEFINED
else:
r = request(
"https://biztoc.p.rapidapi.com/pages",
headers={
"X-RapidAPI-Key": current_user.credentials.API_BIZTOC_TOKEN,
"X-RapidAPI-Host": "biztoc.p.rapidapi.com",
},
)
if r.status_code in [401, 403, 404]:
logger.warning("BizToc API key defined, test failed")
status = KeyStatus.DEFINED_TEST_FAILED
elif r.status_code == 200:
status = KeyStatus.DEFINED_TEST_PASSED
else:
logger.warning("BizToc API key defined, test inconclusive")
status = KeyStatus.DEFINED_TEST_INCONCLUSIVE
if show_output:
console.print(status.colorize())
return str(status)
def set_tradier_key(key: str, persist: bool = False, show_output: bool = False) -> str:
"""Set Tradier key
Parameters
----------
key: str
API key
persist: bool, optional
If False, api key change will be contained to where it was changed. For example, a Jupyter notebook session.
If True, api key change will be global, i.e. it will affect terminal environment variables.
By default, False.
show_output: bool, optional
Display status string or not. By default, False.
Returns
-------
str
Status of key set
Examples
--------
>>> from openbb_terminal.sdk import openbb
>>> openbb.keys.tradier(key="example_key")
"""
handle_credential("API_TRADIER_TOKEN", key, persist)
return check_tradier_key(show_output)
def check_tradier_key(show_output: bool = False) -> str:
"""Check Tradier key
Parameters
----------
show_output: bool
Display status string or not. By default, False.
Returns
-------
str
Status of key set
"""
if show_output:
console.print("Checking status...")
current_user = get_current_user()
if current_user.credentials.API_TRADIER_TOKEN == "REPLACE_ME": # nosec# noqa: S105
status = KeyStatus.NOT_DEFINED
else:
r = request(
"https://sandbox.tradier.com/v1/markets/quotes",
params={"symbols": "AAPL"},
headers={
"Authorization": f"Bearer {current_user.credentials.API_TRADIER_TOKEN}",
"Accept": "application/json",
},
)
if r.status_code in [401, 403]:
logger.warning("Tradier key not defined, test failed")
status = KeyStatus.DEFINED_TEST_FAILED
elif r.status_code == 200:
status = KeyStatus.DEFINED_TEST_PASSED
else:
logger.warning("Tradier key not defined, test inconclusive")
status = KeyStatus.DEFINED_TEST_INCONCLUSIVE
if show_output:
console.print(status.colorize())
return str(status)
def set_cmc_key(key: str, persist: bool = False, show_output: bool = False) -> str:
"""Set Coinmarketcap key
Parameters
----------
key: str
API key
persist: bool, optional
If False, api key change will be contained to where it was changed. For example, a Jupyter notebook session.
If True, api key change will be global, i.e. it will affect terminal environment variables.
By default, False.
show_output: bool, optional
Display status string or not. By default, False.
Returns
-------
str
Status of key set
Examples
--------
>>> from openbb_terminal.sdk import openbb
>>> openbb.keys.cmc(key="example_key")
"""
handle_credential("API_CMC_KEY", key, persist)
return check_cmc_key(show_output)
def check_cmc_key(show_output: bool = False) -> str:
"""Check Coinmarketcap key
Parameters
----------
show_output: bool
Display status string or not. By default, False.
Returns
-------
status: str
"""
if show_output:
console.print("Checking status...")
current_user = get_current_user()
if current_user.credentials.API_CMC_KEY == "REPLACE_ME":
status = KeyStatus.NOT_DEFINED
else:
cmc = CoinMarketCapAPI(current_user.credentials.API_CMC_KEY)
try:
cmc.cryptocurrency_map()
status = KeyStatus.DEFINED_TEST_PASSED
except Exception:
status = KeyStatus.DEFINED_TEST_FAILED
if show_output:
console.print(status.colorize())
return str(status)
def set_finnhub_key(key: str, persist: bool = False, show_output: bool = False) -> str:
"""Set Finnhub key
Parameters
----------
key: str
API key
persist: bool, optional
If False, api key change will be contained to where it was changed. For example, a Jupyter notebook session.
If True, api key change will be global, i.e. it will affect terminal environment variables.
By default, False.
show_output: bool, optional
Display status string or not. By default, False.
Returns
-------
str
Status of key set
Examples
--------
>>> from openbb_terminal.sdk import openbb
>>> openbb.keys.finnhub(key="example_key")
"""
handle_credential("API_FINNHUB_KEY", key, persist)
return check_finnhub_key(show_output)
def check_finnhub_key(show_output: bool = False) -> str:
"""Check Finnhub key
Parameters
----------
show_output: bool
Display status string or not. By default, False.
Returns
-------
str
Status of key set
"""
if show_output:
console.print("Checking status...")
current_user = get_current_user()
if current_user.credentials.API_FINNHUB_KEY == "REPLACE_ME":
status = KeyStatus.NOT_DEFINED
else:
r = request(
f"https://finnhub.io/api/v1/quote?symbol=AAPL&token={current_user.credentials.API_FINNHUB_KEY}"
)
if r.status_code in [403, 401, 400]:
logger.warning("Finnhub key defined, test failed")
status = KeyStatus.DEFINED_TEST_FAILED
elif r.status_code == 200:
status = KeyStatus.DEFINED_TEST_PASSED
else:
logger.warning("Finnhub key defined, test inconclusive")
status = KeyStatus.DEFINED_TEST_INCONCLUSIVE
if show_output:
console.print(status.colorize())
return str(status)
def set_reddit_key(
client_id: str,
client_secret: str,
password: str,
username: str,
useragent: str,
persist: bool = False,
show_output: bool = False,
) -> str:
"""Set Reddit key
Parameters
----------
client_id: str
Client ID
client_secret: str
Client secret
password: str
User password
username: str
User username
useragent: str
User useragent
persist: bool, optional
If False, api key change will be contained to where it was changed. For example, a Jupyter notebook session.
If True, api key change will be global, i.e. it will affect terminal environment variables.
By default, False.
show_output: bool, optional
Display status string or not. By default, False.
Returns
-------
str
Status of key set
Examples
--------
>>> from openbb_terminal.sdk import openbb
>>> openbb.keys.reddit(
client_id="example_id",
client_secret="example_secret",
password="example_password",
username="example_username",
useragent="example_useragent"
)
"""