# Writing Algorithms

## Strategy Library

### Introduction

The Strategy Library is a collection of tutorials written by the QuantConnect team and community members. Review these tutorials to learn about trading strategies found in the academic literature and how to implement them with LEAN.

### Tutorials

Strategy Name
CAPM Alpha Ranking Strategy on Dow 30 Companies

Applies CAPM model to rank Dow Jones 30 companies.

Combining Mean Reversion and Momentum in Forex Market

Combines momentum and mean reversion techniques in the forex markets.

Pairs Trading-Copula vs Cointegration

Applies Copula and Cointergration method to pairs trading.

The Dynamic Breakout II Strategy

A demonstration of dynamic breakout II strategy.

Dual Thrust Trading Algorithm

A demontration of Dual Thrust Intraday strategy.

Can Crude Oil Predict Equity Returns

Applies regression method to predict the return from the stock market and compare it to the short-term U.S. T-bill rate.

Intraday Dynamic Pairs Trading using Correlation and Cointegration Approach

A high frequency pairs trading algorithm based on cointegration.

The Momentum Strategy Based on the Low Frequency Component of Forex Market

Applies high frequency filter to the momentum strategy.

Stock Selection Strategy Based on Fundamental Factors

MorningStar Fundamental factors universe selection algorithm.

Short-Term Reversal Strategy in Stocks

A short term reversal algorithm which gives the opposite signal by analyzing recent period price action.

Fundamental Factor Long Short Strategy

A basic monthly rebalance long short algorithm based on fundamental factors.

Asset Class Trend Following

Selects ETFs over ten-month moving average and assigns an equally weighted allocation.

Source: Quantpedia

Asset Class Momentum

Selects ETFs in different asset classes with the highest momentum and assigns an equally weighted allocation.

Source: Quantpedia

Residual Momentum

Constructs a long/short portfolio based on trailing residual momentum normalized by its standard deviation

Source: Quantpedia

Sector Momentum

Selects ETFs in different sectors with the highest momentum and assigns an equally weighted allocation.

Source: Quantpedia

Overnight Anomaly

Buy SPY ETF at its closing price and sell it at the opening each day.

Source: Quantpedia

Goes long the currency with the highest central bank interest rate and goes short the currency with the lowest interest rate.

Source: Quantpedia

Volatility Effect in Stocks

Constructs equally weighted portfolios by selecting stocks with the lowest volatility in the past one year.

Source: Quantpedia

Forex Momentum

Goes long currencies with strongest 12 month momentum against USD and goes short currencies with the lowest 12 month momentum against USD.

Source: Quantpedia

Pairs Trading with Stocks

Looks for the security that minimizes the sum of squared deviations and long-short position is opened when pair prices have diverged by multiple of standard deviations.

Source: Quantpedia

Short Term Reversal

Goes long stocks with the lowest return in the previous month and goes short stocks with the greatest return from the previous month.

Source: Quantpedia

Momentum Effect in Stocks

Goes long stocks with the best 12-month momentum in the large-cap universe.

Source: Quantpedia

Momentum Effect in Country Equity Indexes

Goes long stocks with the best 12-month momentum in the country equity indexes ETFs.

Source: Quantpedia

Mean Reversion Effect in Country Equity Indexes

Goes long country equity indexes ETFs with the worst 36-month return and short ETFs with the best 36-month return.

Source: Quantpedia

Liquidity Effect in Stocks

Goes long stocks with the lowest turnover and short on stocks with the highest turnover from the lowest market-cap quartile.

Source: Quantpedia

Volatility Risk Premium Effect

Sells at-the-money straddle with one month until maturity and buys an offsetting 15% out-of-the-money puts each month.

Source: Quantpedia

Momentum Effect in Commodities Futures

Goes long commodity futures with the highest momentum and short on futures with the lowest momentum.

Source: Quantpedia

Small Capitalization Stocks Premium Anomaly

Goes long stocks with the lowest market capitalization and rebalances the portfolio once a year.

Source: Quantpedia

Paired Switching

Goes long asset with better performance over the last period and rebalances portfolio every quarter.

Source: Quantpedia

Term Structure Effect in Commodities

Buys each month the 20% of commodities with the highest roll-returns and shorts the 20% of commodities with the lowest roll-returns and holds the long-short positions for one month.

Source: Quantpedia

Momentum Effect Combined with Term Structure in Commodities

Portfolios are formed based on roll returns and the algorithm goes long and short contracts with the highest and lowest one-month performance.

Source: Quantpedia

Book-to-Market Value Anomaly

Quintile portfolios are formed based on the Book-to-Market ratio and the highest quintile is held for one year.

Source: Quantpedia

Gold Market Timing

Goes long gold when the Fed model shows that the market is undervalued (the earnings yield is higher than the bond yield and their ratio is at least 2).

Source: Quantpedia

Turn of the Month in Equity Indexes

Buys SPY the day before the end of the month and liquidates position on 3rd trading day of new month.

Source: Quantpedia

Momentum - Short Term Reversal Strategy

Goes long stocks with the decreasing return from the winner group and short stocks with the increasing return from the loser group.

Source: Quantpedia

Pairs Trading with Country ETFs

Identifies the price divergence from two highly correlated country ETFs and takes a market neutral position.

Source: Quantpedia

Sentiment and Style Rotation Effect in Stocks

Creates long-short positions of growth and value stocks based on the investment sentiment.

Source: Quantpedia

Asset Growth Effect

Creates long-short positions of stocks based on the annual change of their total assets.

Source: Quantpedia

Momentum and State of Market Filters

Goes long and short stocks with the highest and lowest six-month momentum respectively if the previous 12 months return on the broad market index was positive.

Source: Quantpedia

Accrual Anomaly

Decile portfolios are formed based on balance sheet based accruals and highest decile is shorted while lowest decile is bought for a year.

Source: Quantpedia

Momentum in Mutual Fund Returns

Forms a long-short portfolio of asset management firms based on trailing rate of change and nearness to trailing high.

Source: Quantpedia

Momentum and Style Rotation Effect

Goes long style index ETF with the highest 12-month momentum and short ETF with the lowest 12-month momentum.

Source: Quantpedia

Goes long the spread if the spread is below 20-day moving average and short if the spread is above 20-day moving average.

Source: Quantpedia

Momentum Effect in REITs

Tercile portfolios are formed based on momentum and the best performing portfolio is held.

Source: Quantpedia

Option Expiration Week Effect

Goes long S&P 100 index ETF during option expiration week and stays in cash during other days.

Source: Quantpedia

Earnings Quality Factor

Goes long stocks with high earnings quality and short stocks with low earnings quality based on composite factor score.

Source: Quantpedia

January Effect in Stocks

Invests into small cap stocks at the beginning of each January and stays invested in large cap stocks for rest of the year.

Source: Quantpedia

Momentum and Reversal Combined with Volatility Effect in Stocks

Goes long on stocks from the highest performing quintile from the highest volatility group and short on stocks from the lowest performing quintile from the highest volatility group.

Source: Quantpedia

ROA Effect within Stocks

Goes long on stocks with highest ROA and short stocks with the lowest ROA from each market capitalization group.

Source: Quantpedia

January Barometer

Invested in equity market with ETF only if January return is positive otherwise switch investments to T-Bills.

Source: Quantpedia

Lunar Cycle in Equity Market

Goes long in emerging market index ETF 7 days before the new moon and switch to a short position on emerging market index ETF 7 days before the full moon.

Source: Quantpedia

VIX Predicts Stock Index Returns

Goes long on equity index ETF if the VIX is in the highest percentile short if VIX is in the lowest percentile in the last two-year history.

Source: Quantpedia

Combining Momentum Effect with Volume

Goes long stocks with the highest volume from the top momentum decile and short stocks with the highest volume from the bottom momentum decile.

Source: Quantpedia

Short Term Reversal with Futures

Goes long (short) on futures from the high-volume, low-open interest group with the lowest (greatest) returns in the previous week.

Source: Quantpedia

Pre-holiday Effect

Invests in equity market 2 days preceding holiday days and stays in cash during the other trading days.

Source: Quantpedia

Beta Factors in Stocks

Goes long stocks with the bottom beta and short stocks with the top beta, securities are weighted by the ranked betas.

Source: Quantpedia

Exploiting Term Structure of VIX Futures

Buys or sells the nearest VIX futures based on the daily roll and hedge against the open positions with E-mini S&P500 futures.

Source: Quantpedia

12 Month Cycle in Cross-Section of Stocks Returns

Reviews the returns from last January, going long on the top 10% winners and short the bottom 10%.

Source: Quantpedia

Momentum Effect in Stocks in Small Portfolios

Goes long in the 10 stocks with the highest performance and goes short in the 10 stocks with the lowest performance in the previous one year.

Source: Quantpedia

Value Effect within Countries

Invests in the cheapest 33% of country ETFs according to CAPE ratios.

Source: Quantpedia

Beta Factor in Country Equity Indexes

Goes long on the low-beta portfolio and short on the high-beta portfolio in country indexes ETFs.

Source: Quantpedia

Price to Earnings Anomaly

Invests in stocks with low P/E ratio.

Fama French Five Factors

Stock selecting strategy based on Fama-French Five Factors Model.

Source: NYU

Mean-Reversion Statistical Arbitrage Strategy in Stocks

Apply statistical arbitrage to take advantage of pricing inefficiencies in stocks.

Source: NYU

Expected Idiosyncratic Skewness

Stock selection strategy that calculates expected idiosyncratic skewness using Fama-French three-factor model, sorts stocks based on the calculated skewness, and longs the bottom 5%.

Source: NYU

Risk Premia in Forex Markets

A strategy based on asymmetric tail risks and excess returns in forex markets.

Source: NYU

Seasonality Effect based on Same-Calendar Month Returns

A strategy that takes long and short positions based on historical same-calendar month returns

Source: NYU

Standardized Unexpected Earnings

Stock selection strategy that calculates the unexpected earnings, standardizes the unexpected earnings, goes long on the top 5%, and rebalances the portfolio monthly.

Source: NYU

Price and Earnings Momentum

A momentum strategy based on quarterly returns and earnings growth

Source: NYU

Improved Momentum Strategy on Commodities Futures

An advanced momentum strategy that modifies the basic momentum strategies by introducing Baltas and Kosowski weights and rebalances the portfolio monthly. The new weighing scheme incorporates trend strength into the trading signal, uses an efficient volatility estimator, and adds a dynamic leverage mechanism.

Source: NYU

Commodities Futures Trend Following

A simple trend following strategy on commodities futures.

Source: NYU

Forecasting Stock Prices using a Temporal CNN Model

Applying a Temporal Convolutional Neural Network to forecasting future stock prices.

Source: Tampere University

Leveraged ETFs with Systematic Risk Management

We apply Simple Moving Averages to manage the risk of holding leveraged ETFs in an attempt to beat the S&P500

Source: The Lead-Lag Report

Ichimoku Clouds in the Energy Sector

A techincal indicator crossover strategy trading the largest energy companies.

Source: SSRN

A momentum strategy based on returns of the market open

Source: NYU

Intraday Arbitrage Between Index ETFs

A strategy that tracks the price paths of two correlated ETFs and takes advantage of mis-pricings that arise when the price paths diverge

Source: SSRN

Mathematically Deriving the Optimal Entry and Liquidation Values of a Pairs Trading Process

Source: arXiv

G-Score Investing

Applying G-Score Investing to Invest in a Portfolio of Technology Stocks

Source: SSRN

SVM Wavelet Forecasting

Forecasting EURJPY prices with an SVM Wavelet model

Forecasts future intraday returns with a gradient boosting model trained on technical indicators

Source: arXiv

Using News Sentiment to Predict Price Direction of Drug Manufacturers

Analyzes the news releases of drug manufacturers and places intraday trades for the stocks with positive news.

Source: arXiv

Gaussian Naive Bayes Model

Forecasts the next day's return of technology stocks by fitting a gaussian naive bayes model to the historical returns of the technology sector constituents.

### Contribute Tutorials

Follow these steps to contribute a strategy to the Strategy Library:

1. Review filtered sources like SSRN, arXiv, and other academic journals/papers for a strategy to implement.
2. Create a 3-point development plan and contact us for approval.
3. The development plan should include the tutorial name and a link to the source research paper.

4. Add an Issue to the Tutorials GitHub repository
5. For an example, see GitHub Issue #277.

6. Develop the strategy.
7. Add the Apache license and required imports to the main.py or Main.cs file.
8. Publish a strategy write-up, along with any associated images and link to backtesting, in Google Docs, and add designated QuantConnect Staff members for review.
9. For examples, see the preceding Strategy Library tutorials.

10. Convert the strategy write-up to HTML form.
11. For examples, see the Tutorials GitHub repository.

12. Make a pull request to the Tutorials GitHub repository and wait for it to be merged.
13. Adhere to the following guidelines while you make the pull request:

• Read the Contributor's Guide in the LEAN GitHub repository.
• Add the summary HTML files to the Strategy Library directory.
• If you didn't source the strategy from Quantpedia, set the ID number in the directory name to the next available after 1023.

• If you sourced the strategy from Quantpedia, add the strategy ID and backtest ID to the \$strategyMap in the quantpedia.json file.
• Add some strategy metadata to the 01 Strategy Library.php file.
14. Send the tutorial URL and a 1-sentence summary of the strategy.
15. Post the strategy to the forum with the backtest of the algorithm and a short summary of the project.
16. For an example forum post, see Strategy Library Addition: Residual Momentum.

You can also see our Videos. You can also get in touch with us via Discord.