Volume CompressorTurns volume into a more informative representation, ready to be further analyzed
...
Rationale
Volume
Back in the "before the quant" days I was a big fan of market & volume profile. Thing is J. Steidlmayer had lotta different ideas & works aside of profiling, it's just most of them ain't got to mainstream, one of them was "Hot / Cold volume" (yes, you can't really google it). From my interpretation, the idea was that in a given asset there is a usual constant volume that stays there no matter what, and if it ever changes it changes very slow and gradually; and there's another kind of, so to say, 'active' volume that actually influences price dynamics and very volatile by its nature. So I've met concept lately, and decided to quantify & model it one day when I'll have an idea how. That day was yesterday.
Compression
When we do music we always use different kinds of filters (low-pass, high pass, etc) for equalization and filtering itself. That stuff we use in finance as well. What we also always use in music are compressors, there dynamic processors that automatically adjust volume so it will be more consistent. Almost all the cool music you hear is compressed (both individual instruments (especially vocals) and the whole track afterwards), otherwise stuff will be too quite and too weak to flex on it, and also DJing it would be a nightmare. I am a big adept of loudness war. So I was like, how can I use compression in finance, when ima get an idea? That day was yesterday as well.
Volume structure
Being inspired by Steidlmayer's idea, I decided to distinguish volume this way:
1) Passive / static volume. The ~ volume that's always there no matter what (hedges, arbitrages, spread legs, portfolio parts etc etc), doesn't affect things;
2) Active / dynamic volume. The volume that flows from one asset to another, really matters and affects things;
3) Excess volume. The last portion of number 2 volume, that doesn't represent any powerful value to affect things.
Now it's clear that we can get rid of number 1 and number 3, the components that don't really matter, and concentrate on number 2 in order to improve information gain, both for ourselves and for the models we feed this data. How?
Model
I don't wanna explain it all in statistical / DSP way for once.
First of all, I think the population of volumes is log-normally distributed, so let's take logs of volumes, now we have a ~ normally distributed data. We take linearly weighted mean, add and subtract linearly weighted standard deviation from it, these would be our thresholds, the borders between different kinds of volumes explained before.
The upper threshold is for downward compression, that will not let volume pass it higher.
The lower threshold is for upward compression, all the volumes lower than this threshold will be brought up to the threshold's level.
Then we apply multipliers to the thresholds in order to adjust em and find the sweet spots. We do it the same way as in sound engineering when we don't aim for overcompression, we adjust the thresholds until they start to touch the signal and all good.
Afterwards, we delete all the number 1 and number 3 volume, leaving us exclusively with the clear main component, ready to be processed further.
We return the volumes to dem real scale.
About the parameters, based on testing I don't recommend changing the thresholds from dem default values, first of all they make sense statistically and second they work as intended.
Window length can and should be adjusted, find your own way, or leave the default value. ML (moving location) length is up to you as well.
So yeah, you can see now we can smooth the data and make it visually appealing not only by applying a smooth filter over it.
All good TV?
Statistics
All Central Bank Interest RatesWith another period of mass interest rates manipulation, I created this indicator to show them all. It reveals latest interest ratest (at a time of the last update) and a date when each central bank manipulated the rates.
If you would rather view a single pair data check: and
Portfolio Laboratory [Kioseff Trading]Hello!
This script looks to experiment with historical portfolio performance. However, a hypothetical cash balance is not used; weighted percentage increases and decreases are used.
You can select up to 10 assets to include in the portfolio. Long and short positions are possible.
Show in the image are the portfolio's weight, the total return of the portfolio and the total return of the asset on the chart over the selected timeframe.
Shown in the image above are the constituents of the portfolio, which can include any asset, the weighted percentage gain/loss of the constituents in addition to 10 major indices and their respective total percentage gain/loss over the timeframe.
Shown in the image above are the dividend yield % of the portfolio and relevant portfolio metrics - ex-post calculations are applied and are predicated on simple returns.
Shown in the image above is a portfolio of all short positions; portfolio calculations adjusted to the modifications.
Also shown is a change in the index the portfolio is calculated against. I have been asked a few times to include NIFTY 50 in my scripts - I made sure this was achieved, lol!
Show in the image is a performance line of performance of percentage increases/decreases for the index calculated against, the asset on the chart, and the portfolio.
All lines start simultaneously on the selected start date at the close price of the session for the asset on your chart.
However, the right-hand scale, whether displaying price or percent, cannot be used to assess the performance of each line - they are useful for visualization only and can extend below zero on a low-priced asset. Calculations will not execute correctly when selecting a start date prior to any asset in the portfolio's first trading session; calculations do not begin on the first bar of the asset on your chart.
I decided to code the script this way so statistics remain fixed when moving from asset to asset!
To compensate for this limitation, I included a label plot and background color change at the first session in which all assets in the portfolio had at least one bar of price data. You can adjust the calculation start date to the date portrayed on the label to test al possible price data!
The statistics table, and the performance lines, can be hidden in the user input section.
I plan on putting a bit more work into this script. I have some ideas on what to include; however, any input is greatly appreciated! If there's something you would like me to include please let me know.
@scheplick mentioned me in a script he recently coded:
My inspiration came from his script! I thank him for that!
Z-Score with Buy & Sell SignalsThis is my open-source indicator of z-score with buy and sell indicators.
I see there are other z-score indicators, I just am particular about how I like my z-scores calculated and so decided to make my own and add buy and sell signals to help guide me. And I figured I could share it openly here!
What is a Z-Score
A z-score is a statistical measures of the distance, in standard deviations, a value is from its given mean. It is expressed as a standard deviation (or SD). The further a value (in this case, a stock) is from their mean, the more likely a regression to the mean is possible (i.e. a return to the average). So if a stock is trading at 3 standard deviations away from its mean, then we can anticipate it wanting to regress back towards 1 to 0 standard deviations from its mean (i.e. sell off back to a value that brings it closer to that SD).
The inverse is true if it is trading below.
Z-Scores and Stocks
Stocks, like everything in nature, like to trade between -1 and +1 SD away from its mean. Anything above this, we can interpret that there is "stress" on the stock. Anything over 2.50 is tremendous stress on the stock and we can anticipate that it will want to revert to its mean in the near future and bring that value down to at least 1, ideally between the -0.5 and 0.5 range.
Please note, I set the standard VERY high for the indicator to issue a buy and sell signal (/=2.50). Lately with the volatility, stocks have been entering these ranges frequently and so there have been plenty of signals, but traditionally in a stable environment you may not get these signals. I set the bar extremely high because I want to avoid false buy and sell signals (you will still get them though, nothing is perfect!). So the value in this indicator is in interpreting the actual z-score itself, so please be sure you understand exactly what the Z-score is (see the description above).
How the indicator works
The indicator works by calculating the average Z-Score between a stocks high and low. This indicator will present the average deviation a stock has from its high and low average. The higher the Z-Score, the more "overbought" the stock is. The lower the z-score, the more "oversold" the stock is. It uses the previous 500 candles worth of data to calculate its SMA and its Standard deviation in order to calculate the z-score.
Anytime a stock trades 2.50 SDs or more above or below its mean, you will be presented with a Buy or Sell signal, as generally, statistically speaking, after something has travelled 2.50 SDs aware from its mean, there is an increased probability of a reversion happening.
You can use this indicator to determine whether the stock is trading within normal parameters or not and to help you in your analysis as to whether or not a stock could be shorted or longed.
I personally like this for swing trading on the 1 hour chart; however, this can be used on any time from 1 minute to 1 hour. It also allows you to track a stocks progress in its reversion to the mean.
Examples of it in Use:
Gold ETF (ARCA: GLD) on 1 minute
Dow Jones ETF (ARCA: DIA) on 1 minute (my favourite Stock!)
SPY ETF (ARCA: SPY) on 1 hour chart
Disclaimer:
This is not meant to be placed as a sole and single strategy. It should be used in COJUNCTION with your other strategies to help you make a determination.
No indicator is infallible and should never be relied on 100%!
Please let me know your questions/comments/experiences/recommendations below!
Thanks everyone!
Market Profile Fixed ViewSome instruments does not provide any volume information, therefore, as a fixed volume profile user, I needed a fixed market profile indicator to use the same principles, regardless of whether the volumes are available or not.
This script draws a market profile histogram corresponding to price variations within a specific duration, you only need to specify Start and End date/time values to see the histogram on your chart.
Details
Two lines corresponding to highest/lowest prices are displayed around the histogram
The redline corresponds to the POC (point of control)
Options
Start calculation
End calculation
Bars number (histogram resolution, currently locked to a max value of 50 bars)
Display side/Width (allows to modify size of bars, to the left or to the right)
Bars/Borders/POC Color customization
Notes
This script will probably be updated (to add VAH/VAL zones, and maybe other options). However, some common market profile attributes have not been implemented yet since I don't really use them)
MonthlyReturnsVsMarketLibrary "MonthlyReturnsVsMarket" is a repackaging of the script here
Credits to @QuantNomad for orginal script
Now you can avoid to pollute your own strategy's code with the monthly returns table code and just import the library and call displayMonthlyPnL(int precision) function
To be used in strategy scripts.
SymMatrixTableSimple Example Table for Displaying Price, RSI, Volume of multiple Tickers on selected Timeframe
Displays Price, RSI and Volume of 3 Tickers and Timeframe selected by user input
Conditional Table Cell coloring
Price color green if > than previous candle close and red if < previous candle close
RSI color green if < 30 and red if > 70 (RSI14 by default)
Volume color green if above average volume and red if less than that (SMA20 volume by default)
Can turn on/off whole table, header columns, row indices, or select individual columns or rows to show/hide
// Example Mixed Type Matrix To Table //
access the simple example script by uncommenting the code at the end
Basically I wanted to have the headers and indices as strings and the rest of the matrix for the table body as floats, then conditional coloring on the table cells
And also the functionality to turn rows and columns on/off from table through checkboxes of user input
Before I was storing each of the values separately in arrays that didn't have a centralized way of controlling table structure
so now the structure is :
- string header array, string index array
- float matrix for table body
- color matrix with bool conditions for coloring table cells
- bool checkboxes for controlling table display
Coins x Value CalculatorThrough this script you will be able to calculate in real time your total number of coins correlated to the value that is at that moment, so you will not need to log into the brokerage or be simulating sales to know what your total value is in the asset...
To use it, just add it to your favorites and then right after adding it to the chart, clicking on its gear, a field will appear for you to enter your total amount of coins corresponding to that chart, then immediately calculate the value that is the total of your coins , will also show the entire history of appreciation or devaluation that its capital corresponding to that asset had.
Translator Portuguese:
Através desse script você poderá calcular em tempo real o seu numero de moedas total correlacionado ao valor que se encontra naquele momento ,assim nao precisara logar na corretora ou ficar simulando vendas para saber qual valor esta seu total no ativo...
Para usar basta adicionar ele a seus favoritos e então logo após adicionar ao gráfico, clicando na engrenagem dele aparecera um campo para voce digitar sua quantidade de moedas total correspondente a aquele gráfico logo em seguida calculara imediatamente o valor que se encontra o total de suas moedas, também mostrara todo o histórico de valorização ou desvalorização que seu capital correspondente aquele ativo teve.
Wick/ Long / Short Monitor- Wanted to check if price movement on a particular candle for day trading is less than my target movement.
- A user can place this on chart and on the candles where the price movement is not as predicted from the open price, a red * will be placed above or below the bar
- it is best used in fixed profit scalping strategy
All Time LowThis script is to remind you of how much you would lose if the price went down to the all time low.
This will make you think twice about your purchases!
Sell Half On DoubleNotes:
- In settings leave 0 for actual price, or set a new price and the SHOD levels will change too.
Squeeze Detector 3000This is a bespoke, unfinished script for Kyle.
It is primarily designed to be used to provide useful data for unusually volatile stocks premarket, and for some other situations too.
Featuring:
Pre/post market volume
Short data
RVOL
ATR and turnover
Taylor RuleThe Taylor rule is a simple formula that John Taylor devised to guide policymakers. It calculates what the federal funds rate should be, as a function of the output gap and current inflation. Here, we measure the output gap as the difference between potential output and real GDP. Inflation is measured by changes in the CPI, and we use a target inflation rate of 2%. We also assume a steady-state real interest rate of 2%.
Esqvair's Neural Reversal Probability IndicatorIntroduction
Esqvair's Neural Reversal Probability Indicator is the indicator that shows probability of reversal.
Warning: This script should only be used on 1 minute chart.
How to use
When a signal appears (by default it is a green bar), a reversal should be expected.
The signal appears when the indicator value >= Threshold.
If you want more signals, you must lower the threshold, if less, you must increase the threshold.
For some assets, like Forex pairs, you have to optimize the threshold yourself, but for most stocks, the default threshold works well.
How well a threshold fits an asset depends on the volatility of the asset.
For most assets, the indicator ranges from 35 to 75.
Settings
Smoothing - The default is 1, which means no smoothing. Indicator smoothing by SMA.
Threshold - default 71.0 is responsible for the occurrence of signals, read "How to use" part to learn more
The Indicator
This indicator is a pre-trained neural network that was trained outside of TradingView and then its structure and weights values were converted to PineScript.
Warning: A neural network is a black box in the sense that although it can approximate any function, studying its structure will not give you any idea about the structure of the function being approximated.
Possible questions
Why does the indicator value most time range from 35 to 75 when the probability should ranges from 0 to 100?
-Due to some randomness in the markets, a neural network can never be 100% sure.
What data was used to train the neural network?
-This was BTCUSD 1 minute chart data from 02/05/2020 to 02/05/2022.
Where did you train the neural network and convert it to PineScript?
-I used a programming language that I know.
CanvasLibrary "Canvas"
A library implementing a kind of "canvas" using a table where each pixel is represented by a table cell and the pixel color by the background color of each cell.
To use the library, you need to create a color matrix (represented as an array) and a canvas table.
The canvas table is the container of the canvas, and the color matrix determines what color each pixel in the canvas should have.
max_canvas_size() Function that returns the maximum size of the canvas (100). The canvas is always square, so the size is equal to rows (as opposed to not rows multiplied by columns).
Returns: The maximum size of the canvas (100).
get_bg_color(color_matrix) Get the current background color of the color matrix. This is the default color used when erasing pixels or clearing a canvas.
Parameters:
color_matrix : The color matrix.
Returns: The current background color.
get_fg_color(color_matrix) Get the current foreground color of the color matrix. This is the default color used when drawing pixels.
Parameters:
color_matrix : The color matrix.
Returns: The current foreground color.
set_bg_color(color_matrix, bg_color) Set the background color of the color matrix. This is the default color used when erasing pixels or clearing a canvas.
Parameters:
color_matrix : The color matrix.
bg_color : The new background color.
set_fg_color(color_matrix, fg_color) Set the foreground color of the color matrix. This is the default color used when drawing pixels.
Parameters:
color_matrix : The color matrix.
fg_color : The new foreground color.
color_matrix_rows(color_matrix, rows) Function that returns how many rows a color matrix consists of.
Parameters:
color_matrix : The color matrix.
rows : (Optional) The number of rows of the color matrix. This can be omitted, but if used, can speed up execution.
Returns: The number of rows a color matrix consists of.
pixel_color(color_matrix, x, y, rows) Get the color of the pixel at the specified coordinates.
Parameters:
color_matrix : The color matrix.
x : The X coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
y : The Y coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
rows : (Optional) The number of rows of the color matrix. This can be omitted, but if used, can speed up execution.
Returns: The color of the pixel at the specified coordinates.
draw_pixel(color_matrix, x, y, pixel_color, rows) Draw a pixel at the specified X and Y coordinates. Uses the specified color.
Parameters:
color_matrix : The color matrix.
x : The X coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
y : The Y coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
pixel_color : The color of the pixel.
rows : (Optional) The number of rows of the color matrix. This can be omitted, but if used, can speed up execution.
draw_pixel(color_matrix, x, y, rows) Draw a pixel at the specified X and Y coordinates. Uses the current foreground color.
Parameters:
color_matrix : The color matrix.
x : The X coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
y : The Y coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
rows : (Optional) The number of rows of the color matrix. This can be omitted, but if used, can speed up execution.
erase_pixel(color_matrix, x, y, rows) Erase a pixel at the specified X and Y coordinates, replacing it with the background color.
Parameters:
color_matrix : The color matrix.
x : The X coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
y : The Y coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1".
rows : (Optional) The number of rows of the color matrix. This can be omitted, but if used, can speed up execution.
init_color_matrix(rows, bg_color, fg_color) Create and initialize a color matrix with the specified number of rows. The number of columns will be equal to the number of rows.
Parameters:
rows : The number of rows the color matrix should consist of. This can be omitted, but if used, can speed up execution. It can never be greater than "max_canvas_size()".
bg_color : (Optional) The initial background color. The default is black.
fg_color : (Optional) The initial foreground color. The default is white.
Returns: The array representing the color matrix.
init_canvas(color_matrix, pixel_width, pixel_height, position) Create and initialize a canvas table.
Parameters:
color_matrix : The color matrix.
pixel_width : (Optional) The pixel width (in % of the pane width). The default width is 0.35%.
pixel_height : (Optional) The pixel width (in % of the pane height). The default width is 0.60%.
position : (Optional) The position for the table representing the canvas. The default is "position.middle_center".
Returns: The canvas table.
clear(color_matrix, rows) Clear a color matrix, replacing all pixels with the current background color.
Parameters:
color_matrix : The color matrix.
rows : The number of rows of the color matrix. This can be omitted, but if used, can speed up execution.
update(canvas, color_matrix, rows) This updates the canvas with the colors from the color matrix. No changes to the canvas gets plotted until this function is called.
Parameters:
canvas : The canvas table.
color_matrix : The color matrix.
rows : The number of rows of the color matrix. This can be omitted, but if used, can speed up execution.
Vertical LinesSPEICALLY USED FOR BANKNIFTY RIGHT NOW
Draw vertical lines based on script, based on many conditions :
Conditions used right now are :
1. its a wednesday and the range of day is less than 600 points
Open InterestSimple indicator that shows the open interest of whatever crypto contract you're looking at in candlestick form.
If it doesn't show anything then Tradingview doesn't have the open interest data for that contract.
At the time of publishing there's data for Binance, Bitmex and Kraken.
You can change the colors in the settings.
Multi Asset + Correlation OverlayFrom time to time, you may want to overlay multiple assets on the same chart instead of using multi-chart views. This can be a much cleaner way of viewing and comparing multiple assets. There is some functionality built into TradingView that lets you do this to a certain extent, but I wanted additional options, correlation labeling and ways to adjust the overlay location. So, today I am releasing to the community my Multi-Asset + Correlation Overlay script / indicator.
What is does: This script allows you to overlay the price of any ticker onto your chart. It also labels the line with the ticker name, and calculates / labels the correlation coefficient of your newly overlayed asset.
How to use it: Add the indicator to your chart. Then, go into the indicator settings to set the ticker of the asset you want to pull in along with how you want to "offset" it. Your 2 tickers may not be priced near each-other, so the offset setting allows you to pull the ticker you added up/down to better visually align with your chart's price range/layout. For instance, if the asset you added is priced $400 higher than the underlying chart price, you may want to set the offset to -400.
If you would like to add multiple tickers and multiple overlays, you can do that by just adding the indicator to your chart more than once. The color is adjustable, and the ticker of the asset will print to the right of the line representing the asset price. The script also calculates the correlation coefficient between the ticker overlay and the underlying chart asset. The correlation coefficient prints to the right of the ticker.
Swap Trading Pair Price This script was inspired by STEPN, where we should always be aware of the price change between GSTUSDT and SOLUSDT to make better profit.
We can easily compare any trading pair price from any desired exchange we want even if they don't have direct trading pair on certain exchange to monitor thier price correlation.
We can define the lower range we are prefer to sell GST into SOL and the upper range to buy SOL into GST
[Mubeen] True Bar VolumeTrue Bar Volume, or TB Volume, is an indicator that measures the volume against the price action that has occurred.
Volume can sometimes be miss leading as it does not necessary show whether it had an impact on the price of the underlying, as one individual (represented as one volume) who has put $100 into the underlying can impact the underlying the same as hundred individuals (represented as hundred volume) putting $1 into the underlying: but the volume will widely differ and can cause confusion for outsiders. With the True Bar indicator, it aims to show abnormal behaviour in the price change against the amount of volume that was stated. It visualises the effect of the volume on the underlying by colour coding the different levels of True Bar results, divided into Red, Yellow, Green, Purple.
Red indicates that the price has changed way out of portion compared with the volume that was seen. It is compared against the highest TB Volume values through selected periods and once the volume as broken out of the high, it is considered an anomaly.
Yellow indicates that the TB Volume values are representing the mean values so it is considered as normal trading activity. Spikes in yellow values can also be seen as rise in high interest in the underlying.
Green indicates that the TB Volume values are under performing in market activity.
Purple indicates that is it a null result as investors might be looking for a better entry into a market, or seen as interest is low in the market.
TB Volume should not be used on it's own as it only gives a reporting measurement of the volume performance, which may be meaningless without the supplementation of other indicators.
CoinFlip Indicator + StrategyFlip a coin every Monday.
Heads, go long. Tail, go short. Stoploss at 1 ATR, and Take profit at 1 ATR too. 1:1 risk to reward ratio.
After backtesting 2018, 2019, and 2020 with 28 major currency pairs. We are getting close to a 50% win rate with an 8% standard deviation.
Believe it or not, this simple performs better than lots of the popular indicators out there.
Don't believe me? Test it out yourself!!
Use this as a baseline for your backtest and expose all your other crappy indicators :)
HOW TO USE:
As an indicator:
1. Use a daily chart
2. Green arrow below chart, go long, set a stop-loss at 1 x ATR, and take profit at 1 x ATR
3. Red arrow above chart, go short, set a stop-loss at 1 x ATR, and take profit at 1 x ATR
As an indicator:
1. In setting, set a year to test (default to 2020)
2. Go to the strategy tester and observe the stats
P.s. You can also set the period of the ATR to another value other than 14 periods.
OrdinaryLeastSquaresLibrary "OrdinaryLeastSquares"
One of the most common ways to estimate the coefficients for a linear regression is to use the Ordinary Least Squares (OLS) method.
This library implements OLS in pine. This implementation can be used to fit a linear regression of multiple independent variables onto one dependent variable,
as long as the assumptions behind OLS hold.
solve_xtx_inv(x, y) Solve a linear system of equations using the Ordinary Least Squares method.
This function returns both the estimated OLS solution and a matrix that essentially measures the model stability (linear dependence between the columns of 'x').
NOTE: The latter is an intermediate step when estimating the OLS solution but is useful when calculating the covariance matrix and is returned here to save computation time
so that this step doesn't have to be calculated again when things like standard errors should be calculated.
Parameters:
x : The matrix containing the independent variables. Each column is regarded by the algorithm as one independent variable. The row count of 'x' and 'y' must match.
y : The matrix containing the dependent variable. This matrix can only contain one dependent variable and can therefore only contain one column. The row count of 'x' and 'y' must match.
Returns: Returns both the estimated OLS solution and a matrix that essentially measures the model stability (xtx_inv is equal to (X'X)^-1).
solve(x, y) Solve a linear system of equations using the Ordinary Least Squares method.
Parameters:
x : The matrix containing the independent variables. Each column is regarded by the algorithm as one independent variable. The row count of 'x' and 'y' must match.
y : The matrix containing the dependent variable. This matrix can only contain one dependent variable and can therefore only contain one column. The row count of 'x' and 'y' must match.
Returns: Returns the estimated OLS solution.
standard_errors(x, y, beta_hat, xtx_inv) Calculate the standard errors.
Parameters:
x : The matrix containing the independent variables. Each column is regarded by the algorithm as one independent variable. The row count of 'x' and 'y' must match.
y : The matrix containing the dependent variable. This matrix can only contain one dependent variable and can therefore only contain one column. The row count of 'x' and 'y' must match.
beta_hat : The Ordinary Least Squares (OLS) solution provided by solve_xtx_inv() or solve().
xtx_inv : This is (X'X)^-1, which means we take the transpose of the X matrix, multiply that the X matrix and then take the inverse of the result.
This essentially measures the linear dependence between the columns of the X matrix.
Returns: The standard errors.
estimate(x, beta_hat) Estimate the next step of a linear model.
Parameters:
x : The matrix containing the independent variables. Each column is regarded by the algorithm as one independent variable. The row count of 'x' and 'y' must match.
beta_hat : The Ordinary Least Squares (OLS) solution provided by solve_xtx_inv() or solve().
Returns: Returns the new estimate of Y based on the linear model.
FunctionPolynomialFitLibrary "FunctionPolynomialFit"
Performs Polynomial Regression fit to data.
In statistics, polynomial regression is a form of regression analysis in which
the relationship between the independent variable x and the dependent variable
y is modelled as an nth degree polynomial in x.
reference:
en.wikipedia.org
www.bragitoff.com
gauss_elimination(A, m, n) Perform Gauss-Elimination and returns the Upper triangular matrix and solution of equations.
Parameters:
A : float matrix, data samples.
m : int, defval=na, number of rows.
n : int, defval=na, number of columns.
Returns: float array with coefficients.
polyfit(X, Y, degree) Fits a polynomial of a degree to (x, y) points.
Parameters:
X : float array, data sample x point.
Y : float array, data sample y point.
degree : int, defval=2, degree of the polynomial.
Returns: float array with coefficients.
note:
p(x) = p * x**deg + ... + p
interpolate(coeffs, x) interpolate the y position at the provided x.
Parameters:
coeffs : float array, coefficients of the polynomial.
x : float, position x to estimate y.
Returns: float.