Learn R Programming

Test Investment Strategies with English-Like Code

PortfolioTesteR is an R package designed for students and individual investors to test investment strategies using clear, readable code. Unlike complex quantitative libraries, PortfolioTesteR uses intuitive function names that read like plain English, making strategy development accessible to everyone.

Why PortfolioTesteR?

  • English-like syntax: Functions like filter_top_n(), weight_equally(), and run_backtest() are self-explanatory
  • Educational focus: Perfect for learning quantitative investing without getting lost in code complexity
  • Comprehensive toolkit: 70+ functions covering everything from technical indicators to risk analysis
  • Fast backtesting: Optimized for testing strategies on large stock universes
  • Ready-to-use data: Includes sample price data to start testing immediately
  • Realistic results: Handles warmup periods, transaction tracking, and proper return calculations

Installation

Install from GitHub:

# install.packages("devtools")
devtools::install_github("AlbertoPallotta/PortfolioTesteR")

Quick Start Example

library(PortfolioTesteR)

# Load sample data
data(sample_prices_weekly)

# Calculate 12-week momentum
momentum <- calc_momentum(sample_prices_weekly, lookback = 12)

# Select top 10 momentum stocks
top_momentum <- filter_top_n(momentum, n = 10)

# Weight selected stocks equally
weights <- weight_equally(top_momentum)

# Run backtest
result <- run_backtest(
  prices = sample_prices_weekly,
  weights = weights,
  initial_capital = 100000,
  name = "Simple Momentum"
)

# View results
print(result)
summary(result)
plot(result)

Main Functions

Data Loading

  • sql_adapter() - Load from SQLite databases
  • csv_adapter() - Load from CSV files
  • load_mixed_symbols() - Combine different data sources

Technical Indicators

  • calc_momentum() - Price momentum
  • calc_rsi() - Relative Strength Index
  • calc_moving_average() - Simple moving averages
  • calc_stochastic_d() - Stochastic oscillator
  • calc_rolling_volatility() - Rolling historical volatility (std / range / MAD / abs-return)
  • calc_distance() - Distance between price series

Stock Selection

  • filter_top_n() - Select top/bottom N stocks
  • filter_above() - Select above threshold
  • filter_below() - Select below threshold
  • filter_between() - Select within range
  • combine_filters() - Combine multiple conditions
  • apply_regime() - Filter based on market conditions

Portfolio Weighting

  • weight_equally() - Equal weight (1/N)
  • weight_by_signal() - Weight by signal strength
  • weight_by_rank() - Weight by ranking
  • weight_by_volatility() - Inverse volatility weighting
  • weight_by_hrp() - Hierarchical Risk Parity

Backtesting & Analysis

  • run_backtest() - Execute strategy backtest
  • analyze_performance() - Detailed performance metrics
  • print() - Display backtest results
  • summary() - Show detailed statistics
  • plot() - Visualize performance

Sample Data Included

The package includes three datasets for immediate testing:

  • sample_prices_weekly - Weekly prices for 20 stocks (2017-2020)
  • sample_prices_daily - Daily prices for detailed analysis
  • sample_sp500_sectors - Sector classifications

Load them with:

data(sample_prices_weekly)
data(sample_prices_daily)
data(sample_sp500_sectors)

Documentation

Every function includes detailed documentation with examples:

?run_backtest
?calc_momentum
?filter_top_n

Disclaimer

This package is for educational and research purposes only. Past performance does not guarantee future results. Always conduct your own research before making investment decisions. The author is not responsible for any financial losses incurred from using this software.

Author

Alberto Pallotta

License

MIT License

Contributing

We welcome contributions! Please feel free to submit issues and pull requests on GitHub.

Copy Link

Version

Install

install.packages('PortfolioTesteR')

Monthly Downloads

233

Version

0.1.4

License

MIT + file LICENSE

Issues

Pull Requests

Stars

Forks

Maintainer

Alberto Pallotta

Last Published

November 1st, 2025

Functions in PortfolioTesteR (0.1.4)

calc_stochastic_d

Calculate Stochastic D Indicator
calc_sector_breadth

Calculate Market Breadth by Sector
calculate_erc_weights

Calculate Equal Risk Contribution weights (simplified)
calc_stochrsi

Stochastic RSI (StochRSI) for multiple price series
calculate_hrp_weights

Calculate HRP weights for a given returns matrix
cap_turnover

Cap turnover sequentially across dates
calc_sector_relative_indicators

Calculate Indicators Relative to Sector Average
carry_forward_weights

Carry-forward weights between rebalances (validation helper)
csv_adapter

Load Price Data from CSV File
cv_tune_seq

Purged/embargoed K-fold CV for sequence models (inside IS window)
.wf_make_splits

Create Window Splits for Walk-Forward
combine_weights

Combine Multiple Weighting Schemes
convert_to_nweeks

Convert Data to N-Week Frequency
demo_sector_map

Demo sector (group) map for examples/tests
calculate_drawdowns

Calculate Portfolio Drawdowns
calculate_enhanced_metrics

Calculate Enhanced Performance Metrics
calc_moving_average

Calculate Moving Average
invert_signal

Invert Signal Values for Preference Reversal
ic_series

Information Coefficient time series
calculate_annualized_return

Calculate Annualized Return
filter_between

Filter Stocks Between Two Values
calculate_drawdown_series

Calculate Drawdown Time Series
filter_below

Filter Stocks Below Threshold
list_examples

List available example scripts
download_sp500_sectors

Download S&P 500 Sector Mappings from Wikipedia
load_mixed_symbols

Load Mixed Symbols Including VIX
combine_filters

Combine Multiple Filter Conditions
ensure_dt_copy

Ensure Data.Table Without Mutation
calculate_daily_values

Daily equity curve from positions and daily prices
combine_scores

Combine multiple score panels (mean / weighted / rank-average / trimmed)
ml_ic_series_on_scores

Rank-IC series computed on score (rebalance) dates
ml_make_ensemble

NA-tolerant ensemble blender (row-wise)
calculate_max_div_weights

Calculate Maximum Diversification Portfolio weights
cap_exposure

Apply post-weight exposure caps
evaluate_scores

Evaluate scores vs labels (IC and hit-rate)
filter_above

Filter Stocks Above Threshold
calculate_cluster_variance_optimized

Optimized cluster variance calculation
coverage_by_date

Count finite entries per date
plot.wf_optimization_result

Plot Walk-Forward Results
ml_add_interactions

Add interaction panels to a feature list
ml_plot_ic_roll

Rolling rank-IC plot (rebalance dates; leakage-safe)
ml_panel_op

Panel-safe binary operation on aligned wide panels
manual_adapter

Adapter for User-Provided Data
ml_prepare_features

Prepare tabular features (weekly + aligned daily volatility)
ml_backtest

One-call backtest wrapper (tabular features)
portfolio_returns

Portfolio returns from weights and prices (CASH-aware)
filter_top_n

Select Top N Stocks by Signal Value
filter_threshold

Filter by Threshold Value
perf_metrics

Portfolio performance metrics
filter_rank

Select Top or Bottom N Stocks by Signal
make_labels

Make future-return labels aligned to the decision date
membership_stability

Membership stability across dates
ml_panel_reduce

Reduce multiple panels with a binary operator
filter_by_percentile

Filter by Percentile
plot.backtest_result

Plot Backtest Results
ml_make_model

Model factory for tabular cross-sectional learners
run_backtest

Run Portfolio Backtest
run_walk_forward

Walk-Forward Optimization Analysis
roll_ic_stats

Rolling IC mean, standard deviation, and ICIR
roll_fit_predict_seq

Rolling fit/predict for sequence models (flattened steps-by-p features)
print.backtest_result

Print Backtest Results
print.param_grid_result

Print a param_grid_result
roll_fit_predict

Rolling fit/predict for tabular features (pooled / per-symbol / per-group)
metric_sharpe

Calculate Sharpe Ratio with Frequency Detection
print.wf_optimization_result

Print a wf_optimization_result
print.performance_analysis

Print Performance Analysis Results
filter_top_n_where

Select Top N from Qualified Stocks
get_data_frequency

Detect Data Frequency from Dates
create_regime_buckets

Convert Continuous Indicator to Discrete Regimes
standardize_data_format

Standardize Data to Library Format
validate_data_format

Validate Data Format for Library Functions
safe_any

Safe ANY Operation with NA Handling
sample_prices_weekly

Sample Weekly Stock Prices
sql_adapter_adjusted

Load Adjusted Price Data from SQL Database
validate_group_map

Validate a symbol-to-group mapping
ml_make_seq_model

Deterministic sequence model factory (GRU/LSTM/CNN1D with linear fallback)
pt_collect_results

Collect diagnostics from two ml_backtest_multi() runs
sample_sp500_sectors

S&P 500 Sector Mappings
ml_backtest_multi

Run multi-horizon ML backtests (pooled or sector-neutral)
weight_by_regime

Regime-Based Adaptive Weighting
weight_by_rank

Rank-Based Portfolio Weighting
plot.performance_analysis

Plot Performance Analysis Results
ml_backtest_seq

One-call backtest wrapper (sequence features)
plot.param_grid_result

Plot Parameter Grid Results (1D/2D/3D and Facets)
switch_weights

Switch Between Weighting Schemes
summary.backtest_result

Summary method for backtest results
run_example

Run an Example Script
run_param_grid

Run Parameter Grid Optimization (safe + ergonomic)
join_panels

Join multiple panels on intersecting dates (unique symbol names)
limit_positions

Limit per-date selections to top-K (legacy API)
panel_lag

Lag each symbol column by k steps
scores_oos_only

Mask score tables to out-of-sample decision dates
select_top_k_scores

Select top-K scores per date
rank_within_sector

Rank Indicators Within Each Sector
weight_by_risk_parity

Risk Parity Weighting Suite
panel_returns_simple

Panel simple returns from prices
weight_by_signal

Signal-Based Portfolio Weighting
transform_scores

Per-date score transform (z-score or rank)
safe_divide

Safe Division with NA and Zero Handling
recursive_bisection_optimized

Optimized recursive bisection for HRP
rebalance_calendar

Rebalance calendar (rows with non-zero allocation)
validate_no_leakage

Quick leakage guard: date alignment & NA expectations
tune_ml_backtest

Quick grid tuning for tabular pipeline
validate_performance_inputs

Validate Performance Analysis Inputs
sample_prices_daily

Sample Daily Stock Prices
select_top_k_scores_by_group

Select top-k symbols per group by score
weight_by_hrp

Hierarchical Risk Parity Weighting
vol_target

Volatility targeting (row-wise) with optional down-only cap
sql_adapter

Load Price Data from SQL Database
weight_from_scores

Map scores to portfolio weights
weight_equally

Equal Weight Portfolio Construction
weight_by_volatility

Volatility-Based Portfolio Weighting
wf_report

Generate Walk-Forward Report
update_vix_in_db

Update VIX data in database
turnover_by_date

Turnover by date
yahoo_adapter

Download Price Data from Yahoo Finance
wf_stitch

Stitch Out-of-Sample Results (overlap-safe)
wf_sweep_tabular

Walk-forward sweep of tabular configs (window-wise distribution of metrics)
analyze_performance

Analyze Backtest Performance with Daily Monitoring
align_to_timeframe

Align Data to Strategy Timeframe
as_selection

Convert Conditions to Selection Format
PortfolioTesteR-package

PortfolioTesteR: Test Investment Strategies with English-Like Code
apply_regime

Apply Market Regime Filter
analyze_by_period

Period-level summary statistics
backtest_metrics

Calculate Comprehensive Backtest Metrics
analyze_drawdowns

Analyze Drawdown Characteristics
analyze_vs_benchmark

Benchmark-relative performance statistics
calc_relative_strength_rank

Calculate Cross-Sectional Ranking of Indicators
calc_rolling_volatility

Calculate Rolling Volatility
calc_rolling_correlation

Rolling correlation of each symbol to a benchmark
calc_rsi

Calculate Relative Strength Index (RSI)
calc_momentum

Calculate Price Momentum
apply_weighting_method

Apply Weighting Method to Values
bucket_returns

Bucketed label analysis by score rank
calc_distance

Calculate Distance from Reference
calc_market_breadth

Calculate Market Breadth Percentage
calc_cci

Calculate Commodity Channel Index (CCI)