npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

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!