Cerca negli script per "科创50指数资金流向如何"
UO_30-50-70Ultimate Oscillator with bands present at the 30, 50, and 70 pt levels.
Personally use this every time, created a script to hard code these lines so I wouldn't need to redraw them all the time.
Enjoy
EMA Crossover Strategy (15m)50 and 200 ema crossing when leaving anchor. when 50 and 200 crosses will give you direction of where market is going. wait for a pull back and take trade. sl on highest or lowest point of apex tp open . when you see multiple equal ( low or High) get put of trade.
The Lazy Trader - Index (ETF) Trend Following Robot50/150 moving average, index (ETF) trend following robot. Coded for people who cannot psychologically handle dollar-cost-averaging through bear markets and extreme drawdowns (although DCA can produce better results eventually), this robot helps you to avoid bear markets. Be a fair-weathered friend of Mr Market, and only take up his offer when the sun is shining! Designed for the lazy trader who really doesn't care...
Recommended Chart Settings:
Asset Class: ETF
Time Frame: Daily
Necessary ETF Macro Conditions:
a) Country must have healthy demographics, good ratio of young > old
b) Country population must be increasing
c) Country must be experiencing price-inflation
Default Robot Settings:
Slow Moving Average: 50 (integer) //adjust to suit your underlying index
Fast Moving Average: 150 (integer) //adjust to suit your underlying index
Bullish Slope Angle: 5 (degrees) //up angle of moving averages
Bearish Slope Angle: -5 (degrees) //down angle of moving averages
Average True Range: 14 (integer) //input for slope-angle formula
Risk: 100 (%) //100% risk means using all equity per trade
ETF Test Results (Default Settings):
SPY (1993 to 2020, 27 years), 332% profit, 20 trades, 6.4 profit factor, 7% drawdown
EWG (1996 to 2020, 24 years), 310% profit, 18 trades, 3.7 profit factor, 10% drawdown
EWH (1996 to 2020, 24 years), 4% loss, 26 trades, 0.9 profit factor, 36% drawdown
QQQ (1999 to 2020, 21 years), 232% profit, 17 trades, 3.6 profit factor, 2% drawdown
EEM (2003 to 2020, 17 years), 73% profit, 17 trades, 1.1 profit factor, 3% drawdown
GXC (2007 to 2020, 13 years), 18% profit, 14 trades, 1.3 profit factor, 26% drawdown
BKF (2009 to 2020, 11 years), 11% profit, 13 trades, 1.2 profit factor, 33% drawdown
A longer time in the markets is better, with the exception of EWH. 6 out of 7 tested ETFs were profitable, feel free to test on your favourite ETF (default settings) and comment below.
Risk Warning:
Not tested on commodities nor other financial products like currencies (code will not work), feel free to leave comments below.
Moving Average Slope Angle Formula:
Reproduced and modified from source:
50-Minute Opening Range BreakoutThis is a test of the opening range with Bearish/Bullish confirmation
50-Line Oscillator // (\_/)
// ( •.•)
// (")_(")
25-Line Oscillator
Description:
The 25-Line Oscillator is a sophisticated technical analysis tool designed to visualize market trends through the use of multiple Simple Moving Averages (SMAs). This indicator computes a series of 26 SMAs, incrementally increasing the base length, providing traders with a comprehensive view of price dynamics.
Features:
Customizable Base Length: Adjust the base length of the SMAs according to trading preferences, enhancing versatility for different market conditions.
Rainbow Effect: The indicator employs a visually appealing rainbow color scheme to differentiate between the various trend lines, making it easy to identify crossovers and momentum shifts.
Crossovers Detection: The script includes logic to detect crossover events between consecutive trend lines, which can serve as signals for potential entry or exit points in trading.
Clear Visualization: Suitable for both novice and seasoned traders, the plots enable quick interpretation of trends and market behavior.
How to Use:
Add the indicator to your chart and customize the base length as desired.
Observe the rainbow-colored lines for trend direction.
Look for crossover events between the SMAs as potential trading signals.
Application: This indicator is particularly useful for swing traders and trend followers who aim to capitalize on market momentum and identify reversals. By monitoring the behavior of multiple SMAs, traders can gain insights into the strength and direction of price movements over various time frames.
AK Simple Moving Average 50 days Simple Moving average suitable for Intraday on 1Hr,30Min.15Min Time frames
1. When candle crossing above SMA Line - Go for Long Entries
2. When candle crossing below SMA Line - Go for short Entries
50 SMA / 200 EMA / 128EMA Moving Average CrossFound success using 50SMA vs 200EMA.
128 EMA also charted for it's BTC relevance.
50/100/200 Moving Averages (Pine Script For Copy)by fresca
SCRIPT LANGUAGE
Copy script below and adjust based on your preferences.
-function (change function from "sma" to "ema", "wma" and more)
-length (25 Day, 150 Day or add more averages to the three in this script.)
-color, (red, yellow, etc. or use color hex codes i.e. #FEDA15, #FFAD8F, etc.)
-transparency (set to desired level 1-100)
Or add more options.
RESOURCES
Color hex codes site: www.canva.com
Trading View Pine Script Editor Reference Guide: www.tradingview.com
Taint's Multi Time Frame MA50-100-200 SMA with two 200 EMA's all with the ability choose a time frame for each.
Volatility-Targeted Momentum Portfolio [BackQuant]Volatility-Targeted Momentum Portfolio
A complete momentum portfolio engine that ranks assets, targets a user-defined volatility, builds long, short, or delta-neutral books, and reports performance with metrics, attribution, Monte Carlo scenarios, allocation pie, and efficiency scatter plots. This description explains the theory and the mechanics so you can configure, validate, and deploy it with intent.
Table of contents
What the script does at a glance
Momentum, what it is, how to know if it is present
Volatility targeting, why and how it is done here
Portfolio construction modes: Long Only, Short Only, Delta Neutral
Regime filter and when the strategy goes to cash
Transaction cost modelling in this script
Backtest metrics and definitions
Performance attribution chart
Monte Carlo simulation
Scatter plot analysis modes
Asset allocation pie chart
Inputs, presets, and deployment checklist
Suggested workflow
1) What the script does at a glance
Pulls a list of up to 15 tickers, computes a simple momentum score on each over a configurable lookback, then volatility-scales their bar-to-bar return stream to a target annualized volatility.
Ranks assets by raw momentum, selects the top 3 and bottom 3, builds positions according to the chosen mode, and gates exposure with a fast regime filter.
Accumulates a portfolio equity curve with risk and performance metrics, optional benchmark buy-and-hold for comparison, and a full alert suite.
Adds visual diagnostics: performance attribution bars, Monte Carlo forward paths, an allocation pie, and scatter plots for risk-return and factor views.
2) Momentum: definition, detection, and validation
Momentum is the tendency of assets that have performed well to continue to perform well, and of underperformers to continue underperforming, over a specific horizon. You operationalize it by selecting a horizon, defining a signal, ranking assets, and trading the leaders versus laggards subject to risk constraints.
Signal choices . Common signals include cumulative return over a lookback window, regression slope on log-price, or normalized rate-of-change. This script uses cumulative return over lookback bars for ranking (variable cr = price/price - 1). It keeps the ranking simple and lets volatility targeting handle risk normalization.
How to know momentum is present .
Leaders and laggards persist across adjacent windows rather than flipping every bar.
Spread between average momentum of leaders and laggards is materially positive in sample.
Cross-sectional dispersion is non-trivial. If everything is flat or highly correlated with no separation, momentum selection will be weak.
Your validation should include a diagnostic that measures whether returns are explained by a momentum regression on the timeseries.
Recommended diagnostic tool . Before running any momentum portfolio, verify that a timeseries exhibits stable directional drift. Use this indicator as a pre-check: It fits a regression to price, exposes slope and goodness-of-fit style context, and helps confirm if there is usable momentum before you force a ranking into a flat regime.
3) Volatility targeting: purpose and implementation here
Purpose . Volatility targeting seeks a more stable risk footprint. High-vol assets get sized down, low-vol assets get sized up, so each contributes more evenly to total risk.
Computation in this script (per asset, rolling):
Return series ret = log(price/price ).
Annualized volatility estimate vol = stdev(ret, lookback) * sqrt(tradingdays).
Leverage multiplier volMult = clamp(targetVol / vol, 0.1, 5.0).
This caps sizing so extremely low-vol assets don’t explode weight and extremely high-vol assets don’t go to zero.
Scaled return stream sr = ret * volMult. This is the per-bar, risk-adjusted building block used in the portfolio combinations.
Interpretation . You are not levering your account on the exchange, you are rescaling the contribution each asset’s daily move has on the modeled equity. In live trading you would reflect this with position sizing or notional exposure.
4) Portfolio construction modes
Cross-sectional ranking . Assets are sorted by cr over the chosen lookback. Top and bottom indices are extracted without ties.
Long Only . Averages the volatility-scaled returns of the top 3 assets: avgRet = mean(sr_top1, sr_top2, sr_top3). Position table shows per-asset leverages and weights proportional to their current volMult.
Short Only . Averages the negative of the volatility-scaled returns of the bottom 3: avgRet = mean(-sr_bot1, -sr_bot2, -sr_bot3). Position table shows short legs.
Delta Neutral . Long the top 3 and short the bottom 3 in equal book sizes. Each side is sized to 50 percent notional internally, with weights within each side proportional to volMult. The return stream mixes the two sides: avgRet = mean(sr_top1,sr_top2,sr_top3, -sr_bot1,-sr_bot2,-sr_bot3).
Notes .
The selection metric is raw momentum, the execution stream is volatility-scaled returns. This separation is deliberate. It avoids letting volatility dominate ranking while still enforcing risk parity at the return contribution stage.
If everything rallies together and dispersion collapses, Long Only may behave like a single beta. Delta Neutral is designed to extract cross-sectional momentum with low net beta.
5) Regime filter
A fast EMA(12) vs EMA(21) filter gates exposure.
Long Only active when EMA12 > EMA21. Otherwise the book is set to cash.
Short Only active when EMA12 < EMA21. Otherwise cash.
Delta Neutral is always active.
This prevents taking long momentum entries during obvious local downtrends and vice versa for shorts. When the filter is false, equity is held flat for that bar.
6) Transaction cost modelling
There are two cost touchpoints in the script.
Per-bar drag . When the regime filter is active, the per-bar return is reduced by fee_rate * avgRet inside netRet = avgRet - (fee_rate * avgRet). This models proportional friction relative to traded impact on that bar.
Turnover-linked fee . The script tracks changes in membership of the top and bottom baskets (top1..top3, bot1..bot3). The intent is to charge fees when composition changes. The template counts changes and scales a fee by change count divided by 6 for the six slots.
Use case: increase fee_rate to reflect taker fees and slippage if you rebalance every bar or trade illiquid assets. Reduce it if you rebalance less often or use maker orders.
Practical advice .
If you rebalance daily, start with 5–20 bps round-trip per switch on liquid futures and adjust per venue.
For crypto perp microcaps, stress higher cost assumptions and add slippage buffers.
If you only rotate on lookback boundaries or at signals, use alert-driven rebalances and lower per-bar drag.
7) Backtest metrics and definitions
The script computes a standard set of portfolio statistics once the start date is reached.
Net Profit percent over the full test.
Max Drawdown percent, tracked from running peaks.
Annualized Mean and Stdev using the chosen trading day count.
Variance is the square of annualized stdev.
Sharpe uses daily mean adjusted by risk-free rate and annualized.
Sortino uses downside stdev only.
Omega ratio of sum of gains to sum of losses.
Gain-to-Pain total gains divided by total losses absolute.
CAGR compounded annual growth from start date to now.
Alpha, Beta versus a user-selected benchmark. Beta from covariance of daily returns, Alpha from CAPM.
Skewness of daily returns.
VaR 95 linear-interpolated 5th percentile of daily returns.
CVaR average of the worst 5 percent of daily returns.
Benchmark Buy-and-Hold equity path for comparison.
8) Performance attribution
Cumulative contribution per asset, adjusted for whether it was held long or short and for its volatility multiplier, aggregated across the backtest. You can filter to winners only or show both sides. The panel is sorted by contribution and includes percent labels.
9) Monte Carlo simulation
The panel draws forward equity paths from either a Normal model parameterized by recent mean and stdev, or non-parametric bootstrap of recent daily returns. You control the sample length, number of simulations, forecast horizon, visibility of individual paths, confidence bands, and a reproducible seed.
Normal uses Box-Muller with your seed. Good for quick, smooth envelopes.
Bootstrap resamples realized returns, preserving fat tails and volatility clustering better than a Gaussian assumption.
Bands show 10th, 25th, 75th, 90th percentiles and the path mean.
10) Scatter plot analysis
Four point-cloud modes, each plotting all assets and a star for the current portfolio position, with quadrant guides and labels.
Risk-Return Efficiency . X is risk proxy from leverage, Y is expected return from annualized momentum. The star shows the current book’s composite.
Momentum vs Volatility . Visualizes whether leaders are also high vol, a cue for turnover and cost expectations.
Beta vs Alpha . X is a beta proxy, Y is risk-adjusted excess return proxy. Useful to see if leaders are just beta.
Leverage vs Momentum . X is volMult, Y is momentum. Shows how volatility targeting is redistributing risk.
11) Asset allocation pie chart
Builds a wheel of current allocations.
Long Only, weights are proportional to each long asset’s current volMult and sum to 100 percent.
Short Only, weights show the short book as positive slices that sum to 100 percent.
Delta Neutral, 50 percent long and 50 percent short books, each side leverage-proportional.
Labels can show asset, percent, and current leverage.
12) Inputs and quick presets
Core
Portfolio Strategy . Long Only, Short Only, Delta Neutral.
Initial Capital . For equity scaling in the panel.
Trading Days/Year . 252 for stocks, 365 for crypto.
Target Volatility . Annualized, drives volMult.
Transaction Fees . Per-bar drag and composition change penalty, see the modelling notes above.
Momentum Lookback . Ranking horizon. Shorter is more reactive, longer is steadier.
Start Date . Ensure every symbol has data back to this date to avoid bias.
Benchmark . Used for alpha, beta, and B&H line.
Diagnostics
Metrics, Equity, B&H, Curve labels, Daily return line, Rolling drawdown fill.
Attribution panel. Toggle winners only to focus on what matters.
Monte Carlo mode with Normal or Bootstrap and confidence bands.
Scatter plot type and styling, labels, and portfolio star.
Pie chart and labels for current allocation.
Presets
Crypto Daily, Long Only . Lookback 25, Target Vol 50 percent, Fees 10 bps, Regime filter on, Metrics and Drawdown on. Monte Carlo Bootstrap with Recent 200 bars for bands.
Crypto Daily, Delta Neutral . Lookback 25, Target Vol 50 percent, Fees 15–25 bps, Regime filter always active for this mode. Use Scatter Risk-Return to monitor efficiency and keep the star near upper left quadrants without drifting rightward.
Equities Daily, Long Only . Lookback 60–120, Target Vol 15–20 percent, Fees 5–10 bps, Regime filter on. Use Benchmark SPX and watch Alpha and Beta to keep the book from becoming index beta.
13) Suggested workflow
Universe sanity check . Pick liquid tickers with stable data. Thin assets distort vol estimates and fees.
Check momentum existence . Run on your timeframe. If slope and fit are weak, widen lookback or avoid that asset or timeframe.
Set risk budget . Choose a target volatility that matches your drawdown tolerance. Higher target increases turnover and cost sensitivity.
Pick mode . Long Only for bull regimes, Short Only for sustained downtrends, Delta Neutral for cross-sectional harvesting when index direction is unclear.
Tune lookback . If leaders rotate too often, lengthen it. If entries lag, shorten it.
Validate cost assumptions . Increase fee_rate and stress Monte Carlo. If the edge vanishes with modest friction, refine selection or lengthen rebalance cadence.
Run attribution . Confirm the strategy’s winners align with intuition and not one unstable outlier.
Use alerts . Enable position change, drawdown, volatility breach, regime, momentum shift, and crash alerts to supervise live runs.
Important implementation details mapped to code
Momentum measure . cr = price / price - 1 per symbol for ranking. Simplicity helps avoid overfitting.
Volatility targeting . vol = stdev(log returns, lookback) * sqrt(tradingdays), volMult = clamp(targetVol / vol, 0.1, 5), sr = ret * volMult.
Selection . Extract indices for top1..top3 and bot1..bot3. The arrays rets, scRets, lev_vals, and ticks_arr track momentum, scaled returns, leverage multipliers, and display tickers respectively.
Regime filter . EMA12 vs EMA21 switch determines if the strategy takes risk for Long or Short modes. Delta Neutral ignores the gate.
Equity update . Equity multiplies by 1 + netRet only when the regime was active in the prior bar. Buy-and-hold benchmark is computed separately for comparison.
Tables . Position tables show current top or bottom assets with leverage and weights. Metric table prints all risk and performance figures.
Visualization panels . Attribution, Monte Carlo, scatter, and pie use the last bars to draw overlays that update as the backtest proceeds.
Final notes
Momentum is a portfolio effect. The edge comes from cross-sectional dispersion, adequate risk normalization, and disciplined turnover control, not from a single best asset call.
Volatility targeting stabilizes path but does not fix selection. Use the momentum regression link above to confirm structure exists before you size into it.
Always test higher lag costs and slippage, then recheck metrics, attribution, and Monte Carlo envelopes. If the edge persists under stress, you have something robust.






















