当前位置:网站首页>Common skills for quantitative investment - drawing 3: drawing the golden section line
Common skills for quantitative investment - drawing 3: drawing the golden section line
2022-06-13 00:54:00 【Your name is Yu yuezheng】
Quantitative investment common skills —— Drawing 3
Preface
Previous articles have described how to Draw a line chart of the closing price 、 Candlelight 、 Draw a moving average based on the closing price , Next, how to draw the golden section line
You can pay attention to our Tiktok :“ Financial observation ”(JRGC8888) Learn more about
The golden section
The golden section line is also known to us 0.382,0.618 Split line
Visually 0.382 And visual 0.618
The calculation method is as follows :
sp382 = (max - min) * 0.382 + min
sp618 = (max - min) * 0.618 + min
Statistically 0.382 And statistical 0.618
We need to use scipy Under the Treasury stats Class scoreatpercentile() Method , Use pip You can install scipy
pip install scipy
How to use it is as follows
- stats.scoreatpercentile(arr, per)
- arr For input data , It can be a list or DataFrame
- per The percentage you need to get , The value involved in the calculation is per/100, so 0.628 You should enter per=62.8
sp382_stats = stats.scoreatpercentile(data, 38.2)
sp618_stats = stats.scoreatpercentile(data, 61.8)
Delimit the golden section line
The golden section line delimits two areas 0.382 Split line and two 0.618 The range between , So we use the following function to calculate the range
above618 = np.maximum(sp618, sp618_stats) # From vision 0.618 And statistics 0.618 Filter for larger values in
below618 = np.minimum(sp618, sp618_stats) # From vision 0.618 And statistics 0.618 Filter smaller values in
above382 = np.maximum(sp382, sp382_stats) # From vision 0.382 And statistics 0.382 Filter for larger values in
below382 = np.minimum(sp382, sp382_stats) # From vision 0.382 And statistics 0.382 Filter smaller values in
Draw the golden section
The data we use is through abupy Library imported tsla Historical data of , Combined with the introduction of Draw a candle Methods , The code for drawing the golden section line is as follows
import abupy
import numpy as np
import matplotlib.pyplot as plt
import mpl_finance as mpf
from scipy import stats
from matplotlib.dates import date2num
from abupy import ABuSymbolPd, pd_rolling_mean, nd
# ———————————————————— #
# ———— Default parameter settings ———— #
# ———————————————————— #
__colorup__ = "red"
__colordown__ = "green"
abupy.env.enable_example_env_ipython() # Using sandbox data , The goal is the same data environment as in the book , If not used, an error will be reported
tsla_df = ABuSymbolPd.make_kl_df('usTSLA', n_folds=2) # Fixed import tsla Market data of
tsla_df = tsla_df[:50] # Before selection 50 individual , Too much data makes it difficult to observe
print(tsla_df[:10])
# ———————————————————— #
def plot_ochl(data_df=tsla_df, axs=None, show=False):
''' Draw a candle :param data_df: Input data , By default tsla Historical market data of , The input data type currently only supports DataFrame type :param axs: Whether to draw on the subgraph :param show: Whether to display the image :return: '''
drawer = plt if axs is None else axs
fig, ax = drawer.subplots(figsize=(14, 7))
qutotes = []
for index, (d, o, c, h, l) in enumerate(
zip(data_df.index, data_df.open, data_df.close,
data_df.high, data_df.low)):
d = date2num(d) # The date of the candle chart should be used matplotlib.finance.date2num To a unique numeric value
val = (d, o, c, h, l) # date , The opening quotation , The close , The highest , The lowest composition tuple object val
qutotes.append(val) # Add val Join in qutotes
# Use mpf.candlestick_ochl Drawing candles ,ochl representative :open,close,high,low
mpf.candlestick_ochl(ax, qutotes, width=0.6, colorup=__colorup__, colordown=__colordown__)
ax.autoscale_view()
ax.xaxis_date()
if show:
plt.show()
def plot_goldline(data_df=tsla_df, axs=None, show=False):
''' Draw the golden section :param data_df: Input data , By default tsla Historical market data of , The input data type currently only supports DataFrame type :param axs: Whether to draw on the subgraph :param show: Whether to display the image :return: '''
cs_max = data_df.close.max() # The maximum value in the closing price series
cs_min = data_df.close.min() # The lowest value in the closing price series
# Visually 0.382 And visual 0.618
sp382 = (cs_max - cs_min) * 0.382 + cs_min
sp618 = (cs_max - cs_min) * 0.618 + cs_min
# Statistically 0.382 And statistical 0.618
sp382_stats = stats.scoreatpercentile(data_df.close, 38.2)
sp618_stats = stats.scoreatpercentile(data_df.close, 61.8)
above618 = np.maximum(sp618, sp618_stats) # From vision 0.618 And statistics 0.618 Filter for larger values in
below618 = np.minimum(sp618, sp618_stats) # From vision 0.618 And statistics 0.618 Filter smaller values in
above382 = np.maximum(sp382, sp382_stats) # From vision 0.382 And statistics 0.382 Filter for larger values in
below382 = np.minimum(sp382, sp382_stats) # From vision 0.382 And statistics 0.382 Filter smaller values in
plt.axhline(sp382, c='r') # Horizontal line vision 0.382
plt.axhline(sp382_stats, c='m') # Horizontal line statistics 0.382
plt.axhline(sp618, c='g') # Horizontal line vision 0.618
plt.axhline(sp618_stats, c='k') # Horizontal line statistics 0.618
plt.fill_between(data_df.index, above618, below618, alpha=0.5, color="r") # fill 0.618 red
plt.fill_between(data_df.index, above382, below382, alpha=0.5, color="g") # fill 0.382 green
plt.legend(['close', 'sp382', 'sp382_stats', 'sp618', 'sp618_stats'], loc='best') # Label the names according to the drawing order
if show:
plt.show()
if __name__ == '__main__':
plot_ochl() # Draw a candle , Will create a new canvas
plot_goldline(show=True) # Draw the golden section
The output image is as follows :
Welcome to pay attention to us
Our tiktok : Financial observation (JRGC8888)
边栏推荐
- [JS component] create a custom horizontal and vertical scroll bar following the steam style
- [JS] battle chess
- Physical orbit simulation
- MCU serial port interrupt and message receiving and sending processing -- judge and control the received information
- Set sail
- 单片机串口中断以及消息收发处理——对接受信息进行判断实现控制
- [JS component] dazzle radio box and multi box
- Kotlin coroutine withcontext switch thread
- Today's sleep quality record 74 points
- [network protocol] problems and solutions in the use of LwIP
猜你喜欢

Kotlin 协程的四种启动模式

Comparison of disk partition modes (MBR and GPT)

DNS attack surface analysis

硬(磁)盘(一)

MySQL异常:com.mysql.jdbc.PacketTooBigException: Packet for query is too large(4223215 > 4194304)

今日睡眠质量记录74分

pytorch和tensorflow有什么区别?

Summary of openstack installation problems

What is the difference between pytorch and tensorflow?

Breadth first search for node editor runtime traversal
随机推荐
Notes: the 11th and 12th generation mobile versions of Intel support the native thunderbolt4 interface, but the desktop version does not
Kotlin 协程,job的生命周期
Basic operations of FreeMarker
Androi weather
Kotlin collaboration, the life cycle of a job
[JS component] previous queue prompt
gpu加速pytorch能用吗?
Static analysis of malicious code
Hard (magnetic) disk (I)
天津银行周传凯:从 0 到 1,我的分布式数据库落地经验谈
深度学习每周期的步数多少合适?
How many rounds of deep learning training? How many iterations?
(01). Net Maui actual construction project
Composite key relationships using Sqlalchemy - relationships on composite keys using Sqlalchemy
Druid reports an error connection holder is null
Physical orbit simulation
ROS2之OpenCV人脸识别foxy~galactic~humble
sort
What is dummy change?
Et5.0 value type generation