Tengo una dataframe por lo cual quiero utilizar una funcion para cambiar ratio
pero solo para lineas donde Country es ESP
.
Ticker Name Exchange Category Name Country ratio earnings
0 AAPL Apple Inc. NMS Electronic Equipment USA NaN NaN
1 BAC Bank of America Corporation NYQ Money Center Banks USA NaN NaN
2 AMZN Amazon.com, Inc. NMS Catalog & Mail Order Houses USA NaN NaN
3 T AT&T Inc. NYQ Telecom Services - Domestic USA NaN NaN
4 GOOG Alphabet Inc. NMS Internet Information Providers ESP NaN NaN
Por eso intenté np.where:
np.where(df['Country'] == 'ESP',
df.apply(update_current_ratio_US),
df['ratio'])
Pero me devuelve:
0 AAPL
1 BAC
2 AMZN
3 T
4 GOOG
...
20723 2GB.F
20724 A7A.F
20725 GROG
20726 INDSWFTLTD.NS
20727 N1H.AX
Name: Ticker, Length: 20728, dtype: object
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-93-065d34d423e5> in <module>
1 np.where(df['Country'] == 'USA',
----> 2 df.apply(update_current_ratio_US),
3 df['ratio'])
C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py in apply(self, func, axis, raw, result_type, args, **kwds)
6876 kwds=kwds,
6877 )
-> 6878 return op.get_result()
6879
6880 def applymap(self, func) -> "DataFrame":
C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\apply.py in get_result(self)
184 return self.apply_raw()
185
--> 186 return self.apply_standard()
187
188 def apply_empty_result(self):
C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\apply.py in apply_standard(self)
294 try:
295 result = libreduction.compute_reduction(
--> 296 values, self.f, axis=self.axis, dummy=dummy, labels=labels
297 )
298 except ValueError as err:
pandas\_libs\reduction.pyx in pandas._libs.reduction.compute_reduction()
pandas\_libs\reduction.pyx in pandas._libs.reduction.Reducer.get_result()
<ipython-input-92-8243964de6d7> in update_current_ratio_US(row)
1 def update_current_ratio_US(row):
2 print(row)
----> 3 name = row['Ticker']
4 if row['ratio'] == None:
5 bs = requests.get(f'https://financialmodelingprep.com/api/v3/financials/balance-sheet-statement/{ticker}?period=quarter')
C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
869 key = com.apply_if_callable(key, self)
870 try:
--> 871 result = self.index.get_value(self, key)
872
873 if not is_scalar(result):
C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key)
4403 k = self._convert_scalar_indexer(k, kind="getitem")
4404 try:
-> 4405 return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None))
4406 except KeyError as e1:
4407 if len(self) > 0 and (self.holds_integer() or self.is_boolean()):
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()
KeyError: 'Ticker'
La funcion es:
def update_current_ratio_US(row):
print(row)
name = row['Ticker']
if row['ratio'] == None:
bs = requests.get(f'https://financialmodelingprep.com/api/v3/financials/balance-sheet-statement/{ticker}?period=quarter')
bs = bs.json()
try:
total_assets = bs.get("financials")[0].get("Total assets")
total_liabilities = bs.get("financials")[0].get('Total liabilities')
try:
ratio = float(total_assets)/float(total_liabilities)
return ratio
except ZeroDivisionError:
print("ZeroDivisionError, total_liabilities: ", ticker, " ", total_liabilities)
except ValueError:
print("ValueError, total_assets", total_assets, " total_liabilities", total_liabilities)
except TypeError:
print("ticker: ", ticker)
pass # here we will try with webscrapping