Sunday, October 20, 2024

MB RVNL

 # Install necessary libraries (if not already installed)

install.packages("quantmod")

install.packages("TTR")

install.packages("PerformanceAnalytics")

install.packages("xts")

install.packages("dplyr")

install.packages("ggplot2")


# Load libraries

library(quantmod)

library(TTR)

library(PerformanceAnalytics)

library(xts)

library(dplyr)

library(ggplot2)


# Step 1: Download Historical Data for RVNL

getSymbols("RVNL.NS", src = "yahoo", from = "2020-01-01", to = Sys.Date())


# Convert xts object to a data frame for processing

RVNL_df <- data.frame(Date = index(RVNL.NS), coredata(RVNL.NS))

colnames(RVNL_df) <- c("Date", "Open", "High", "Low", "Close", "Volume", "Adjusted")


# Step 2: Calculate Moving Averages and Add Indicators

RVNL_df <- RVNL_df %>%

  mutate(

    Change_Percent = (Close - lag(Close)) / lag(Close) * 100,           # Daily percentage change

    Prev_Volume = lag(Volume),                                          # Previous day's volume

    MA7 = SMA(Close, 7),                                                # 7-day moving average

    MA65 = SMA(Close, 65),                                              # 65-day moving average

    MA_Ratio = MA7 / MA65                                               # Ratio of MA7 to MA65

  )


# Step 3: Define Buy Condition

# Buy when stock is up 4% in a day, volume > previous day, volume >= 100,000, and MA ratio > 1.05

buy_condition <- RVNL_df %>%

  filter(

    Change_Percent >= 4,                       # Stock up 4% or more

    Volume > Prev_Volume,                      # Volume greater than previous day

    Volume >= 100000,                          # Volume greater than or equal to 100,000

    MA_Ratio > 1.05                            # 7-day MA / 65-day MA > 1.05

  )


# Step 4: Create Buy Signals and Calculate Stop Losses

buy_signals <- buy_condition %>%

  mutate(

    Buy_Signal = 1,

    Stop_Loss_Day1 = Low,                       # Initial stop loss is the low of the buy day

    Stop_Loss_NextDay = NA,                     # Placeholder for stop loss of subsequent days

    Sell_Date = as.Date(NA),                    # Placeholder for sell date

    Return = NA,                                # Placeholder for return on each trade

    Days_Held = NA                              # Placeholder for holding days on each trade

  )


# Step 5: Apply Dynamic Stop Loss and Sell After 4 Days

for (i in 1:nrow(buy_signals)) {

  buy_date <- buy_signals$Date[i]

  next_4_days <- RVNL_df %>% filter(Date > buy_date) %>% head(4)

  

  stop_loss_next <- buy_signals$Stop_Loss_Day1[i]  # Start with Day 1 stop loss

  

  for (j in 1:nrow(next_4_days)) {

    day_data <- next_4_days[j, ]

    price_range <- day_data$High - day_data$Low

    stop_loss_next <- max(stop_loss_next, day_data$Low - (price_range / 2))

    

    if (day_data$Low <= stop_loss_next) {

      # Stop loss hit, sell on this day

      buy_signals$Sell_Date[i] <- day_data$Date

      buy_signals$Return[i] <- (day_data$Close - buy_signals$Close[i]) / buy_signals$Close[i]

      buy_signals$Days_Held[i] <- as.numeric(difftime(day_data$Date, buy_signals$Date[i], units = "days"))

      break

    } else if (j == 4) {

      # Sell at the end of 4th day if stop loss not hit

      buy_signals$Sell_Date[i] <- day_data$Date

      buy_signals$Return[i] <- (day_data$Close - buy_signals$Close[i]) / buy_signals$Close[i]

      buy_signals$Days_Held[i] <- as.numeric(difftime(day_data$Date, buy_signals$Date[i], units = "days"))

    }

  }

}


# Step 6: Initialize Starting Capital and Apply Compounded Returns

starting_capital <- 100000  # Starting capital of 100,000 INR

capital <- starting_capital

buy_signals$Capital <- NA   # To track capital at each step

equity_curve <- numeric(length = nrow(buy_signals) + 1)  # To track the equity curve

equity_curve[1] <- starting_capital


# Step 7: Calculate Compounded Returns and Update Capital for Each Trade

for (i in 1:nrow(buy_signals)) {

  trade_return <- buy_signals$Return[i]

  capital <- capital * (1 + trade_return)  # Update capital with compounded return

  buy_signals$Capital[i] <- capital        # Store updated capital

  equity_curve[i + 1] <- capital           # Update equity curve

}


# Step 8: Prepare Data for Plotting the Equity Curve

equity_df <- data.frame(Date = c(buy_signals$Date, max(buy_signals$Sell_Date, na.rm = TRUE)), 

                        Capital = equity_curve)


# Step 9: Prepare Data for Plotting Buy and Sell Signals on Price Chart

RVNL_df$Buy_Signal <- ifelse(RVNL_df$Date %in% buy_signals$Date, "Buy", NA)

RVNL_df$Sell_Signal <- ifelse(RVNL_df$Date %in% buy_signals$Sell_Date, "Sell", NA)


# Step 10: Plot Price Chart with Buy (Green) and Sell (Red) Candles Using ggplot2

price_chart <- ggplot(RVNL_df, aes(x = Date)) +

  geom_line(aes(y = Close), color = "blue") +  # Plot Close prices

  geom_point(data = RVNL_df %>% filter(!is.na(Buy_Signal)), aes(y = Low), color = "darkgreen", size = 3, shape = 24, fill = "darkgreen") +  # Buy Signal

  geom_point(data = RVNL_df %>% filter(!is.na(Sell_Signal)), aes(y = High), color = "red", size = 3, shape = 25, fill = "red") +          # Sell Signal

  labs(title = "RVNL Trading Strategy: Buy (Green) and Sell (Red) Signals", y = "Price", x = "Date") +

  theme_minimal()


# Plot the Price Chart

print(price_chart)


# Step 11: Plot Equity Curve Using ggplot2

equity_chart <- ggplot(equity_df, aes(x = Date, y = Capital)) +

  geom_line(color = "blue", size = 1) +

  labs(title = "Equity Curve for RVNL Trading Strategy", y = "Capital (INR)", x = "Date") +

  theme_minimal()


# Plot the Equity Curve

print(equity_chart)


# Step 12: Display Results Table with Total Return, Total Days Held, and Final Capital

trade_results <- buy_signals %>%

  select(Date, Sell_Date, Return, Days_Held, Capital) %>%

  filter(!is.na(Sell_Date))  # Filter out rows without Sell Date


# Calculate total return and total days held

final_capital <- capital

total_return <- (final_capital - starting_capital) / starting_capital * 100  # Total return as percentage

total_days_held <- sum(trade_results$Days_Held, na.rm = TRUE)


# Display results

print("Trade Results (Buy Date, Sell Date, Return, Days Held, Capital):")

print(trade_results)


print(paste("Final Capital:", round(final_capital, 2), "INR"))

print(paste("Total Return Generated:", round(total_return, 2), "%"))

print(paste("Total Days Held:", total_days_held))


# If you want to save the results as a CSV file:

write.csv(trade_results, "RVNL_Trading_Strategy_Results.csv", row.names = FALSE)





Changing buy to 3%, the performance increases 




50% time sold on fourth day, 50% time SL hit on 3/2/1 day.


No comments:

Post a Comment

ESTERINDUSTRIES #PotentialBoom?

 -Strong Price Action -JV, new product