### Install Finalytics (Go) Source: https://github.com/nnamdi-sys/finalytics/blob/main/README.md Get the finalytics Go package using the go get command. ```bash go get github.com/Nnamdi-sys/finalytics/go/finalytics ``` -------------------------------- ### JavaScript Bindings - Promise-Based API Example Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/06-bindings-python-js-go.md A comprehensive example showing how to use the promise-based API for portfolio analysis in JavaScript. ```APIDOC ### Promise-Based API All async operations return Promises: ```javascript async function analyzePortfolio() { const portfolio = await Portfolio.builder() .tickerSymbols(["AAPL", "MSFT", "NVDA"]) .startDate("2023-01-01") .endDate("2024-12-31") .objectiveFunction(ObjectiveFunction.MaxSharpe) .build(); portfolio.optimize(); const report = await portfolio.report(ReportType.Optimization); report.show(); } analyzePortfolio().catch(err => console.error(err)); ``` ``` -------------------------------- ### Install Dioxus CLI Source: https://github.com/nnamdi-sys/finalytics/blob/main/web/README.md Installs the Dioxus command-line interface, which is required for building and running Dioxus applications. ```bash cargo install dioxus-cli ``` -------------------------------- ### Install Finalytics (Node.js) Source: https://github.com/nnamdi-sys/finalytics/blob/main/README.md Install the finalytics Node.js package using npm. ```bash npm install finalytics ``` -------------------------------- ### Build a Portfolio Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/01-core-models.md Use the Portfolio builder to configure and create a portfolio. This example sets ticker symbols, date range, and the optimization objective. The `build()` method must be awaited. ```rust let portfolio = Portfolio::builder() .ticker_symbols(vec!["AAPL", "MSFT", "NVDA"]) .start_date("2023-01-01") .end_date("2024-12-31") .objective_function(ObjectiveFunction::MaxSharpe) .build() .await?; ``` -------------------------------- ### Install Finalytics JavaScript Binding Source: https://github.com/nnamdi-sys/finalytics/blob/main/js/README.md Install the Finalytics JavaScript binding using npm. Ensure you also download the required native binary. ```bash npm install finalytics curl -O https://raw.githubusercontent.com/Nnamdi-sys/finalytics/refs/heads/main/js/download_binaries.sh bash download_binaries.sh ``` -------------------------------- ### Ticker Construction Example Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/01-core-models.md Demonstrates how to use the TickerBuilder to construct a Ticker instance with specified parameters. Data fetching is deferred until methods like .report() are called. ```rust let ticker = Ticker::builder() .ticker("AAPL") .start_date("2023-01-01") .end_date("2024-12-31") .interval(Interval::OneDay) .benchmark_symbol("^GSPC") .confidence_level(0.95) .risk_free_rate(0.02) .build(); ``` -------------------------------- ### Portfolio with Rebalancing and DCA Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/00-quick-reference.md Set up a portfolio with initial weights, quarterly rebalancing, and monthly scheduled cash flows using Dollar-Cost Averaging (DCA). This example demonstrates advanced portfolio construction. ```rust let mut portfolio = Portfolio::builder() .ticker_symbols(vec!["AAPL", "MSFT", "NVDA"]) .weights(vec![25_000.0, 25_000.0, 25_000.0]) // Initial: $25k each .rebalance_strategy(Some(RebalanceStrategy::Calendar(ScheduleFrequency::Quarterly))) .scheduled_cash_flows(Some(vec![ScheduledCashFlow { amount: 2_000.0, frequency: ScheduleFrequency::Monthly, allocation: CashFlowAllocation::ProRata, start_date: None, end_date: None, }])) .build().await?; portfolio.performance_stats()?; portfolio.report(Some(ReportType::Performance)).await?.show()?; ``` -------------------------------- ### Load Custom Data and Optimize Portfolio in Rust Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/07-complete-examples.md This example shows how to load custom financial data from CSV files for multiple tickers and a benchmark, then build, optimize, and report on a portfolio. It also demonstrates updating the portfolio with new out-of-sample data and evaluating its performance. ```rust use finalytics::prelude::*; #[tokio::main] async fn main() -> Result<(), Box> { // Load custom data from CSV let aapl = KLINE::from_csv("AAPL", "data/aapl.csv")?; let msft = KLINE::from_csv("MSFT", "data/msft.csv")?; let nvda = KLINE::from_csv("NVDA", "data/nvda.csv")?; let gspc = KLINE::from_csv("^GSPC", "data/gspc.csv")?; // Create portfolio from custom data let mut portfolio = Portfolio::builder() .ticker_symbols(vec!["AAPL", "MSFT", "NVDA"]) .benchmark_symbol("^GSPC") .confidence_level(0.95) .risk_free_rate(0.02) .objective_function(ObjectiveFunction::MaxSharpe) .tickers_data(Some(vec![aapl.clone(), msft.clone(), nvda.clone()])) .benchmark_data(Some(gspc.clone())) .build() .await?; portfolio.optimize()?; let report = portfolio.report(Some(ReportType::Optimization)).await?; report.show()?; // Switch to new data for out-of-sample evaluation let aapl_new = KLINE::from_csv("AAPL", "data/aapl_2025.csv")?; let msft_new = KLINE::from_csv("MSFT", "data/msft_2025.csv")?; let nvda_new = KLINE::from_csv("NVDA", "data/nvda_2025.csv")?; let gspc_new = KLINE::from_csv("^GSPC", "data/gspc_2025.csv")?; portfolio.update_data( vec![aapl_new, msft_new, nvda_new], Some(gspc_new), ).await?; portfolio.performance_stats()?; let oos_report = portfolio.report(Some(ReportType::Performance)).await?; oos_report.show()?; Ok(()) } ``` -------------------------------- ### JavaScript Promise-Based Portfolio Analysis Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/06-bindings-python-js-go.md An example of using async/await with JavaScript Promises to analyze a portfolio and display its optimization report. ```javascript async function analyzePortfolio() { const portfolio = await Portfolio.builder() .tickerSymbols(["AAPL", "MSFT", "NVDA"]) .startDate("2023-01-01") .endDate("2024-12-31") .objectiveFunction(ObjectiveFunction.MaxSharpe) .build(); portfolio.optimize(); const report = await portfolio.report(ReportType.Optimization); report.show(); } analyzePortfolio().catch(err => console.error(err)); ``` -------------------------------- ### Compare Multi-Asset Performance and Correlations Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/07-complete-examples.md This example demonstrates how to compare the performance and correlation of multiple assets, including stocks and cryptocurrencies. It requires the 'finalytics' crate and 'tokio' runtime. ```rust use finalytics::prelude::*; #[tokio::main] async fn main() -> Result<(), Box> { // Analyze multiple assets let tickers = Tickers::builder() .tickers(vec!["NVDA", "GOOG", "AAPL", "MSFT", "BTC-USD"]) .start_date("2023-01-01") .end_date("2024-12-31") .interval(Interval::OneDay) .benchmark_symbol("^GSPC") .confidence_level(0.95) .risk_free_rate(0.02) .build(); // Show comparative performance let report = tickers.report(Some(ReportType::Performance)).await?; report.show()?; // Get correlation matrix let correlations = tickers.correlation_matrix()?; println!("Correlations:\n{}", correlations); Ok(()) } ``` -------------------------------- ### Install Finalytics (Python) Source: https://github.com/nnamdi-sys/finalytics/blob/main/README.md Install the finalytics Python package using pip. ```bash pip install finalytics ``` -------------------------------- ### Simulate Portfolio with Rebalancing and DCA Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/07-complete-examples.md This example simulates a portfolio with monthly dollar-cost averaging and quarterly rebalancing. It sets up a portfolio with explicit asset allocations, defines a rebalancing strategy, and configures scheduled cash flows for DCA. The code then calculates and displays performance statistics and a report. ```rust use finalytics::prelude::*; #[tokio::main] async fn main() -> Result<(), Box> { // Build portfolio with explicit allocation, DCA, and rebalancing let mut portfolio = Portfolio::builder() .ticker_symbols(vec!["AAPL", "MSFT", "NVDA", "BTC-USD"]) .start_date("2023-01-01") .end_date("2024-12-31") .interval(Interval::OneDay) .confidence_level(0.95) .risk_free_rate(0.02) // Initial allocation: $25k per asset .weights(vec![25_000.0, 25_000.0, 25_000.0, 25_000.0]) // Rebalance quarterly .rebalance_strategy(Some(RebalanceStrategy::Calendar( ScheduleFrequency::Quarterly, ))) // $2,000/month DCA distributed by target weights .scheduled_cash_flows(Some(vec![ScheduledCashFlow { amount: 2_000.0, frequency: ScheduleFrequency::Monthly, start_date: None, end_date: None, allocation: CashFlowAllocation::ProRata, }])) .build() .await?; // Calculate performance with rebalancing and DCA applied portfolio.performance_stats()?; let report = portfolio.report(Some(ReportType::Performance)).await?; report.show()?; Ok(()) } ``` -------------------------------- ### Build and Execute Stock Screener Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/07-complete-examples.md Use the Screener builder to define filters and sorting criteria for stocks. This example finds large-cap tech stocks on NASDAQ with strong returns. Requires `finalytics` and `tokio` crates. ```rust use finalytics::prelude::*; #[tokio::main] async fn main() -> Result<(), Box> { // Build screener let screener = Screener::builder() .quote_type(QuoteType::Equity) // Filter: NASDAQ exchange .add_filter(ScreenerFilter::EqStr( ScreenerMetric::Equity(EquityScreener::Exchange), Exchange::NASDAQ.as_ref(), )) // Filter: Technology sector .add_filter(ScreenerFilter::EqStr( ScreenerMetric::Equity(EquityScreener::Sector), Sector::Technology.as_ref(), )) // Filter: Large cap (>$10B market cap) .add_filter(ScreenerFilter::Gte( ScreenerMetric::Equity(EquityScreener::MarketCapIntraday), 10_000_000_000.0, )) // Filter: Strong ROE (>15%) .add_filter(ScreenerFilter::Gte( ScreenerMetric::Equity(EquityScreener::ReturnOnEquity), 0.15, )) // Sort by market cap (largest first) .sort_by( ScreenerMetric::Equity(EquityScreener::MarketCapIntraday), true, ) .size(50) .build() .await?; // Display results screener.overview().show()?; let metrics = screener.metrics().await?; metrics.show()?; Ok(()) } ``` -------------------------------- ### Install Finalytics Crate (Rust) Source: https://github.com/nnamdi-sys/finalytics/blob/main/README.md Install the finalytics crate into your Rust project using the cargo add command. ```bash cargo add finalytics ``` -------------------------------- ### Run Finalytics Web Application Locally Source: https://github.com/nnamdi-sys/finalytics/blob/main/web/README.md Starts a local development server for the Finalytics web application using the Dioxus CLI. ```bash dx serve --platform web ``` -------------------------------- ### Portfolio Optimization with Custom Data in Rust Source: https://github.com/nnamdi-sys/finalytics/blob/main/rust/README.md Perform portfolio optimization using custom data loaded from CSV files. This example sets up a Portfolio object with multiple tickers, a benchmark, and specifies an objective function (MaxSharpe), then optimizes and reports on the results. ```rust let mut portfolio = Portfolio::builder() .ticker_symbols(vec!["NVDA", "GOOG", "AAPL", "MSFT", "BTC-USD"]) .benchmark_symbol("^GSPC") .confidence_level(0.95) .risk_free_rate(0.02) .objective_function(ObjectiveFunction::MaxSharpe) .tickers_data(Some(vec![ KLINE::from_csv("NVDA", "examples/datasets/nvda.csv")?, KLINE::from_csv("GOOG", "examples/datasets/goog.csv")?, KLINE::from_csv("AAPL", "examples/datasets/aapl.csv")?, KLINE::from_csv("MSFT", "examples/datasets/msft.csv")?, KLINE::from_csv("BTC-USD", "examples/datasets/btcusd.csv")?, ])) .benchmark_data(Some(KLINE::from_csv("^GSPC", "examples/datasets/gspc.csv")?)) .build().await?; portfolio.optimize()?; portfolio.report(Some(ReportType::Optimization)).await?.show()?; ``` -------------------------------- ### JavaScript Interval Enumeration Example Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/06-bindings-python-js-go.md Lists the available Interval enumeration values for setting data frequency in JavaScript. ```javascript const { Interval } = require('finalytics'); Interval.TwoMinutes Interval.FiveMinutes Interval.FifteenMinutes Interval.ThirtyMinutes Interval.SixtyMinutes Interval.OneHour Interval.OneDay // Default Interval.OneWeek Interval.OneMonth ``` -------------------------------- ### Handle DataFetch Error Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/03-errors.md Demonstrates how to match and handle a `DataFetch` error, which occurs during network requests or API calls. This example shows logging the error and suggests fallback strategies. ```rust match ticker.report(Some(ReportType::Performance)).await { Err(FinalyticsError::DataFetch { source, message }) => { eprintln!("Failed to fetch from {}: {}", source, message); // Retry logic, use cached data, skip this ticker } Err(e) => return Err(e), Ok(report) => { /* ... */ } } ``` -------------------------------- ### Analyze a Single Security with Ticker Source: https://github.com/nnamdi-sys/finalytics/blob/main/python/README.md Utilize the Ticker module for in-depth analysis of a single security. This example fetches performance, financials, options, and news for AAPL, with specified date ranges and benchmark. ```python from finalytics import Ticker ticker = Ticker( symbol="AAPL", start_date="2023-01-01", end_date="2024-12-31", interval="1d", benchmark_symbol="^GSPC", confidence_level=0.95, risk_free_rate=0.02 ) ticker.report("performance") ticker.report("financials") ticker.report("options") ticker.report("news") ``` -------------------------------- ### Load and Use Custom Multiple Ticker Data in Rust Source: https://github.com/nnamdi-sys/finalytics/blob/main/rust/README.md Load data from CSV files into KLINE structs for multiple ticker analysis. This example demonstrates how to prepare data for several tickers and a benchmark, then use them to build and report on a Tickers object. ```rust let nvda = KLINE::from_csv("NVDA", "examples/datasets/nvda.csv")?; let goog = KLINE::from_csv("GOOG", "examples/datasets/goog.csv")?; let aapl = KLINE::from_csv("AAPL", "examples/datasets/aapl.csv")?; let msft = KLINE::from_csv("MSFT", "examples/datasets/msft.csv")?; let btcusd = KLINE::from_csv("BTC-USD", "examples/datasets/btcusd.csv")?; let gspc = KLINE::from_csv("^GSPC", "examples/datasets/gspc.csv")?; // Multiple Tickers from custom data let tickers = Tickers::builder() .tickers(vec!["NVDA", "GOOG", "AAPL", "MSFT", "BTC-USD"]) .benchmark_symbol("^GSPC") .confidence_level(0.95) .risk_free_rate(0.02) .tickers_data(Some(vec![nvda, goog, aapl, msft, btcusd])) .benchmark_data(Some(gspc.clone())) .build(); tickers.report(Some(ReportType::Performance)).await?.show()?; ``` -------------------------------- ### Get Portfolio Drawdown Periods Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/05-data-and-reporting.md Returns a list of major drawdown periods, including their start and end dates and magnitudes. ```rust pub fn get_drawdown_periods(&self) -> Result, FinalyticsError> ``` -------------------------------- ### Build and Use Screener Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/01-core-models.md Demonstrates how to build a Screener with specific filters and then retrieve overview and detailed metrics. Ensure necessary imports and async context for execution. ```rust let screener = Screener::builder() .quote_type(QuoteType::Equity) .add_filter(ScreenerFilter::EqStr( ScreenerMetric::Equity(EquityScreener::Exchange), Exchange::NASDAQ.as_ref(), )) .size(50) .build() .await?; screener.overview().show()?; let metrics = screener.metrics().await?; metrics.show()?; ``` -------------------------------- ### Stock Screener Configuration and Overview (Python) Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/06-bindings-python-js-go.md Set up a stock screener using the Screener builder, specifying quote type and filters, then retrieve and display an overview of the matching stocks. Imports for Screener, QuoteType, ScreenerFilter, ScreenerMetric, EquityScreener, and Exchange are required. ```python from finalytics import Screener, QuoteType, ScreenerFilter, ScreenerMetric, EquityScreener, Exchange screener = Screener.builder() \ .quote_type(QuoteType.Equity) \ .add_filter(ScreenerFilter.EqStr( ScreenerMetric.Equity(EquityScreener.Exchange), Exchange.NASDAQ.as_ref() )) \ .size(100) \ .build() screener.overview().show() metrics = screener.metrics() metrics.show() ``` -------------------------------- ### Get News Articles for a Ticker Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/05-data-and-reporting.md Fetches recent news articles related to a specific ticker. ```rust pub async fn get_news(&self) -> Result, Box> ``` -------------------------------- ### Get Portfolio Performance by Period Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/05-data-and-reporting.md Fetches the performance of a portfolio for a specified period, such as YTD, 1-year, or 5-year. ```rust pub fn get_performance_by_period( &self, period: PerformancePeriod ) -> Result ``` -------------------------------- ### Build Portfolio with Rebalancing and DCA Source: https://github.com/nnamdi-sys/finalytics/blob/main/go/README.md Construct a portfolio with explicit weights, calendar-based rebalancing, and scheduled monthly cash flows using a pro-rata allocation strategy. ```go import "encoding/json" weights, _ := json.Marshal([]float64{25000.0, 25000.0, 25000.0, 25000.0}) rebalance, _ := json.Marshal(map[string]interface{}{ "type": "calendar", "frequency": "quarterly", }) cashFlows, _ := json.Marshal([]map[string]interface{}{ { "amount": 2000.0, "frequency": "monthly", "start_date": nil, "end_date": nil, "allocation": "pro_rata", }, }) portfolio, err := finalytics.NewPortfolioBuilder(). TickerSymbols([]string{"AAPL", "MSFT", "NVDA", "BTC-USD"}). BenchmarkSymbol("^GSPC"). StartDate("2023-01-01"). EndDate("2024-12-31"). Interval("1d"). ConfidenceLevel(0.95). RiskFreeRate(0.02). Weights(string(weights)). RebalanceStrategy(string(rebalance)). ScheduledCashFlows(string(cashFlows)). Build() if err != nil { panic(err) } def portfolio.Free() report, _ := portfolio.Report("performance") report.Show() ``` -------------------------------- ### Build and Use Screener Module Source: https://github.com/nnamdi-sys/finalytics/blob/main/go/README.md Build a screener with custom filters and display the results. Ensure to free the screener resource after use. ```go screener, err := finalytics.NewScreenerBuilder(). QuoteType("EQUITY"). AddFilter(`{"operator":"eq","operands":["exchange","NMS"]}`). AddFilter(`{"operator":"eq","operands":["sector","Technology"]}`). AddFilter(`{"operator":"gte","operands":["intradaymarketcap",10000000000]}`). AddFilter(`{"operator":"gte","operands":["returnonequity.lasttwelvemonths",0.15]}`). SortField("intradaymarketcap"). SortDescending(true). Offset(0). Size(10). Build() if err != nil { panic(err) } def screener.Free() screener.Display() symbols, _ := screener.Symbols() fmt.Println("Symbols:", symbols) ``` -------------------------------- ### Get Portfolio Allocation Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/05-data-and-reporting.md Retrieves the current asset allocation of a portfolio as a vector of (ticker, weight) pairs. ```rust pub fn get_allocation(&self) -> Vec<(String, f64)> ``` -------------------------------- ### Get Single Ticker Data Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/05-data-and-reporting.md Retrieves a single Ticker instance with pre-populated data from a collection of tickers. ```rust pub async fn get_ticker(self, symbol: &str) -> Result> ``` -------------------------------- ### JavaScript Bindings - Ticker Class Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/06-bindings-python-js-go.md Example of using the Ticker class in JavaScript for financial data retrieval. ```APIDOC ## JavaScript/Node.js Bindings **Location:** `js/` **Installation:** `npm install finalytics` WASM-based bindings providing JavaScript interface to Rust core. ### Core Classes #### Ticker ```javascript const { Ticker, Interval, ReportType } = require('finalytics'); const ticker = Ticker.builder() .ticker("AAPL") .startDate("2023-01-01") .endDate("2024-12-31") .interval(Interval.OneDay) .benchmarkSymbol("^GSPC") .confidenceLevel(0.95) .riskFreeRate(0.02) .build(); await ticker.report(ReportType.Performance).then(report => { report.show(); }); ``` **Methods:** - `static builder()` → TickerBuilder - `report(reportType)` → Promise ``` -------------------------------- ### Download Finalytics Native Binary Source: https://github.com/nnamdi-sys/finalytics/blob/main/go/README.md Download the required native binary for the Finalytics Go binding. ```bash curl -O https://raw.githubusercontent.com/Nnamdi-sys/finalytics/refs/heads/main/go/download_binaries.sh bash download_binaries.sh ``` -------------------------------- ### Get Ticker Statistics Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/05-data-and-reporting.md Fetches summary statistics for a ticker, such as P/E ratio, dividend yield, and market capitalization. ```rust pub async fn get_ticker_stats(&self) -> Result> ``` -------------------------------- ### JavaScript Bindings - Screener Class Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/06-bindings-python-js-go.md Example of using the Screener class in JavaScript to filter and retrieve equity data. ```APIDOC #### Screener ```javascript const { Screener, QuoteType, ScreenerFilter, ScreenerMetric, EquityScreener, Exchange } = require('finalytics'); const screener = await Screener.builder() .quoteType(QuoteType.Equity) .addFilter(ScreenerFilter.eqStr( ScreenerMetric.equity(EquityScreener.Exchange), Exchange.NASDAQ )) .size(100) .build(); screener.overview().show(); ``` ``` -------------------------------- ### JavaScript Screener Builder and Overview Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/06-bindings-python-js-go.md Shows how to configure and build a Screener object to filter equities by exchange and display an overview. ```javascript const { Screener, QuoteType, ScreenerFilter, ScreenerMetric, EquityScreener, Exchange } = require('finalytics'); const screener = await Screener.builder() .quoteType(QuoteType.Equity) .addFilter(ScreenerFilter.eqStr( ScreenerMetric.equity(EquityScreener.Exchange), Exchange.NASDAQ )) .size(100) .build(); screener.overview().show(); ``` -------------------------------- ### JavaScript Bindings - Tickers Class Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/06-bindings-python-js-go.md Example of using the Tickers class in JavaScript to analyze multiple financial instruments. ```APIDOC #### Tickers ```javascript const tickers = Tickers.builder() .tickers(["NVDA", "GOOG", "AAPL", "MSFT", "BTC-USD"]) .startDate("2023-01-01") .endDate("2024-12-31") .benchmarkSymbol("^GSPC") .build(); await tickers.report(ReportType.Performance).then(report => { report.show(); }); ``` ``` -------------------------------- ### JavaScript ReportType Enumeration Example Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/06-bindings-python-js-go.md Lists the available ReportType enumeration values for specifying report content in JavaScript. ```javascript const { ReportType } = require('finalytics'); ReportType.Performance ReportType.Financials ReportType.Options ReportType.News ReportType.Optimization ``` -------------------------------- ### Build and Optimize Portfolio Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/04-analytics-and-performance.md Constructs a portfolio with specified tickers and objective, then runs in-sample optimization. Requires the `Portfolio` struct and `ObjectiveFunction` enum. ```rust let mut portfolio = Portfolio::builder() .ticker_symbols(vec!["AAPL", "MSFT", "NVDA"]) .start_date("2023-01-01") .end_date("2024-12-31") .objective_function(ObjectiveFunction::MaxSharpe) .build() .await?; portfolio.optimize()?; let result = &portfolio.optimization_result; println!("Optimal weights: {:?}", result.optimal_weights); println!("Sharpe ratio: {}", result.sharpe_ratio); ``` -------------------------------- ### Configure and Build a Screener Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/00-quick-reference.md Instantiate a Screener object, setting the quote type and adding a filter for technology sector equities. ```rust Screener::builder() .quote_type(QuoteType::Equity) .add_filter(ScreenerFilter::EqStr( ScreenerMetric::Equity(EquityScreener::Sector), Sector::Technology.as_ref() )) .size(100) .build() ``` -------------------------------- ### Create and Optimize a Portfolio Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/06-bindings-python-js-go.md Use the PortfolioBuilder to define a portfolio with specific ticker symbols and an objective function (e.g., MaxSharpe). The Optimize method then finds the optimal allocation, and a report can be generated. ```go portfolio, _ := finalytics.NewPortfolioBuilder(). TickerSymbols([]string{"AAPL", "MSFT", "NVDA"}). StartDate("2023-01-01"). EndDate("2024-12-31"). ObjectiveFunction(finalytics.ObjectiveFunctionMaxSharpe). Build() portfolio.Optimize() report, _ := portfolio.Report(finalytics.ReportTypeOptimization) report.Show() ``` -------------------------------- ### JavaScript Transaction Data Type Example Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/06-bindings-python-js-go.md Defines the structure for a financial transaction, including date, ticker, and amount, in JavaScript. ```javascript const txn = { date: "2024-06-15", ticker: "AAPL", amount: 5000.0 }; ``` -------------------------------- ### Error Handling Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/INDEX.md Reference for all error types in Finalytics, including trigger conditions, example messages, and recommended handling patterns. ```APIDOC ## Error Handling ### Description Complete error type reference with trigger conditions, example messages, and handling patterns for the Finalytics library. ### Error Types - **FinalyticsError:** Unified error type with 12 variants. - **Data Layer Errors:** DataFetch, DataParse - **DataFrame/Series Layer Errors:** DtypeMismatch, NullValues, ColumnNotFound, DataFrameOperation - **Computation Layer Errors:** InsufficientData, NonFiniteResult, OptimizationFailed - **Configuration Layer Errors:** InvalidParameter - **Pass-Through Errors:** Polars, External ### Helper Functions - series_to_vec_f64 - series_to_optional_vec_f64 - column_to_vec_f64 - require_min_length ``` -------------------------------- ### Build and Use Ticker Module Source: https://github.com/nnamdi-sys/finalytics/blob/main/go/README.md Build a ticker for a specific symbol and retrieve various reports like performance, financials, options, and news. Ensure to free the ticker resource after use. ```go ticker, err := finalytics.NewTickerBuilder(). Symbol("AAPL"). StartDate("2023-01-01"). EndDate("2024-12-31"). Interval("1d"). BenchmarkSymbol("^GSPC"). ConfidenceLevel(0.95). RiskFreeRate(0.02). Build() if err != nil { panic(err) } def ticker.Free() for _, reportType := range []string{"performance", "financials", "options", "news"} { report, err := ticker.Report(reportType) if err == nil { report.Show() } } ``` -------------------------------- ### Optimize Portfolio with Asset and Categorical Constraints Source: https://github.com/nnamdi-sys/finalytics/blob/main/go/README.md Optimize a portfolio by setting per-asset weight bounds and categorical constraints based on sector and asset class. ```go import "encoding/json" // Per-asset bounds: [lower, upper] in the same order as ticker_symbols assetConstraints, _ := json.Marshal([][]float64{ {0.05, 0.40}, // AAPL {0.05, 0.40}, // MSFT {0.05, 0.40}, // NVDA {0.05, 0.30}, // JPM {0.05, 0.20}, // XOM {0.05, 0.25}, // BTC-USD }) categoricalConstraints, _ := json.Marshal([]map[string]interface{}{ { "name": "Sector", "category_per_symbol": []string{"Tech", "Tech", "Tech", "Finance", "Energy", "Crypto"}, "weight_per_category": [][]interface{}{ {"Tech", 0.30, 0.60}, {"Finance", 0.05, 0.30}, {"Energy", 0.05, 0.20}, {"Crypto", 0.05, 0.25}, }, }, { "name": "Asset Class", "category_per_symbol": []string{"Equity", "Equity", "Equity", "Equity", "Equity", "Crypto"}, "weight_per_category": [][]interface{}{ {"Equity", 0.70, 0.95}, {"Crypto", 0.05, 0.30}, }, }, }) portfolio, err := finalytics.NewPortfolioBuilder(). TickerSymbols([]string{"AAPL", "MSFT", "NVDA", "JPM", "XOM", "BTC-USD"}). BenchmarkSymbol("^GSPC"). StartDate("2023-01-01"). EndDate("2024-12-31"). Interval("1d"). ConfidenceLevel(0.95). RiskFreeRate(0.02). ObjectiveFunction("max_sharpe"). AssetConstraints(string(assetConstraints)). CategoricalConstraints(string(categoricalConstraints)). Build() if err != nil { panic(err) } def portfolio.Free() report, _ := portfolio.Report("optimization") report.Show() ``` -------------------------------- ### Get Options Chain for a Ticker Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/05-data-and-reporting.md Fetches and processes the options chain data for a ticker, including strikes, expirations, and implied volatility. ```rust pub async fn get_options_chain(&self) -> Result> ``` -------------------------------- ### Get Historical Data for a Ticker Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/05-data-and-reporting.md Fetches OHLCV data for a specific ticker from Yahoo Finance. The data is cached in the Ticker struct. ```rust pub async fn get_historical_data(&self) -> Result ``` -------------------------------- ### JavaScript ScheduledCashFlow Data Type Example Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/06-bindings-python-js-go.md Defines the structure for a scheduled cash flow, including amount, frequency, and allocation, in JavaScript. ```javascript const dca = { amount: 2000.0, frequency: ScheduleFrequency.Monthly, startDate: null, endDate: null, allocation: CashFlowAllocation.ProRata }; ``` -------------------------------- ### Build and Use a Security Screener Source: https://github.com/nnamdi-sys/finalytics/blob/main/rust/README.md Construct a screener to filter and rank securities based on various metrics and criteria. Requires importing the prelude. ```rust use finalytics::prelude::*; let screener = Screener::builder() .quote_type(QuoteType::Equity) .add_filter(ScreenerFilter::EqStr( ScreenerMetric::Equity(EquityScreener::Exchange), Exchange::NASDAQ.as_ref() )) .add_filter(ScreenerFilter::EqStr( ScreenerMetric::Equity(EquityScreener::Sector), Sector::Technology.as_ref() )) .add_filter(ScreenerFilter::Gte( ScreenerMetric::Equity(EquityScreener::MarketCapIntraday), 10_000_000_000.0 )) .add_filter(ScreenerFilter::Gte( ScreenerMetric::Equity(EquityScreener::ReturnOnEquity), 0.15 )) .sort_by( ScreenerMetric::Equity(EquityScreener::MarketCapIntraday), true ) .size(10) .build() .await?; screener.overview().show()?; screener.metrics().await?.show()?; ``` -------------------------------- ### Create and Optimize a Portfolio Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/00-quick-reference.md Instantiate a Portfolio object for multi-asset optimization, specifying tickers, dates, and the objective function. ```rust Portfolio::builder() .ticker_symbols(vec!["AAPL", "MSFT", "NVDA"]) .start_date("2023-01-01") .end_date("2024-12-31") .objective_function(ObjectiveFunction::MaxSharpe) .build() ``` -------------------------------- ### compute_groups Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/04-analytics-and-performance.md Groups dates by a specified frequency for return calculations. Returns a vector containing the period key, start index, and end index for each group. ```APIDOC ## compute_groups ### Description Groups dates by a specified frequency for return calculations. Returns a vector containing the period key, start index, and end index for each group. ### Signature ```rust pub fn compute_groups( dates: &[String], freq: ReturnsFrequency, ) -> Vec<(String, usize, usize)> ``` ### Parameters #### Path Parameters - **dates** (String) - Required - A slice of dates. - **freq** (ReturnsFrequency) - Required - The desired frequency for grouping. ### Returns `Vec<(String, usize, usize)>` - A vector of tuples, where each tuple represents a group with its key, start index, and end index. ``` -------------------------------- ### Get Financial Statements for a Ticker Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/05-data-and-reporting.md Fetches income statements, balance sheets, and cash flow statements for a given ticker. Returns a formatted table of financial metrics. ```rust pub async fn get_financials(&self) -> Result> ``` -------------------------------- ### JavaScript Bindings - Portfolio Class Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/06-bindings-python-js-go.md Demonstrates building and optimizing a portfolio using the Portfolio class in JavaScript. ```APIDOC #### Portfolio ```javascript const { Portfolio, ObjectiveFunction } = require('finalytics'); const portfolio = await Portfolio.builder() .tickerSymbols(["AAPL", "MSFT", "NVDA"]) .startDate("2023-01-01") .endDate("2024-12-31") .objectiveFunction(ObjectiveFunction.MaxSharpe) .build(); portfolio.optimize(); await portfolio.report(ReportType.Optimization).then(report => { report.show(); }); ``` ``` -------------------------------- ### Run Finalytics Web Application Locally Source: https://github.com/nnamdi-sys/finalytics/blob/main/README.md Clone the repository, navigate to the web directory, and serve the application using the Dioxus CLI. ```bash cargo install dioxus-cli git clone https://github.com/Nnamdi-sys/finalytics.git cd finalytics/web dx serve --platform web ``` -------------------------------- ### Build and Use Tickers Module Source: https://github.com/nnamdi-sys/finalytics/blob/main/go/README.md Build a tickers object for multiple symbols and retrieve an aggregated performance report. Ensure to free the tickers resource after use. ```go tickers, err := finalytics.NewTickersBuilder(). Symbols([]string{"NVDA", "GOOG", "AAPL", "MSFT", "BTC-USD"}). StartDate("2023-01-01"). EndDate("2024-12-31"). Interval("1d"). BenchmarkSymbol("^GSPC"). ConfidenceLevel(0.95). RiskFreeRate(0.02). Build() if err != nil { panic(err) } def tickers.Free() report, err := tickers.Report("performance") if err == nil { report.Show() } ``` -------------------------------- ### Multi-Security Analysis with Tickers Source: https://github.com/nnamdi-sys/finalytics/blob/main/python/README.md Employ the Tickers module to perform batch analytics and portfolio construction across multiple securities. This example generates a performance report for a list of symbols against a benchmark. ```python from finalytics import Tickers tickers = Tickers( symbols=["NVDA", "GOOG", "AAPL", "MSFT", "BTC-USD"], start_date="2023-01-01", end_date="2024-12-31", interval="1d", benchmark_symbol="^GSPC", confidence_level=0.95, risk_free_rate=0.02 ) tickers.report("performance") ``` -------------------------------- ### RebalanceStrategy Enumerations (Python) Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/06-bindings-python-js-go.md Illustrates the different rebalancing strategies available for portfolios, including calendar-based, threshold-based, and combined approaches. Imports for RebalanceStrategy and ScheduleFrequency are needed. ```python from finalytics import RebalanceStrategy, ScheduleFrequency RebalanceStrategy.Calendar(ScheduleFrequency.Quarterly) RebalanceStrategy.Threshold(0.05) RebalanceStrategy.CalendarOrThreshold(ScheduleFrequency.Monthly, 0.03) ``` -------------------------------- ### Get Applicable Performance Periods Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/04-analytics-and-performance.md Determines the valid performance evaluation periods (e.g., YTD, OneYear) for a given date range. This function helps in selecting appropriate metrics for performance analysis. ```rust let periods = applicable_periods("2023-01-01", "2024-12-31"); // Returns: [YTD, OneMonth, ThreeMonths, SixMonths, OneYear, Since] ``` -------------------------------- ### Build ETF Screener with Filters and Sorting Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/05-data-and-reporting.md Builds a screener for ETFs, filtering by fund category and assets, then sorting by Year-To-Date return in descending order. Limits results to 100. ```rust let screener = Screener::builder() .quote_type(QuoteType::Etf) .add_filter(ScreenerFilter::Gte( ScreenerMetric::Etf(EtfScreener::FundNetAssets), 1_000_000_000.0, )) .add_filter(ScreenerFilter::EqStr( ScreenerMetric::Etf(EtfScreener::FundsByCategory), FundCategory::Technology.as_ref(), )) .sort_by( ScreenerMetric::Etf(EtfScreener::TrailingYTDReturn), true, // Highest returns first ) .size(100) .build() .await?; screener.overview().show()?; let metrics = screener.metrics().await?; metrics.show()? ``` -------------------------------- ### JavaScript Portfolio Builder and Optimization Report Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/06-bindings-python-js-go.md Illustrates creating a Portfolio object, setting an objective function, optimizing it, and displaying the optimization report. ```javascript const { Portfolio, ObjectiveFunction } = require('finalytics'); const portfolio = await Portfolio.builder() .tickerSymbols(["AAPL", "MSFT", "NVDA"]) .startDate("2023-01-01") .endDate("2024-12-31") .objectiveFunction(ObjectiveFunction.MaxSharpe) .build(); portfolio.optimize(); await portfolio.report(ReportType.Optimization).then(report => { report.show(); }); ``` -------------------------------- ### Build and Report with Tickers (Python) Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/06-bindings-python-js-go.md Analyze multiple tickers by using the Tickers builder to configure and generate performance reports. Imports for Tickers and ReportType are required. ```python from finalytics import Tickers tickers = Tickers.builder() \ .tickers(["NVDA", "GOOG", "AAPL", "MSFT", "BTC-USD"]) \ .start_date("2023-01-01") \ .end_date("2024-12-31") \ .benchmark_symbol("^GSPC") \ .build() report = tickers.report(ReportType.Performance) report.show() ``` -------------------------------- ### Create and Configure a Ticker Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/06-bindings-python-js-go.md Use the TickerBuilder to create a Ticker object with specific parameters like symbol, date range, interval, and risk-free rate. The Report method can then be called to generate performance reports. ```go package main import "github.com/Nnamdi-sys/finalytics/go/finalytics" func main() { ticker := finalytics.NewTickerBuilder(). Ticker("AAPL"). StartDate("2023-01-01"). EndDate("2024-12-31"). Interval(finalytics.IntervalOneDay). BenchmarkSymbol("^GSPC"). ConfidenceLevel(0.95). RiskFreeRate(0.02). Build() report, _ := ticker.Report(finalytics.ReportTypePerformance) report.Show() } ``` -------------------------------- ### Handle DataParse Error Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/03-errors.md Illustrates how to catch and manage a `DataParse` error, typically arising from malformed JSON or incorrect data formats. The example logs the parsing issue and suggests alternative data handling. ```rust match KLINE::from_json("AAPL", "data.json") { Err(FinalyticsError::DataParse { source, message }) => { eprintln!("Malformed JSON from {}: {}", source, message); // Log raw response, fall back to CSV, notify user } _ => { /* ... */ } } ``` -------------------------------- ### Create a Ticker Analysis Instance Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/00-quick-reference.md Instantiate a Ticker object for single security analysis, specifying dates and a benchmark. ```rust Ticker::builder() .ticker("AAPL") .start_date("2023-01-01") .end_date("2024-12-31") .benchmark_symbol("^GSPC") .build() ``` -------------------------------- ### Go Error Handling Pattern Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/06-bindings-python-js-go.md All Go methods in the Finalytics library return a result and an error. Always check the error value after calling a method to handle potential issues gracefully, for example, by logging the error. ```go portfolio, err := finalytics.NewPortfolioBuilder(). TickerSymbols([]string{"AAPL", "MSFT"}). Build() if err != nil { log.Fatal(err) } err = portfolio.Optimize() if err != nil { log.Fatal(err) } ``` -------------------------------- ### ScreenerBuilder::build() Source: https://github.com/nnamdi-sys/finalytics/blob/main/_autodocs/05-data-and-reporting.md Executes the configured screener query and returns the results. ```APIDOC #### `build()` → `Screener` (async) ### Description Executes the screener query. ### Signature ```rust pub async fn build(self) -> Result ``` ### Returns `Result` ### Example ```rust let screener = Screener::builder() .quote_type(QuoteType::Etf) .add_filter(ScreenerFilter::Gte( ScreenerMetric::Etf(EtfScreener::FundNetAssets), 1_000_000_000.0, )) .add_filter(ScreenerFilter::EqStr( ScreenerMetric::Etf(EtfScreener::FundsByCategory), FundCategory::Technology.as_ref(), )) .sort_by( ScreenerMetric::Etf(EtfScreener::TrailingYTDReturn), true, // Highest returns first ) .size(100) .build() .await?; screener.overview().show()?; let metrics = screener.metrics().await?; metrics.show()?; ``` ``` -------------------------------- ### Portfolio Allocation with Rebalancing and DCA Source: https://github.com/nnamdi-sys/finalytics/blob/main/js/README.md Build a portfolio with explicit weights, a rebalancing strategy, and scheduled cash flows (Dollar-Cost Averaging). Remember to free the portfolio instance after use. ```javascript import { PortfolioBuilder } from 'finalytics'; const portfolio = await new PortfolioBuilder() .tickerSymbols(['AAPL', 'MSFT', 'NVDA', 'BTC-USD']) .benchmarkSymbol('^GSPC') .startDate('2023-01-01') .endDate('2024-12-31') .interval('1d') .confidenceLevel(0.95) .riskFreeRate(0.02) .weights(JSON.stringify([25000.0, 25000.0, 25000.0, 25000.0])) .rebalanceStrategy(JSON.stringify({ type: 'calendar', frequency: 'quarterly' })) .scheduledCashFlows(JSON.stringify([ { amount: 2000.0, frequency: 'monthly', start_date: null, end_date: null, allocation: 'pro_rata', }, ])) .build(); const report = await portfolio.report('performance'); await report.show(); portfolio.free(); ``` -------------------------------- ### Portfolio with Rebalancing and DCA Source: https://github.com/nnamdi-sys/finalytics/blob/main/python/README.md Configure a portfolio with explicit initial weights, a rebalancing strategy, and scheduled cash flows (Dollar-Cost Averaging). Useful for simulating systematic investment strategies. ```python from finalytics import Portfolio portfolio = Portfolio( ticker_symbols=["AAPL", "MSFT", "NVDA", "BTC-USD"], benchmark_symbol="^GSPC", start_date="2023-01-01", end_date="2024-12-31", interval="1d", confidence_level=0.95, risk_free_rate=0.02, weights=[25000.0, 25000.0, 25000.0, 25000.0], rebalance_strategy={"type": "calendar", "frequency": "quarterly"}, scheduled_cash_flows=[ { "amount": 2000.0, "frequency": "monthly", "start_date": None, "end_date": None, "allocation": "pro_rata" } ] ) portfolio.report("performance") ```