Close Menu
    Facebook X (Twitter) Instagram
    Articles Stock
    • Home
    • Technology
    • AI
    • Pages
      • About ArticlesStock — AI & Technology Journalist
      • Contact us
      • Disclaimer For Articles Stock
      • Privacy Policy
      • Terms and Conditions
    Facebook X (Twitter) Instagram
    Articles Stock
    AI

    A Coding Implementation to Portfolio Optimization with skfolio for Constructing Testing, Tuning, and Evaluating Trendy Funding Methods

    Naveed AhmadBy Naveed Ahmad12/05/2026Updated:12/05/2026No Comments2 Mins Read
    blog11 11


    factor_prices = load_factors_dataset()
    X_full, F_full = prices_to_returns(costs, factor_prices)
    
    
    X_tr, X_te, F_tr, F_te = train_test_split(
       X_full, F_full, test_size=0.33, shuffle=False
    )
    
    
    fm = MeanRisk(
       objective_function=ObjectiveFunction.MAXIMIZE_RATIO,
       risk_measure=RiskMeasure.VARIANCE,
       prior_estimator=FactorModel(),
    )
    fm.match(X_tr, F_tr)
    ptf_fm = fm.predict(X_te); ptf_fm.identify = "Issue Mannequin"
    print(f"nFactor-model Sharpe: {ptf_fm.annualized_sharpe_ratio:.3f}")
    
    
    pipe = Pipeline([
       ("preselect",   SelectKExtremes(k=8, highest=True)),
       ("optimize",    MeanRisk(
           objective_function=ObjectiveFunction.MAXIMIZE_RATIO,
           risk_measure=RiskMeasure.VARIANCE)),
    ])
    pipe.match(X_train)
    ptf_pipe = pipe.predict(X_test); ptf_pipe.identify = "High-8 + Max Sharpe"
    
    
    wf_model = MeanRisk(
       objective_function=ObjectiveFunction.MAXIMIZE_RATIO,
       risk_measure=RiskMeasure.VARIANCE,
    )
    mp_portfolio = cross_val_predict(
       wf_model, X,
       cv=WalkForward(train_size=252*2, test_size=63),
       n_jobs=-1,
    )
    mp_portfolio.identify = "Stroll-Ahead Max Sharpe"
    print(f"nWalk-forward portfolio  Sharpe={mp_portfolio.annualized_sharpe_ratio:.3f}  "
         f"CalmarRatio={mp_portfolio.calmar_ratio:.3f}")
    mp_portfolio.plot_cumulative_returns().present()
    
    
    tuned = MeanRisk(
       objective_function=ObjectiveFunction.MAXIMIZE_RATIO,
       risk_measure=RiskMeasure.VARIANCE,
       prior_estimator=EmpiricalPrior(mu_estimator=EWMu(alpha=0.1)),
    )
    grid = GridSearchCV(
       estimator=tuned,
       cv=WalkForward(train_size=252*2, test_size=63),
       n_jobs=-1,
       param_grid={
           "l2_coef": [0.0, 0.01, 0.1],
           "prior_estimator__mu_estimator__alpha": [0.05, 0.1, 0.2, 0.5],
       },
    )
    grid.match(X_train)
    print("nBest params:", grid.best_params_)
    print(f"Greatest CV rating (Sharpe): {grid.best_score_:.3f}")
    
    
    ptf_tuned = grid.best_estimator_.predict(X_test); ptf_tuned.identify = "Tuned Max Sharpe"
    
    
    last = Inhabitants([
       *baseline_population,
       ptf_min_var, ptf_max_sharpe,
       ptf_rb_var, ptf_rb_cvar,
       ptf_hrp, ptf_nco,
       ptf_robust, ptf_gerber,
       ptf_constr, ptf_bl, ptf_fm,
       ptf_pipe, ptf_tuned,
    ])
    
    
    _full = last.abstract()
    _wanted_final = [
       "Annualized Mean", "Annualized Standard Deviation",
       "Annualized Sharpe Ratio", "Annualized Sortino Ratio",
       "CVaR at 95%", "Maximum Drawdown", "Max Drawdown",
    ]
    _have_final = [r for r in _wanted_final if r in _full.index]
    abstract = _full.loc[_have_final].T.sort_values(
       "Annualized Sharpe Ratio", ascending=False
    )
    
    
    print("n" + "=" * 80)
    print("FINAL HORSE RACE — sorted by Sharpe (out-of-sample take a look at set)")
    print("=" * 80)
    print(abstract.to_string())
    
    
    last.plot_cumulative_returns().present()
    
    
    last.plot_composition().present()
    
    
    ptf_rb_var.plot_contribution(measure=RiskMeasure.VARIANCE).present()
    
    
    print("nDone. Strive swapping threat measures, including constraints, or wiring in")
    print("your individual returns DataFrame — each estimator follows the sklearn API.")



    Source link

    Naveed Ahmad

    Naveed Ahmad is a technology journalist and AI writer at ArticlesStock, covering artificial intelligence, machine learning, and emerging tech policy. Read his latest articles.

    Related Posts

    AI voice startup Vapi hits $500M valuation after profitable Amazon Ring over 40 rivals

    12/05/2026

    Amazon launches 30-minute supply throughout the U.S.

    12/05/2026

    Tilde Analysis Introduces Aurora: A Leverage-Conscious Optimizer That Fixes a Hidden Neuron Demise Downside in Muon

    12/05/2026
    Leave A Reply Cancel Reply

    Categories
    • AI
    Recent Comments
      Facebook X (Twitter) Instagram Pinterest
      © 2026 ThemeSphere. Designed by ThemeSphere.

      Type above and press Enter to search. Press Esc to cancel.