python rsi_使用python与rsi进行算法交易

python rsi

Machine Learning is computationally intensive, as the algorithm is not deterministic and therefore must be constantly tweaked over time. However, technical indicators are much quicker, as the equations do not change. This therefore improves their ability to be used for real-time trading.

机器学习是计算密集型的,因为该算法不是确定性的,因此必须随着时间不断进行调整。 但是,技术指标要快得多,因为方程式不会改变。 因此,这提高了它们用于实时交易的能力。

什么是RSI? (What is RSI?)

To create a program that uses RSI, we must first understand the RSI indicator. RSI is an acronym of Relative Strength Index. It is a momentum indicator, that uses the magnitude of price changes, to evaluate if a security is overbought or oversold.

要创建使用RSI的程序,我们必须首先了解RSI指示器。 RSI是相对强度指数的缩写。 它是一种动量指标,它使用价格变化的幅度来评估证券是超买还是超卖。

If the RSI value is over 70, the security is considered overbought, if the value is lower than 30, it is considered to be oversold. Overbought refers that the bubble created from the buying might pop soon, and therefore the price will drop. This creates a strong entry point.

如果RSI值超过70,则认为该证券超买,如果该值低于30,则认为其超卖。 超买是指由购买产生的泡沫可能会很快消失,因此价格将下降。 这创建了一个强大的切入点。

However, good practice is to make a selling order, only when the RSI value intersects the overbought line, as this is a more conservative approach. At least to guessing when the RSI will reach the highest point.

但是,好的做法是仅在RSI值与超买线相交时下达卖单,因为这是一种较为保守的方法。 至少要猜测RSI何时达到最高点。

概念: (Concept:)

This program seeks to use the talib (technical analysis) library to implement the intersection between the RSI line and the oversold and overbought line. The bulk of the program does not come from programming the indicator (as it has been created in the library), but rather the implementation of how the oversold and overbought regions can be used to make trades.

该程序试图使用talib(技术分析)库来实现RSI线与超卖和超买线之间的交集。 该程序的大部分不是来自对指标进行编程(因为它已在库中创建),而是实现了如何使用超卖和超买区域进行交易。

代码: (The Code:)

import yfinance
import talib
from matplotlib import pyplot as plt

These are the prerequisites for the program. Yfinance is used to download stock data, talib is to calculate the indicator values. Matplotlib of course is to plot the data as a graph.

这些是程序的先决条件。 Yfinance用于下载股票数据,talib用于计算指标值。 Matplotlib当然是将数据绘制为图形。

data = yfinance.download('NFLX','2016-1-1','2020-1-1')
rsi = talib.RSI(data["Close"])

This script accesses the data and also calculates the rsi values, based on these two equations:

该脚本根据以下两个方程式访问数据并计算rsi值:

RSIstep1​=100−[100/(1+Average loss/Average gain​)]

RSIstep1 = 100− [100 /(1+平均损失/平均收益)]

RSIstep2​=100−[100/(1+Average average loss∗13+Current loss/Previous average gain∗13+Current gain​)​]

RSIstep2 = 100− [100 /(1+平均平均损失* 13 +电流损失/先前的平均收益* 13 +电流增益))]

fig = plt.figure()
fig.set_size_inches((25, 18))
ax_rsi = fig.add_axes((0, 0.24, 1, 0.2))
ax_rsi.plot(data.index, [70] * len(data.index), label="overbought")
ax_rsi.plot(data.index, [30] * len(data.index), label="oversold")
ax_rsi.plot(data.index, rsi, label="rsi")
ax_rsi.plot(data["Close"])
ax_rsi.legend()

This plot shows all the overbought and oversold territories, along with the RSI values calculated for each value of recorded closing price of the stock. This gives a good visualization of the stock data

该图显示了所有超买和超卖区域,以及为每个记录的股票收盘价计算的RSI值。 这样可以很好地可视化库存数据

python rsi_使用python与rsi进行算法交易_第1张图片
Image by Author 图片作者

This is the resultant graph. We can see the RSI value fluctuating between the different sections, as time goes on. The good thing about RSI is that it is relative. This means the strength of the signal is relative not to the actual value, but the relationship of past values.

这是结果图。 随着时间的流逝,我们可以看到RSI值在不同部分之间波动。 RSI的优点在于它是相对的。 这意味着信号强度不是相对于实际值,而是相对于过去值的关系。

缺少的步骤: (The Missing Step:)

Usually, the articles stop here. They end after giving the preliminary code of the stock trading program. It is necessary to go further and truly evaluate the stock trading program, based on the profitability of the program. This is why I will hand in the program.

通常,文章在这里停止。 在给出了股票交易程序的初步代码之后,它们结束了。 有必要根据该程序的获利能力进一步进行真实评估。 这就是为什么我要提交程序的原因。

section = None
sections = []
for i in range(len(rsi)):
if rsi[i] < 30:
section = 'oversold'
elif rsi[i] > 70:
section = 'overbought'
else:
section = None
sections.append(section)

This script records the sections in which every point falls in. It is either in the overbought, oversold or the None region, which refers to in between the two lines.

该脚本记录了每个点所属的部分。它位于超买,超卖或无区域中,该区域指的是两行之间。

trades = []
for i in range(1,len(sections)):
trade = None
if sections[i-1] == 'oversold' and sections[i] == None:
trade = True
if sections[i-1] == 'overbought' and sections[i] == None:
trade = False
trades.append(trade)

This script integrates the basic strategy for RSI trading. The trading strategy is when the value leaves the overbought and oversold sections, it makes the appropriate trade. For example, if it leaves the oversold section, a buy trade is made. If it leaves the overbought section, a sell trade is made.

该脚本集成了RSI交易的基本策略。 交易策略是当价值离开超买和超卖部分时,进行适当的交易。 例如,如果离开超卖部分,则进行买入交易。 如果离开超买区域,则会进行卖出交易。

acp = data['Close'][len(data['Close'])-len(trades):].values
profit = 0
qty = 10
for i in range(len(acp)-1):
true_trade = None
if acp[i] < acp[i+1]:
true_trade = True
elif acp[i] > acp[i+1]:
true_trade = False
if trades[i] == true_trade:
profit += abs(acp[i+1] - acp[i]) * qty
elif trades[i] != true_trade:
profit += -abs(acp[i+1] - acp[i]) * qty

This script uses the trades made by the program to calculate the profit or the loss from each trade. This gives the best evaluation of the program, as it targets exactly the variable to look for. The qty variable calculates how many shares are bought.

该脚本使用程序进行的交易来计算每笔交易的收益或损失。 由于它精确定位要查找的变量,因此可以对程序进行最佳评估。 qty变量计算购买了多少股。

After running the program, the profit calculated is:

运行该程序后,计算出的利润为:

Profit : $58.3

结论: (Conclusion:)

As a matter of fact, a profit of 58.3 dollars is actually not a very good investment, when considering the risk to reward ratio. There are quite a few ways you can improve my program:

实际上,考虑风险回报率时,58.3美元的利润实际上并不是一个很好的投资。 有很多方法可以改善我的程序:

  1. Tweak the patience variable

    调整耐心变量

This variable is how long after the RSI value, the trade will be made. Toy with this value, find a pattern, and optimize it to get better results.

该变量是RSI值之后多长时间进行交易。 以此值进行计算,找到一个模式,然后对其进行优化以获得更好的结果。

2. Find the best company

2.找到最好的公司

For which stock does this algorithm work best? Test this program on different companies to evaluate.

该算法最适合哪种股票? 在不同的公司上测试此程序以进行评估。

Thank you for reading my article!

感谢您阅读我的文章!

翻译自: https://towardsdatascience.com/algorithmic-trading-with-rsi-using-python-f9823e550fe0

python rsi

你可能感兴趣的:(算法,python,人工智能,机器学习,区块链)