Disponemos del siguiente DataFrame.
import pandas as pd
from datetime import datetime
# Diccionario dicc_retornos
dicc_retornos = {'Close': {Timestamp('2010-12-30 00:00:00'): 9859.099609375, Timestamp('2011-01-03 00:00:00'): 9888.2998046875, Timestamp('2011-01-04 00:00:00'): 9888.400390625, Timestamp('2011-01-05 00:00:00'): 9801.400390625, Timestamp('2011-01-06 00:00:00'): 9702.7001953125, Timestamp('2011-01-07 00:00:00'): 9560.7001953125, Timestamp('2011-01-10 00:00:00'): 9437.7998046875, Timestamp('2011-01-11 00:00:00'): 9582.099609375, Timestamp('2011-01-12 00:00:00'): 10101.2001953125, Timestamp('2011-01-13 00:00:00'): 10370.7998046875, Timestamp('2011-01-14 00:00:00'): 10385.099609375, Timestamp('2011-01-17 00:00:00'): 10280.0, Timestamp('2011-01-18 00:00:00'): 10583.400390625, Timestamp('2011-01-19 00:00:00'): 10556.5, Timestamp('2011-01-20 00:00:00'): 10636.900390625, Timestamp('2011-01-21 00:00:00'): 10829.099609375, Timestamp('2011-01-24 00:00:00'): 10815.400390625, Timestamp('2011-01-25 00:00:00'): 10664.400390625, Timestamp('2011-01-26 00:00:00'): 10670.7001953125, Timestamp('2011-01-27 00:00:00'): 10828.7001953125}, 'EMA_100': {Timestamp('2010-12-30 00:00:00'): 9859.099609375, Timestamp('2011-01-03 00:00:00'): 9859.677831064357, Timestamp('2011-01-04 00:00:00'): 9860.246594620012, Timestamp('2011-01-05 00:00:00'): 9859.081323253773, Timestamp('2011-01-06 00:00:00'): 9855.984667254936, Timestamp('2011-01-07 00:00:00'): 9850.137449988748, Timestamp('2011-01-10 00:00:00'): 9841.972348101595, Timestamp('2011-01-11 00:00:00'): 9836.826353275326, Timestamp('2011-01-12 00:00:00'): 9842.061478860222, Timestamp('2011-01-13 00:00:00'): 9852.531544718187, Timestamp('2011-01-14 00:00:00'): 9863.07744698862, Timestamp('2011-01-17 00:00:00'): 9871.33333912746, Timestamp('2011-01-18 00:00:00'): 9885.433676780875, Timestamp('2011-01-19 00:00:00'): 9898.722118824819, Timestamp('2011-01-20 00:00:00'): 9913.339510345613, Timestamp('2011-01-21 00:00:00'): 9931.47337369273, Timestamp('2011-01-24 00:00:00'): 9948.976878978518, Timestamp('2011-01-25 00:00:00'): 9963.143681189338, Timestamp('2011-01-26 00:00:00'): 9977.154701270985, Timestamp('2011-01-27 00:00:00'): 9994.016988281708}, 'EMA_200': {Timestamp('2010-12-30 00:00:00'): 9859.099609375, Timestamp('2011-01-03 00:00:00'): 9859.39015858209, Timestamp('2011-01-04 00:00:00'): 9859.678817607391, Timestamp('2011-01-05 00:00:00'): 9859.098932761797, Timestamp('2011-01-06 00:00:00'): 9857.542726419018, Timestamp('2011-01-07 00:00:00'): 9854.589069393083, Timestamp('2011-01-10 00:00:00'): 9850.441912530341, Timestamp('2011-01-11 00:00:00'): 9847.77183986213, Timestamp('2011-01-12 00:00:00'): 9850.29351504074, Timestamp('2011-01-13 00:00:00'): 9855.472682101901, Timestamp('2011-01-14 00:00:00'): 9860.742601776261, Timestamp('2011-01-17 00:00:00'): 9864.914317181474, Timestamp('2011-01-18 00:00:00'): 9872.063432340117, Timestamp('2011-01-19 00:00:00'): 9878.873746446185, Timestamp('2011-01-20 00:00:00'): 9886.416300119607, Timestamp('2011-01-21 00:00:00'): 9895.796233545034, Timestamp('2011-01-24 00:00:00'): 9904.946523665234, Timestamp('2011-01-25 00:00:00'): 9912.503278560356, Timestamp('2011-01-26 00:00:00'): 9920.047526488239, Timestamp('2011-01-27 00:00:00'): 9929.088846576044}, 'Position': {Timestamp('2010-12-30 00:00:00'): 0.0, Timestamp('2011-01-03 00:00:00'): 1.0, Timestamp('2011-01-04 00:00:00'): 1.0, Timestamp('2011-01-05 00:00:00'): 0.0, Timestamp('2011-01-06 00:00:00'): 0.0, Timestamp('2011-01-07 00:00:00'): 0.0, Timestamp('2011-01-10 00:00:00'): 0.0, Timestamp('2011-01-11 00:00:00'): 0.0, Timestamp('2011-01-12 00:00:00'): 0.0, Timestamp('2011-01-13 00:00:00'): 0.0, Timestamp('2011-01-14 00:00:00'): 1.0, Timestamp('2011-01-17 00:00:00'): 1.0, Timestamp('2011-01-18 00:00:00'): 1.0, Timestamp('2011-01-19 00:00:00'): 1.0, Timestamp('2011-01-20 00:00:00'): 1.0, Timestamp('2011-01-21 00:00:00'): 1.0, Timestamp('2011-01-24 00:00:00'): 1.0, Timestamp('2011-01-25 00:00:00'): 1.0, Timestamp('2011-01-26 00:00:00'): 1.0, Timestamp('2011-01-27 00:00:00'): 1.0}}
# Convertir el diccionario en un DataFrame
datos_df = pd.DataFrame(dicc_retornos)
El códgo siguiente.
stop_loss_pct = 0.05 # Porcentaje de stop loss (2% en este ejemplo)
take_profit_pct = 0.05 # Porcentaje de take profit (5% en este ejemplo)
# Calcular stop loss y take profit
datos_df['Stop_loss'] = datos_df['Close'] * (1 - stop_loss_pct)
datos_df['Take_profit'] = datos_df['Close'] * (1 + take_profit_pct)
# Aplicar trailing stop y take profit
for date_index in datos_df.index[1:]:
# Comprueba si la posición es una señal de compra o venta
if datos_df.loc[date_index, 'Position'] == 1: # Señal de compra
# Calcular stop loss para posiciones largas
stop_loss_triggered_long = datos_df.loc[date_index, 'Close'] < datos_df.loc[date_index - pd.Timedelta(days=1), 'Stop_loss']
if stop_loss_triggered_long:
datos_df.loc[date_index:, 'Position'] = 0 # Vender si se alcanza el stop loss
# Calcular take profit para posiciones largas
take_profit_triggered_long = datos_df.loc[date_index, 'Close'] > datos_df.loc[date_index - pd.Timedelta(days=1), 'Take_profit']
if take_profit_triggered_long:
datos_df.loc[date_index:, 'Position'] = 0 # Vender si se alcanza el take profit
elif datos_df.loc[date_index, 'Position'] == -1: # Señal de venta
# Calcular stop loss para posiciones cortas
stop_loss_triggered_short = datos_df.loc[date_index, 'Close'] > datos_df.loc[date_index - pd.Timedelta(days=1), 'Stop_loss']
if stop_loss_triggered_short:
datos_df.loc[date_index:, 'Position'] = 0 # Comprar si se alcanza el stop loss
# Calcular take profit para posiciones cortas
take_profit_triggered_short = datos_df.loc[date_index, 'Close'] < datos_df.loc[date_index - pd.Timedelta(days=1), 'Take_profit']
if take_profit_triggered_short:
datos_df.loc[date_index:, 'Position'] = 0 # Comprar si se alcanza el take profit
Me devuelve el error.
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
File ~/Descargas/yes/envs/py38/lib/python3.8/site-packages/pandas/_libs/index.pyx:581, in pandas._libs.index.DatetimeEngine.get_loc()
File pandas/_libs/hashtable_class_helper.pxi:2606, in pandas._libs.hashtable.Int64HashTable.get_item()
File pandas/_libs/hashtable_class_helper.pxi:2630, in pandas._libs.hashtable.Int64HashTable.get_item()
KeyError: 1293926400000000000
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
File ~/Descargas/yes/envs/py38/lib/python3.8/site-packages/pandas/core/indexes/base.py:3653, in Index.get_loc(self, key)
3652 try:
-> 3653 return self._engine.get_loc(casted_key)
3654 except KeyError as err:
File ~/Descargas/yes/envs/py38/lib/python3.8/site-packages/pandas/_libs/index.pyx:549, in pandas._libs.index.DatetimeEngine.get_loc()
File ~/Descargas/yes/envs/py38/lib/python3.8/site-packages/pandas/_libs/index.pyx:583, in pandas._libs.index.DatetimeEngine.get_loc()
KeyError: Timestamp('2011-01-02 00:00:00')
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
File ~/Descargas/yes/envs/py38/lib/python3.8/site-packages/pandas/core/indexes/datetimes.py:584, in DatetimeIndex.get_loc(self, key)
583 try:
--> 584 return Index.get_loc(self, key)
585 except KeyError as err:
File ~/Descargas/yes/envs/py38/lib/python3.8/site-packages/pandas/core/indexes/base.py:3655, in Index.get_loc(self, key)
3654 except KeyError as err:
-> 3655 raise KeyError(key) from err
3656 except TypeError:
3657 # If we have a listlike key, _check_indexing_error will raise
3658 # InvalidIndexError. Otherwise we fall through and re-raise
3659 # the TypeError.
KeyError: Timestamp('2011-01-02 00:00:00')
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
Cell In[20], line 16
12 for date_index in datos_df.index[1:]:
13 # Comprueba si la posición es una señal de compra o venta
14 if datos_df.loc[date_index, 'Position'] == 1: # Señal de compra
15 # Calcular stop loss para posiciones largas
---> 16 stop_loss_triggered_long = datos_df.loc[date_index, 'Close'] < datos_df.loc[date_index - pd.Timedelta(days=1), 'Stop_loss']
17 if stop_loss_triggered_long:
18 datos_df.loc[date_index:, 'Position'] = 0 # Vender si se alcanza el stop loss
File ~/Descargas/yes/envs/py38/lib/python3.8/site-packages/pandas/core/indexing.py:1096, in _LocationIndexer.__getitem__(self, key)
1094 key = tuple(com.apply_if_callable(x, self.obj) for x in key)
1095 if self._is_scalar_access(key):
-> 1096 return self.obj._get_value(*key, takeable=self._takeable)
1097 return self._getitem_tuple(key)
1098 else:
1099 # we by definition only have the 0th axis
File ~/Descargas/yes/envs/py38/lib/python3.8/site-packages/pandas/core/frame.py:3877, in DataFrame._get_value(self, index, col, takeable)
3871 engine = self.index._engine
3873 if not isinstance(self.index, MultiIndex):
3874 # CategoricalIndex: Trying to use the engine fastpath may give incorrect
3875 # results if our categories are integers that dont match our codes
3876 # IntervalIndex: IntervalTree has no get_loc
-> 3877 row = self.index.get_loc(index)
3878 return series._values[row]
3880 # For MultiIndex going through engine effectively restricts us to
3881 # same-length tuples; see test_get_set_value_no_partial_indexing
File ~/Descargas/yes/envs/py38/lib/python3.8/site-packages/pandas/core/indexes/datetimes.py:586, in DatetimeIndex.get_loc(self, key)
584 return Index.get_loc(self, key)
585 except KeyError as err:
--> 586 raise KeyError(orig_key) from err
KeyError: Timestamp('2011-01-02 00:00:00')
La fecha '2011-01-02 00:00:00', no está en los registros de mi diccionario porque, el índice de las filas son fechas en las que habido cotizaciones en la bolsa. ¿Cómo puedo solucionar este problema?. Aradeceré ayuda.