달력

3

« 2024/3 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
728x90
반응형

이전글에서는 decreasing 에 대해서 알아보았구요.

이번에는 순서상 중요한 것이 hoverinfo 가 있겠네요. 한번 알아보도록 하겠습니다.

 

[링크]

https://plotly.com/python-api-reference/generated/plotly.graph_objects.layout.template.data.html 

 

property high 

Sets the high values. 

The ‘high property is an array that may be specified as a tuple, list, numpy array, or pandas Series 

Returns 

Return type 

numpy.ndarray 

# high는 고가, 기본적인 데이터라고 보면 됩니다. 이거와 기본적으로 들어가는 것들이 open(시가), close(종가), low(저가)

 

property highsrc 

Sets the source reference on Chart Studio Cloud for high . 

The ‘highsrc property must be specified as a string or as a plotly.grid_objs.Column object 

Returns 

Return type 

str 

# 이 파라미터 또한 chart studio 에서 쓰는 옵션 인 것 같네요.

 

property hoverinfo 

Determines which trace information appear on hover. If none or skip are set, no information is displayed upon hovering. But, if none is set, click and hover events are still fired. 

The ‘hoverinfo property is a flaglist and may be specified as a string containing: 

  • Any combination of [‘x’, ‘y’, ‘z’, ‘text’, ‘name’] joined with ‘+’ characters (e.g. ‘x+y’) OR exactly one of [‘all’, ‘none’, ‘skip’] (e.g. ‘skip’) 
  • A list or array of the above 

Returns 

Return type 

Any|numpy.ndarray 

# 이 옵션은 차트를 그려놓은 상태에서 캔들에 마우스를 올리게 되면 띄워지는 옵션이라고 보면됩니다.

# 기본적인 셋팅은 아래와 같습니다.

# 마우수를 가져가면 캔들 위로 x 축 레이블, open, close, high, low 값이 뜨게 됩니다.

import plotly.graph_objects as go

fig = go.Figure(data=[go.Candlestick(x=[1, 2, 3, 4, 5],
                open  = [ 1, 6, 7, 10, 5 ],
                close = [ 2, 10, 3, 12, 8  ],
                high  = [ 10, 12, 8, 15, 18 ],
                low   = [ 0.1, 5, 2, 8, 5 ],                                                                               
                )])

fig.show()

 

# 설명에 있는 대로 옵션을 조금씩 바꿔 보도록 하겠습니다.

hoverinfo = 'x'

 

hoverinfo = 'y'

hoverinfo = 'z'

# z 값은 3차원 그래프에서 적용되는 듯 한데요. 적용을 해도 아무 표시도 뜨지 않네요.

hoverinfo = 'text'

# 이 옵션은 text 값을 별도로 넣어주어야 합니다.

import plotly.graph_objects as go

fig = go.Figure(data=[go.Candlestick(x=[1, 2, 3, 4, 5],
                open  = [ 1, 6, 7, 10, 5 ],
                close = [ 2, 10, 3, 12, 8  ],
                high  = [ 10, 12, 8, 15, 18 ],
                low   = [ 0.1, 5, 2, 8, 5 ],     
                text = '캔들차트',
                hoverinfo = 'text'
                )])

fig.show()

# 여기서 text 파라미터에 대해서 함께 살펴보면 text 에는 list 형태로도 올수 있다고 합니다.

# 리스트에 각각의 값을 넣어주면 캔들마다 표시가 됩니다. 다시 말해 위와 같이 text='캔들차트' 하나만 넣게 되면 모든 캔들에 '캔들차트'라고 뜨지만 아래와 같이 리스트로 정해주면 정해준 숫자만큼 앞에서 부터 지정이 됩니다.

# 뒤쪽에 지정안된 캔들은 표시가 안됨.

 

property text 

Sets hover text elements associated with each sample point. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to this trace’s sample points. 

The ‘text property is a string and must be specified as: 

  • A string 
  • A number that will be converted to a string 
  • A tuple, list, or one-dimensional numpy array of the above 

Returns 

Return type 

str|numpy.ndarray 

text = ['캔들1', '캔들2']

 

# name 옵션은 범례를 표시한다고 생각하시면 됩니다. 이것 또한 모든 캔들위에 저것만 표시가 됩니다.

name = '주식회사',
hoverinfo = 'name'

property name 

Sets the trace name. The trace name appear as the legend item and on hover. 

The ‘name property is a string and must be specified as: 

  • A string 
  • A number that will be converted to a string 

Returns 

Return type 

str 

 

# 조합을 통해서도 나타낼 수 있습니다.

hoverinfo = 'x+y'

# 초기 셋팅이랑 동일합니다.

# 하나만 더 해보자면

text = ['캔들1', '캔들2', '캔들3', '캔들4', '캔들5'],
hoverinfo = 'x+text'

# 이런식으로도 조합이 가능합니다.

# x+y, y+text, x+name 등등 필요 용도에 따라 조합해서 사용하시면 될듯합니다.

 

# 그리고 all, none, skip 이 있습니다. none과 skip 은 어떠한 정보도 표시하지 않습니다.

# all은 아래와 같이 모든 정보가 표시됩니다.

name = '주식회사',
text = ['캔들1', '캔들2', '캔들3', '캔들4', '캔들5'],
hoverinfo = 'all'

# 이렇게 하나씩 살펴보니 참 다양한 옵션들이 있네요. 정작 주식을 잘하기 위해서 이게 무슨 쓸모가 있을지는 모르겠지만..^^;; 오늘도 이렇게 하나씩 공부를 해나간다는 생각으로 앞으로 나아가겠습니다.


[이전글]

2021/02/17 - [Programming/Python] - plotly-01 #Candlestick Charts 살펴보기

2021/02/19 - [Programming/Python] - plotly-02 #Candlestick Parameters 살펴보기1-decreasing

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

 

[Candlestick Documentation]

plotly.github.io/plotly.py-docs/generated/plotly.graph_objects.Candlestick.html

 

# 상기 주소로 가서 Candlestick class 의 parameter 을 살펴보면 다양한 종류가 있습니다.

 

# 이전 살펴보기에서 어떤식으로 간략히 그릴수 있는지 살펴봤었고, x, close, high, open, low 값을 통해 그릴 수 있었습니다.

# 이외에도 다양하게 있는데 하나씩 살펴볼려고 합니다.

* 찾아봐도 모르겠는건 과감히~~^^ pass~~^^;;;;;;;;;;;; 누가 좀 알려주세용~^^

 

* close – Sets the close values.

# 종가 가격

 

* closesrc – Sets the source reference on Chart Studio Cloud for close .

# Chart Studio Cloud 에서 어떤 셋팅을 하는 것 같다. 주피터에서는 별다른 작동을 안함.

 

* customdata – Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, “scatter” traces also appends customdata items in the markers DOM elements

# unknown function ^^;;

 

* decreasing – plotly.graph_objects.candlestick.Decreasing instance or dict with compatible properties 

* class plotly.graph_objects.candlestick.Decreasing(arg=None, fillcolor=None, line=None, **kwargs)

plotly.graph_objects.candlestick package — 4.14.3 documentation

# decreasing 은 캔들에서 떨어가지는 캔들에 대한 fillcolor 와 line 에 대한 정의를 할 수 있습니다.

 

Bases: plotly.basedatatypes.BaseTraceHierarchyTypeproperty fillcolor

Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available.

The ‘fillcolor’ property is a color and may be specified as:

  • A hex string (e.g. ‘#ff0000’)
  • An rgb/rgba string (e.g. ‘rgb(255,0,0)’)
  • An hsl/hsla string (e.g. ‘hsl(0,100%,50%)’)
  • An hsv/hsva string (e.g. ‘hsv(0,100%,100%)’)
  • A named CSS color:aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen

ReturnsReturn type

str

property line

The ‘line’ property is an instance of Line that may be specified as:

  • An instance of plotly.graph_objects.candlestick.decreasing.Line
  • A dict of string/value properties that will be passed to the Line constructorcolorwidth
  • Sets the width (in px) of line bounding the box(es).
  • Sets the color of line bounding the box(es).
  • Supported dict properties:

ReturnsReturn type

plotly.graph_objects.candlestick.decreasing.Line

 

# 우선 여기서 비교를 위해서 아래와 같이 주피터 노트북으로 간단한 캔들차트를 그려보았습니다.

import plotly.graph_objects as go

fig = go.Figure(data=[go.Candlestick(x=[1, 2, 3, 4, 5],
                open  = [ 1, 6, 7, 10, 5 ],
                close = [ 2, 10, 3, 12, 8  ],
                high  = [ 10, 12, 8, 15, 18 ],
                low   = [ 0.1, 5, 2, 8, 5 ],                                                                                                   
                )])

fig.show()

기본 차트

 

# decreasing 적용을 위해서는 아래와 같이 dict 형태로 묶어서 전달하는 해주면 됩니다.

import plotly.graph_objects as go

fig = go.Figure(data=[go.Candlestick(x=[1, 2, 3, 4, 5],
                open  = [ 1, 6, 7, 10, 5 ],
                close = [ 2, 10, 3, 12, 8  ],
                high  = [ 10, 12, 8, 15, 18 ],
                low   = [ 0.1, 5, 2, 8, 5 ],                                                               
                decreasing = dict(fillcolor='blue')                                                     
                )])

fig.show()

# decreasing 의 fillcolor 는 위의 설명에서 보듯, rgd 코드, css 타입등등으로 넣을 수 있습니다. 전, 익숙한 blue 로 색을 채워보았습니다.

 

# 선이 아직도 빨간색이라서 선도 파란색으로 넣어 보겠습니다.

# 선 또한 rgb, hex 등등으로 색을 변경할 수 있습니다.

import plotly.graph_objects as go

fig = go.Figure(data=[go.Candlestick(x=[1, 2, 3, 4, 5],
                open  = [ 1, 6, 7, 10, 5 ],
                close = [ 2, 10, 3, 12, 8  ],
                high  = [ 10, 12, 8, 15, 18 ],
                low   = [ 0.1, 5, 2, 8, 5 ],                                                               
                decreasing = dict(fillcolor='blue', line=dict(color='blue'))                                                     
                )])

fig.show()

# 선의 굵기도 조정할 수 있습니다.

line=dict(color='blue', width=5)

# 5정도로 하면 아래와 같습니다.

# 여기서 alpha 값을 줘서 파란색을 배경이 보이는 형태로 만들고 싶으면. rgba 를 사용하면됩니다.

# rgb 표 색상은 구글에 검색하시면 엄청 잘 나와있어요~^^

fillcolor='rgba(0,0,255,0.5)'

# rgba(red, green, blue, alpha) 값을 나타냅니다. alpha 를 0.5 정도로 적용하면 아래와 같습니다.

# alpha 값은 0.0 (투명) ~ 1.0 (불투명) 으로 보시면 됩니다.

 


[이전글]

2021/02/16 - [Programming/Python] - plotly-00 #시작

2021/02/17 - [Programming/Python] - plotly-01 #Candlestick Charts 살펴보기

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

# 시작에 이어서 우리에게 필요한(?) 캔들 차트 그리기를 알아보도록 하겠습니다.

 

# 오늘도 스스로를 위한 공부시작!!!!

 

# 오늘도 소스는 plotly 공식 사이트를 참고해 보았습니다.


[참고 사이트]

plotly.com/python/candlestick-charts/

 

# 주식 정보들을 다루다 보면 필연적으로 pandas 와 많이 부딪치게 되는 것 같습니다. pandas 에 정보를 담아서 주가를 그려보도록 하겠습니다.

# 주가 데이터셋 또한 plotly 에서 제공해주기 때문에 연습할 때 용이합니다.

# 전체코드
import plotly.graph_objects as go

import pandas as pd
from datetime import datetime

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')

fig = go.Figure(data=[go.Candlestick(x=df['Date'],
                open=df['AAPL.Open'],
                high=df['AAPL.High'],
                low=df['AAPL.Low'],
                close=df['AAPL.Close'])])

fig.show()

차트 예시

# 실행해보면 밑에 컨트롤바와 함께 이쁜 차트가 자동으로 완성됩니다.

# 마수를 캔들위에 놓으면 캔들의 시가, 고가, 종가, 저가를 알수가 있고, 아래의 컨트롤바를 움직이면 확대하거나 해서 원하는 시간대로 이동할수도 있습니다.


 

[코드 살펴보기]

 

import plotly.graph_objects as go

# import 를 해주는 것이고, as 는 보통 go 로 통상적으로 많이 사용하고 있습니다.

import pandas as pd

# pandas 도 import

# 만약 설치가 안되어있다면 jupyter notebook 에서 아래와 같이 설치하여 실행하시기 바랍니다.

!pip install pandas
from datetime import datetime

# datetime 은 왜 import 했는지 모르겠네요~^^ 사이트에서 제공하는 코드소스인데도.. 뭔가 쓸데 없는 것이..~^^;;;;

# 사용을 하지 않으므로 주석처리 또는 삭제 처리 해주셔도 되네요.

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')

# dataframe 형태로 사이트에서 제공해주는 데이터셋을 불러와 정보를 담습니다.

fig = go.Figure(data=[go.Candlestick(x=df['Date'],
                open=df['AAPL.Open'],
                high=df['AAPL.High'],
                low=df['AAPL.Low'],
                close=df['AAPL.Close'])])

# 정보를 불어모녀 x축과 y축에 각각 정보를 줘야 합니다. fig에 위와 같이 x 축에는 날짜 항목을 불러오고, y축에는 open(시가), high(고가), low(저가), close(종가) 불러 옵니다. 여기서는 애플의 주가를 불러왔나보네요.

fig.show()

# 마지막으로 정보 불러온것을 보여줍니다.

# mpl_finance 를 이용해서 candlestick 을 그리시는 분들도 있지만. 저는 plotly 가 더 저한테는 맞는것 같더라구요. ^^

 

# 다음에도 plotly 사이트에 있는 문서들을 좀 더 살펴보고 하나씩 하나씩 공부해 나가도록 하겠습니다.


[이전글]

2021/02/16 - [Programming/Python] - plotly-00 #시작

728x90
반응형
:
Posted by 패치#노트