17

In Pandas 0.19.2++: def Bolinger_Bands(stock_price, window_size, num_of_std): rolling_mean = stock_price.rolling(window=window_size).mean() rolling_std = stock_price.rolling(window=window_size).std() upper_band = rolling_mean + (rolling_std*num_of_std) lower_band = rolling_mean - (rolling_std*num_of_std) return rolling_mean, ...


12

The answer to your question about the theoretical justification for technical analysis depends on the price series being analyzed. There is some evidence for a few technical indicators to have predictive value. In general, though, there is little theory behind technical analysis apart from an appeal to psychology. Indicators There are many indicators used by ...


11

def bbands(price, length=30, numsd=2): """ returns average, upper band, and lower band""" ave = pd.stats.moments.rolling_mean(price,length) sd = pd.stats.moments.rolling_std(price,length) upband = ave + (sd*numsd) dnband = ave - (sd*numsd) return np.round(ave,3), np.round(upband,3), np.round(dnband,3) sp['ave'], sp['upper'], sp['...


9

I believe that the answers given here are incorrect as they return the sample standard deviation while the the population measure is the correct calculation for Bollinger Bands. The bands usign the sample calc will be too wide. Pandas does not appear to allow a choice between the sample and population calculations for either solution presented here. sd = pd....


9

The Exponentially Weighted Moving Average (EWMA for short) is characterized my the size of the lookback window $N$ and the decay parameter $\lambda$. The corresponding volatility forecast is then given by: $$ \sigma_t^2 = \sum_{k = 0}^N \lambda^k x_{t-k}^2 $$ Sometimes the above expression is normed such that the sum of the weights is equal to one. ...


8

Usually the formula for the sample variance of a stock is given by: \begin{equation} Var(R_{i}) = E (R_t - E(R_t))^2 \end{equation} If you are using daily data to compute the variance then the second term: $E(R_t) \approx 0$, therefore you can drop it from the computation. Which yields: \begin{equation} Var(R_{i}) \approx E (R_t)^2 \end{equation} ...


7

Really great question. Having studied finance academically, in an academic setting, you will always be told that technical analysis is non-sense. In the world of pure academics, the efficient market hypothesis is still the preferred way of thinking. Furthermore, academics will point out that empirical data and historical back-tests thoroughly disprove ...


6

The point of the recursive formula is that you can easily calculate the current EWMA if you have last period's EWMA. Equivalently, you can calculate all the weights directly and sum them that way. $$ \text{EWMA}_t = S_t(1-\lambda) + S_{t-1}(1-\lambda)\lambda + S_{t-2}(1-\lambda)\lambda^2 + \dots $$ where $\lambda$ is your smoothing parameter between $0$ and ...


5

My understanding, in that context, is that signal indicates that you want to hold a share (signal is 1) or hold no shares (signal is zero). Therefore taking the diff will tell you if you want to buy (signal zero to 1, diff is 1), sell (signal 1 to zero, diff is -1) or do nothing (signal stays at zero or stays at 1, diff is zero).


5

Did you try solving for $w_k$? $$\bar{r}_t = \sum_{k=0}^p w_k r_{t-k}$$ $$\bar R = W R$$ Since you probably have $t>>k$, you can solve for $W$ using OLS $$\bar R = W R +\varepsilon$$ -- UPDATE You can try applying Kalman filter. Here, your state evolution is $$r_t=\mu+\varepsilon_t$$. You introduce new vector $x_t=(r_t, r_{t-1}, \dots, r_{t-p+1})$...


5

I've been waiting for someone to ask this question since every published method with which I am familiar propose weights which converge to $1$ only when the numbers of terms goes to infininity. This is quite annoying as it either requires we use a biased estimate which underestimates the true exponentially weighted mean or use back-dated information to ...


5

The theoretical justification for technical analysis (TA) is less about market (in)efficiency; and more about prices as a signal of sentiment and positioning biases, that are neither always neutral nor unbiased. Anecdotes are cheap; but sometimes still helpful. In a past job, I was a traditional sell-side fundamental market strategist. But I was sat next to ...


4

Thanks @Aksakal for suggesting Kalman Filter. Here I provide more details. We will view it as a state-space model: $$ \begin{split} z_t &= A_t z_{t-1} + B_t u_t + \epsilon_t, \\ y_t &= C_t z_t + D_t u_t + \delta_t, \\ \epsilon_t &\sim \mathcal{N}(0, Q_t),\ \delta_t \sim \mathcal{N}(0, R_t), \end{split} $$ where $z_t$ is the latent variable, $y_t$...


4

As can be seen from this example from Yahoo!Finance this should not happen (click on "+ The adjusted close"): https://help.yahoo.com/kb/finance/SLN2311.html?impressions=true Another more complete example can be found here: http://luminouslogic.com/how-to-normalize-historical-data-for-splits-dividends-etc.htm So my explanation is that this is a glitch in ...


4

Note: Assuming you're a bit of a beginner trying to learn the ropes of how this whole process works at a high level, I can definitely make a couple recommendations (if I'm interpreting that wrong then I apologize if the explanation below isn't what you're after). If you're trying to learn some basic backtesting fundamentals, while QuantStart is an amazing ...


3

The current data point is said to have age 0, the previous has age 1, and so on going backwards. For a straight N period moving average of the form $\frac{1}{N}(x_t+x_{t-1}+\cdots+x_{t-N+1})$ it is easy to see that the average age of the data is $\frac{N-1}{2}$. Sometimes this is stated in term of "centering": a 3 period moving average is centered on the ...


3

Recently I came across interesting platform. https://www.quantopian.com/ they offer exactly what you need and for free. Basically, you code your algo in python, they provide data using api and backtesting. Hope it helps.


3

I have used https://www.tickdata.com/ and https://www.quantgo.com/ I enjoy the simplistic nature of obtaining data that they use, so for someone new to quantitative finance like you, I recommend that you try them. https://www.quandl.com also have excellent quality data, easy to use APIs


3

The TA_lib Technical Analysis library here has open source code for numerous indicators.


3

Moving averages of prices are closely related to moving averages of price differences. In particular, if the price is a cumulative sum of historical price differences, $$ p_t = \sum_{j=0} \delta p_{t-j} $$ then a moving average of prices with weights $w_k$ can be written as a moving average of price differences with weights $v_k$ $$ \sum_{k=0}w_k p_{t-k} =...


3

Welcome to Quant SE. Unfortunately there is no closed form formula for computing the american contract value $\max_{\tau}E^P\left[e^{-r\tau}(A_{\tau} - K)\right]$, so you have to resort to an american monte carlo method or a 2 dimensional PDE finite differences scheme for the joint dynamics $$ dS_t/S_t = (r - q) dt + \sigma dW_t \\ dA_t = d\left(\frac{1}{t} ...


3

Questions: 1=> Does anyone have a suggestion to determine a trend correctly. My answer is in general and an opinion. Hong Kong Stock Exchange is third largest market behind Tokyo and Shanghai and most volatile market in the world. It is related to Singapore, Shanghai and Shenzhen, Korea, Taiwan and other famous Asian markets. For rough overall trends, ...


2

The Technical Analysis of Financial markets is considered as a milestone of the matter. I suggest to read that before starting to test your strategy. It explains well the use of each indicator, providing the economic reason behind that and when it is useful to use that; moreover, the book deals the stock market with mainly, as you need for. In my humble ...


2

A very good reference can be found here: http://www.asiapacfinance.com/trading-strategies/technicalindicators


2

First of all, I do not believe the "optimal smoothing" of an estimator (like the mean or the variance) and the "regression case" are the same. The smoothing of an existing estimator (like mean or variance in the blog post), is an univariate problem, where the regression is a multivariate one. In the regression case, you should be able to change the ...


2

Try to plot the rolling mean against your quotes for SP and see if it makes sense. Although you line of code to compute the rolling mean is correct, there might be something wrong in the data that you pass as input.


2

It is unlikely that you could beat the market in the long-term with such a simple strategy. But, since you ask about optimization (not real trading), all you have to do to is run the optimization tests over and over again with different parameters until you find the exact moving average combinations that would predict the past perfectly. The only problem is ...


2

The moving average is determined as of the close of a particular day. Then to calculate the P&L you have to multiply today's state (1 or -1) by TOMORROWs return, instead you are using todays! So for example the formula in H13 needs to be E14/E13-1 and not as you incorrectly have it E13/E12-1. HTH


2

If you are by any chance familiar with R take a look at the following post LINK It offers an easy way to obtain data from Yahoo finance, Google etc. Cheers. PS: Jameson, I am in a similar situation as you are. I was digging a bit deeper a found also Quandl


2

If you are just looking for basic intraday data (open, high, low, close, and volume data), you can check out Alpha Vantage. File can either be in json or csv format. They provide 500 API requests per day. If you require a higher API volume limit and technical support, you need to sign up for their premium membership. Another API-based data vendor is IEX ...


Only top voted, non community-wiki answers of a minimum length are eligible