Option Explicit
' ===== PCR ANALYSIS MODULE FOR NIFTY [Link] =====
' This module provides:
' 1. One-touch data refresh button
' 2. PCR Analysis tab creation and management
' 3. Conditional formatting and visualization tools
' 4. Integration with NSE data feed
' ===== GLOBALS =====
Public Const PCR_SHEET_NAME As String = "PCR Analysis"
Public Const DATA_SHEET_NAME As String = "PCR_Data"
Public Const SCRIPT_PATH As String = "C:\Users\DOGA\Documents\NIFTY PCR\
very_simple_excel_integration.py"
Public Const CSV_PATH As String = "C:\Users\DOGA\Documents\NIFTY PCR\data\
pcr_data.csv"
' Window state constants
Public Const WINDOW_NORMAL = 1
Public Const WINDOW_MINIMIZED = 2
Public Const WINDOW_MAXIMIZED = 3
' ===== MAIN FUNCTIONS =====
Sub RefreshPCRData()
' One-touch refresh button implementation
' Fetches fresh PCR data and updates analysis
' Show status
[Link] = "Fetching PCR data from NSE..."
' Disable screen updating to prevent flicker
[Link] = False
' Check if PCR Analysis sheet exists, create if not
If Not SheetExists(PCR_SHEET_NAME) Then
CreatePCRAnalysisSheet
End If
' Check if data sheet exists
If Not SheetExists(DATA_SHEET_NAME) Then
' Create data sheet if it doesn't exist
[Link] = DATA_SHEET_NAME
End If
' Run Python script to fetch data
Dim command As String
command = "python """ & SCRIPT_PATH & """"
' Run the command using Shell
Dim returnValue As Variant
returnValue = Shell("[Link] /c " & command, WINDOW_MINIMIZED)
' Wait for script to complete
[Link] Now + TimeValue("[Link]")
' Import the CSV data into the Excel sheet
ImportCSVData
' Update PCR analysis
UpdatePCRAnalysis
' Reset status
[Link] = False
[Link] = True
' Show completion message
MsgBox "PCR data updated successfully!", vbInformation, "PCR Analysis"
End Sub
Sub ImportCSVData()
' Imports CSV data into the PCR_Data sheet
Dim wsData As Worksheet
' Get or create the data sheet
On Error Resume Next
Set wsData = [Link](DATA_SHEET_NAME)
On Error GoTo 0
If wsData Is Nothing Then
[Link] = DATA_SHEET_NAME
Set wsData = [Link](DATA_SHEET_NAME)
End If
' Clear existing data
[Link]
' Check if CSV file exists
If Dir(CSV_PATH) = "" Then
MsgBox "CSV data file not found at: " & CSV_PATH, vbExclamation
Exit Sub
End If
' Open the CSV file
Dim fso As Object
Dim textStream As Object
Dim line As String
Dim values() As String
Dim row As Long
Set fso = CreateObject("[Link]")
Set textStream = [Link](CSV_PATH, 1) ' 1 = ForReading
' Read CSV data line by line
row = 1
Do While Not [Link]
line = [Link]
values = Split(line, ",")
' Write values to the sheet
Dim col As Long
For col = 0 To UBound(values)
[Link](row, col + 1).Value = values(col)
Next col
row = row + 1
Loop
' Close the text stream
[Link]
Set textStream = Nothing
Set fso = Nothing
' Format the data sheet
If row > 1 Then
[Link](1).[Link] = True
[Link]
End If
End Sub
Sub CreatePCRAnalysisSheet()
' Creates a new PCR Analysis sheet with proper formatting
' Add a new sheet if it doesn't exist
Dim ws As Worksheet
' Check if sheet exists already
On Error Resume Next
Set ws = [Link](PCR_SHEET_NAME)
On Error GoTo 0
If ws Is Nothing Then
' Create new sheet
Set ws = [Link]
[Link] = PCR_SHEET_NAME
End If
' Set up the PCR Analysis sheet
With ws
' Clear any existing content
.[Link]
' Add title
.Range("A1").Value = "NIFTY OPTIONS PCR ANALYSIS"
.Range("A1:H1").Merge
.Range("A1").[Link] = 16
.Range("A1").[Link] = True
.Range("A1").HorizontalAlignment = xlCenter
' Add last updated timestamp
.Range("A2").Value = "Last Updated:"
.Range("B2").Value = Now()
.Range("B2").NumberFormat = "dd-mmm-yyyy hh:mm:ss"
' Add refresh button (text)
.Range("G2").Value = "REFRESH DATA"
.Range("G2:H2").Merge
.Range("G2").[Link] = True
.Range("G2").HorizontalAlignment = xlCenter
.Range("G2").[Link] = RGB(0, 176, 80)
.Range("G2").[Link] = RGB(255, 255, 255)
' Add section headers
.Range("A4").Value = "CURRENT PCR VALUES"
.Range("A4:H4").Merge
.Range("A4").[Link] = True
.Range("A4").[Link] = RGB(91, 155, 213)
.Range("A4").[Link] = RGB(255, 255, 255)
' Current PCR metrics
.Range("A5").Value = "Weekly PCR:"
.Range("A6").Value = "Overall PCR:"
.Range("A7").Value = "PCR Trend:"
' Add summary area
.Range("A9").Value = "MARKET SIGNALS"
.Range("A9:H9").Merge
.Range("A9").[Link] = True
.Range("A9").[Link] = RGB(91, 155, 213)
.Range("A9").[Link] = RGB(255, 255, 255)
' Market signal metrics
.Range("A10").Value = "Market Sentiment:"
.Range("A11").Value = "Signal Strength:"
.Range("A12").Value = "Reversal Risk:"
' Add chart section
.Range("A14").Value = "PCR TREND ANALYSIS"
.Range("A14:H14").Merge
.Range("A14").[Link] = True
.Range("A14").[Link] = RGB(91, 155, 213)
.Range("A14").[Link] = RGB(255, 255, 255)
' Add data table section
.Range("A29").Value = "RECENT PCR DATA"
.Range("A29:H29").Merge
.Range("A29").[Link] = True
.Range("A29").[Link] = RGB(91, 155, 213)
.Range("A29").[Link] = RGB(255, 255, 255)
' Column headers for data table
.Range("A30").Value = "Date"
.Range("B30").Value = "Weekly PCR"
.Range("C30").Value = "Overall PCR"
.Range("D30").Value = "Weekly Put OI"
.Range("E30").Value = "Weekly Call OI"
.Range("F30").Value = "Overall Put OI"
.Range("G30").Value = "Overall Call OI"
.Range("H30").Value = "Signal"
' Format column headers
.Range("A30:H30").[Link] = True
.Range("A30:H30").[Link] = RGB(198, 224, 180)
' Add notes section
.Range("A45").Value = "NOTES"
.Range("A45:H45").Merge
.Range("A45").[Link] = True
.Range("A45").[Link] = RGB(91, 155, 213)
.Range("A45").[Link] = RGB(255, 255, 255)
' Add notes content
.Range("A46").Value = "PCR Interpretation:"
.Range("A47").Value = "PCR > 1.2: Bearish sentiment (too many puts,
potential reversal to upside)"
.Range("A48").Value = "PCR 1-1.2: Slightly bearish"
.Range("A49").Value = "PCR 0.8-1: Slightly bullish"
.Range("A50").Value = "PCR < 0.8: Bullish sentiment (too many calls,
potential reversal to downside)"
' Size columns appropriately
.Columns("A:H").AutoFit
' Create named ranges for easier reference
On Error Resume Next
[Link] Name:="WeeklyPCR", RefersTo:=.Range("B5")
[Link] Name:="OverallPCR", RefersTo:=.Range("B6")
[Link] Name:="PCRTrend", RefersTo:=.Range("B7")
[Link] Name:="MarketSentiment", RefersTo:=.Range("B10")
[Link] Name:="SignalStrength", RefersTo:=.Range("B11")
[Link] Name:="ReversalRisk", RefersTo:=.Range("B12")
On Error GoTo 0
' Assign refresh button macro
AssignRefreshButtonMacro
End With
End Sub
Sub UpdatePCRAnalysis()
' Updates the PCR Analysis sheet with latest data
' Get the PCR Analysis sheet
Dim wsAnalysis As Worksheet
Dim wsData As Worksheet
On Error Resume Next
Set wsAnalysis = [Link](PCR_SHEET_NAME)
Set wsData = [Link](DATA_SHEET_NAME)
On Error GoTo 0
' Check if sheets exist
If wsAnalysis Is Nothing Then
CreatePCRAnalysisSheet
Set wsAnalysis = [Link](PCR_SHEET_NAME)
End If
If wsData Is Nothing Then
MsgBox "Data sheet not found. Please refresh data first.", vbExclamation
Exit Sub
End If
' Check if data exists
Dim lastRow As Long
lastRow = [Link]([Link], 1).End(xlUp).Row
If lastRow <= 1 Then
[Link]("B5").Value = "No data"
[Link]("B6").Value = "No data"
Exit Sub
End If
' Get the latest data
' Based on CSV format:
' 0: Timestamp
' 1: Date
' 2: Weekly_PCR
' 3: Weekly_Put_OI
' 4: Weekly_Call_OI
' 5: Overall_PCR
' 6: Overall_Put_OI
' 7: Overall_Call_OI
Dim latestWeeklyPCR As Double
Dim latestOverallPCR As Double
latestWeeklyPCR = CDbl([Link](lastRow, 3).Value) ' Weekly PCR in column
3
latestOverallPCR = CDbl([Link](lastRow, 6).Value) ' Overall PCR in
column 6
' Update the current PCR values
[Link]("B5").Value = latestWeeklyPCR
[Link]("B6").Value = latestOverallPCR
' Format PCR values
[Link]("B5").NumberFormat = "0.000"
[Link]("B6").NumberFormat = "0.000"
' Determine trend (if at least 2 data points)
Dim pcrTrend As String
pcrTrend = "Neutral"
If lastRow > 2 Then
Dim previousWeeklyPCR As Double
previousWeeklyPCR = CDbl([Link](lastRow - 1, 3).Value)
If latestWeeklyPCR > previousWeeklyPCR + 0.1 Then
pcrTrend = "Rising ↑"
[Link]("B7").[Link] = RGB(0, 128, 0) ' Green
ElseIf latestWeeklyPCR < previousWeeklyPCR - 0.1 Then
pcrTrend = "Falling ↓"
[Link]("B7").[Link] = RGB(255, 0, 0) ' Red
Else
pcrTrend = "Neutral →"
[Link]("B7").[Link] = RGB(0, 0, 0) ' Black
End If
End If
[Link]("B7").Value = pcrTrend
' Update last updated timestamp
[Link]("B2").Value = Now()
' Determine market signals
Dim sentiment As String
Dim signalStrength As String
Dim reversalRisk As String
' Sentiment based on latest Weekly PCR
If latestWeeklyPCR > 1.5 Then
sentiment = "Extremely Bearish"
[Link]("B10").[Link] = RGB(192, 0, 0) ' Dark Red
signalStrength = "Strong"
reversalRisk = "High"
ElseIf latestWeeklyPCR > 1.2 Then
sentiment = "Bearish"
[Link]("B10").[Link] = RGB(255, 0, 0) ' Red
signalStrength = "Moderate"
reversalRisk = "Moderate"
ElseIf latestWeeklyPCR > 1 Then
sentiment = "Slightly Bearish"
[Link]("B10").[Link] = RGB(255, 128, 128) ' Light Red
signalStrength = "Weak"
reversalRisk = "Low"
ElseIf latestWeeklyPCR >= 0.8 Then
sentiment = "Neutral"
[Link]("B10").[Link] = RGB(0, 0, 0) ' Black
signalStrength = "Neutral"
reversalRisk = "Low"
ElseIf latestWeeklyPCR >= 0.6 Then
sentiment = "Slightly Bullish"
[Link]("B10").[Link] = RGB(0, 176, 80) ' Light Green
signalStrength = "Weak"
reversalRisk = "Low"
ElseIf latestWeeklyPCR >= 0.4 Then
sentiment = "Bullish"
[Link]("B10").[Link] = RGB(0, 128, 0) ' Green
signalStrength = "Moderate"
reversalRisk = "Moderate"
Else
sentiment = "Extremely Bullish"
[Link]("B10").[Link] = RGB(0, 100, 0) ' Dark Green
signalStrength = "Strong"
reversalRisk = "High"
End If
' Update market signals
[Link]("B10").Value = sentiment
[Link]("B11").Value = signalStrength
[Link]("B12").Value = reversalRisk
' Update data table
' Copy last 15 rows of data (or all if less than 15)
Dim dataRows As Long
dataRows = [Link](15, lastRow - 1)
Dim startRow As Long
startRow = lastRow - dataRows + 1
' Clear existing data
[Link]("A31:H45").ClearContents
' Copy data
Dim i As Long
For i = 0 To dataRows - 1
' Make sure startRow + i is not less than 2 (to skip header)
If startRow + i >= 2 Then
' Date (column 2 in CSV data)
[Link](31 + i, 1).Value = [Link](startRow + i, 2).Value
[Link](31 + i, 1).NumberFormat = "dd-mmm-yyyy hh:mm"
' Weekly PCR (column 3 in CSV data)
[Link](31 + i, 2).Value = [Link](startRow + i, 3).Value
[Link](31 + i, 2).NumberFormat = "0.000"
' Overall PCR (column 6 in CSV data)
[Link](31 + i, 3).Value = [Link](startRow + i, 6).Value
[Link](31 + i, 3).NumberFormat = "0.000"
' Weekly Put OI (column 4 in CSV data)
[Link](31 + i, 4).Value = [Link](startRow + i, 4).Value
[Link](31 + i, 4).NumberFormat = "#,##0"
' Weekly Call OI (column 5 in CSV data)
[Link](31 + i, 5).Value = [Link](startRow + i, 5).Value
[Link](31 + i, 5).NumberFormat = "#,##0"
' Overall Put OI (column 7 in CSV data)
[Link](31 + i, 6).Value = [Link](startRow + i, 7).Value
[Link](31 + i, 6).NumberFormat = "#,##0"
' Overall Call OI (column 8 in CSV data)
[Link](31 + i, 7).Value = [Link](startRow + i, 8).Value
[Link](31 + i, 7).NumberFormat = "#,##0"
' Signal
Dim rowPCR As Double
rowPCR = CDbl([Link](startRow + i, 3).Value)
If rowPCR > 1.2 Then
[Link](31 + i, 8).Value = "Bearish"
[Link](31 + i, 8).[Link] = RGB(255, 0, 0)
ElseIf rowPCR > 1 Then
[Link](31 + i, 8).Value = "Slightly Bearish"
[Link](31 + i, 8).[Link] = RGB(255, 128, 128)
ElseIf rowPCR >= 0.8 Then
[Link](31 + i, 8).Value = "Neutral"
[Link](31 + i, 8).[Link] = RGB(0, 0, 0)
ElseIf rowPCR >= 0.6 Then
[Link](31 + i, 8).Value = "Slightly Bullish"
[Link](31 + i, 8).[Link] = RGB(0, 176, 80)
Else
[Link](31 + i, 8).Value = "Bullish"
[Link](31 + i, 8).[Link] = RGB(0, 128, 0)
End If
End If
Next i
' Create PCR trend chart
CreatePCRTrendChart
' Apply conditional formatting to the PCR values
ApplyConditionalFormattingToPCR
End Sub
Sub CreatePCRTrendChart()
' Creates or updates the PCR trend chart
Dim wsAnalysis As Worksheet
Dim wsData As Worksheet
On Error Resume Next
Set wsAnalysis = [Link](PCR_SHEET_NAME)
Set wsData = [Link](DATA_SHEET_NAME)
On Error GoTo 0
' Check if sheets exist
If wsAnalysis Is Nothing Or wsData Is Nothing Then
Exit Sub
End If
' Delete existing chart if it exists
Dim chartObj As ChartObject
For Each chartObj In [Link]
[Link]
Next chartObj
' Get data count
Dim lastRow As Long
lastRow = [Link]([Link], 1).End(xlUp).Row
' Need at least 2 data points for a chart
If lastRow <= 2 Then
Exit Sub
End If
' Determine how many data points to use (max 20)
Dim dataPoints As Long
dataPoints = [Link](20, lastRow - 1)
' Define chart data range
Dim startRow As Long
startRow = lastRow - dataPoints + 1
' Make sure startRow is at least 2 to skip header
If startRow < 2 Then startRow = 2
' Create chart
Dim chartObj1 As ChartObject
Set chartObj1 = [Link](Left:=[Link]("A15").Left,
_
Width:=350, _
Top:=[Link]("A15").Top + 20,
_
Height:=200)
' Set up chart
With [Link]
.ChartType = xlLine
' Use columns based on CSV format:
' Column 2: Date
' Column 3: Weekly PCR
' Column 6: Overall PCR
.SetSourceData Source:=[Link]("B" & startRow & ":B" & lastRow & ",C"
& startRow & ":C" & lastRow & ",F" & startRow & ":F" & lastRow)
.HasTitle = True
.[Link] = "PCR Trend Analysis"
' Format axes
.Axes(xlCategory).HasTitle = True
.Axes(xlCategory).[Link] = "Date"
.Axes(xlValue).HasTitle = True
.Axes(xlValue).[Link] = "PCR Value"
' Add horizontal line at PCR = 1 (neutral level)
Dim neutralLine As Series
Set neutralLine = .[Link]
[Link] = "Neutral Line"
[Link] = Array(1, 1)
[Link] =
Array(.Axes(xlCategory).MinimumScale, .Axes(xlCategory).MaximumScale)
[Link] = msoLineDash
[Link] = RGB(255, 0, 0)
' Set series names
.SeriesCollection(1).Name = "Weekly PCR"
.SeriesCollection(2).Name = "Overall PCR"
' Format series colors
.SeriesCollection(1).[Link] = RGB(0, 112, 192)
.SeriesCollection(2).[Link] = RGB(0, 176, 80)
' Add markers
.SeriesCollection(1).MarkerStyle = xlMarkerStyleCircle
.SeriesCollection(2).MarkerStyle = xlMarkerStyleDiamond
' Add legend
.HasLegend = True
.[Link] = xlLegendPositionBottom
End With
End Sub
Sub ApplyConditionalFormattingToPCR()
' Applies conditional formatting to PCR values
Dim wsAnalysis As Worksheet
On Error Resume Next
Set wsAnalysis = [Link](PCR_SHEET_NAME)
On Error GoTo 0
If wsAnalysis Is Nothing Then
Exit Sub
End If
' Clear existing conditional formatting
[Link]("B5:B6").[Link]
[Link]("B31:B45").[Link]
[Link]("C31:C45").[Link]
' Weekly PCR value
With [Link]("B5").[Link](Type:=xlCellValue,
Operator:=xlGreater, Formula1:="1.2")
.[Link] = RGB(255, 199, 206) ' Light red
End With
With [Link]("B5").[Link](Type:=xlCellValue,
Operator:=xlLess, Formula1:="0.8")
.[Link] = RGB(198, 239, 206) ' Light green
End With
' Overall PCR value
With [Link]("B6").[Link](Type:=xlCellValue,
Operator:=xlGreater, Formula1:="1.2")
.[Link] = RGB(255, 199, 206) ' Light red
End With
With [Link]("B6").[Link](Type:=xlCellValue,
Operator:=xlLess, Formula1:="0.8")
.[Link] = RGB(198, 239, 206) ' Light green
End With
' Weekly PCR values in table
With [Link]("B31:B45").[Link](Type:=xlCellValue,
Operator:=xlGreater, Formula1:="1.2")
.[Link] = RGB(255, 199, 206) ' Light red
End With
With [Link]("B31:B45").[Link](Type:=xlCellValue,
Operator:=xlLess, Formula1:="0.8")
.[Link] = RGB(198, 239, 206) ' Light green
End With
' Overall PCR values in table
With [Link]("C31:C45").[Link](Type:=xlCellValue,
Operator:=xlGreater, Formula1:="1.2")
.[Link] = RGB(255, 199, 206) ' Light red
End With
With [Link]("C31:C45").[Link](Type:=xlCellValue,
Operator:=xlLess, Formula1:="0.8")
.[Link] = RGB(198, 239, 206) ' Light green
End With
End Sub
Sub AssignRefreshButtonMacro()
' Assigns the refresh macro to the refresh button text cell
Dim wsAnalysis As Worksheet
On Error Resume Next
Set wsAnalysis = [Link](PCR_SHEET_NAME)
On Error GoTo 0
If wsAnalysis Is Nothing Then
Exit Sub
End If
' Create a button shape if it doesn't exist
Dim shp As Shape
Dim shapeExists As Boolean
shapeExists = False
For Each shp In [Link]
If [Link] = "RefreshButton" Then
shapeExists = True
Exit For
End If
Next shp
If Not shapeExists Then
Set shp = [Link](msoShapeRectangle, _
[Link]("G2").Left, _
[Link]("G2").Top, _
[Link]("G2:H2").Width, _
[Link]("G2").Height)
[Link] = "RefreshButton"
[Link] = RGB(0, 176, 80)
[Link] = RGB(0, 112, 52)
[Link] = "REFRESH PCR DATA"
[Link] = RGB(255, 255, 255)
[Link] = msoTrue
[Link] = msoAlignCenter
[Link] = msoAnchorMiddle
End If
' Assign macro to the button
[Link]("RefreshButton").OnAction = "RefreshPCRData"
End Sub
' ===== HELPER FUNCTIONS =====
Function SheetExists(sheetName As String) As Boolean
' Checks if a sheet exists in the workbook
Dim ws As Worksheet
On Error Resume Next
Set ws = [Link](sheetName)
On Error GoTo 0
SheetExists = Not ws Is Nothing
End Function
' ===== INSTRUCTIONS =====
'
' HOW TO USE THIS MODULE:
'
' 1. Open NIFTY [Link]
' 2. Press Alt+F11 to open the VBA Editor
' 3. Insert > Module and paste this entire code
' 4. Save as a macro-enabled workbook (.xlsm)
' 5. Run the "RefreshPCRData" macro to:
' - Create the PCR Analysis sheet
' - Fetch the latest PCR data
' - Update the analysis
'
' The one-touch button for refreshing data will be automatically created
' on the PCR Analysis tab.
'
' To refresh data:
' - Simply click the "REFRESH PCR DATA" button on the PCR Analysis tab
'
' The PCR Analysis tab provides:
' - Current PCR values with trend indicators
' - Market sentiment analysis
' - PCR trend chart
' - Recent PCR data table with signal indicators
' - Explanatory notes
'