Statistics
EMA Difference MinMax ScaledDifference between two EMAs and then transformed through a MinMax scaler
Time Range StatisticsA good amount of users requested a text box showing various price statistics, the following script returns various of these stats in a user-selected range, and include classical ones such as a central tendency measurement (mean), dispersion (normalized range) and percent change, but also include less common statistics such as average traded volume and number of gaps. The script also calculates the correlation between the closing price and another user-selected instrument.
The script is currently the longest one I ever made and took some efforts, as I wasn't satisfied with the statistics to be originally included. Big thx to Gael for the enormous feedback and the idea of the normalized range, to user @Cookiecrush for the feedback ( without ya I would have posted something bad you know umu ? ), and Lulidolce for the support, friendship is magic!
Selected Range
The setting Start determine the bar at which the range starts, while End determine at which bar the range end. To help you select these values, the current bar number (bar index) is displayed at the right of the indicator title in blue.
The setting evaluate to last bar will use a range starting at Start and ending at the last bar, as such you can use a full range by using Start = 0 and select evaluate to last bar
The range is highlighted by an area on the chart. By default Start = 9000 and End = 10000, you might not have this amount of data in your chart, as such use the displayed bar index to select Start and End, then set the settings as default.
Displayed Statistics
The statistics panel is displayed on the right side of the last bar, the panel has 3 sections, a title section who shows the symbol ticker, timeframe, and overall trends represented by a chart emoji, the overall trends are determined by comparing the number of higher highs with the number of lower low.
Below are displayed the date ranges with time format: year/month/day/hour:minute.
The second section shows the general statistics. The first one is the mean, also represented by the orange line in the chart, the blue line displayed represent the highest price value in the range, while the red one represents the lowest price value.
The second stat is the normalized range, and determine how spread is the price in the user-selected range, why not the standard deviation? Because the standard deviation might return results varying widely depending on the scale of the closing price, you could get measures such as 0.0156 or 16 or even 56 depending on the instrument, as such using a normalized range can be more appropriate as it lays in a range of (0,1). Lower values indicate a low degree of price variation. Note that I still want to find another measure in the future.
The percentage change (or relative change) indicates at which percentage the price has increased or decreased, and is calculated by subtracting the closing at bar Start with the price at bar End , divided by the price at bar End , the result is then multiplied by 100.
The average traded volume calculate the mean of the volume in the selected range, I used the same format used by the original volume indicator for clarity.
Finally, the last stats of the section is the number of gaps, this stat is by default hidden. An up gap is detected when the open price is superior to the previous high, while a down gap is detected when the open price is inferior to the previous low, this allow to only retain significant gaps.
The last section of the indicator panel shows the correlation between the closing price and another instrument, by default GOOG, this correlation is also calculated within the user-selected range. Positive values indicate a positive relationship, that is the two instruments tend to move in the same direction. Negative values indicate a negative relationship, both instruments tend to move in a direction opposite to each other. Values closer to 1 or -1 indicate a stronger relationship, while values closer to 0 indicate no relationship.
In Summary
The script shows various stats, each calculated within a user-selected range, in general one would be more interested in how these stats might evolve with time, but checking them in a custom range can be quite interesting.
Thx for reading. umu
Statistical Histogram with configurable bins and Data WindowCreates a Histogram for Statistical Analysis of any source.
Input Parameters:
Sample Source: Select your source here, can be any numerical source.
Sample Period: Sample size for Mean and Standard Deviation Calculations.
Enable Cumulative Mode: Will attempt to calculate the bin for every sample in the entire dataset.
Window Period: Used only in Window Mode (Enable Cumulative Mode unchecked), Calculates the bin for the past Window Period sample size.
Bin Label Spacing: Adjust horizontal spacing of Bin Labels below the histogram for easier viewing.
Center Bin: Selects the center Bin, usually set to (0 - Bin Width) < Sample <= 0 standard deviations or (z_score)
Bin Width: Selects the Bin Width in standard deviations.
How you can use it:
View characteristics of dataset such as unimodal/bimodal and skewness to determine preferred statistical analysis.
Additional Reference:
en.wikipedia.org
en.wikipedia.org
Credits:
Thanks goes out to www.tradingview.com , for cleaning up some of the code and www.tradingview.com for the original idea.
Usage Tips:
When adjusting the bin parameters, center bin and bin width, verify that the total sum of the bins (Sum Frequency in the Data Window) is close to the Total Samples. If your Sum Frequency is drastically lower it means you need to adjust your center bin and/or bin width to capture more of the data available.
COVID Statistics Tracker & Model Projections by Cryptorhythms😷 COVID-19 Coronavirus Tracker & Statistics Tools by Cryptorhythms 😷
📜Intro
I wanted to put some more meaning behind the numbers for 2020's Covid pandemic. I hope this tool can help people analyze and deal with these hard times. With these metrics I hope to give greater depth and dimension to whats available. While also at the same time creating something that looks decently presentable and gives actionable information.
I had planned on including a few forecasting models and letting the user play with values to see how social distancing works. But alas I couldnt complete those in the scope of time I gave myself for the indicator. If you are interested in collaborating on it, I will share what I have with you and we can further work on it.
📋Description
The script contains 3 main parts you will interact with. I suggest you enable the chart labels for "indicator name" and "indicator last value" to make the charts more readable (right click on the scale of your chart and goto the "labels" pop out menu). Depending on what plots and data you choose to chart, logarithmic and regular scales can both be applied in different situations. To get similar visuals to the examples I will show below, you can goto the indicator options > style tab. I then play with the line styles, colors and transparencies to achieve the nice looking charts. Please also note there is a distinction between "Infected" and "Infectious". A model telling you the number of infected doesnt designate whether that person can still pass the virus on to others (infectious). So Infectious numbers are usually lower than total confirmed, but this isnt always the case if for example a country wasnt testing very much during the early phase or something else.
🚧Disclaimer
I am not a medical professional and none of this should be considered medical advice. All of the models, numbers and math I sourced from professional places but this is not a guarantee of the future only an approximation based on current information. Numbers change daily and so can these models!
🌐PART ONE
In this area you select a region to read the proper statistics data from tradingview. You can do global totals, country totals, or for a few places (AU, CA, CN, US) you can see state/province totals. Remember to SELECT ONLY ONE region.
🧮PART TWO
The Plots/Stats/Data section includes:
1. ) Plot the Days to Double Number of Confirmed
2. ) Plot the Infection Growth Ratio
3. ) Plot Fatality Risk Rate (Total Deaths / Total Outcomes)
4. ) Plot Overall Fatality Rate / Recovery Rate
5. ) Plot % of World Infected & % of USA Infected
6. ) Plot Daily New Deaths, Confirmed & Recovered
7. ) Plot Daily Change Percentages
🎱PART THREE
Forecasting Models and Settings:
1 .) Plot the % of Custom Population Infected (Vs. the Region Selected in Part 1 of Settings)
2 .) Plot the True Num. of Infectious (Death Model / DM)
3 .) Plot the Current and Next Weeks Cumulative Infection Projection (DM)
4 .) Plot Estimated Infection Rates? (DM)
5 .) Enable Basic Trajectory Projection?
6 .) Plot the Likelihood of > 0 **Infectious** in a Group (DM) for Today, Tomorrow and Next Week
7 .) Plot the True Num. of Infected (Confirmed/Tested Model)
8 .) Plot the Estimated Epidemiology for 7 and 14 Days Out (Hospital Beds, ICU Beds, Ventilator Units)
Planned But not completed
9.) SIR Epidemiology Model
10.) Exponential Growth Plot & Correlation
To use the Estimator for likelihood of Infected in N group of people you need to do 2 things. Select and use "Custom Population" as the population source for part 3. Then you need to enable "Custom Infected" as the source for the model. Then you enter your geographical area's population and confirmed cases. Its best to goto the smallest / most granular level of data available to accurately estimate the likelihood. So for instance in the order of least effective to most effective data source: global, country, state, county, city...etc.
If you do not understand what these terms or numbers represent, please read the source materials I have linked in the code, or use google. I dont have the time or expertise to explain all the various specific methods and terms included here. This entire project was a learning journey for me and I have zero experience in epidemiology so please excuse any errors I may have made. (and tell me, so I can change it!)
🔮Future Additions
If anyone has a model or stat they would like included I will be happy to add your code to this toolbox to make it more effective and give you credit here in the description. If you want to collaborate please message me.
📊Some Example Charts:
The Cryptorhythms Team wish you and your families all the absolute best of health!
P.S. Stay safe and act smart I dont think this will be the EOTW.
Function : Multiple Correlation
This script was written to calculate the correlation coefficient (Adjusted R-Squared) for one dependent and two independent variables.(3-way)
Pearson correlation method was used with exponential moving averages as the correlation calculation method.
Use your source ( i use "close" generally ) as the dependent variable.
Inspired by this article : www.real-statistics.com
The Adjusted R-Squared coefficient is used as output, but the R-Squared coefficient is also available in the code.
Adjusted R-Squared is often used for multiple correlations.
It also gives better results in large samples.
Here is the article about the difference of the two coefficients : www.investopedia.com
I wrote this function to increase the efficiency of my Dow Factor I used before.
When my research is over, I will apply the 3-factor correlation to my scripts.
I hope that I will achieve more efficient indicators and oscillators and even strategies.
In this command, I gave a few variable values and plotted them as an example.
I hope this function is useful in your work.
Finally, you can use periods as mutable variables.
The function is recovered from integer loads.
Best regards. Noldo
Volume Weighted DistanceThis script holds several useful functions from statistics and machine learning (ML) and takes measurement of a volume weighted distance in order to identify local trends. It attempts at applying ML techniques to time series processing, shows how different distance measures behave and gives you an arsenal of tools for your endeavors. Tested with BTCUSD.
REM: oddly enough, many people forget that the scripts in PS are generally just STUDIES, i.e. exercises, experiments, trials, and do not embody a final solution. Please treat them as intended ;))
[RS]ZigZag Percent Reversal - Multiple StatisticsMultiple Statistics from zigzag:
• Price range between swings.
• Bar range between swings.
returns maximum value, avg value and mean deviation.
if you find something missing, please leave a message bellow.
Price Move exceed % Threshold & BE Evaluation -Tom1traderwww.tradingview.com
Category is difficult with this one. I chose ROC as the closest as this measures the historical % of a given change amount.
This indicator is in a separate panel above or below the main chart. I use it only for Options trading to help with probability reckoning.
Use it (at your own risk) and the code freely and please ask any questions, glad to add detail / clarify and glad to know if you see I screwed something up. :-)
1. Plots when a percent move per candle is exceeded +exceeded is an "x" at top of panel and - is an "x" at panel bottom.
2. Plots (at last candle only) prices that are the selected % above and below the current close with thick black lines. TIP: For this to work best, in chart settings
"Scales" tab, check the "Indicator last value" and "No overlapping labels" check box.
3. Sums the number of times it occurs in a given number of candles ("Bars to sum . ." input).
TIP: On longer time frames (month+) reduce the length ("Bars . . sum" input) until get sums% plot.
4. Plots green and red lines for plus and minus sums as a percentage.
User inputs:
***** BTW did you know you can customize the time frame so one candle is (for example) 3 trading days?
1. Set the time frame of chart - NOTE this can be customized to what you need by scrolling to the bottom and adding the time frame you want i.e. 3 days or 2
weeks per candle. Remember these are trading times so 21 calendar days are 3 weeks or 15 trading days.
2. Choose the % threshold default 2% (+1.02 and its inverse for -) steps are 1/10th of a % (.001).
3. Choose the sum length("Bars . . sum . ") from 10 to 100 in number of candles.
Bottom line you can see the historical percentages and prices for a given percent move or can dial in a given break even (plus , minus or both) to see its past % occurrence and % move. One has to take into account changes in the market which show up clearly from the x above or below showing each occurrence (example: See more hits ("x"s) recently? Sum for recent length only to get more accurate reflection of market now.). Anyhow it is fun to play with and is part of how I do my own probability reckoning.
Partial CorrelationComputes the partial correlation between 2 symbols while removing the influence of a third.
Ex.:
Computes the correlation between AAPL and AMZN while removing the influence of SPX.
Multi-Timeframe VWAPShows the Daily, Weekly, Monthly, Quarterly, and Yearly VWAP.
Also shows the previous closing VWAP, which is usually very near the HLC3 standard pivot for the previous time frame. i.e. The previous daily VWAP closing price is usually near the current Daily Pivot. Tickers interact well with the previous Daily and Weekly closing VWAP.
Enabling the STDEV bands shows 3 separate standard deviation levels, defaulted at 1, 2, and 3. The lookback period for the bands is always changing with each new bar, since the standard deviation is calculated from the current bar to the beginning of the period. This is different from bollinger bands, as the lookback is constant (usually 20 periods is the textbook default).
The STDEV bands interval of interest can be changed from Day (D), Week (W), Month (M), Quarter (Q), Year (Y).
Tickers tend to bounce very well on Daily, Weekly, and Yearly VWAP (Yes... Year). Use this code and observe the Year VWAP on several major symbols through the past few years and eyes will be opened.
DownAfterLowProba// The script is useful to inspect probability:
// If previous day closed at lowest price for several days
// how often next day would be red bar
// As one can see gray lines indicate bars with lowest close. If next bar is green, increment diff_hi, overwise increment diff_lo
// Probability is counted as diff_lo / (diff_hi+diff_lo)
// One can copy script and change conditions to count other interesting probabilities
GEOMETRIC STANDARD DEVIATION BANDS v1 by @XeL_ArjonaGEOMETRIC STANDARD DEVIATION BANDS
Ver.1 By Ricardo M Arjona @XeL_Arjona
DISCLAIMER:
The Following indicator/code IS NOT intended to be a formal investment advice or recommendation by the author, nor should be construed as such. Users will be fully responsible by their use regarding their own trading vehicles/assets.
The embedded code and ideas within this work are FREELY AND PUBLICLY available on the Web for NON LUCRATIVE ACTIVITIES and must remain as is.
WHAT'S THIS?
This IS NOT the wheel "Re-Invention"... This is exactly what the name says: A pair of Envelope Bands to measure "volatility", constructed at statistical relation from within price series and their Rolling back MEAN (Simple Moving Average). YES, What Mr. Bollinger did and put it's name to this simple, cleaver and popular formula.
This time, I took the time to make another simple mod, but seems to me to be quite functional in REAL VOLATILE assets like in the example chart: TO USE THEIR GEOMETRIC MODE!!
Cheers!
Any feedback or public modification(s) are quite welcome to the community....!
@XeL_Arjona
Apr 28 2016
ATR%, ATR Timer and Range Expansion signalThese 3 indicators can be really useful.
The usage is fairly straightforward, if you understand price action, having an statistical edge like these provide can be useful.
Refer to Tim West's charts to learn more about range expansion bars.
The idea for the Atr% and Atr timer come from discussions I had with Yacine Kanoun, props to him for his contribution.
BACKTEST SCRIPT 0.999 ALPHATRADINGVIEW BACKTEST SCRIPT by Lionshare (c) 2015
THS IS A REAL ALTERNATIVE FOR LONG AWAITED TV NATIVE BACKTEST ENGINE.
READY FOR USE JUST RIGHT NOW.
For user provided trading strategy, executes the trades on pricedata history and continues to make it over live datafeed.
Calculates and (plots on premise) the next performance statistics:
profit - i.e. gross profit/loss.
profit_max - maximum value of gross profit/loss.
profit_per_trade - each trade's profit/loss.
profit_per_stop_trade - profit/loss per "stop order" trade.
profit_stop - gross profit/loss caused by stop orders.
profit_stop_p - percentage of "stop orders" profit/loss in gross profit/loss.
security_if_bought_back - size of security portfolio if bought back.
trades_count_conseq_profit - consecutive gain from profitable series.
trades_count_conseq_profit_max - maxmimum gain from consecutive profitable series achieved.
trades_count_conseq_loss - same as for profit, but for loss.
trades_count_conseq_loss_max - same as for profit, but for loss.
trades_count_conseq_won - number of trades, that were won consecutively.
trades_count_conseq_won_max - maximum number of trades, won consecutively.
trades_count_conseq_lost - same as for won trades, but for lost.
trades_count_conseq_lost_max - same as for won trades, but for lost.
drawdown - difference between local equity highs and lows.
profit_factor - profit-t-loss ratio.
profit_factor_r - profit(without biggest winning trade)-to-loss ratio.
recovery_factor - equity-to-drawdown ratio.
expected_value - median gain value of all wins and loss.
zscore - shows how much your seriality of consecutive wins/loss diverges from the one of normal distributed process. valued in sigmas. zscore of +3 or -3 sigmas means nonrandom realitonship of wins series-to-loss series.
confidence_limit - the limit of confidence in zscore result. values under 0.95 are considered inconclusive.
sharpe - sharpe ratio - shows the level of strategy stability. basically it is how the profit/loss is deviated around the expected value.
sortino - the same as sharpe, but is calculated over the negative gains.
k - Kelly criterion value, means the percentage of your portfolio, you can trade the scripted strategy for optimal risk management.
k_margin - Kelly criterion recalculated to be meant as optimal margin value.
DISCLAIMER :
The SCRIPT is in ALPHA stage. So there could be some hidden bugs.
Though the basic functionality seems to work fine.
Initial documentation is not detailed. There could be english grammar mistakes also.
NOW Working hard on optimizing the script. Seems, some heavier strategies (especially those using the multiple SECURITY functions) call TV processing power limitation errors.
Docs are here:
docs.google.com
Indicators: Three included :: IFT on CCI, Z-Score and R-Squared*** Full description in the comment below ******
This chart has 3 indicators:
- Chande's R2
- Zscore
- Inverse Fisher Transform on CCI
Feel free to "make mine" (click on the SHARE button) and use these indicators in your charts.