Skip to main content
deleted 1 character in body
Source Link
toolic
  • 15.7k
  • 5
  • 29
  • 216

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 and if the current price, i.e., price for the date falls below the stop_loss levels, sell the stock!.

Here I have included my code which takes in stop loss calculated using certain logic for all the days. Another dataframe tells me about the trading dates, with TRUE valeuvalue indicating, I enter the trade, and FALSE value indicating, I exit the trade. With this logic, I enter the trade, and see if stop loss is met? If. If not, get going to the next date, if it is met, then sell else continue the loop till the end of the closing price dataframe is met. I will then log the entry and exit prices in a dataframe and save it.

This code, returns empty logging_stop_loss dataframe, and it has no entry in the dataframe. This being the case, I want to understand what is causing the issue and rectify it. Can someone lead me to the direction which is causing this error and I can modify my logic accordingly.

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 and if the current price, i.e., price for the date falls below the stop_loss levels, sell the stock!

Here I have included my code which takes in stop loss calculated using certain logic for all the days. Another dataframe tells me about the trading dates, with TRUE valeu indicating, I enter the trade and FALSE value indicating, I exit the trade. With this logic I enter the trade, see if stop loss is met? If not get going to the next date, if it is met, then sell else continue the loop till the end of the closing price dataframe is met. I will then log the entry and exit prices in a dataframe and save it.

This code, returns empty logging_stop_loss dataframe and it has no entry in the dataframe. This being the case, I want to understand what is causing the issue and rectify it. Can someone lead me to the direction which is causing this error and I can modify my logic accordingly.

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 and if the current price, i.e., price for the date falls below the stop_loss levels, sell the stock.

I have included my code which takes in stop loss calculated using certain logic for all the days. Another dataframe tells me about the trading dates, with TRUE value indicating I enter the trade, and FALSE value indicating I exit the trade. With this logic, I enter the trade and see if stop loss is met. If not, get going to the next date, if it is met, then sell else continue the loop till the end of the closing price dataframe is met. I will then log the entry and exit prices in a dataframe and save it.

This code returns empty logging_stop_loss dataframe, and it has no entry in the dataframe. This being the case, I want to understand what is causing the issue and rectify it. Can someone lead me to the direction which is causing this error and I can modify my logic accordingly.

deleted 3701 characters in body; edited title
Source Link
driver
  • 222
  • 1
  • 9

Remove loops and use vectorised functions Maintain a log containing values if certain conditions are met

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.

Remove loops and use vectorised functions

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 enter the trade, false will ensure I stay out.

For the first instance, I calculate the stop loss level, and save it, then I apply loops to calculate the stop loss in a similar fashion for the stock but in the context of the next day, using the data for the proceeding day.

This is taking very very long because of the loops and I am afraid this code doesn't work correctly either.

def drawdown(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 - 250)
                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]

                drawdowns = []
                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_levels = pd.DataFrame(
        np.minimum(20,
                   np.minimum(0.4 * expectations, (1 / volatility))),
        index=expectations.index,
        columns=expectations.columns
    )

    stop_loss_levels = stop_loss_levels.where(expectations.notna() & volatility.notna())

    return stop_loss_levels

def volatility_cal(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_df.iloc[idx][stock]:
                past_date_idx = max(0, idx - 250)
                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]
                standard_dev = last_year.std()
                volatility_year.iloc[idx][stock] = standard_dev
    return volatility_year


def logging_stop_loss(dict_dfs, result_df):
    trades = []
    positions = {}
    expectations = drawdown(result_df, dict_dfs)
    volatility = volatility_cal(result_df, dict_dfs)
    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):
            if result_df.iloc[date_idx, stock_idx]:
                if stock not in positions:
                    entry_price = dict_dfs['close'].iloc[date_idx, stock_idx]
                    positions[(stock, date)] = {
                        'entry_date': date,
                        'entry_price': entry_price,
                        'stop_loss': entry_price * (1 - stop_loss_levels.iloc[date_idx, stock_idx])
                    }

        closed_positions = []
        count = 0
        for (stock, entry_date) in list(positions.keys()):
            count=count+1
            pos = positions[(stock, entry_date)]
            date = result_df.index[date_idx+count]
            current_price = dict_dfs['close'].loc[date, stock]

            current_expectations = drawdown(result_df.shift(count), dict_dfs)
            current_volatility = volatility_cal(result_df.shift(count), dict_dfs)
            current_stop_loss_levels = stop_loss(current_expectations, current_volatility)

            pos['stop_loss'] = current_price * (1 - current_stop_loss_levels.loc[date, stock])

            if current_price < pos['stop_loss']:
                trades.append({
                    'stock': stock,
                    'entry_date': pos['entry_date'],
                    'entry_price': pos['entry_price'],
                    'exit_date': date,
                    'exit_price': current_price,
                    'return': (current_price - pos['entry_price']) / pos['entry_price']
                })
                closed_positions.append((stock, pos['entry_date']))

        for stock, entry_date in closed_positions:
            del positions[(stock, entry_date)]
    return pd.DataFrame(trades)

Here drawdown is the first function to be called and it gives me the expected returns. The logic for the same is absolutely correct and no changes should happen there. Next is volatility_cal function and it gives me standard deviation. Next is then Stop Loss calculator, which lets me know the stop loss percent that I can incur the following percent loss.

Post this, I then aim at logging the information of when to exit the trades based on continuous stop loss calculations. I first calculate the entry price and stop loss associated with it. With 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, now I enter the trade on this day again and accordingly gives me the stop loss levels. If the price falls below stop loss percentages, I exit the trade and marks the observations in the logger.

Once all the TRUE values from original boolean dataframe is satisfied, it returns the logger.

The code is getting stuck in an infinite loop or it is just inefficient, as I have not been able to observe the results for the above function even after waiting a couple of hours.

Therefore please help me improve the time complexity by using dataframes and matrix, instead of loops.

Maintain a log containing values if certain conditions are met

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 and if the current price, i.e., price for the date falls below the stop_loss levels, sell the stock!

def logging_stop_loss(dict_dfs, result_df, stop_loss_levels):
    trades = []
    positions = {}

    for date_idx, date in enumerate(result_df.index):
        for stock in result_df.columns[result_df.iloc[date_idx]]:
            if (stock, date) not in positions:
                entry_price = dict_dfs['close'].at[date, stock]
                stop_loss_level = stop_loss_levels.at[date, stock]
                positions[(stock, date)] = {
                    'entry_date': date,
                    'entry_price': entry_price,
                    'stop_loss': entry_price * (1 - stop_loss_level),
                    'count': 0  # Initialize count to track days since entry
                }

        closed_positions = []
        for (stock, entry_date), pos in list(positions.items()):
            pos['count'] += 1
            future_date = result_df.index[min(date_idx + pos['count'], len(result_df) - 1)]
            current_price = dict_dfs['close'].at[future_date, stock]
            stop_loss_level = stop_loss_levels.at[future_date, stock]
            pos['stop_loss'] = current_price * (1 - 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': future_date,
                    'exit_price': current_price,
                    'return': (current_price - pos['entry_price']) / pos['entry_price']
                })
                closed_positions.append((stock, entry_date))

        for stock_entry in closed_positions:
            del positions[stock_entry]

    return pd.DataFrame(trades)

Here I have included my code which takes in stop loss calculated using certain logic for all the days. Another dataframe tells me about the trading dates, with TRUE valeu indicating, I enter the trade and FALSE value indicating, I exit the trade. With this logic I enter the trade, see if stop loss is met? If not get going to the next date, if it is met, then sell else continue the loop till the end of the closing price dataframe is met. I will then log the entry and exit prices in a dataframe and save it.

This code, returns empty logging_stop_loss dataframe and it has no entry in the dataframe. This being the case, I want to understand what is causing the issue and rectify it. Can someone lead me to the direction which is causing this error and I can modify my logic accordingly.

Source Link
driver
  • 222
  • 1
  • 9

Remove loops and use vectorised functions

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 enter the trade, false will ensure I stay out.

For the first instance, I calculate the stop loss level, and save it, then I apply loops to calculate the stop loss in a similar fashion for the stock but in the context of the next day, using the data for the proceeding day.

This is taking very very long because of the loops and I am afraid this code doesn't work correctly either.

Below is the implementation for the same:

def drawdown(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 - 250)
                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]

                drawdowns = []
                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_levels = pd.DataFrame(
        np.minimum(20,
                   np.minimum(0.4 * expectations, (1 / volatility))),
        index=expectations.index,
        columns=expectations.columns
    )

    stop_loss_levels = stop_loss_levels.where(expectations.notna() & volatility.notna())

    return stop_loss_levels

def volatility_cal(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_df.iloc[idx][stock]:
                past_date_idx = max(0, idx - 250)
                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]
                standard_dev = last_year.std()
                volatility_year.iloc[idx][stock] = standard_dev
    return volatility_year


def logging_stop_loss(dict_dfs, result_df):
    trades = []
    positions = {}
    expectations = drawdown(result_df, dict_dfs)
    volatility = volatility_cal(result_df, dict_dfs)
    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):
            if result_df.iloc[date_idx, stock_idx]:
                if stock not in positions:
                    entry_price = dict_dfs['close'].iloc[date_idx, stock_idx]
                    positions[(stock, date)] = {
                        'entry_date': date,
                        'entry_price': entry_price,
                        'stop_loss': entry_price * (1 - stop_loss_levels.iloc[date_idx, stock_idx])
                    }

        closed_positions = []
        count = 0
        for (stock, entry_date) in list(positions.keys()):
            count=count+1
            pos = positions[(stock, entry_date)]
            date = result_df.index[date_idx+count]
            current_price = dict_dfs['close'].loc[date, stock]

            current_expectations = drawdown(result_df.shift(count), dict_dfs)
            current_volatility = volatility_cal(result_df.shift(count), dict_dfs)
            current_stop_loss_levels = stop_loss(current_expectations, current_volatility)

            pos['stop_loss'] = current_price * (1 - current_stop_loss_levels.loc[date, stock])

            if current_price < pos['stop_loss']:
                trades.append({
                    'stock': stock,
                    'entry_date': pos['entry_date'],
                    'entry_price': pos['entry_price'],
                    'exit_date': date,
                    'exit_price': current_price,
                    'return': (current_price - pos['entry_price']) / pos['entry_price']
                })
                closed_positions.append((stock, pos['entry_date']))

        for stock, entry_date in closed_positions:
            del positions[(stock, entry_date)]
    return pd.DataFrame(trades)

Here drawdown is the first function to be called and it gives me the expected returns. The logic for the same is absolutely correct and no changes should happen there. Next is volatility_cal function and it gives me standard deviation. Next is then Stop Loss calculator, which lets me know the stop loss percent that I can incur the following percent loss.

Post this, I then aim at logging the information of when to exit the trades based on continuous stop loss calculations. I first calculate the entry price and stop loss associated with it. With 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, now I enter the trade on this day again and accordingly gives me the stop loss levels. If the price falls below stop loss percentages, I exit the trade and marks the observations in the logger.

Once all the TRUE values from original boolean dataframe is satisfied, it returns the logger.

The code is getting stuck in an infinite loop or it is just inefficient, as I have not been able to observe the results for the above function even after waiting a couple of hours.

Therefore please help me improve the time complexity by using dataframes and matrix, instead of loops.