In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces how to use Python to achieve random relative strength index StochRSI, the article is very detailed, has a certain reference value, interested friends must read it!
Random relative strength index, referred to as StochRSI, is a technical analysis index, which is used to determine whether assets are overbought or oversold, as well as to determine the current market situation. As the name implies, StochRSI is a derivative of the standard relative strength index (RSI), so it is regarded as an index that can measure the index. It is an oscillator that fluctuates above and below the centerline.
StochRSI was first described in a book entitled "The NewTechnical Trader" written by Stanley Kroll and Tushar Chande in 1994. It is often used by stock traders.
1. How does StochRSI work?
The StochRSI is generated from the standard RSI by applying the random oscillator generation formula. The result is a single digital rating that swings up and down in a range of 0-1 around the centerline (0.5). However, the modified version of StochRSI multiplies the result by 100, so the value is between 0 and 100 rather than between 0 and 1. It is also common to refer to the simple moving average (SMA) over a period of three days and the StochRSI trend as signal lines designed to reduce the risk of false signal trading.
The standard random volatility index formula depends on the closing price of the asset and the highest and lowest prices during the set period. However, when using a formula to calculate StochRSI, it uses RSI data directly (regardless of price).
Stoch RSI = (Current RSI-Lowest RSI) / (Highest RSI-Lowest RSI)
Like standard RSI, the most common time period used by StochRSI is 14. The 14 cycles involved in the StochRSI calculation are based on the chart time range. Therefore, the daily chart shows the past 14 days (K chart), and the hourly chart shows the StochRSI generated over the past 14 hours.
Cycles can be set to days, hours, or even minutes, and the way they are used varies from trader to trader (depending on their situation and strategy). You can also adjust the number of cycles up or down to determine long-term or short-term trends. Setting the periodic value to 20 is a very popular choice for the StochRSI indicator.
As mentioned above, some StochRSI chart modes specify a range of values from 0 to 100 instead of 0 to 1. In these charts, the centerline is 50 instead of 0.5. As a result, the overbought signal that usually occurs at 0.8 will be represented as 80, while the oversold signal will be represented as 20 instead of 0.2. A chart with a 0-100 setting may look slightly different, but the actual explanation is basically the same.
Second, how to use StochRSI?
The significance of the StochRSI index is most significant if it appears near the upper and lower limits of its range. Therefore, the main use of the indicator is to identify potential buy and sell points, as well as price reversals. Therefore, a value of 0.2 or less indicates that the asset may be oversold, while a value of 0.8 or more indicates that the asset may be overbought.
In addition, values closer to the centerline can also provide traders with information about market trends. For example, when the centerline is used as the support line and the StochRSi line moves steadily above 0.5, especially when the value approaches 0.8, it may indicate that it continues to be bullish or upward. Similarly, when the value is always below 0.5 and approaches 0.2, it indicates a downward trend or a downward trend.
We will introduce the two methods of RSI and StochRSI through the back test in Python.
Third, StochRSI strategy based on mean regression.
The most common StochRSI strategy is based on mean regression. Like RSI, StochRSI usually uses 80 to indicate the overbought level of short selling and 20 to indicate the oversold level to buy. In addition, 14-day retrospective and smooth periods are common. For our purposes, we will stick to these standard values.
Now write the code and let's import some standard packages in Python.
Import numpy as np import pandas as pd import matplotlib.pyplot as plt import yfinance as yf
Next, we will build a function to calculate our metrics. We call it calcStochRSI (), and it will rely on some functions to calculate the RSI and random oscillator to get the index we choose.
Def calcRSI (data, pendant 14): # Calculate gains and losses data ['diff_close'] = data [' Close']-data ['Close'] .shift (1) data [' gain'] = np.where (data ['diff_close'] > 0, data [' diff_close'] 0) data ['loss'] = np.where (data [' diff_close'] P avg_gain = np.zeros (len (data)) avg_loss = np.zeros (len (data)) for I, _ row in enumerate (data.iterrows ()): row = _ row [1] if I
< P - 1: last_row = row.copy() continue elif i == P-1: avg_gain[i] += row['init_avg_gain'] avg_loss[i] += row['init_avg_loss'] else: avg_gain[i] += ((P - 1) * avg_gain[i] + row['gain']) / P avg_loss[i] += ((P - 1) * avg_loss[i] + row['loss']) / P last_row = row.copy() data['avg_gain'] = avg_gain data['avg_loss'] = avg_loss # Calculate RS and RSI data['RS'] = data['avg_gain'] / data['avg_loss'] data['RSI'] = 100 - 100 / (1 + data['RS']) return data def calcStochOscillator(data): data['low_N'] = data['RSI'].rolling(N).min() data['high_N'] = data['RSI'].rolling(N).max() data['StochRSI'] = 100 * (data['RSI'] - data['low_N']) / \ (data['high_N'] - data['low_N']) return data def calcStochRSI(data, P=14, N=14): data = calcRSI(data) data = calcStochOscillator(data) return data def calcReturns(df): # Helper function to avoid repeating too much code df['returns'] = df['Close'] / df['Close'].shift(1) df['log_returns'] = np.log(df['returns']) df['strat_returns'] = df['position'].shift(1) * df['returns'] df['strat_log_returns'] = df['position'].shift(1) * df['log_returns'] df['cum_returns'] = np.exp(df['log_returns'].cumsum()) - 1 df['strat_cum_returns'] = np.exp(df['strat_log_returns'].cumsum()) - 1 df['peak'] = df['cum_returns'].cummax() df['strat_peak'] = df['strat_cum_returns'].cummax() return df 有了这些功能,我们只需要为我们的策略构建逻辑就可以了。还要注意,我们有一个名为 calcReturns 的辅助函数,我们可以快速将其应用于回测的结果以从中获取所有返回值。 这意味着回归模型将在 StochRSI 高于 80 时做空或卖出,并在低于 20 时买入。 def StochRSIReversionStrategy(data, P=14, N=14, short_level=80, buy_level=20, shorts=True): '''Buys when the StochRSI is oversold and sells when it's overbought''' df = calcStochRSI(data, P, N) df['position'] = np df['position'] = np.where(df['StochRSI']short_level, -1, df['position']) else: df['position'] = np.where(df['StochRSI']>Short_level, 0 Df ['position']) df [' position'] = df ['position'] .ffill () return calcReturns (df) table = pd.read_html (' https://en.wikipedia.org/wiki/List_of_S%26P_500_companies') df = table [0] syms = df ['Symbol'] # Sample symbols # ticker = np.random.choice (syms.values) ticker = "BSX" print (f "Ticker Symbol: {ticker}) ") start= '2000-01-01' end = '2020-12-31' # Get Data yfyfObj = yf.Ticker (ticker) data = yfObj.history (startstart=start) Endend=end) data.drop (['Open',' High', 'Low',' Volume', 'Dividends',' Stock Splits'], inplace=True, axis=1) # Run test df_rev = StochRSIReversionStrategy (data.copy ()) # Plot results colors = plt.rcParams ['axes.prop_cycle']. By_key () [' color'] fig, ax = plt.subplots (2, figsize= (12,8) ax [0] .plot (df_rev ['strat_cum_returns'] * 100) Label='Mean Reversion') ax [0] .plot (df_rev ['cum_returns'] * 100, label='Buy and Hold') ax [0] .set _ ylabel (' Returns (%)') ax [0] .set _ title ('Cumulative Returns for Mean Reversion and' + f' Buy and Hold Strategies for {ticker}') ax [0] .plot (bbox_to_anchor= [1,0.6]) ax [1] .plot (df_rev ['StochRSI']) Label='StochRSI', linewidth=0.5) ax [1] .plot (df_rev ['RSI'], label='RSI', linewidth=1) ax [1] .axhline (80, label='Over Bought', color=colors [1], linestyle=':') ax [1] .axhline (20, label='Over Sold', color=colors [2], linestyle=':') ax [1] .axhline (50, label='Centerline', color='k') Linestyle=':') ax [1] .set _ ylabel ('Stochastic RSI') ax [1] .set _ xlabel (' Date') ax [1] .set _ title (f'Stochastic RSI for {ticker}') ax [1] .setting (bbox_to_anchor= [1,0.75]) plt.tight_layout () plt.show ()
During the 21 years we studied, the mean regression strategy beat the buy and hold strategies of Boston Scientific (BSX), with a return of 28 times, compared with 2 times for the latter.
StochRSI and some key metrics are shown in the second figure. I also added RSI to compare with the more unstable StochRSI. This leads to frequent transactions, which can seriously affect your actual returns if your account is small and the transaction cost is relatively high. We just run it on a tool, so we end up with 443 transactions, or once every 12 days, which doesn't seem like much. However, if we use this indicator to manage the appropriate portfolio of tools and trade frequently, we may go in and out of multiple transactions every day, and transaction costs will become very high.
# Get trades diff = df_rev ['position'] .diff (). Dropna () trade_idx = diff.index [np.where (diffuser 0)] fig, ax = plt.subplots (figsize= (12,8)) ax.plot (df_rev [' Close'], linewidth=1, label=f' {ticker}') ax.scatter (trade_idx, df_ revolutions [trade _ idx] ['Close'], c=colors [1], marker=' ^' Label='Trade') ax.set_ylabel ('Price') ax.set_title (f' {ticker} Price Chart and Trades for' + 'StochRSI Mean Reversion Strategy') ax.legend () plt.show ()
To see some of the key metrics of the overall strategy, let's look at using the following getStratStats function.
Def getStratStats (log_returns: pd.Series Risk_free_rate: float = 0.02): stats = {} # Total Returns stats ['tot_returns'] = np.exp (log_returns.sum ())-1 # Mean Annual Returns stats [' annual_returns'] = np.exp (log_returns.mean () * 252)-1 # Annual Volatility stats ['annual_volatility'] = log_returns * np.sqrt (252) # Sortino Ratio annualized_downside = log_ locals [log _ returns50, 1 Df ['position']) if shorts: df [' position'] = np.where (df ['StochRSI']
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 227
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.