/
ratios_controller.py
6322 lines (5262 loc) · 245 KB
/
ratios_controller.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
"""Ratios Module"""
__docformat__ = "google"
import numpy as np
import pandas as pd
from financetoolkit.helpers import calculate_growth, handle_errors
from financetoolkit.ratios import (
efficiency_model,
liquidity_model,
profitability_model,
solvency_model,
valuation_model,
)
# pylint: disable=too-many-lines,too-many-instance-attributes,too-many-public-methods,too-many-locals,eval-used
class Ratios:
"""
The Ratios Module contains over 50+ ratios that can be used to analyse companies.
These ratios are divided into 5 categories which are efficiency, liquidity,
profitability, solvency and valuation. Each ratio is calculated using
the data from the Toolkit module.
"""
def __init__(
self,
tickers: str | list[str],
historical: pd.DataFrame,
balance: pd.DataFrame,
income: pd.DataFrame,
cash: pd.DataFrame,
custom_ratios_dict: dict | None = None,
quarterly: bool = False,
rounding: int | None = 4,
):
"""
Initializes the Ratios Controller Class.
Args:
tickers (str | list[str]): The tickers to use for the calculations.
historical (pd.DataFrame): The historical data to use for the calculations.
balance (pd.DataFrame): The balance sheet data to use for the calculations.
income (pd.DataFrame): The income statement data to use for the calculations.
cash (pd.DataFrame): The cash flow statement data to use for the calculations.
custom_ratios_dict (dict, optional): A dictionary containing the custom ratios to calculate. This is
an optional parameter given that you can also define the custom ratios through the Toolkit initialization.
quarterly (bool, optional): Whether to use quarterly data. Defaults to False.
rounding (int, optional): The number of decimals to round the results to. Defaults to 4.
As an example:
```python
from financetoolkit import Toolkit
toolkit = Toolkit(["AAPL", "TSLA"], api_key=FMP_KEY)
profitability_ratios = toolkit.ratios.collect_profitability_ratios()
profitability_ratios.loc['AAPL']
```
Which returns:
| | 2018 | 2019 | 2020 | 2021 | 2022 |
|:--------------------------------------------|---------:|---------:|---------:|---------:|---------:|
| Gross Margin | 0.383437 | 0.378178 | 0.382332 | 0.417794 | 0.433096 |
| Operating Margin | 0.26694 | 0.24572 | 0.241473 | 0.297824 | 0.302887 |
| Net Profit Margin | 0.224142 | 0.212381 | 0.209136 | 0.258818 | 0.253096 |
| Interest Burden Ratio | 1.02828 | 1.02827 | 1.01211 | 1.00237 | 0.997204 |
| Income Before Tax Profit Margin | 0.274489 | 0.252666 | 0.244398 | 0.298529 | 0.30204 |
| Effective Tax Rate | 0.183422 | 0.159438 | 0.144282 | 0.133023 | 0.162045 |
| Return on Assets (ROA) | 0.162775 | 0.16323 | 0.177256 | 0.269742 | 0.282924 |
| Return on Equity (ROE) | 0.555601 | 0.610645 | 0.878664 | 1.50071 | 1.96959 |
| Return on Invested Capital (ROIC) | 0.269858 | 0.293721 | 0.344126 | 0.503852 | 0.562645 |
| Return on Capital Employed (ROCE) | 0.305968 | 0.297739 | 0.320207 | 0.495972 | 0.613937 |
| Return on Tangible Assets | 0.555601 | 0.610645 | 0.878664 | 1.50071 | 1.96959 |
| Income Quality Ratio | 1.30073 | 1.25581 | 1.4052 | 1.09884 | 1.22392 |
| Net Income per EBT | 0.816578 | 0.840562 | 0.855718 | 0.866977 | 0.837955 |
| Free Cash Flow to Operating Cash Flow Ratio | 0.828073 | 0.848756 | 0.909401 | 0.893452 | 0.912338 |
| EBT to EBIT Ratio | 0.957448 | 0.948408 | 0.958936 | 0.976353 | 0.975982 |
| EBIT to Revenue | 0.286688 | 0.26641 | 0.254864 | 0.305759 | 0.309473 |
```
"""
self._tickers = tickers
self._balance_sheet_statement: pd.DataFrame = balance
self._income_statement: pd.DataFrame = income
self._cash_flow_statement: pd.DataFrame = cash
self._custom_ratios_dict: dict = (
custom_ratios_dict if custom_ratios_dict else {}
)
self._custom_ratios: pd.DataFrame = pd.DataFrame()
self._custom_ratios_growth: pd.DataFrame = pd.DataFrame()
self._rounding: int | None = rounding
self._quarterly: bool = quarterly
# Initialization of Historical Data
self._historical_data: pd.DataFrame = historical
# Initialization of Fundamentals Variables
self._all_ratios: pd.DataFrame = pd.DataFrame()
self._all_ratios_growth: pd.DataFrame = pd.DataFrame()
self._efficiency_ratios: pd.DataFrame = pd.DataFrame()
self._efficiency_ratios_growth: pd.DataFrame = pd.DataFrame()
self._liquidity_ratios: pd.DataFrame = pd.DataFrame()
self._liquidity_ratios_growth: pd.DataFrame = pd.DataFrame()
self._profitability_ratios: pd.DataFrame = pd.DataFrame()
self._profitability_ratios_growth: pd.DataFrame = pd.DataFrame()
self._solvency_ratios: pd.DataFrame = pd.DataFrame()
self._solvency_ratios_growth: pd.DataFrame = pd.DataFrame()
self._valuation_ratios: pd.DataFrame = pd.DataFrame()
self._valuation_ratios_growth: pd.DataFrame = pd.DataFrame()
@handle_errors
def collect_all_ratios(
self,
include_dividends: bool = False,
diluted: bool = True,
days: int | float | None = None,
rounding: int | None = None,
growth: bool = False,
lag: int | list[int] = 1,
trailing: int | None = None,
) -> pd.Series | pd.DataFrame:
"""
Calculates and collects all ratios based on the provided data.
Args:
include_dividends (bool, optional): Whether to include dividends in the calculations.
Defaults to False.
diluted (bool, optional): Whether to use diluted shares for the calculation.
Defaults to True.
days (int, optional): The number of days to use for the calculation. Defaults to 365.
rounding (int, optional): The number of decimals to round the results to. Defaults to 4.
growth (bool, optional): Whether to calculate the growth of the ratios. Defaults to False.
lag (int | str, optional): The lag to use for the growth calculation. Defaults to 1.
trailing (int): Defines whether to select a trailing period.
E.g. when selecting 4 with quarterly data, the TTM is calculated.
Returns:
pd.Series or pd.DataFrame: Ratios calculated based on the specified parameters.
Notes:
- The method calculates various ratios for each asset in the Toolkit instance.
- If `growth` is set to True, the method calculates the growth of the ratio values
using the specified `lag`.
As an example:
```python
from financetoolkit import Toolkit
toolkit = Toolkit(["AAPL", "TSLA"], api_key=FMP_KEY)
toolkit.ratios.collect_all_ratios()
```
"""
if not days:
days = 365 / 4 if self._quarterly else 365
if self._efficiency_ratios.empty:
self.collect_efficiency_ratios(days=days, trailing=trailing)
if self._liquidity_ratios.empty:
self.collect_liquidity_ratios(trailing=trailing)
if self._profitability_ratios.empty:
self.collect_profitability_ratios(trailing=trailing)
if self._solvency_ratios.empty:
self.collect_solvency_ratios(diluted=diluted, trailing=trailing)
if self._valuation_ratios.empty:
self.collect_valuation_ratios(
include_dividends=include_dividends, diluted=diluted, trailing=trailing
)
self._all_ratios = pd.concat(
[
self._efficiency_ratios,
self._liquidity_ratios,
self._profitability_ratios,
self._solvency_ratios,
self._valuation_ratios,
]
)
self._all_ratios = self._all_ratios.round(
rounding if rounding else self._rounding
)
all_ratios = self._all_ratios
if growth:
self._all_ratios_growth = calculate_growth(
all_ratios,
lag=lag,
rounding=rounding if rounding else self._rounding,
axis="columns",
)
if len(self._tickers) == 1:
return (
self._all_ratios_growth[self._tickers[0]]
if growth
else all_ratios.loc[self._tickers[0]]
)
return self._all_ratios_growth if growth else all_ratios
@handle_errors
def collect_custom_ratios(
self,
custom_ratios_dict: dict | None = None,
rounding: int | None = None,
growth: bool = False,
lag: int | list[int] = 1,
):
"""
Calculates all Custom Ratios based on the data provided.
Note that any of the following characters are considered as operators:
+, -, *, /, **, %, //, <, >, ==, !=, >=, <=, (, )
using any of the above characters as part of the column naming will result into an error.
Args:
custom_ratios (dict, optional): A dictionary containing the custom ratios to calculate. This is
an optional parameter given that you can also define the custom ratios through the Toolkit initialization.
rounding (int, optional): The number of decimals to round the results to. Defaults to 4.
growth (bool, optional): Whether to calculate the growth of the ratios. Defaults to False.
lag (int | str, optional): The lag to use for the growth calculation. Defaults to 1.
trailing (int): Defines whether to select a trailing period.
E.g. when selecting 4 with quarterly data, the TTM is calculated.
Returns:
pd.DataFrame: Custom ratios calculated based on the specified parameters.
Notes:
- The method calculates various custom ratios for each asset in the Toolkit instance.
- If `growth` is set to True, the method calculates the growth of the ratio values
using the specified `lag`.
As an example:
```python
from financetoolkit import Toolkit
custom_ratios = {
'WC / Net Income as %': '(Working Capital / Net Income) * 100',
'Large Revenues': 'Revenue > 1000000000',
'Quick Assets': 'Cash and Short Term Investments + Accounts Receivable',
'Cash Op Expenses':'Cost of Goods Sold + Selling, General and Administrative Expenses '
'- Depreciation and Amortization',
'Daily Cash Op Expenses': 'Cash Op Expenses / 365',
'Defensive Interval':'Quick Assets / Daily Cash Op Expenses'
}
companies = Toolkit(
["AAPL", "MSFT", "GOOGL", "AMZN"], api_key=API_KEY, start_date="2022-10-01",
custom_ratios=custom_ratios, quarterly=True
)
custom_ratios = companies.ratios.collect_custom_ratios()
custom_ratios.loc['AMZN']
```
Which returns:
| | 2022Q4 | 2023Q1 | 2023Q2 | 2023Q3 |
|:-----------------------|---------------:|---------------:|---------------:|---------:|
| Cash Op Expenses | 2.1856e+10 | 1.9972e+10 | 2.1322e+10 | nan |
| Daily Cash Op Expenses | 5.98795e+07 | 5.47178e+07 | 5.84164e+07 | nan |
| Defensive Interval | 2260.22 | 2592.34 | 2738.1 | nan |
| Large Revenues | 1 | 1 | 1 | 0 |
| Quick Assets | 1.35341e+11 | 1.41847e+11 | 1.5995e+11 | nan |
| WC / Net Income as % | 463.349 | 427.335 | 398.924 | nan |
"""
if not self._custom_ratios_dict and not custom_ratios_dict:
print(
"Please define custom ratios through the Toolkit initialization or include a "
"dictionary to the custom_ratios_dict parameter.\nSee "
"https://www.jeroenbouma.com/projects/financetoolkit/custom-ratios how to do this."
)
custom_ratios_dict = (
custom_ratios_dict if custom_ratios_dict else self._custom_ratios_dict
)
if self._all_ratios.empty:
self.collect_all_ratios()
custom_ratios = pd.DataFrame(
0,
index=pd.MultiIndex.from_product(
[self._tickers, custom_ratios_dict.keys()]
),
columns=self._balance_sheet_statement.columns,
)
total_financials = pd.concat(
[
self._balance_sheet_statement,
self._income_statement,
self._cash_flow_statement,
self._all_ratios,
custom_ratios,
],
axis=0,
)
total_financials = total_financials[
~total_financials.index.duplicated(keep="first")
]
formula_dict = {}
for name, formula in custom_ratios_dict.items():
# Rearrange the formula dict in case a formula is dependent on another formula
# and the order would result into errors
for sub_name, sub_formula in custom_ratios_dict.items():
if sub_name in formula:
formula_dict[sub_name] = sub_formula
if name not in formula_dict:
formula_dict[name] = formula
for name, formula in formula_dict.items():
formula_names = formula
for operator in [
"+",
"-",
"*",
"/",
"**",
"%",
"//",
"<",
">",
"==",
"!=",
">=",
"<=",
"(",
")",
]:
formula_names = formula_names.replace(operator, "SPLIT")
formula_names = formula_names.split("SPLIT")
formula_names = [
clean_name
for clean_name in formula_names
if clean_name not in ["", " "]
]
formula_adjusted = formula
for formula_section in formula_names:
formula_section_stripped = formula_section.strip()
if formula_section_stripped in total_financials.index.get_level_values(
1
):
formula_adjusted = formula_adjusted.replace(
formula_section_stripped,
f"total_financials.loc[:, '{formula_section_stripped}', :]",
)
else:
try:
float(formula_section_stripped)
except ValueError:
formula_adjusted = None
print(
f"Column {formula_section_stripped} not found in total_financials and is not a number. "
f"Therefore the formula {formula} is invalid."
)
break
if formula_adjusted:
calculation = eval(formula_adjusted) # noqa
total_financials.loc[:, name, :] = calculation.astype(
np.float64
).to_numpy()
self._custom_ratios = total_financials.loc[
:, list(custom_ratios_dict.keys()), :
]
self._custom_ratios = self._custom_ratios.sort_index(
axis=0, level=0, sort_remaining=False
)
self._custom_ratios = self._custom_ratios.round(
rounding if rounding else self._rounding
)
if growth:
self._custom_ratios_growth = calculate_growth(
self._custom_ratios,
lag=lag,
rounding=rounding if rounding else self._rounding,
axis="columns",
)
if len(self._tickers) == 1:
return (
self._custom_ratios_growth[self._tickers[0]]
if growth
else self._custom_ratios.loc[self._tickers[0]]
)
return self._custom_ratios_growth if growth else self._custom_ratios
def collect_efficiency_ratios(
self,
days: int | float | None = None,
rounding: int | None = None,
growth: bool = False,
lag: int | list[int] = 1,
trailing: int | None = None,
) -> pd.Series | pd.DataFrame:
"""
Calculates and collects all Efficiency Ratios based on the provided data.
Args:
days (int, optional): The number of days to use for the calculation. Defaults to 365.
rounding (int, optional): The number of decimals to round the results to. Defaults to 4.
growth (bool, optional): Whether to calculate the growth of the ratios. Defaults to False.
lag (int | str, optional): The lag to use for the growth calculation. Defaults to 1.
trailing (int): Defines whether to select a trailing period.
E.g. when selecting 4 with quarterly data, the TTM is calculated.
Returns:
pd.Series or pd.DataFrame: Efficiency ratios calculated based on the specified parameters.
Notes:
- The method calculates various efficiency ratios for each asset in the Toolkit instance.
- If `growth` is set to True, the method calculates the growth of the ratio values
using the specified `lag`.
As an example:
```python
from financetoolkit import Toolkit
toolkit = Toolkit(["AAPL", "TSLA"], api_key=FMP_KEY)
toolkit.ratios.collect_efficiency_ratios()
```
"""
if not days:
days = 365 / 4 if self._quarterly else 365
efficiency_ratios: dict = {}
efficiency_ratios[
"Days of Inventory Outstanding (DIO)"
] = self.get_days_of_inventory_outstanding(days=days, trailing=trailing)
efficiency_ratios[
"Days of Sales Outstanding (DSO)"
] = self.get_days_of_sales_outstanding(days=days, trailing=trailing)
efficiency_ratios["Operating Cycle (CC)"] = self.get_operating_cycle(
trailing=trailing
)
efficiency_ratios[
"Days of Accounts Payable Outstanding (DPO)"
] = self.get_days_of_accounts_payable_outstanding(days=days, trailing=trailing)
efficiency_ratios[
"Cash Conversion Cycle (CCC)"
] = self.get_cash_conversion_cycle(days=days)
efficiency_ratios["Receivables Turnover"] = self.get_receivables_turnover(
trailing=trailing
)
efficiency_ratios[
"Inventory Turnover Ratio"
] = self.get_inventory_turnover_ratio()
efficiency_ratios[
"Accounts Payable Turnover Ratio"
] = self.get_accounts_payables_turnover_ratio()
efficiency_ratios["SGA-to-Revenue Ratio"] = self.get_sga_to_revenue_ratio(
trailing=trailing
)
efficiency_ratios["Fixed Asset Turnover"] = self.get_fixed_asset_turnover(
trailing=trailing
)
efficiency_ratios["Asset Turnover Ratio"] = self.get_asset_turnover_ratio(
trailing=trailing
)
efficiency_ratios["Operating Ratio"] = self.get_operating_ratio(
trailing=trailing
)
self._efficiency_ratios = (
pd.concat(efficiency_ratios)
.swaplevel(0, 1)
.sort_index(level=0, sort_remaining=False)
.dropna(axis="columns", how="all")
)
self._efficiency_ratios = self._efficiency_ratios.round(
rounding if rounding else self._rounding
)
efficiency_ratios_df = self._efficiency_ratios
if growth:
self._efficiency_ratios_growth = calculate_growth(
efficiency_ratios_df,
lag=lag,
rounding=rounding if rounding else self._rounding,
axis="columns",
)
if len(self._tickers) == 1:
return (
self._efficiency_ratios_growth[self._tickers[0]]
if growth
else efficiency_ratios_df.loc[self._tickers[0]]
)
return self._efficiency_ratios_growth if growth else efficiency_ratios_df
@handle_errors
def get_asset_turnover_ratio(
self,
rounding: int | None = None,
growth: bool = False,
lag: int | list[int] = 1,
trailing: int | None = None,
) -> pd.DataFrame:
"""
Calculate the asset turnover ratio, an efficiency ratio that measures how
efficiently a company uses its assets to generate sales.
The asset turnover ratio is calculated by dividing the company's net sales
(revenue) by its average total assets. It measures how well a company utilizes
its assets to generate revenue. A higher asset turnover ratio indicates that the
company is generating more revenue per unit of assets, which is generally seen
as a positive sign of operational efficiency.
The formula is as follows:
Asset Turnover Ratio = Net Sales / Average Total Assets
Args:
rounding (int, optional): The number of decimals to round the results to. Defaults to 4.
growth (bool, optional): Whether to calculate the growth of the ratios. Defaults to False.
lag (int | str, optional): The lag to use for the growth calculation. Defaults to 1.
trailing (int): Defines whether to select a trailing period.
E.g. when selecting 4 with quarterly data, the TTM is calculated.
Returns:
pd.Series: Asset turnover ratio values.
Notes:
- The method retrieves historical data and calculates the asset turnover ratio
for each asset in the Toolkit instance.
- If `growth` is set to True, the method calculates the growth of the ratio values
using the specified `lag`.
As an example:
```python
from financetoolkit import Toolkit
toolkit = Toolkit(["AAPL", "TSLA"], api_key=FMP_KEY)
asset_turnover_ratios = toolkit.ratios.get_asset_turnover_ratio()
```
"""
if trailing:
asset_turnover_ratio = efficiency_model.get_asset_turnover_ratio(
self._income_statement.loc[:, "Revenue", :].T.rolling(trailing).sum().T,
self._balance_sheet_statement.loc[:, "Total Assets", :]
.shift(axis=1)
.T.rolling(trailing)
.sum()
.T,
self._balance_sheet_statement.loc[:, "Total Assets", :]
.T.rolling(trailing)
.sum()
.T,
)
else:
asset_turnover_ratio = efficiency_model.get_asset_turnover_ratio(
self._income_statement.loc[:, "Revenue", :],
self._balance_sheet_statement.loc[:, "Total Assets", :].shift(axis=1),
self._balance_sheet_statement.loc[:, "Total Assets", :],
)
if growth:
return calculate_growth(
asset_turnover_ratio,
lag=lag,
rounding=rounding if rounding else self._rounding,
)
return asset_turnover_ratio.round(rounding if rounding else self._rounding)
@handle_errors
def get_inventory_turnover_ratio(
self,
rounding: int | None = None,
growth: bool = False,
lag: int | list[int] = 1,
trailing: int | None = None,
) -> pd.DataFrame:
"""
Calculate the inventory turnover ratio, an efficiency ratio that measures
how quickly a company sells its inventory.
The inventory turnover ratio is calculated by dividing the cost of goods sold
(COGS) by the average inventory value. It indicates how many times a company's
inventory is sold and replaced over a period. A higher inventory turnover ratio
suggests that a company is effectively managing its inventory by quickly
converting it into sales.
The formula is as follows:
Inventory Turnover Ratio = Cost of Goods Sold / Average Inventory
Args:
rounding (int, optional): The number of decimals to round the results to. Defaults to 4.
growth (bool, optional): Whether to calculate the growth of the ratios. Defaults to False.
lag (int | str, optional): The lag to use for the growth calculation. Defaults to 1.
trailing (int): Defines whether to select a trailing period.
E.g. when selecting 4 with quarterly data, the TTM is calculated.
Returns:
pd.Series: Inventory turnover ratio values.
Notes:
- The method retrieves historical data and calculates the inventory turnover ratio
for each asset in the Toolkit instance.
- If `growth` is set to True, the method calculates the growth of the ratio values
using the specified `lag`.
As an example:
```python
from financetoolkit import Toolkit
toolkit = Toolkit(["AAPL", "TSLA"], api_key=FMP_KEY)
inventory_turnover_ratios = toolkit.ratios.get_inventory_turnover_ratio()
```
"""
if trailing:
inventory_turnover_ratio = efficiency_model.get_inventory_turnover_ratio(
self._income_statement.loc[:, "Cost of Goods Sold", :]
.T.rolling(trailing)
.sum()
.T,
self._balance_sheet_statement.loc[:, "Inventory", :]
.shift(axis=1)
.T.rolling(trailing)
.sum()
.T,
self._balance_sheet_statement.loc[:, "Inventory", :]
.T.rolling(trailing)
.sum()
.T,
)
else:
inventory_turnover_ratio = efficiency_model.get_inventory_turnover_ratio(
self._income_statement.loc[:, "Cost of Goods Sold", :],
self._balance_sheet_statement.loc[:, "Inventory", :].shift(axis=1),
self._balance_sheet_statement.loc[:, "Inventory", :],
)
if growth:
return calculate_growth(
inventory_turnover_ratio,
lag=lag,
rounding=rounding if rounding else self._rounding,
)
return inventory_turnover_ratio.round(rounding if rounding else self._rounding)
@handle_errors
def get_days_of_inventory_outstanding(
self,
days: int | float | None = None,
rounding: int | None = None,
growth: bool = False,
lag: int | list[int] = 1,
trailing: int | None = None,
) -> pd.DataFrame:
"""
Calculate the days sales in inventory ratio, an efficiency ratio that measures
how long it takes a company to sell its inventory.
The days sales in inventory ratio (DSI) is calculated by dividing the average
inventory by the cost of goods sold (COGS) and then multiplying by the number
of days in the period. It represents the average number of days it takes for
a company to sell its inventory. A lower DSI indicates that the company is
selling its inventory more quickly.
The formula is as follows:
Days Sales in Inventory Ratio = (Average Inventory / Cost of Goods Sold) * Days
Args:
days (int, optional): The number of days to use for the calculation. Defaults to 365.
rounding (int, optional): The number of decimals to round the results to. Defaults to 4.
growth (bool, optional): Whether to calculate the growth of the ratios. Defaults to False.
lag (int | str, optional): The lag to use for the growth calculation. Defaults to 1.
trailing (int): Defines whether to select a trailing period.
E.g. when selecting 4 with quarterly data, the TTM is calculated.
Returns:
pd.DataFrame: Days sales in inventory ratio values.
Notes:
- The method retrieves historical data and calculates the DSI ratio for each
asset in the Toolkit instance.
- If `growth` is set to True, the method calculates the growth of the ratio values
using the specified `lag`.
As an example:
```python
from financetoolkit import Toolkit
toolkit = Toolkit(["AAPL", "TSLA"], api_key=FMP_KEY)
toolkit.ratios.get_days_of_inventory_outstanding()
```
"""
if not days:
days = 365 / 4 if self._quarterly else 365
if trailing:
days_of_inventory_outstanding = (
efficiency_model.get_days_of_inventory_outstanding(
self._balance_sheet_statement.loc[:, "Inventory", :]
.shift(axis=1)
.T.rolling(trailing)
.sum()
.T,
self._balance_sheet_statement.loc[:, "Inventory", :]
.T.rolling(trailing)
.sum()
.T,
self._income_statement.loc[:, "Cost of Goods Sold", :]
.T.rolling(trailing)
.sum()
.T,
)
)
else:
days_of_inventory_outstanding = (
efficiency_model.get_days_of_inventory_outstanding(
self._balance_sheet_statement.loc[:, "Inventory", :].shift(axis=1),
self._balance_sheet_statement.loc[:, "Inventory", :],
self._income_statement.loc[:, "Cost of Goods Sold", :],
days,
)
)
if growth:
return calculate_growth(
days_of_inventory_outstanding,
lag=lag,
rounding=rounding if rounding else self._rounding,
)
return days_of_inventory_outstanding.round(
rounding if rounding else self._rounding
)
@handle_errors
def get_days_of_sales_outstanding(
self,
days: int | float | None = None,
rounding: int | None = None,
growth: bool = False,
lag: int | list[int] = 1,
trailing: int | None = None,
) -> pd.DataFrame:
"""
Calculate the days of sales outstanding ratio, an efficiency ratio that measures
the average number of days it takes a company to collect payment on its
credit sales.
The days of sales outstanding (DSO) ratio is calculated by dividing the accounts
receivable by the total credit sales and then multiplying by the number of days
in the period. It represents the average number of days it takes for a company
to collect payment on its credit sales. A lower DSO indicates that the company
is collecting payments more quickly.
The formula is as follows:
Days of Sales Outstanding Ratio = (Accounts Receivable / Total Credit Sales) * Days
Args:
days (int, optional): The number of days to use for the calculation. Defaults to 365.
rounding (int, optional): The number of decimals to round the results to. Defaults to 4.
growth (bool, optional): Whether to calculate the growth of the ratios. Defaults to False.
lag (int | str, optional): The lag to use for the growth calculation. Defaults to 1.
trailing (int): Defines whether to select a trailing period.
E.g. when selecting 4 with quarterly data, the TTM is calculated.
Returns:
pd.DataFrame: Days of sales outstanding ratio values.
Notes:
- The method retrieves historical data and calculates the DSO ratio for each
asset in the Toolkit instance.
- If `growth` is set to True, the method calculates the growth of the ratio values
using the specified `lag`.
As an example:
```python
from financetoolkit import Toolkit
toolkit = Toolkit(["AAPL", "TSLA"], api_key=FMP_KEY)
dso_ratios = toolkit.ratios.get_days_of_sales_outstanding()
```
"""
if not days:
days = 365 / 4 if self._quarterly else 365
if trailing:
days_of_sales_outstanding = efficiency_model.get_days_of_sales_outstanding(
self._balance_sheet_statement.loc[:, "Accounts Receivable", :]
.shift(axis=1)
.T.rolling(trailing)
.sum()
.T,
self._balance_sheet_statement.loc[:, "Accounts Receivable", :]
.T.rolling(trailing)
.sum()
.T,
self._income_statement.loc[:, "Revenue", :].T.rolling(trailing).sum().T,
)
else:
days_of_sales_outstanding = efficiency_model.get_days_of_sales_outstanding(
self._balance_sheet_statement.loc[:, "Accounts Receivable", :].shift(
axis=1
),
self._balance_sheet_statement.loc[:, "Accounts Receivable", :],
self._income_statement.loc[:, "Revenue", :],
days,
)
if growth:
return calculate_growth(
days_of_sales_outstanding,
lag=lag,
rounding=rounding if rounding else self._rounding,
)
return days_of_sales_outstanding.round(rounding if rounding else self._rounding)
@handle_errors
def get_operating_cycle(
self,
days: int | float | None = None,
rounding: int | None = None,
growth: bool = False,
lag: int | list[int] = 1,
trailing: int | None = None,
) -> pd.DataFrame:
"""
Calculate the operating cycle ratio, an efficiency ratio that measures the average
number of days it takes a company to turn its inventory into cash.
The operating cycle represents the total time required to purchase inventory,
convert it into finished goods, sell the goods to customers, and collect the
accounts receivable. It is calculated by adding the days sales in inventory (DSI)
and the days of sales outstanding (DSO).
The formula is as follows:
Operating Cycle Ratio = Days of Sales in Inventory + Days of Sales Outstanding
Args:
days (int, optional): The number of days to use for the calculation. Defaults to 365.
rounding (int, optional): The number of decimals to round the results to. Defaults to 4.
growth (bool, optional): Whether to calculate the growth of the ratios. Defaults to False.
lag (int | str, optional): The lag to use for the growth calculation. Defaults to 1.
trailing (int): Defines whether to select a trailing period.
E.g. when selecting 4 with quarterly data, the TTM is calculated.
Returns:
pd.DataFrame: Operating cycle ratio values.
Notes:
- The method retrieves historical data and calculates the operating cycle ratio for each
asset in the Toolkit instance.
- If `growth` is set to True, the method calculates the growth of the ratio values
using the specified `lag`.
As an example:
```python
from financetoolkit import Toolkit
toolkit = Toolkit(["AAPL", "TSLA"], api_key=FMP_KEY)
operating_cycle_ratios = toolkit.ratios.get_operating_cycle()
```
"""
if not days:
days = 365 / 4 if self._quarterly else 365
if trailing:
days_of_inventory = efficiency_model.get_days_of_inventory_outstanding(
self._balance_sheet_statement.loc[:, "Inventory", :]
.shift(axis=1)
.T.rolling(trailing)
.sum()
.T,
self._balance_sheet_statement.loc[:, "Inventory", :]
.T.rolling(trailing)
.sum()
.T,
self._income_statement.loc[:, "Cost of Goods Sold", :]
.T.rolling(trailing)
.sum()
.T,
days,
)
days_of_sales = efficiency_model.get_days_of_sales_outstanding(
self._balance_sheet_statement.loc[:, "Accounts Receivable", :]
.shift(axis=1)
.T.rolling(trailing)
.sum()
.T,
self._balance_sheet_statement.loc[:, "Accounts Receivable", :]
.T.rolling(trailing)
.sum()
.T,
self._income_statement.loc[:, "Revenue", :].T.rolling(trailing).sum().T,
days,
)
else:
days_of_inventory = efficiency_model.get_days_of_inventory_outstanding(
self._balance_sheet_statement.loc[:, "Inventory", :].shift(axis=1),
self._balance_sheet_statement.loc[:, "Inventory", :],
self._income_statement.loc[:, "Cost of Goods Sold", :],
days,
)
days_of_sales = efficiency_model.get_days_of_sales_outstanding(
self._balance_sheet_statement.loc[:, "Accounts Receivable", :].shift(
axis=1
),
self._balance_sheet_statement.loc[:, "Accounts Receivable", :],
self._income_statement.loc[:, "Revenue", :],
days,
)
operating_cycle = efficiency_model.get_operating_cycle(
days_of_inventory, days_of_sales
)
if growth:
return calculate_growth(
operating_cycle,
lag=lag,
rounding=rounding if rounding else self._rounding,
)
return operating_cycle.round(rounding if rounding else self._rounding)
@handle_errors
def get_accounts_payables_turnover_ratio(
self,
rounding: int | None = None,
growth: bool = False,
lag: int | list[int] = 1,
trailing: int | None = None,
) -> pd.DataFrame:
"""
Calculate the accounts payable turnover ratio, an efficiency ratio that measures how
quickly a company pays its suppliers.
The accounts payable turnover ratio indicates how many times, on average, a company
pays off its accounts payable during a specific period. A higher turnover ratio is
generally favorable, as it suggests that the company is efficiently managing its
payments to suppliers.
The formula is as follows:
Accounts Payable Turnover Ratio = Cost of Goods Sold / Average Accounts Payable
Args:
rounding (int, optional): The number of decimals to round the results to. Defaults to 4.
growth (bool, optional): Whether to calculate the growth of the ratios. Defaults to False.
lag (int | str, optional): The lag to use for the growth calculation. Defaults to 1.
trailing (int): Defines whether to select a trailing period.
E.g. when selecting 4 with quarterly data, the TTM is calculated.
Returns:
pd.DataFrame: Accounts payable turnover ratio values.
Notes:
- The method retrieves historical data and calculates the accounts payable turnover ratio for each