程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Gold index algorithm for quantitative trading of digital currency [Python]

編輯:Python

In this tutorial , We will learn how to use cross indicators to predict purchases in the cryptocurrency market / Sell signal , The complete Python Code , Using this algorithm on the historical market data can achieve three times the return on bitcoin revenue .

Learn in a familiar language The etheric fang DApp Development : Java | Php | Python | .Net / C# | Golang | Node.JS | Flutter / Dart

1、 Basic knowledge of : The golden cross vs. Death cross

If you have a financial background , You know the golden cross (golden Cross) Cross with death (Death Cross) These two indicators are derived from the moving average algorithm , Also known as cross indicator (cross indicator). These two cross indicators calculate the average value of the market closing price in a specific time period using the following formula :

This concept combines two moving averages ( Short term and long term ) To get cryptocurrency trends . When the short-term moving average exceeds or reviews the long-term moving average , A buy or sell signal will appear .

Mathematically speaking , If you choose 5 A short-term moving average of cycles and 20 A long-term moving average of three cycles , We will pass the following conditions Get a buy signal :

MA(5) The calculation is as follows :

MA(20) The calculation is as follows :

CPrice Corresponding to closing value . for example , The current price of bitcoin is 49,670 dollar ,t Represents a time period definition ( This is explained more in the video at the end of this article ). These cross indicators are part of the equation , It can help detect the global trend of cryptocurrencies studied . these CI( Cross indicator ) It is widely used by many traders and funds around the world , To define the supporting force 、 Resistance level 、 Stop losses and targets and understand potential trends .

Now we have covered some background knowledge , Let's start testing , See how they help predict the cryptocurrency market .

2、 Software stack used

Before continuing with the following tutorial , Please make sure that you have installed Python3 And the following software packages :

  • Pandas:
  • NumPy:
  • Yfinance:
  • Plotly: It's not necessary , But useful in drawing

have access to pip Install the above packages , for example :

pip install yfinance
pip install plotly

3、 Data pipeline and modeling

Now we can define the data processing flow , It mainly includes 3 A different step :

  1. Use Yahoo Finance API Query the data of real-time cryptocurrency
  2. Define a time period , Create new columns for the data we want to calculate , Then update these values every second .
  3. Real time drawing , And check whether our signal is accurate .

In this paper , I won't go into too much code and API The details of the , You can find it in the following article understand How to use Python Get real-time cryptocurrency market data . Now we can start coding !

4、 Import package

The first step will include importing the necessary software packages . Use the following line of code to import a previously installed package :

# Raw Package
import numpy as np
import pandas as pd
#Data Source
import yfinance as yf
#Data viz
import plotly.graph_objs as go

Now you have imported the Library , Next, we can import our cryptocurrency data .

5、 Get real-time market data

Now? , Different packages required have been uploaded . We're going to BTC-USD Trade pairs, for example , adopt Yahoo Finance API Set import .

You can extend the required legal currency and cryptocurrency options . for example , If you are from India or Canada , You can use INR or CAD, You can also set whether you want to Ripple or Ethereum data .

Let's go back to API structure .

call Yahoo Finance API You need to pass in three parameters in order :

  • Transaction pair code (1)
  • Start date + End date or period (2)
  • interval (3)

In our example , Transaction pair code ( Parameters 1) Will be for BTC-USD Yes . Besides , In this example , We will choose the last 7 Days as a time period ( Parameters 2). And set an interval ( Parameters 3) Of 90 minute .

To invoke data , The following structure must be used :

Before proceeding , I'll cover the third parameter (interval) Some of the details of .

6、 Available intervals

Here I'd like to quickly introduce what can be used yahoo finance API Set different intervals .

The various possible intervals are detailed below :

Now we have defined three parameters , Let's execute the query and check the output :

data = yf.download(tickers='BTC-USD',period = '8d', interval = '90m')

Here is the output :

Now? , We have downloaded and stored the data , You can continue and define the East China average and trading signals .

7、 Algorithm implementation

Now? , Our real-time data has been downloaded and stored in a file named data Variables in . The next step involves calculating our moving average And set buy and sell signals .

We will need to create the following calculated fields :

  • MA(5)
  • MA(20)

So , We will use Python The scrolling function contained in the n Average of the latest cycles . About MA(5), We will be in the recent 5 individual 90 Apply our strategy over a period of minutes . This means that we will calculate the most recent 7 Hours 30 minute (5 Times 90 minute ) The average closing price of .

Similar to MA(20), The calculation is 20 A rather than 5 individual 90 The average value of the minute period .Python The code is as follows :

#Moving average using Python Rolling function
data['MA5'] = data['Close'].rolling(5).mean()
data['MA20'] = data['Close'].rolling(20).mean()

After the above code is executed , Will create... For the data frame 2 A new column , As shown below :

Okay , Now we can test the strategy .

8、 Real time drawing

The last step in our plan is to plot the data and check whether we can predict the market trend . In the following illustration , I mark green as a good forecast , Predict black as wrong :

9、 Quantitative trading Python Code

complete Python The code is as follows :

# Raw Package
import numpy as np
import pandas as pd
#Data Source
import yfinance as yf
#Data viz
import plotly.graph_objs as go
#Importing market data
data = yf.download(tickers='BTC-USD',period = '8d', interval = '90m')
#Adding Moving average calculated field
data['MA5'] = data['Close'].rolling(5).mean()
data['MA20'] = data['Close'].rolling(20).mean()
#declare figure
fig = go.Figure()
#Candlestick
fig.add_trace(go.Candlestick(x=data.index,
open=data['Open'],
high=data['High'],
low=data['Low'],
close=data['Close'], name = 'market data'))
#Add Moving average on the graph
fig.add_trace(go.Scatter(x=data.index, y= data['MA20'],line=dict(color='blue', width=1.5), name = 'Long Term MA'))
fig.add_trace(go.Scatter(x=data.index, y= data['MA5'],line=dict(color='orange', width=1.5), name = 'Short Term MA'))
#Updating X axis and graph
# X-Axes
fig.update_xaxes(
rangeslider_visible=True,
rangeselector=dict(
buttons=list([
dict(count=3, label="3d", step="days", stepmode="backward"),
dict(count=5, label="5d", step="days", stepmode="backward"),
dict(count=7, label="WTD", step="days", stepmode="todate"),
dict(step="all")
])
)
)
#Show
fig.show()

10、 Summary of the course

All transactions are not perfect , Sometimes we tend to lag behind in entering or leaving the market , But when bitcoin was stable , The golden cross strategy has become a useful strategy to improve our profits . After simple calculation with the existing historical data , Our algorithm can get 7.1% The return of , The return rate of bitcoin transactions in the same period was stable at 1.7% about .


Link to the original text : Quantitative transaction of cryptocurrency based on cross indicators — Huizhi. Com


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved