Package: PortfolioTesteR 0.1.4

PortfolioTesteR: Test Investment Strategies with English-Like Code

Design, backtest, and analyze portfolio strategies using simple, English-like function chains. Includes technical indicators, flexible stock selection, portfolio construction methods (equal weighting, signal weighting, inverse volatility, hierarchical risk parity), and a compact backtesting engine for portfolio returns, drawdowns, and summary metrics.

Authors:Alberto Pallotta [aut, cre]

PortfolioTesteR_0.1.4.tar.gz
PortfolioTesteR_0.1.4.zip(r-4.7-any)PortfolioTesteR_0.1.4.zip(r-4.6-any)PortfolioTesteR_0.1.4.zip(r-4.5-any)
PortfolioTesteR_0.1.4.tgz(r-4.6-any)PortfolioTesteR_0.1.4.tgz(r-4.5-any)
PortfolioTesteR_0.1.4.tar.gz(r-4.7-any)PortfolioTesteR_0.1.4.tar.gz(r-4.6-any)
PortfolioTesteR_0.1.4.tgz(r-4.6-emscripten)
manual.pdf |manual.html✨
DESCRIPTION |NEWS
card.svg |card.png
PortfolioTesteR/json (API)

# Install 'PortfolioTesteR' in R:
install.packages('PortfolioTesteR', repos = c('https://albertopallotta.r-universe.dev', 'https://cloud.r-project.org'))

Bug tracker:https://github.com/albertopallotta/portfoliotester/issues

Datasets:

On CRAN:

Conda:

asset-allocationbacktestingmachine-learningportfolio-constructionportfolio-managementportfolio-optimizationquantitative-financetime-serieswalk-forward

6.20 score 4 stars 66 scripts 264 downloads 111 exports 6 dependencies

Last updated from:1cda69b18b. Checks:9 OK. Indexed: yes.

TargetResultTimeFilesSyslog
linux-develOK162
source / vignettesOK231
linux-releaseOK163
macos-releaseOK194
macos-oldrelOK210
windows-develOK114
windows-releaseOK115
windows-oldrelOK118
wasm-releaseOK103

Exports:align_to_timeframeanalyze_by_periodanalyze_drawdownsanalyze_performanceanalyze_vs_benchmarkapply_regimeas_selectionbacktest_metricsbucket_returnscalc_ccicalc_distancecalc_market_breadthcalc_momentumcalc_moving_averagecalc_relative_strength_rankcalc_rolling_correlationcalc_rolling_volatilitycalc_rsicalc_sector_breadthcalc_sector_relative_indicatorscalc_stochastic_dcalc_stochrsicalculate_daily_valuescalculate_drawdown_seriescap_exposurecap_turnovercarry_forward_weightscombine_filterscombine_scorescombine_weightsconvert_to_nweekscoverage_by_datecreate_regime_bucketscsv_adaptercv_tune_seqdemo_sector_mapdownload_sp500_sectorsensure_dt_copyevaluate_scoresfilter_abovefilter_belowfilter_betweenfilter_by_percentilefilter_rankfilter_thresholdfilter_top_nfilter_top_n_whereget_data_frequencyic_seriesinvert_signaljoin_panelslimit_positionslist_examplesload_mixed_symbolsmake_labelsmanual_adaptermembership_stabilitymetric_sharpeml_add_interactionsml_backtestml_backtest_multiml_backtest_seqml_ic_series_on_scoresml_make_ensembleml_make_modelml_make_seq_modelml_panel_opml_panel_reduceml_plot_ic_rollml_prepare_featurespanel_lagpanel_returns_simpleperf_metricsportfolio_returnspt_collect_resultsrank_within_sectorrebalance_calendarroll_fit_predictroll_fit_predict_seqroll_ic_statsrun_backtestrun_examplerun_param_gridrun_walk_forwardsafe_dividescores_oos_onlyselect_top_k_scoresselect_top_k_scores_by_groupsql_adaptersql_adapter_adjustedswitch_weightstransform_scorestune_ml_backtestturnover_by_dateupdate_vix_in_dbvalidate_data_formatvalidate_group_mapvalidate_no_leakagevol_targetweight_by_hrpweight_by_rankweight_by_regimeweight_by_risk_parityweight_by_signalweight_by_volatilityweight_equallyweight_from_scoreswf_reportwf_stitchwf_sweep_tabularyahoo_adapter

Dependencies:curldata.tablelatticeTTRxtszoo

Getting Started with PortfolioTesteR
PortfolioTesteR: Test Investment Strategies with English-Like Code | Installation | Load the Library | Strategy 1: Simple Momentum (Beginner) | Strategy 2: Multi-Signal Combination (Intermediate) | Strategy 3: Risk-Managed Momentum with Stop Loss (Intermediate) | Strategy 4: Regime-Adaptive Volatility (Advanced) | Strategy 5: Multi-Factor with Position Limits (Advanced) | Strategy 6: StochRSI Acceleration + Inverse-Vol Risk Parity | Optional: Live Data via Yahoo (CRAN-safe) | Key Concepts Recap | Getting Help | Citation

Last update: 2026-08-17
Started: 2025-09-07

ML Strategies with PortfolioTesteR (Advanced Getting Started)
Why ML in PortfolioTesteR | 1) Baseline ML (pooled): Ridge regression | 2) Ensemble: Ridge + XGBoost | 3) Sector-neutral modelling (tabular XGBoost, per-group) | 4) Sequence model (GRU, pooled): "returns pyramid" | 5) Sequence model (GRU, per-group): sector-neutral sequences | 6) Light tuning: Top-K and softmax temperature | Recap & Next Steps

Last update: 2025-11-01
Started: 2025-10-03

Optimization and Walk-Forward with PortfolioTesteR

Last update: 2025-11-01
Started: 2025-09-25

Readme and manuals

Help Manual

Help pageTopics
Align Data to Strategy Timeframealign_to_timeframe
Period-level summary statisticsanalyze_by_period
Analyze Drawdown Characteristicsanalyze_drawdowns
Analyze Backtest Performance with Daily Monitoringanalyze_performance
Benchmark-relative performance statisticsanalyze_vs_benchmark
Apply Market Regime Filterapply_regime
Convert Conditions to Selection Formatas_selection
Calculate Comprehensive Backtest Metricsbacktest_metrics
Bucketed label analysis by score rankbucket_returns
Calculate Commodity Channel Index (CCI)calc_cci
Calculate Distance from Referencecalc_distance
Calculate Market Breadth Percentagecalc_market_breadth
Calculate Price Momentumcalc_momentum
Calculate Moving Averagecalc_moving_average
Calculate Cross-Sectional Ranking of Indicatorscalc_relative_strength_rank
Rolling correlation of each symbol to a benchmarkcalc_rolling_correlation
Calculate Rolling Volatilitycalc_rolling_volatility
Calculate Relative Strength Index (RSI)calc_rsi
Calculate Market Breadth by Sectorcalc_sector_breadth
Calculate Indicators Relative to Sector Averagecalc_sector_relative_indicators
Calculate Stochastic D Indicatorcalc_stochastic_d
Stochastic RSI (StochRSI) for multiple price seriescalc_stochrsi
Daily equity curve from positions and daily pricescalculate_daily_values
Calculate Drawdown Time Seriescalculate_drawdown_series
Apply post-weight exposure capscap_exposure
Cap turnover sequentially across datescap_turnover
Carry-forward weights between rebalances (validation helper)carry_forward_weights
Combine Multiple Filter Conditionscombine_filters
Combine multiple score panels (mean / weighted / rank-average / trimmed)combine_scores
Combine Multiple Weighting Schemescombine_weights
Convert Data to N-Week Frequencyconvert_to_nweeks
Count finite entries per datecoverage_by_date
Convert Continuous Indicator to Discrete Regimescreate_regime_buckets
Load Price Data from CSV Filecsv_adapter
Purged/embargoed K-fold CV for sequence models (inside IS window)cv_tune_seq
Demo sector (group) map for examples/testsdemo_sector_map
Download S&P 500 Sector Mappings from Wikipediadownload_sp500_sectors
Ensure Data.Table Without Mutationensure_dt_copy
Evaluate scores vs labels (IC and hit-rate)evaluate_scores
Filter Stocks Above Thresholdfilter_above
Filter Stocks Below Thresholdfilter_below
Filter Stocks Between Two Valuesfilter_between
Filter by Percentilefilter_by_percentile
Select Top or Bottom N Stocks by Signalfilter_rank
Filter by Threshold Valuefilter_threshold
Select Top N Stocks by Signal Valuefilter_top_n
Select Top N from Qualified Stocksfilter_top_n_where
Detect Data Frequency from Datesget_data_frequency
Information Coefficient time seriesic_series
Invert Signal Values for Preference Reversalinvert_signal
Join multiple panels on intersecting dates (unique symbol names)join_panels
Limit per-date selections to top-K (legacy API)limit_positions
List available example scriptslist_examples
Load Mixed Symbols Including VIXload_mixed_symbols
Make future-return labels aligned to the decision datemake_labels
Adapter for User-Provided Datamanual_adapter
Membership stability across datesmembership_stability
Calculate Sharpe Ratio with Frequency Detectionmetric_sharpe
Add interaction panels to a feature listml_add_interactions
One-call backtest wrapper (tabular features)ml_backtest
Run multi-horizon ML backtests (pooled or sector-neutral)ml_backtest_multi
One-call backtest wrapper (sequence features)ml_backtest_seq
Rank-IC series computed on score (rebalance) datesml_ic_series_on_scores
NA-tolerant ensemble blender (row-wise)ml_make_ensemble
Model factory for tabular cross-sectional learnersml_make_model
Deterministic sequence model factory (GRU/LSTM/CNN1D with linear fallback)ml_make_seq_model
Panel-safe binary operation on aligned wide panelsml_panel_op
Reduce multiple panels with a binary operatorml_panel_reduce
Rolling rank-IC plot (rebalance dates; leakage-safe)ml_plot_ic_roll
Prepare tabular features (weekly + aligned daily volatility)ml_prepare_features
Lag each symbol column by k stepspanel_lag
Panel simple returns from pricespanel_returns_simple
Portfolio performance metricsperf_metrics
Plot Backtest Resultsplot.backtest_result
Plot Parameter Grid Results (1D/2D/3D and Facets)plot.param_grid_result
Plot Performance Analysis Resultsplot.performance_analysis
Plot Walk-Forward Resultsplot.wf_optimization_result
Portfolio returns from weights and prices (CASH-aware)portfolio_returns
Print Backtest Resultsprint.backtest_result
Print a param_grid_resultprint.param_grid_result
Print Performance Analysis Resultsprint.performance_analysis
Print a wf_optimization_resultprint.wf_optimization_result
Collect diagnostics from two 'ml_backtest_multi()' runspt_collect_results
Rank Indicators Within Each Sectorrank_within_sector
Rebalance calendar (rows with non-zero allocation)rebalance_calendar
Rolling fit/predict for tabular features (pooled / per-symbol / per-group)roll_fit_predict
Rolling fit/predict for sequence models (flattened steps-by-p features)roll_fit_predict_seq
Rolling IC mean, standard deviation, and ICIRroll_ic_stats
Run Portfolio Backtestrun_backtest
Run an Example Scriptrun_example
Run Parameter Grid Optimization (safe + ergonomic)run_param_grid
Walk-Forward Optimization Analysisrun_walk_forward
Safe Division with NA and Zero Handlingsafe_divide
Sample Daily Stock Pricessample_prices_daily
Sample Weekly Stock Pricessample_prices_weekly
S&P 500 Sector Mappingssample_sp500_sectors
Mask score tables to out-of-sample decision datesscores_oos_only
Select top-K scores per dateselect_top_k_scores
Select top-k symbols per group by scoreselect_top_k_scores_by_group
Load Price Data from SQL Databasesql_adapter
Load Adjusted Price Data from SQL Databasesql_adapter_adjusted
Summary method for backtest resultssummary.backtest_result
Switch Between Weighting Schemesswitch_weights
Per-date score transform (z-score or rank)transform_scores
Quick grid tuning for tabular pipelinetune_ml_backtest
Turnover by dateturnover_by_date
Update VIX data in databaseupdate_vix_in_db
Validate Data Format for Library Functionsvalidate_data_format
Validate a symbol-to-group mappingvalidate_group_map
Quick leakage guard: date alignment & NA expectationsvalidate_no_leakage
Volatility targeting (row-wise) with optional down-only capvol_target
Hierarchical Risk Parity Weightingweight_by_hrp
Rank-Based Portfolio Weightingweight_by_rank
Regime-Based Adaptive Weightingweight_by_regime
Risk Parity Weighting Suiteweight_by_risk_parity
Signal-Based Portfolio Weightingweight_by_signal
Volatility-Based Portfolio Weightingweight_by_volatility
Equal Weight Portfolio Constructionweight_equally
Map scores to portfolio weightsweight_from_scores
Generate Walk-Forward Reportwf_report
Stitch Out-of-Sample Results (overlap-safe)wf_stitch
Walk-forward sweep of tabular configs (window-wise distribution of metrics)wf_sweep_tabular
Download Price Data from Yahoo Financeyahoo_adapter