달력

4

« 2024/4 »

  • 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
728x90
반응형

indicator를 포함하는 2개의 머지는 그냥 합치면 된다.

그런데, 3개 이상을 할려면 어떻게 해야 할까...!!!

 

이번에도 역시 chatGPT에게 물어봤다.

You can use the merge() function from the pandas library to merge three dataframes with the indicator option in Python. Here's an example code:

pandas 라이브러리의 merge() 함수를 사용하여 Python에서 표시기 옵션을 사용하여 세 개의 데이터 프레임을 병합할 수 있습니다. 다음은 예제 코드입니다:
import pandas as pd

# create three dataframes
df1 = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], 'value1': [1, 2, 3, 4]})
df2 = pd.DataFrame({'key': ['B', 'D', 'E', 'F'], 'value2': [5, 6, 7, 8]})
df3 = pd.DataFrame({'key': ['A', 'B', 'F', 'G'], 'value3': [9, 10, 11, 12]})

# merge the dataframes using 'key' as the join key and specify the indicator option
merged_df = pd.merge(df1, df2, on='key', how='outer', indicator=True)
merged_df = pd.merge(merged_df, df3, on='key', how='outer', indicator=True)

print(merged_df)
In this example, we create three dataframes df1, df2, and df3, each with a column named 'key'. We then use the merge() function to merge the dataframes, specifying 'key' as the join key and 'outer' as the merge method (which includes all keys from both dataframes). Finally, we set the indicator parameter to True to include a column indicating the source of each row in the merged dataframe. The result is stored in the merged_df variable and printed to the console.

이 예제에서는 각각 'key'라는 열이 있는 세 개의 데이터프레임 df1, df2, df3을 만듭니다. 그런 다음 merge() 함수를 사용하여 데이터 프레임을 병합하고, 조인 키로 'key'를 지정하고 병합 방법(두 데이터 프레임의 모든 키를 포함하는 병합 방법)으로 'outer'를 지정합니다. 마지막으로, 병합된 데이터 프레임에 각 행의 출처를 나타내는 열을 포함하도록 표시기 매개 변수를 True로 설정합니다. 결과는 merged_df 변수에 저장되고 콘솔에 인쇄됩니다.

위와 같이 답변을 받을 수 있었고, 이번에는 번역툴을 파파고나 아닌 딥엘이라는 번역기를 사용해서 작업을 해보았다.

(나쁘지는 않은듯~)

 

하지만!!!!

코드가 먹히지를 않는다!!!!

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-1-35e2c9af28c5> in <module>
      8 # merge the dataframes using 'key' as the join key and specify the indicator option
      9 merged_df = pd.merge(df1, df2, on='key', how='outer', indicator=True)
---> 10 merged_df = pd.merge(merged_df, df3, on='key', how='outer', indicator=True)
     11 
     12 print(merged_df)

2 frames
/usr/local/lib/python3.8/dist-packages/pandas/core/reshape/merge.py in _indicator_pre_merge(self, left, right)
    762                 )
    763         if self.indicator_name in columns:
--> 764             raise ValueError(
    765                 "Cannot use name of an existing column for indicator column"
    766             )

ValueError: Cannot use name of an existing column for indicator column

'Search Stack overflow' 를 눌러서 바로 검색을 해봤다.

https://stackoverflow.com/questions/48669316/valueerror-cannot-use-name-of-an-existing-column-for-indicator-column

 

ValueError: Cannot use name of an existing column for indicator column

I need to work on a problem where I will have a data frame,say df, with Name & age & I need to generate another dataframe with name & gender in for loop & I need to merge the data f...

stackoverflow.com

여기에서 살펴보면 indicator의 이름이 중복되어서 나온다는 것이다.

그래서 거기서에서 알려주는데로 

3번째 하는 머지는 indicator='exists' 로 이름을 명명해줬다. 그랬더니 제대로 된 출력을 할 수 있었다.

 

import pandas as pd

# create three dataframes
df1 = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], 'value1': [1, 2, 3, 4]})
df2 = pd.DataFrame({'key': ['B', 'D', 'E', 'F'], 'value2': [5, 6, 7, 8]})
df3 = pd.DataFrame({'key': ['A', 'B', 'F', 'G'], 'value3': [9, 10, 11, 12]})

# merge the dataframes using 'key' as the join key and specify the indicator option
merged_df = pd.merge(df1, df2, on='key', how='outer', indicator=True)
merged_df = pd.merge(merged_df, df3, on='key', how='outer', indicator='exists')

print(merged_df)

이를 응용해서 3개 이상을 'outer' 머지를 하고 싶은 경우에는 indicator=' ' 를 활용하면 된다.

 

indicator를 쓰게 되면 양쪽 자료에 있는 중복, 고유한 자료들을 표시할 수 있어서 추후에 연산작업이나 그래프로 나타내기가 수월하다.

 

감사합니다.

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

오늘도 난 전혀 감도 없는 인사이트를 얻기 위해.... 삽질중..^^;;

 

오늘도 주중에 키움API 실시간 체결창 정보를 MySQL로 저장한뒤

그 정보를 가지고 몇 시간을 요리조리 해보다가..갑자기 드는 자괴감..

이런다고 돈 많이 버나? ㅎ

 

그래서...

그냥 천천히 하기로 하고 파이썬을 이용해서 간단하게 시각화 해보는 것에 대해서 작성해 본다.

엄청 다양하게 시도해봤지만..딱히 떠오르는 것이 없다.

 

우선은 내가 좋아하는 Interactive Chart 인 plotly 를 이용하기로 했다.

아! 들어가기전에 키움 API를 이용한 데이터 수집에 대해서는 pass~

간단히 시각화 코드만 만들어봤다.

 

import plotly.express as px
import plotly.graph_objs as go
import pandas as pd

라이브러리는 저정도만 입력해보 작동 가능 할 것이다.

나의 코드에는 그 외에도 DB를 이용하기 위한 라이브러리, os 등등 너무 잡다하게 있어서 pass

 

stock_code = '064550'
_dt = '2021-09-10'
day_list = _dt.split('-')

dt_y = day_list[0]
dt_m = day_list[1]
dt_d = day_list[2]
print('검색날짜 :', dt_y, dt_m, dt_d)    

df_stocks_info = stocks_info()
df_tick = tick(dt_y, dt_m, dt_d, stock_code)

위와 같이 정보를 입력하고,

각각 필요한 데이터를 함수를 호출하여 Dataframe 형태로 저장한다..

 

그 형태는 아래와 같다.

df_stocks_info

stocks_info 는 키움의 종목에 대한 정보들을 담기 위한 것이다. 아직은 코스피, 코스닥 구분 및 종목명만 있다.

추후에 필요하다면 시가총액, 등등 정보 다양한 정보를 받을 것이다.

 

df_tick

예전과 다르게 키움에서 조금 업그레이드를 했는지 전일동시거래량도 추가된 것을 볼 수 있다.

여기서 잠깐 사족을 좀 달자면..

체결시간의 경우 키움 API 는 HHMMSS 형태의 string 형태인데. MS(밀리세컨드) 시간이 없다.

그래서 상기 표에서도 나와있지만. 단순히 데이터들 정보가 들어오는 순서 그대로 놔뒀다.

키움 API 게시판에 찾아보니

저 체결량 순서는 체결되는 순서 그대로라고 하니.. 뭐 맞겠지???(추후에 확인해봐야지.ㅋ)

 

우선 간단하게 시간순에 따라서 체결량을 시각화 해봤다.

px 를 이용하여 상단 및 우측에 histogram도 함께 추가하였다.

stock_name = df_stocks_info.loc[stock_code]['NAME']

fig = px.scatter(df_tick, x=df_tick.index, y="VOLUME", color="VOLUME", marginal_x='histogram', 
                 marginal_y="histogram", width=1500, height=1000, title='{} {} 체결창 분석'.format(_dt, stock_name))

fig.show()

바이오니아_체결창.html
6.78MB

 

위에서 보면 9시 10시 2시 정도에 체결량이 증가 한 것을 알 수 있다.

그리고........음....... 뭐냐? 뭐가 있냐!! 제발 보여달라!!! 나에게 인사이트를 내어달라!!!! ㅠ.ㅠ

반응형

이번에는 모든 데이터를 같은 차트에 넣고 볼려고 한다.

자세한 내용은 구글등에서 plotly multipule axes 등 으로 검색하면 관련 자료들이 많다.

한참 구글링 한 다음 만든 차트

fig = go.Figure()
go.Scatter
fig.add_trace(go.Scatter(x=df_tick.index, y=df_tick['VOLUME'], name="체결량", mode='markers', 
                         marker=dict(size=5, color=df_tick['VOLUME'], line_width=1)))
fig.add_trace(go.Line(x=df_tick.index, y=df_tick['PRICE'], name="체결가", yaxis="y2", line=dict(color='#9467bd')))
fig.add_trace(go.Line(x=df_tick.index, y=df_tick['TURNOVER_RATE'], name="회전율", yaxis="y3", line=dict(color='#d62728')))
fig.add_trace(go.Line(x=df_tick.index, y=df_tick['TRANS_STR'], name="체결강도", yaxis="y4", line=dict(color='#ff7f0e')))
fig.add_trace(go.Line(x=df_tick.index, y=df_tick['PAST_STIME_RATE'], name="전동거", yaxis="y5", line=dict(color='#1f77b4')))

fig.update_layout(xaxis=dict(domain=[0.1, 0.8]),
                  yaxis=dict(title='체결량'), 
                  yaxis2=dict(title='체결가', titlefont=dict(color='#9467bd'), tickfont=dict(color='#9467bd'), anchor='free', overlaying='y', side='left', position=0.05),
                  yaxis3=dict(title='회전율',titlefont=dict(color='#d62728'), tickfont=dict(color='#d62728'), anchor='free', overlaying='y', side='left', position=0.01),
                  yaxis4=dict(title='체결강도',titlefont=dict(color='#ff7f0e'), tickfont=dict(color='#ff7f0e'), anchor='x', overlaying='y', side='right'),
                  yaxis5=dict(title='전동거',titlefont=dict(color='#1f77b4'), tickfont=dict(color='#1f77b4'), anchor='free', overlaying='y', side='right', position=0.85))

fig.update_layout(title_text='{} {} 종합분석'.format(_dt, stock_name), width=1500, height=1200)

fig.show()

xaxis 축의 domain 의 경우 표의 구역을 정의 한다고 보면 될 듯한다.

그리고 거기에 맞춰서 position 을 이용하여 원하는 위치에 넣어주면 된다.

 

위와 같이 작성하면 아래와 같은 결과를 얻을 수 있다.

이날 바이오니아 종목의 체결량이 많았는지 꽤 무겁다. 용량도 크고..

 

다른 분들은 저와 같이 삽질하질 마시길...

프로그래밍 공부를 위한 분석인가? 투자를 잘 해서 돈을 벌기 위함 인가???

오늘도 난 고민에 빠진다.... 시간 로스가 너무 많다. 쳇.

 

728x90
반응형
:
Posted by 패치#노트
2021. 6. 28. 19:47

(1292): Truncated incorrect DOUBLE value Programming/Python2021. 6. 28. 19:47

728x90
반응형
sql_80040 = "SELECT * FROM `{}{}{}_80040` WHERE stock_code='{}'".format(dt_y, dt_m, dt_d, stock_code)

위의 코드에서 종목 코드를 mysql에서 제대로 읽어오지 않았던 문제를...

정말 단순했지만 신경을 쓰지 않았던 문제를...

 

mysql에서 데이터를 읽어 올때. where 구문에서 integer 형태로 들어가는

stock_code={ } 부분의 코드를 stock_code = '{ }' 로 바꾸어서 해결..

 

역시 기본에 충실해야 하는 거다...ㅠ.ㅠ

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

어떤 게시판을 크롤링하고 싶어서

selenium 으로 작업하던 도중 pyautogui 를 이용하여 글 제목을 크롤링해서 붙여넣기를 하는데

계속 오류가 발생했었다.

 

그 원인은..... 한글 입력이 되지 않았던것..

그래서 그 해결책을 조금 찾아봤다.

 

우선 

pip install pyperclip

이놈을 인스톨하고 나서.

 

import pyperclip

file_name = '한글 제목'
pyperclip.copy(file_name)
pyautogui.hotkey('ctrl', 'v')

이런식으로 작업을 하면 원하는 곳에 한글을 자동으로 입력할 수 있게 된다.

클립보드로 복사 후 다시 붙여 넣는 방식이라고 생각하면 된다.

 

또한.. 크롤링 시 웹페이지를 자동으로 저장할 때는 특수문자

? < > | : * / \ 등의 특수문자가 들어가게 되면 오류가 발생하게 된다.

이것 또한 해결을 해 주는 것이 좋다.

 

[특수문자 없애기-1]

# 특수문자 없애기-1
characters = "/'!?|*<>:\\"
str_title = "안녕하세요_!@##$%%^^|/'!?|*<>:\\: Goodmorning"
new_title = ''.join(x for x in str_title if x not in characters)
print(new_title)

#출력
안녕하세요_@##$%%^^ Goodmorning

이런식으로 그냥 없애는 방식으로 진행했다.

replace, 정규식의 sub 등이 있는데 번거롭기만 한듯.

위의 방식이 나에게는 가장 간단한 방식이라고 생각한다.

 

[특수문자없애기-2]

# 특수문자 없애기-2
import re

str_title = "안녕하세요_!@##$%%^^|/'!?|*<>:\\: Goodmorning"
new_title = re.sub('[^a-zA-Z0-9ㄱ-힣]', '_', str_title)
print(new_title)

#출력
안녕하세요_______________________Goodmorning

정규식도 이용해서 작업을 해봤다.

1번 방법도 괜찮지만 for문도 돌리고, 혹시나 글 이외의 특수문자들로 인해서 다른 오류가 나면 안되니깐..

2번째 방법은 특수문자나 중간 띄워쓰기 부분은 '_' underscore 로 모두 변환

728x90
반응형
:
Posted by 패치#노트
2021. 6. 10. 13:09

Range 함수 역순 Programming/Python2021. 6. 10. 13:09

728x90
반응형

Range 함수 역순

for문에서 range 를 이용할 때 가끔은 리버스로 순서가 돌아가는 것이 필요할 때가 있다.

 

for i in range(10, 0, -1):
    print(f"카운트 다운!!! {i}")

위와 같이 입력면 역순으로 수를 전달할 수 있다.

여기서 주의할 점은 10이 스타트.. 10부터 시작

0 앞에 까지 가서 멈춘다는 것 즉.. 1까지만 전달이 된다는 것을 염두에 두고 있어야 한다.

# 결과
카운트 다운!!! 10
카운트 다운!!! 9
카운트 다운!!! 8
카운트 다운!!! 7
카운트 다운!!! 6
카운트 다운!!! 5
카운트 다운!!! 4
카운트 다운!!! 3
카운트 다운!!! 2
카운트 다운!!! 1

 

Built-in Types — Python 3.9.5 documentation

 

Built-in Types — Python 3.9.5 documentation

The following sections describe the standard types that are built into the interpreter. The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some collection classes are mutable. The methods that add, subtract,

docs.python.org

Ranges

The range type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops.

class range(stop)class range(start, stop[, step])

The arguments to the range constructor must be integers (either built-in int or any object that implements the __index__ special method). If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. If step is zero, ValueError is raised.

For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.

For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i, but the constraints are i >= 0 and r[i] > stop.

A range object will be empty if r[0] does not meet the value constraint. Ranges do support negative indices, but these are interpreted as indexing from the end of the sequence determined by the positive indices.

Ranges containing absolute values larger than sys.maxsize are permitted but some features (such as len()) may raise OverflowError.

Range examples:

>>>>>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list(range(1, 11)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> list(range(0, 30, 5)) [0, 5, 10, 15, 20, 25] >>> list(range(0, 10, 3)) [0, 3, 6, 9] >>> list(range(0, -10, -1)) [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] >>> list(range(0)) [] >>> list(range(1, 0)) []

Ranges implement all of the common sequence operations except concatenation and repetition (due to the fact that range objects can only represent sequences that follow a strict pattern and repetition and concatenation will usually violate that pattern).

start

The value of the start parameter (or 0 if the parameter was not supplied)

stop

The value of the stop parameter

step

The value of the step parameter (or 1 if the parameter was not supplied)

The advantage of the range type over a regular list or tuple is that a range object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the start, stop and step values, calculating individual items and subranges as needed).

Range objects implement the collections.abc.Sequence ABC, and provide features such as containment tests, element index lookup, slicing and support for negative indices (see Sequence Types — list, tuple, range):

>>>>>> r = range(0, 20, 2) >>> r range(0, 20, 2) >>> 11 in r False >>> 10 in r True >>> r.index(10) 5 >>> r[5] 10 >>> r[:5] range(0, 10, 2) >>> r[-1] 18

Testing range objects for equality with == and != compares them as sequences. That is, two range objects are considered equal if they represent the same sequence of values. (Note that two range objects that compare equal might have different start, stop and step attributes, for example range(0) == range(2, 1, 3) or range(0, 3, 2) == range(0, 4, 2).)

Changed in version 3.2: Implement the Sequence ABC. Support slicing and negative indices. Test int objects for membership in constant time instead of iterating through all items.

Changed in version 3.3: Define ‘==’ and ‘!=’ to compare range objects based on the sequence of values they define (instead of comparing based on object identity).

New in version 3.3: The start, stop and step attributes.

See also

  • The linspace recipe shows how to implement a lazy version of range suitable for floating point applications.
728x90
반응형
:
Posted by 패치#노트
2021. 2. 16. 09:52

파이썬 차트, plotly-00 #시작 Programming/Python2021. 2. 16. 09:52

728x90
반응형

# 파이썬으로 주식 데이터를 분석하다면 그래프를 무조건 사용하게 되어 있다.

나는 초창기에 기본적인 matplotlib을 가지고 시도했었으나 plotly 를 알고 나서부터는 이것만 사용하게 되었다.

 

# 가장 큰 차이점은 matplotlib 의 경우 주가 데이터를 그리더라도 활용도가 plotly 보다 훨~~~~씬 뒤처지는 개인적인 느낌이 있어서 plotly만 사용하고 있는 중이다.

 추후에 더 좋은 것이 나온다면..... 음...~ move move~~

 

# 오늘은 시작하는 느낌으로 기초부터 시작하고

점점 내가 활용하고 있는 단계까지 작성을 해볼려고 한다.

 

# 나를 위한 공부 start!!!!

 

[설치]

pip install plotly

만약 주피터 노트북을 사용한다면

!pip install plotly

 

[공식 사이트]

plotly.com/

 

Plotly: The front end for ML and data science models

Plotly creates & stewards the leading data viz & UI tools for ML, data science, engineering, and the sciences. Language support for Python, R, Julia, and JavaScript.

plotly.com

# 대부분 Jupyter notebook을 활용해서 그래프를 그리고 있으므로 Jupyter notebook 위주로 설명

 

plotly.com/python/getting-started/

[그래프 그려보기]

import plotly.graph_objects as go
fig = go.Figure(data=go.Bar(y=[2, 3, 1]))
fig.show()

 

Jupyter notebook 구현

# matplotlib은 이미지를 화면에 찍어내지만, plotly 는 위와 같이 쉽게 active 하게 그릴 수 있다.

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