I'm trying to capture profits and set a stop loss in my trading strategy. I want the stop loss to be set daily based on the past data, from the date of calculation into the past.
For calculating the stop-loss, I first measure the expected returns that I aim at securing, the volatility of the stock and based on these informations, I then calculate stop loss level.
The data that I have is, a dataframe which contain information on when to enter the trade for which stock? It is a boolean dataframe where the row index are dates and columns are stock names. If it is a true, I will enterif the tradecurrent price, false will ensure I stay outi.
For the first instance, I calculate the stop loss level, and save ite., then I apply loops to calculate the stop loss in a similar fashionprice for the stock but in the context ofdate falls below the next daystop_loss levels, using the data for the proceeding day.
This is taking very very long because ofsell the loops and I am afraid this code doesn't work correctly either.stock!
def drawdownlogging_stop_loss(result_df, dict_dfs):
last_year_df = pd.DataFrame(data=np.nan, index=result_df.index, columns=result_df.columns)
for idx in range(len(result_df)):
for stock in result_df.columns:
if result_df.iloc[idx][stock]:
past_date_idx = max(0, idx - 250stop_loss_levels)
past_date = result_df.index[past_date_idx]
current_date = result_df.index[idx]
last_year = dict_dfs['close'].loc[past_date:current_date, stock]
drawdownstrades = []
for i in range(len(last_year)):
rolling_min = last_year.iloc[:i + 1].min()
rolling_max = last_year.iloc[i:].max()
if rolling_min != 0:
drawdown = (rolling_max - rolling_min) / rolling_min
drawdowns.append(drawdown)
last_year_df.iloc[idx][stock] = np.median(drawdowns)
return last_year_df
def stop_loss(expectations, volatility):
stop_loss_levelspositions = pd.DataFrame(
np.minimum(20,{}
np.minimum(0.4 * expectations, (1 / volatility))),
for index=expectations.indexdate_idx,
columns=expectations.columns
)
stop_loss_levels = stop_loss_levels.where(expectations.notna() & volatility.notna())
returndate stop_loss_levels
defin volatility_calenumerate(result_df, dict_dfs):
volatility_year = pd.DataFrame(data=np.nan, index=result_df.index, columns=result_df.columns)
for idx in range(len(result_df)):
for stock in result_df.columns:
if result_dfcolumns[result_df.iloc[idx][stock]iloc[date_idx]]:
past_date_idx =if max(0stock, idx - 250date)
past_date = result_df.index[past_date_idx]
current_datenot =in result_df.index[idx]
positions:
last_yearentry_price = dict_dfs['close'].loc[past_date:current_dateat[date, stock]
standard_devstop_loss_level = last_year.std()
volatility_yearstop_loss_levels.iloc[idx][stock] = standard_dev
return volatility_year
def logging_stop_loss(dict_dfsat[date, result_df):
trades = []stock]
positions = {}
expectations = drawdown(result_df, dict_dfs)
volatility = volatility_calpositions[(result_dfstock, dict_dfsdate)
stop_loss_levels] = stop_loss(expectations, volatility)
for date_idx in range(len(result_df.index)):{
date = result_df.index[date_idx]
for stock_idx, stock in enumerate(result_df.columns)'entry_date':
if result_df.iloc[date_idxdate, stock_idx]:
if stock not in positions'entry_price':
entry_price = dict_dfs['close'].iloc[date_idx, stock_idx]
positions[(stock, date)] = {
'entry_date''stop_loss': date,
entry_price * (1 'entry_price':- entry_pricestop_loss_level),
'stop_loss''count': entry_price0 * (1# -Initialize stop_loss_levels.iloc[date_idx,count stock_idx])
to track days since entry
}
closed_positions = []
count = 0
for (stock, entry_date), pos in list(positions.keysitems()):
count=count+1
pos =pos['count'] positions[(stock,+= entry_date)]1
datefuture_date = result_df.index[date_idx+count]
current_priceindex[min(date_idx =+ dict_dfs['close'].loc[datepos['count'], stock]
current_expectations = drawdownlen(result_df.shift(count), dict_dfs- 1)]
current_volatilitycurrent_price = volatility_cal(result_dfdict_dfs['close'].shift(count)at[future_date, dict_dfs)stock]
current_stop_loss_levelsstop_loss_level = stop_loss(current_expectationsstop_loss_levels.at[future_date, current_volatility)
stock]
pos['stop_loss'] = current_price * (1 - current_stop_loss_levels.loc[date, stock]stop_loss_level)
if current_price < pos['stop_loss']:
trades.append({
'stock': stock,
'entry_date': pos['entry_date'],
'entry_price': pos['entry_price'],
'exit_date': datefuture_date,
'exit_price': current_price,
'return': (current_price - pos['entry_price']) / pos['entry_price']
})
closed_positions.append((stock, pos['entry_date']entry_date))
for stock, entry_datestock_entry in closed_positions:
del positions[(stock, entry_date)]positions[stock_entry]
return pd.DataFrame(trades)
Here drawdown is the first function to be called and it gives me the expected returns. TheI have included my code which takes in stop loss calculated using certain logic for all the same is absolutely correct and no changes should happen there. Next is volatility_cal function and it gives me standard deviationdays. Next is then Stop Loss calculator, which lets
Another dataframe tells me knowabout the stop loss percent thattrading dates, with TRUE valeu indicating, I can incurenter the following percent loss.
Post thistrade and FALSE value indicating, I then aim at logging the information of when to exit the trades based on continuous stop loss calculationstrade.
I first calculate the entry price and stop loss associated with it. WithWith this I maintain a counter which say how many days have passed after entering the trade and helps in moving the boolean dataframe into the future. By moving the boolean dataframe into the future, I get an idea that yes, nowlogic I enter the trade on this day again and accordingly gives me the, see if stop loss levels.is met? If not get going to the price falls below stop loss percentagesnext date, I exitif it is met, then sell else continue the trade and marksloop till the observations inend of the loggerclosing price dataframe is met.
Once all
I will then log the TRUE values from original booleanentry and exit prices in a dataframe is satisfied,and save it returns the logger.
TheThis code is getting stuck in an infinite loop or, returns empty logging_stop_loss dataframe and it is just inefficienthas no entry in the dataframe. This being the case, as I have not been ablewant to observe the results forunderstand what is causing the above function even after waiting a couple of hoursissue and rectify it.
Therefore please help Can someone lead me improveto the time complexity by using dataframesdirection which is causing this error and matrix, instead of loopsI can modify my logic accordingly.