summaryrefslogtreecommitdiffstats
path: root/openbb_terminal/portfolio/portfolio_optimization/parameters/params_controller.py
blob: b4debb8ee344863a57db88e8bc0caa7961c05413 (plain)
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
# type: ignore
""" Parameters Controller Module """
__docformat__ = "numpy"
# pylint: disable=C0302, no-else-return

import argparse
import contextlib
import logging
from typing import List, Optional

from openbb_terminal.core.session.current_user import get_current_user
from openbb_terminal.custom_prompt_toolkit import NestedCompleter
from openbb_terminal.decorators import log_start_end
from openbb_terminal.menu import session
from openbb_terminal.parent_classes import BaseController
from openbb_terminal.portfolio.portfolio_optimization.parameters import (
    params_helpers,
    params_view,
)
from openbb_terminal.portfolio.portfolio_optimization.parameters.params_statics import (
    AVAILABLE_OPTIONS,
    DEFAULT_BOOL,
    DEFAULT_PARAMETERS,
    MODEL_PARAMS,
)
from openbb_terminal.rich_config import MenuText, console

logger = logging.getLogger(__name__)


class ParametersController(BaseController):
    """Portfolio Optimization Parameters Controller class"""

    CHOICES_COMMANDS = [
        "set",
        "load",
        "save",
        "new",
        "clear",
        "arg",
    ]
    CHOICES_PARAMS = ["freq", "threshold", "method", "alpha", "maxnan"]
    CHOICES_COMMANDS += CHOICES_PARAMS

    PATH = "/portfolio/po/params/"

    models = [
        "maxsharpe",
        "minrisk",
        "maxutil",
        "maxret",
        "maxdiv",
        "maxdecorr",
        "ef",
        "riskparity",
        "relriskparity",
        "hrp",
        "herc",
        "nco",
    ]

    current_model = ""
    current_file = ""

    def __init__(
        self,
        file: str,
        queue: Optional[List[str]] = None,
        params: Optional[dict] = None,
        current_model=None,
    ):
        """Constructor"""
        super().__init__(queue)

        self.params: dict = params if params else {}
        self.current_file = file
        self.current_model = current_model
        self.description: Optional[str] = None
        self.DATA_FILES = params_helpers.load_data_files()

        if session and get_current_user().preferences.USE_PROMPT_TOOLKIT:
            choices: dict = self.choices_default
            choices["set"] = {c: None for c in self.models}
            choices["set"]["--model"] = {c: None for c in self.models}
            choices["set"]["-m"] = "--model"
            choices["arg"] = {c: None for c in AVAILABLE_OPTIONS}
            choices["load"] = {c: {} for c in self.DATA_FILES}
            choices["load"]["--file"] = {c: {} for c in self.DATA_FILES}
            choices["load"]["-f"] = "--file"
            choices["save"]["--file"] = None
            choices["save"]["-f"] = "--file"
            choices["arg"] = {
                "--argument": None,
                "-a": "--argument",
                "--show_arguments": {},
                "-s": "--show_arguments",
            }
            self.choices = choices
            self.completer = NestedCompleter.from_nested_dict(choices)

    def update_runtime_choices(self):
        if session and get_current_user().preferences.USE_PROMPT_TOOLKIT:
            self.DATA_FILES = params_helpers.load_data_files()
            self.choices["load"]["--file"] = {c: {} for c in self.DATA_FILES}
            self.completer = NestedCompleter.from_nested_dict(self.choices)

    def print_help(self):
        """Print help"""
        mt = MenuText("portfolio/po/params/")
        mt.add_param("_loaded", self.current_file)
        mt.add_raw("\n")
        mt.add_cmd("load")
        mt.add_cmd("save")
        mt.add_raw("\n")
        mt.add_param("_model", self.current_model or "")
        mt.add_raw("\n")
        mt.add_cmd("clear", self.current_file)
        mt.add_cmd("set", self.current_file)
        mt.add_cmd("arg", self.current_file)
        if self.current_file:
            mt.add_raw("\n")
            mt.add_info("_parameters_")
            if self.current_model:
                max_len = max(len(k) for k in self.params)
                for k, v in self.params.items():
                    clean_v = params_helpers.booltostr(v)
                    all_params = DEFAULT_PARAMETERS + MODEL_PARAMS[self.current_model]
                    if k in all_params:
                        mt.add_raw(
                            f"    [param]{k}{' ' * (max_len - len(k))} :[/param] {clean_v}\n"
                        )
            else:
                max_len = max(len(k) for k in self.params)
                for k, v in self.params.items():
                    clean_v = params_helpers.booltostr(v)
                    mt.add_raw(
                        f"    [param]{k}{' ' * (max_len - len(k))} :[/param] {clean_v}\n"
                    )
        console.print(
            text=mt.menu_text, menu="Portfolio - Portfolio Optimization - Parameters"
        )

    def custom_reset(self):
        """Class specific component of reset command"""
        if self.current_file:
            if self.current_model:
                return [
                    "portfolio",
                    "po",
                    f"file {self.current_file}",
                    "params",
                    f"set {self.current_model}",
                ]
            else:
                return ["portfolio", "po", f"file {self.current_file}", "params"]
        return []

    @log_start_end(log=logger)
    def call_load(self, other_args: List[str]):
        """Process load command"""
        parser = argparse.ArgumentParser(
            add_help=False,
            formatter_class=argparse.ArgumentDefaultsHelpFormatter,
            prog="file",
            description="Select parameter file to use (ini or xlsx). The OpenBB Parameters Template can be "
            "found inside the Portfolio Optimization documentation. Please type `about` to access the documentation.",
        )

        parser.add_argument(
            "-f",
            "--file",
            nargs="+",
            dest="file",
            help="Parameter file to be used",
        )

        if other_args and "-" not in other_args[0][0]:
            other_args.insert(0, "-f")
        ns_parser = self.parse_known_args_and_warn(parser, other_args)

        if ns_parser:
            if not ns_parser.file:
                console.print(
                    "[green]The OpenBB Parameters Template can be found inside "
                    "the Portfolio Optimization documentation. Please type `about` "
                    "to access the documentation. [green]\n"
                )
            else:
                self.current_file = " ".join(ns_parser.file)

                if self.current_file in self.DATA_FILES:
                    file_location = str(self.DATA_FILES[self.current_file])
                else:
                    file_location = str(self.current_file)

                self.params, self.current_model = params_view.load_file(file_location)

    @log_start_end(log=logger)
    def call_save(self, other_args: List[str]):
        """Process save command"""
        parser = argparse.ArgumentParser(
            add_help=False,
            formatter_class=argparse.ArgumentDefaultsHelpFormatter,
            prog="save",
            description="Save portfolio risk parameters (ini or xlsx)",
        )