if (!pnlSheet || !pnlI_Sheet || !outputSheet) {
SpreadsheetApp.getUi().alert("One or more sheets not found. Please check the sheet names.");
return;
}
// Get filter parameters from "PnL_One" sheet
const filterSheet = outputSheet;
const startDate = filterSheet.getRange("B2").getValue(); // Start Date
const endDate = filterSheet.getRange("C2").getValue(); // End Date
const assetClassFilter = filterSheet.getRange("A3").getValue().toString().trim();
const brokerFilter = filterSheet.getRange("B3").getValue().toString().trim();
const userFilter = filterSheet.getRange("C3").getValue().toString().trim();
const tradeTypeFilter = filterSheet.getRange("D3").getValue().toString().trim(); // Delivery, Intraday, Both
// Function to clean and parse numbers, removing commas and currency symbols
function parseNumber(value) {
if (typeof value === 'number') return value;
if (typeof value === 'string') {
// Remove commas and any non-numeric characters except for the decimal point and minus sign
let cleaned = value.replace(/[^0-9.-]/g, '');
return parseFloat(cleaned) || 0;
}
return 0;
}
// Function to parse date from string (e.g., "30-Apr-2020") or return as is if already a Date
function parseDate(value) {
if (value instanceof Date) {
return value;
} else if (typeof value === 'string') {
// Expected format: "DD-MMM-YYYY"
const dateParts = value.split("-");
if (dateParts.length === 3) {
const day = parseInt(dateParts[0], 10);
const monthStr = dateParts[1].toLowerCase();
const year = parseInt(dateParts[2], 10);
const monthNames = ["jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov", "dec"];
const month = monthNames.indexOf(monthStr.substring(0,3)) + 1; // 1-based
if (month >= 1 && month <= 12) {
return new Date(year, month -1, day); // months are 0-based in JavaScript
}
}
}
return null;
}
// Function to retrieve and process data from a sheet
function getPnLData(sheet, isDelivery) {
let data = [];
if (isDelivery) {
// "PnL" sheet: headers in row 4, data starts from row 5
const lastRow = sheet.getLastRow();
const lastCol = sheet.getLastColumn();
if (lastRow < 5) return data; // No data
// Retrieve data from both sheets
let deliveryData = getPnLData(pnlSheet, true); // Delivery trades
let intradayData = getPnLData(pnlI_Sheet, false); // Intraday trades
// Combine all data
let allData = deliveryData.concat(intradayData);
// Apply filters
let filteredData = allData.filter(trade => {
// Date filter: Inclusive
if (startDate instanceof Date && trade.date < startDate) return false;
if (endDate instanceof Date && trade.date > endDate) return false;
code
// Asset Class filter
if (assetClassFilter && assetClassFilter.toUpperCase() !== "ALL" && trade.assetClass.toUpperCase() !== assetClassFilter.toUpperCase()) return false;
// Broker filter
if (brokerFilter && brokerFilter.toUpperCase() !== "ALL" && trade.broker.toUpperCase() !== brokerFilter.toUpperCase()) return false;
// User filter
if (userFilter && userFilter.toUpperCase() !== "ALL" && trade.user.toUpperCase() !== userFilter.toUpperCase()) return false;
// Trade Type filter: Delivery, Intraday, Both
if (tradeTypeFilter === "Delivery" && trade.tradeMode !== "Delivery") return false;
if (tradeTypeFilter === "Intraday" && trade.tradeMode !== "Intraday") return false;
// If "Both", include all trade modes
return true;
});
// Clear previous output starting from row 5 (to preserve headers and other manual data)
const lastRowOutput = outputSheet.getLastRow();
if (lastRowOutput > 4) {
outputSheet.getRange(5, 1, lastRowOutput - 4, 11).clearContent();
}
if (filteredData.length === 0) {
SpreadsheetApp.getUi().alert("No PnL data matches the specified filters.");
return;
}
// Aggregate data by Ticker
let aggregationMap = {};
// Set headers in row 4 (A4:K4)
outputSheet.getRange("A4:K4").setValues([headers]);
// Write data starting from row 5
if (finalOutput.length > 0) {
outputSheet.getRange(5, 1, finalOutput.length, finalOutput[0].length).setValues(finalOutput);
}
// Record the last update date and time
let now = new Date();
let formattedNow = Utilities.formatDate(now, "Asia/Kolkata", "dd-MMM-yyyy HH:mm:ss");
outputSheet.getRange('A1').setValue(formattedNow);
// Inform the user
SpreadsheetApp.getUi().alert("PnL data has been successfully filtered and aggregated.");
}"
what this code do exactly.
The provided code is a Google Apps Script function named filterAndAggregatePnL(). This script is designed to work within a Google Sheets environment, specifically tailored to handle and process trade data for financial analysis.
Here's a detailed step-by-step explanation of what the code does:
1. Accessing the Spreadsheet and Sheets
Active Spreadsheet Access:
javascript
const ss = SpreadsheetApp.getActiveSpreadsheet();
The script begins by accessing the active Google Spreadsheet where it is deployed.
The script retrieves references to these sheets using their names.
Sheet Existence Check:
javascript
if (!pnlSheet || !pnlI_Sheet || !outputSheet) {
SpreadsheetApp.getUi().alert("One or more sheets not found. Please check the sheet names.");
return;
}
It ensures that all required sheets exist. If any are missing, it alerts the user and stops execution.
2. Reading Filter Parameters
Assigning Filter Sheet:
javascript
const filterSheet = outputSheet;
The output sheet ("PnL_One") is also used to retrieve filter parameters.
Retrieving Filter Values:
javascript
const startDate = filterSheet.getRange("B2").getValue(); // Start Date
const endDate = filterSheet.getRange("C2").getValue(); // End Date
const assetClassFilter = filterSheet.getRange("A3").getValue().toString().trim();
const brokerFilter = filterSheet.getRange("B3").getValue().toString().trim();
const userFilter = filterSheet.getRange("C3").getValue().toString().trim();
const tradeTypeFilter = filterSheet.getRange("D3").getValue().toString().trim(); // Delivery, Intraday, Both
It reads the following filters from specific cells on the output sheet:
Start Date (B2): The beginning of the date range for filtering trades.
End Date (C2): The end of the date range.
Asset Class Filter (A3): Filters trades by asset class (e.g., Equity, Forex).
Broker Filter (B3): Filters trades by broker name.
User Filter (C3): Filters trades by user or trader's name.
Trade Type Filter (D3): Filters by trade type ("Delivery", "Intraday", or "Both").
3. Helper Functions
Parsing Numbers:
javascript
function parseNumber(value) { ... }
A utility function to parse and clean numeric values from strings, handling commas, currency symbols, and other non-numeric characters, ensuring accurate numerical calculations.
Parsing Dates:
javascript
function parseDate(value) { ... }
A function to convert date strings (e.g., "30-Apr-2020") into JavaScript Date objects for accurate date comparisons and filtering.
4. Retrieving and Processing Trade Data
Function to Get PnL Data:
javascript
function getPnLData(sheet, isDelivery) { ... }
A function that retrieves and processes trade data from either the delivery or intraday sheet:
Parameters:
sheet: The sheet to process (pnlSheet or pnlI_Sheet).
isDelivery: A boolean indicating whether to process delivery trades.
Within getPnLData():
Data Extraction:
Delivery Trades:
Starts reading data from row 5, as headers are assumed to be in row 4.
Expected columns include Buy Date, Sell Date, Ticker, Shares, Buy Price, Sell Price, Asset Class, Broker, User, Fees, etc.
Intraday Trades:
Starts reading data from row 4, with headers in row 3.
Similar expected columns tailored for intraday data.
Data Parsing:
For each row, it extracts and parses relevant trade information using the helper functions.
Trades with valid tickers and dates are pushed into a data array as objects with structured properties.
Additional property tradeMode is added to indicate whether the trade is "Delivery" or "Intraday".
5. Aggregating and Filtering Trades
Combining Trade Data:
javascript
let allData = deliveryData.concat(intradayData);
Combines delivery and intraday trade data into a single dataset for comprehensive analysis.
Applying Filters:
javascript
let filteredData = allData.filter(trade => { ... });
Filters the combined trade data based on the user's specified criteria:
Date Range: Only includes trades within the specified start and end dates.
Asset Class: Filters by the selected asset class unless "ALL" is specified.
Broker: Filters by broker name unless "ALL" is specified.
User: Filters by user name unless "ALL" is specified.
Trade Type: Includes only delivery trades, intraday trades, or both, depending on the selection.
Handling No Data Scenario:
javascript
if (filteredData.length === 0) {
SpreadsheetApp.getUi().alert("No PnL data matches the specified filters.");
return;
}
If no trades match the filters, the script alerts the user and stops execution.
Before writing new data, the script clears any previous results from the output sheet, beginning from row 5 (preserving headers and filter settings above).
7. Aggregating Data by Ticker
Initializing Aggregation Map:
javascript
let aggregationMap = {};
An object to accumulate trade data grouped by ticker symbol.
Aggregating Trades:
javascript
filteredData.forEach(trade => { ... });
For each filtered trade, the script:
Groups Trades by Ticker:
Checks if the ticker exists in aggregationMap; if not, initializes an entry.
Accumulates Values:
Total Shares: Sums up quantities traded.
Total Buy Value: Sums up the product of shares and buy prices.
Total Sell Value: Sums up the product of shares and sell prices.
Total Fees: Accumulates transaction fees associated with the trades.
8. Preparing Output Data
Calculating Aggregated Metrics:
javascript
let outputData = [];
for (let ticker in aggregationMap) { ... }
For each ticker in the aggregation map, the script computes:
Buy Average Price:Total Buy Value / Total Shares
Sell Average Price:Total Sell Value / Total Shares
Value at Buy: Total amount spent buying the shares.
Value at Sell: Total amount received from selling the shares.
Gross PnL:Value at Sell - Value at Buy
Net PnL:Gross PnL - Total Fees
Percentage PnL:(Net PnL) / Value at Buy (expressed as a decimal; multiply by 100 for percentage)
These metrics are stored in the outputData array.
9. Sorting and Writing Output
Sorting Output Data:
javascript
outputData.sort((a, b) => a.ticker.localeCompare(b.ticker));
The aggregated data is sorted alphabetically by the ticker symbol for organized presentation.
Preparing Final Output Array:
javascript
let finalOutput = [];
outputData.forEach((row, index) => { ... });
Constructs a two-dimensional array (finalOutput) where each sub-array represents a row in the output sheet, including:
Writes the header row in the output sheet at row 4, columns A to K.
Writing Data to Sheet:
javascript
if (finalOutput.length > 0) {
outputSheet.getRange(5, 1, finalOutput.length, finalOutput[0].length).setValues(finalOutput);
}
Inputs the aggregated and sorted data into the output sheet, starting from row 5.
10. Recording the Last Update Time
Timestamping:
javascript
let now = new Date();
let formattedNow = Utilities.formatDate(now, "Asia/Kolkata", "dd-MMM-yyyy HH:mm:ss");
outputSheet.getRange('A1').setValue(formattedNow);
Records the date and time when the script was last run into cell A1 of the output sheet. The time is formatted according to the "Asia/Kolkata" timezone.
11. User Notification
Completion Alert:
javascript
SpreadsheetApp.getUi().alert("PnL data has been successfully filtered and aggregated.");
Once processing is complete, the script displays an alert to inform the user.
Summary
The function filterAndAggregatePnL() automates the process of analyzing trade data within a Google Sheet by performing the following actions:
Data Retrieval:
Extracts trade data from two sheets: one for delivery trades ("PnL") and one for intraday trades ("PnL_i").
Filtering:
Applies user-defined filters based on date range, asset class, broker, user, and trade type (delivery or intraday).
Aggregation:
Groups the filtered trades by ticker symbol.
Calculates key financial metrics for each ticker, such as total quantities, average prices, gross and net profits, and profit percentages.
Output:
Writes the aggregated results into a designated output sheet ("PnL_One"), organizing the data in a clear and structured format with headers.
Records the timestamp of the last update for reference.
User Interaction:
Provides alerts to guide the user, such as notifying if sheets are missing, if no data matches the filters, or when the processing is successfully completed.
Overall, this script streamlines the analysis of profit and loss data from trading activities, enabling users to easily generate summary reports based on specific criteria without manual data manipulation.