adaptic-utils
v0.0.20
Published
Utility functions used in Adaptic app and Lambda functions
Downloads
1,187
Readme
Adaptic Utilities
A comprehensive utility library for financial data processing, time manipulation, and formatting.
NPM repo: https://www.npmjs.com/package/adaptic-utils
Installation
npm install adaptic-utils
Usage
Import the functions from the library:
import { adaptic } from 'adaptic-utils';
Alpaca Functions
fetchAccountDetails(accountId: string)
Asynchronously retrieves detailed information about a specific Alpaca trading account.
Example:
const accountDetails = await adaptic.alpaca.fetchAccountDetails('your-account-id');
// Output: { accountId: 'your-account-id', ... }
fetchPositions(accountId: string)
Asynchronously fetches current open positions for a specific Alpaca trading account.
Example:
const positions = await adaptic.alpaca.fetchPositions('your-account-id');
// Output: [{ symbol: 'AAPL', qty: 10, ... }, ...]
fetchPortfolioHistory(accountId: string, params: { period?: string, timeframe?: string, start?: string, end?: string })
Asynchronously retrieves historical portfolio performance data with flexible time range options.
Example:
const portfolioHistory = await adaptic.alpaca.fetchPortfolioHistory('your-account-id', {
period: '1M', // Optional: '1D', '1W', '1M', '3M', '1Y'
timeframe: '1D' // Optional: granularity of data
});
// Output: { equity: [...], timestamp: [...] }
getConfiguration(account: AlpacaAccount)
Asynchronously retrieves the current configuration for a specific Alpaca account.
Example:
const config = await adaptic.alpaca.getConfiguration(alpacaAccount);
// Output: { tradeSuspendedByUser: false, ... }
updateConfiguration(user: User, account: AlpacaAccount, updatedConfig: Partial<AccountConfiguration>)
Asynchronously updates the configuration for a specific Alpaca account.
Example:
const updatedConfig = await adaptic.alpaca.updateConfiguration(
user, // Current user object
alpacaAccount, // Alpaca account to update
{
tradeSuspendedByUser: false,
dtbpCheck: 'entry'
}
);
// Output: { tradeSuspendedByUser: false, ... }
Metrics Functions
fetchTradeMetrics()
Calculates and retrieves comprehensive trade performance metrics.
Example:
const tradeMetrics = await adaptic.metrics.fetchTradeMetrics();
// Output: { totalReturnYTD: '5%', alpha: '0.5', beta: '1.2', ... }
Performance Metrics
calculateAlphaAndBeta(returns: number[])
Computes the alpha and beta of an investment portfolio.
Example:
const { alpha, beta } = adaptic.metrics.performance.calculateAlphaAndBeta(returns);
// Output: { alpha: '0.5', beta: '1.2' }
calculateMaxDrawdown(portfolioValues: number[])
Calculates the maximum percentage drop from a peak during a specific period.
Example:
const maxDrawdown = adaptic.metrics.performance.calculateMaxDrawdown(portfolioValues);
// Output: '10.5%'
calculateDailyReturns(portfolioValues: number[])
Computes daily returns from a series of portfolio values.
Example:
const dailyReturns = adaptic.metrics.performance.calculateDailyReturns(portfolioValues);
// Output: [0.02, -0.01, 0.03, ...]
alignReturnsByDate(returnsSeries: any[])
Aligns multiple return series by their dates.
Example:
const alignedReturns = adaptic.metrics.performance.alignReturnsByDate(returnsSeries);
// Output: { alignedPortfolioReturns: [...], alignedBenchmarkReturns: [...] }
calculateBetaFromReturns(assetReturns: number[], benchmarkReturns: number[])
Calculates beta using historical returns data.
Example:
const beta = adaptic.metrics.performance.calculateBetaFromReturns(assetReturns, benchmarkReturns);
// Output: 1.2
calculateInformationRatio(portfolioReturns: number[], benchmarkReturns: number[])
Measures a portfolio's risk-adjusted performance relative to a benchmark.
Example:
const infoRatio = adaptic.metrics.performance.calculateInformationRatio(portfolioReturns, benchmarkReturns);
// Output: 0.75
fetchPerformanceMetrics()
Retrieves comprehensive performance metrics for a portfolio.
Example:
const performanceMetrics = await adaptic.metrics.performance.fetchPerformanceMetrics();
// Output: { totalReturnYTD: '5%', alpha: '0.5', beta: '1.2', ... }
Time Utilities
toUnixTimestamp(date: Date)
Converts a date to Unix timestamp.
Example:
const timestamp = adaptic.time.toUnixTimestamp(new Date());
// Output: 1633058400
getTimeAgo(date: Date)
Returns a human-readable time difference from now.
Example:
const timeAgo = adaptic.time.getTimeAgo(new Date(Date.now() - 60000));
// Output: '1 minute ago'
normalizeDate(date: Date)
Standardizes a date to a consistent format.
Example:
const normalizedDate = adaptic.time.normalizeDate(new Date());
// Output: '2024-11-09'
getDateInNY()
Returns the current date in New York timezone.
Example:
const nyDate = adaptic.time.getDateInNY();
// Output: new Date('2024-11-09T00:00:00-05:00')
createMarketTimeUtil()
Creates a utility for market time-related operations.
Example:
const marketTimeUtil = adaptic.time.createMarketTimeUtil();
// Use marketTimeUtil for market operations
getStartAndEndTimestamps(period: string)
Generates start and end timestamps for a given period.
Example:
const { start, end } = adaptic.time.getStartAndEndTimestamps('1D');
// Output: { start: 1633058400, end: 1633144800 }
daysLeft(endDate: Date)
Calculates the number of days remaining until a specific date.
Example:
const remainingDays = adaptic.time.daysLeft(new Date('2024-12-31'));
// Output: 52
formatDate(date: Date)
Formats a date in a readable string format.
Example:
const formattedDate = adaptic.time.formatDate(new Date());
// Output: 'November 9, 2024'
Price Utilities
helloWorld(name?: string)
A simple greeting function with an optional name parameter.
Example:
const greeting = adaptic.hello('World'); // Returns "Hello, World!"
// Output: "Hello, World!"
computeTotalFees(trade: Trade)
Calculates the total fees for a given trade across different asset types.
Example:
const totalFees = adaptic.price.computeTotalFees(tradeData);
// Output: 12.34
getEquityValues(equityData: EquityPoint[])
Extracts equity values from historical portfolio data.
Example:
const { latestEquity, initialEquity } = adaptic.price.getEquityValues(equityHistory);
// Output: { latestEquity: 1500, initialEquity: 1000 }
Formatting Utilities
nanoid()
Generates a unique, short, non-sequential ID.
Example:
const uniqueId = adaptic.format.nanoid();
// Output: 'A1bC2D3'
capitalize(string)
Capitalizes the first letter of a string.
Example:
const capitalized = adaptic.format.capitalize('hello'); // Returns "Hello"
// Output: "Hello"
formatEnum(enum)
Formats an enum value for display.
Example:
const formatted = adaptic.format.formatEnum(MyEnum.VALUE);
// Output: 'My Enum Value'
formatCurrency(value: number)
Formats a number as currency.
Example:
const currency = adaptic.format.formatCurrency(1234.56); // Returns "$1,234.56"
// Output: "$1,234.56"
formatPercentage(value: number)
Formats a number as a percentage.
Example:
const percentage = adaptic.format.formatPercentage(0.75); // Returns "75%"
// Output: "75%"
Contributing to the Repository
Contributions are welcome! Please submit a pull request or open an issue for any enhancements or bug fixes.
Author
This project is a product of Lumic.ai.
Thanks for reading this far! Why did the trader bring a ladder to the bar? Because they heard the drinks were on the house!