달력

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
반응형

2개의 데이터 프레임을 한줄씩 교차로 합쳐보는 것을 한번 해보겠습니다.

구글링을 해봐도 검색 스킬이 부족해서 인지 제가 원하는 그런 예제가 없더라구요.

그리고, dataframe의 기능들을 살펴봐도 잘 모르겠구요.

그래서 임시방편으로 한줄씩 읽어서 교차적으로 concat 을 이용해서 붙여보았습니다.

두개의 데이터프레임을 합치기 붙이고자 하는 데이터프레임의 컬럼수는 맞아야 합니다.

df1과 df2과 각각의 로우에 대해서 불러와야 하므로 loc 함수를 이용해서 한줄을 불러옵니다.

불러왔지만, 데이터가 series 형식처럼 row가 아닌 column 으로 배치가 되어 T 를 사용해서 transform 해줍니다.

이렇게 변형되는 것을 확인 후에는 for 문을 사용하여 한줄씩 붙여보도록 하겠습니다.

위와 같이 한줄씩 concat으로 적용된 것을 볼 수 있습니다.

 

여담이지만, 이렇게 코랩에서 간단하게 연습을 해보고 파이참으로 이 코드를 적용해봤을때는 

왜 그런지 또~~^^;; 적용이 안되더라구요.. 에잇!

 

그래서, 파이참에서 적용할때는 각각의 데이터프레임을 걍 리스트로 만들고

그 리스트를 하나씩 순차적으로 돌아가면서 리스트를 형성 뒤 데이터프레임으로 만들었습니다. ㅠ.ㅠ

노가다....젠장.

 

혹시나 다른 좋은 방법 있으시면 좀 알려주세요~!!!!!!!!!

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

파이썬 소수점 자리 표기하는 여러가지 예제를 알아보도록 하겠습니다.

자주 안쓰면 은근히 찾아 볼때가 많아서 정리도 할겸 한번 알아보겠습니다.

 

round() 함수를 사용하는 방법 

round() 함수는 숫자를 지정된 자릿수로 반올림합니다. 예를 들어, 다음과 같이 사용할 수 있습니다.

 

문자열 포맷팅을 사용하는 방법

문자열 포맷팅을 사용하여 소수점 자리를 표기할 수 있습니다. 예를 들어, 다음과 같이 사용할 수 있습니다.

 

f-string을 사용하는 방법

f-string을 사용하여 소수점 자리를 표기할 수 있습니다. 예를 들어, 다음과 같이 사용할 수 있습니다

 

 

% 연산자를 사용하는 방법

% 연산자를 사용하여 소수점 자리를 표기할 수 있습니다. 예를 들어, 다음과 같이 사용할 수 있습니다.


소수점과 콤마를 동시에 표현하는 방법

 

f-string을 사용하는 방법

f-string을 사용하여 숫자를 포맷팅하고, format() 함수를 사용하여 콤마를 추가할 수 있습니다. 예를 들어, 다음과 같이 사용할 수 있습니다.

 

 

문자열 포맷팅을 사용하는 방법

문자열 포맷팅을 사용하여 숫자를 포맷팅하고, format() 함수를 사용하여 콤마를 추가할 수 있습니다. 예를 들어, 다음과 같이 사용할 수 있습니다.

 

f-string의 경우에는 파이썬 3.5 이하의 버전에는 지원하지 않기 때문에 문자열 포맷팅을 사용해야 합니다.

감사합니다.

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

요즘 chatGPT를 많이 사용하고 있는데요.

내용이 짤릴때 이전에는 별 생각이 없어서 넘어갔지만 파이썬 코드등을 볼떄면 너무 불편했습니다.

 

이번에도 주식관련 머신러닝 파이썬 코드에 대해서 알아보고 있었는데요.

짤리길래, 걍 넘어갈려고 하다가 '계속' 이렇게 입력을 해봤습니다.

(혹시나 다른 좋은 방법 있으시면 알려주세요.)

뭔가 내용이 마무리 돨때까지 계속을 입력하는 것입니다.

 

계속을..계속입력합니다.

그러다보면 이렇게 내용도 짧아지고, 뭔가 마무리 하는 멘트를 chatGPT 가 날려줍니다.ㅋ

이거 혹시 설명서나 뭐 가이드에 나와있는 내용인가요?ㅋ

전 막 검색해보던지라..ㅋㅋ 그 따위(?)것은 과감히 패스~~^^;;;

 

참고로 전 chatGPT plus 를 구독하고 있기는 하지만 무료계정에서도 동일하지 않을까요?

안된다면 너무 치사.......^^;;

 

한글로 입력해주기는 했지만 영어로 질문하고 "continue" 를 입력해도 동일하게 계속 내용을 이어 줄거라 믿습니다.~^^

 


이렇게 마칠려고 했는데요. 궁금했습니다. 그래서 제가 해봤습니다.

"그래서 왜요?"와 비슷한 느낌의 "계속"과 "왜요?" 지옥...

뭔가 자꾸 마무리 하는 느낌이 듭니다. 그래도 난 멈추지 않아~~~~~~~~~~~~!

 

자꾸 겉도는 느낌으로 비슷한 내용으로 대답을 합니다.

근데 우오~~~ 단 한번도 같은 답변을 안 하는 군요. 챗대리~

그래서 왜 그런지 물어봤습니다.

자신의 입장을 이야기 하는 군요. 그리고, 공통점이. 뭔가 짜증나는 느낌이... 느낌표( ! )로 자꾸 물어보지말라고 이야하는 것 같습니다. ^^;;

 

오늘도 슬기로운 chatGPT 생활이었습니다.

감사합니다.

 

 

728x90
반응형
:
Posted by 패치#노트
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
반응형

안녕하세요.

오늘도 챗GPT와 함께 파이썬 코드를 만들어보았습니다.

 

주식 차트중 하나인 일목균형표입니다.

https://namu.wiki/w/%EC%9D%BC%EB%AA%A9%EA%B7%A0%ED%98%95%ED%91%9C

 

일목균형표 - 나무위키

전환선 (과거 9일간의 최고가+과거 9일간의 최저가)/2기준선(과거 26일간의 최고가+과거 26일간의 최저가)/2후행스팬금일 종가를 26일 전에 기입선행스팬1(금일 전환선값+금일 기준선값)/2, 이 수치

namu.wiki

일명 구름대라고 하는 곳을 벗어나는 주식이 좀더 강하다라는 이야기 인데 이걸 파이썬 코드로 한번 짜보겠습니다.

예전에는 이런것들을 일일이 구글링해서 운좋게 파이썬 코드가 있으면 복붙하면 되지만,

만약에 없었다면 수식을 보면서 일일이 만들어야 하는 수고로움이 있었죠.

하지만. chatGPT와 함께.ㅎㅎ 요즘 너무 친하게 지내는 것 같습니다.^^;;

짧은 영어실력임에도 영어로 질문하면 뭔가 조금더 정밀하게 대답을 해주는 것 같아서 영어로 진행해 보았습니다.

https://openai.com/blog/chatgpt/

 

ChatGPT: Optimizing Language Models for Dialogue

We’ve trained a model called ChatGPT which interacts in a conversational way. The dialogue format makes it possible for ChatGPT to answer followup questions, admit its mistakes, challenge incorrect premises, and reject inappropriate requests. ChatGPT is

openai.com

 

please make a Ichimoku Chart for stock in python
Sure, I can guide you through creating an Ichimoku Chart for a stock in Python. The Ichimoku Chart is a popular technical analysis tool that combines multiple indicators to provide a comprehensive view of a stock's price action.

To create an Ichimoku Chart, we need to calculate several indicators and plot them on a chart. The indicators we will use are:
Tenkan-sen (Conversion Line): This is the midpoint of the highest high and lowest low over the past 9 periods.Kijun-sen (Base Line): This is the midpoint of the highest high and lowest low over the past 26 periods.Senkou Span A (Leading Span A): This is the average of the Tenkan-sen and Kijun-sen plotted 26 periods ahead.Senkou Span B (Leading Span B): This is the midpoint of the highest high and lowest low over the past 52 periods, plotted 26 periods ahead.Chikou Span (Lagging Span): This is the current closing price plotted 26 periods behind.
Here is the Python code to calculate these indicators and plot the Ichimoku Chart for a stock:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Load stock price data into a pandas dataframe
df = pd.read_csv('stock_price_data.csv')

# Calculate Tenkan-sen (Conversion Line)
period9_high = df['High'].rolling(window=9).max()
period9_low = df['Low'].rolling(window=9).min()
df['tenkan_sen'] = (period9_high + period9_low) / 2

# Calculate Kijun-sen (Base Line)
period26_high = df['High'].rolling(window=26).max()
period26_low = df['Low'].rolling(window=26).min()
df['kijun_sen'] = (period26_high + period26_low) / 2

# Calculate Senkou Span A (Leading Span A)
df['senkou_span_a'] = ((df['tenkan_sen'] + df['kijun_sen']) / 2).shift(26)

# Calculate Senkou Span B (Leading Span B)
period52_high = df['High'].rolling(window=52).max()
period52_low = df['Low'].rolling(window=52).min()
df['senkou_span_b'] = ((period52_high + period52_low) / 2).shift(26)

# Calculate Chikou Span (Lagging Span)
df['chikou_span'] = df['Close'].shift(-26)

# Plot the Ichimoku Chart
plt.figure(figsize=(12,8))
plt.plot(df['Date'], df['tenkan_sen'], color='red', label='Tenkan-sen')
plt.plot(df['Date'], df['kijun_sen'], color='blue', label='Kijun-sen')
plt.fill_between(df['Date'], df['senkou_span_a'], df['senkou_span_b'], where=df['senkou_span_a'] >= df['senkou_span_b'], color='green', alpha=0.2, label='Bullish Cloud')
plt.fill_between(df['Date'], df['senkou_span_a'], df['senkou_span_b'], where=df['senkou_span_a'] < df['senkou_span_b'], color='red', alpha=0.2, label='Bearish Cloud')
plt.plot(df['Date'], df['chikou_span'], color='purple', label='Chikou Span')
plt.plot(df['Date'], df['Close'], color

일목균형표에 대한 간략한 설명과 함께 코드를 리턴해주었습니다만!!!!!!!!!!!!!!!!!!!

짤렸네요.ㅋㅋㅋ

그래서 코드로 옮길시 제가 임의로 막 작성했어요.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Load stock price data into a pandas dataframe
df = pd.read_csv('stock_price_data.csv')

# Calculate Tenkan-sen (Conversion Line)
period9_high = df['High'].rolling(window=9).max()
period9_low = df['Low'].rolling(window=9).min()
df['tenkan_sen'] = (period9_high + period9_low) / 2

# Calculate Kijun-sen (Base Line)
period26_high = df['High'].rolling(window=26).max()
period26_low = df['Low'].rolling(window=26).min()
df['kijun_sen'] = (period26_high + period26_low) / 2

# Calculate Senkou Span A (Leading Span A)
df['senkou_span_a'] = ((df['tenkan_sen'] + df['kijun_sen']) / 2).shift(26)

# Calculate Senkou Span B (Leading Span B)
period52_high = df['High'].rolling(window=52).max()
period52_low = df['Low'].rolling(window=52).min()
df['senkou_span_b'] = ((period52_high + period52_low) / 2).shift(26)

# Calculate Chikou Span (Lagging Span)
df['chikou_span'] = df['Close'].shift(-26)

# Plot the Ichimoku Chart
plt.figure(figsize=(12,8))
plt.plot(df['Date'], df['tenkan_sen'], color='red', label='Tenkan-sen')
plt.plot(df['Date'], df['kijun_sen'], color='blue', label='Kijun-sen')
plt.fill_between(df['Date'], df['senkou_span_a'], df['senkou_span_b'], where=df['senkou_span_a'] >= df['senkou_span_b'], color='green', alpha=0.2, label='Bullish Cloud')
plt.fill_between(df['Date'], df['senkou_span_a'], df['senkou_span_b'], where=df['senkou_span_a'] < df['senkou_span_b'], color='red', alpha=0.2, label='Bearish Cloud')
plt.plot(df['Date'], df['chikou_span'], color='purple', label='Chikou Span')
plt.plot(df['Date'], df['Close'], color='black', label='Close')

이렇게 짤린부분을 수습(?)을 하고 나서 실행을 해보았으나..에러가 나요~^^

전 그나마 얼마되지 않는 짬밥 좀 있다고 위에 리턴해준 코드를 보자마자 에러 날것을 알고 있었지만...

이런 문구를 보니 친절하지 않는 GPT에게 서운함이..ㅎㅎ

상단에 csv로 저장하는 부분. 즉 데이터가 있어야 합니다.

역시나 엄청 친절하지는 않는 GPT아조씨..ㅋ

 

걍 제가 작성해도 되지만..

그래도 다시 한번 물어봤습니다.

how to get the stock_price_data.csv

솔직히 기대를 안하고 물어봤는데...

To get the 'stock_price_data.csv' file, you can use a financial data API or a web scraper to retrieve the historical stock price data for the desired stock. Here's an example of how to use the 'yfinance' library in Python to download historical stock price data:
import yfinance as yf

# Set the stock ticker symbol and the date range
ticker = 'AAPL'
start_date = '2020-01-01'
end_date = '2022-02-24'

# Download the historical stock price data using yfinance
data = yf.download(ticker, start=start_date, end=end_date)

# Save the data to a CSV file
data.to_csv('stock_price_data.csv')
This code will download the historical stock price data for Apple (AAPL) from January 1, 2020 to February 24, 2022 and save it to a CSV file named stock_price_data.csv in the current directory. You can modify the code to download the data for a different stock and date range by changing the ticker, start_date, and end_date variables.

예상외로..간략한 사용법과 함께 yfinance 라이브러리로  실행하는 방법을 알려줍니다.

전 구글코랩을 자주 이용하기 때문에 yfinance가 설치가 안되어 있어서 에러가 날줄? 알지만. 걍 복붙 해봅니다.ㅎ

역시나 ' No module named 'yfinance' 를 뱉어내는 군요^^

그래서!!!!!!! 또 물어봤습니다.

how to install yfinance library in python.

(너무나 정직한(?) 저의 검소한 영어 실력.ㅋ)

To install the yfinance library in Python, you can use pip, which is a package manager for Python. Here are the steps to install yfinance:
1. Open a terminal or command prompt.
2. Type pip install yfinance and press Enter.
3. Wait for pip to download and install the yfinance library and its dependencies.
Here's an example of how to use yfinance to download historical stock price data:
import yfinance as yf

# Set the stock ticker symbol and the date range
ticker = 'AAPL'
start_date = '2020-01-01'
end_date = '2022-02-24'

# Download the historical stock price data using yfinance
data = yf.download(ticker, start=start_date, end=end_date)

# Print the data to the console
print(data)
This code will download the historical stock price data for Apple (AAPL) from January 1, 2020 to February 24, 2022 and print it to the console. You can modify the code to download the data for a different stock and date range by changing the ticker, start_date, and end_date variables.

오.. 친절하게 알려줍니다.

그래서 설치

!pip install yfinance

 

설치후 다시 재실행

다시 stock_price_data.csv 를 로딩하고,

코드실행..두근두근..

오...만들어지네요.ㅋ

이게 정확한지는 모르겠지만, 무료의 한계인가요? 짤린 코드 뒤가 궁금하지만. 여기까지 해보았구요.

 

역시나 오늘도 느끼는 거지만 질문을 잘 던져야 한다는 것 같아요. 그래서 좀더 구체적인 질문을 해보았어요.

이렇게 답변을 주길래 실행을 해봤는데..

에러가 나네요.ㅋ

아마도 mplfinance 라이브러리가 뭔가 업데이트가 되면서 mpf.make_ichimoku 모듈이 없나봐요.

 

오늘도 chatGPT한테서 하나 배우고 갑니다.

 

좋은 하루 되세요~^^

728x90
반응형
:
Posted by 패치#노트
2023. 2. 23. 21:30

로또 번호 생성기 ^^ (feat. chatGPT) Programming/Python2023. 2. 23. 21:30

728x90
반응형

■ chat GPT 와 함께 놀기

로또 번호 생성기를 파이썬으로 만들어 보았습니다.

우선 아래와 같이 진행을 했구요.

https://openai.com/blog/chatgpt/

 

ChatGPT: Optimizing Language Models for Dialogue

We’ve trained a model called ChatGPT which interacts in a conversational way. The dialogue format makes it possible for ChatGPT to answer followup questions, admit its mistakes, challenge incorrect premises, and reject inappropriate requests. ChatGPT is

openai.com

please make the code for lotto number using python language in South Korea.
 
 

Sure, here is an example code for generating a set of six random lotto numbers (1-45) in Python:

import random

# Set the number of lotto numbers to generate
num_numbers = 6

# Set the range of possible lotto numbers (1-45)
min_number = 1
max_number = 45

# Generate a list of unique random lotto numbers
lotto_numbers = random.sample(range(min_number, max_number+1), num_numbers)

# Sort the lotto numbers in ascending order
lotto_numbers.sort()

# Print the lotto numbers
print("Today's lotto numbers are:")
for number in lotto_numbers:
    print(number, end=' ')

Please note that this code is for educational purposes only and should not be used to generate actual lotto numbers for gambling or other purposes.

친절한 주석과 함께 결과를 리턴해줍니다.


구글 코랩에서 이 코드를 실행해보았습니다.

Today's lotto numbers are:
12 22 23 26 30 34
Today's lotto numbers are:
5 8 11 37 38 42

어찌보면 간단하다고 볼수 있지만, 생각도 하지 않고 검색해서 뚝딱하고 나오니 소오름~~~^^;;

간단한 대학 퀴즈나 레폿같은것은 정말 도움이 많이 되겠는걸요.

매일 매일 이것저것 하나씩 만들어보면서 실행해봐야겠습니다.

좋은 하루되세요~^^

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 패치#노트
728x90
반응형

오늘 키움 호가창 실시간 데이터를 mysql DB에 수집하는 C#을 가동해봤다...

10시 50분부터 시작을 해서 16시 11분까지..

집중되는 9시~10시 사이는 코딩 수정때문에 수집을 하지는 못했음에도 불구하고..

헐...6.4 기가라니.....

 

호가창 분석은 일자 limit를 두던지 아니면 해야 할듯..

 

관리가 필요할 듯 하다...

DB까지도 공부해야 하나? ㅠ.ㅠ

 

아니면 초기 integer 자릿수에 대해서 정확히 안배해 볼까?

음....

근데 내가 이 데이터로 멀 할려는 거지? 젠장..

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

파이썬 datetime의 timedelta 에는 day 를 더해서 몇일 후의 날짜를 구할 수는 있지만,

다음달을 계산해주지는 않는다.

 

timedelta 를 편법적으로 사용해서 하는 방법도 있지만,

calendar 함수를 사용하면 아주 편하게 return 받을 수 있다.

 

calendar 함수는 기본함수이므로 바로 import를 해준다.

import calendar

기본 문서는 아래 링크를 통해서 확인 할 수 있다.

calendar — General calendar-related functions — Python 3.9.7 documentation

 

calendar — General calendar-related functions — Python 3.9.7 documentation

calendar — General calendar-related functions Source code: Lib/calendar.py This module allows you to output calendars like the Unix cal program, and provides additional useful functions related to the calendar. By default, these calendars have Monday as

docs.python.org

 

여기서 몇 가지의 예제를 살펴보면

내가 가장 찾고 있었던 기능인 다음달 계산은 nextmonth 함수와 연도, 달..

입력으로 다음달을 계산해 준다.

calendar.nextmonth(2021, 12)

위와 같이 한줄로 바로 알아낼수가 있다. 하지만!!!!!

여기서 주의할 점은..

그럴리는 잘 없지만 잘못된 달을 입력하게 되면 이런식으로 리턴받게 된다.

calendar.nextmonth(2021, 13)

이건 내부함수에서 볼 수 있듯이 12만 인식을 하고 있다.

def _nextmonth(year, month):
    if month == 12:
        return year+1, 1
    else:
        return year, month+1

그래서 12이상으로 안 들어가도록 미리 input limit 을 준다던지 하는식으로 코딩해줘야 한다.

 

그외에도 아래와 같이 다양하게 활용할 수 있다.

* 캘린더 호출

calendar.calendar(2021)

이렇게 호출하면 되지만, 주피터 노트북에서는 print를 붙여주지 않으면 이런식으로 나온다.

따라서 호출할때는 print( ) 와 함께

print(calendar.calendar(2021))

 

* 원하는 달 호출

calendar.prmonth(2021, 9)

 

* monthrange 를 쓸 경우에는 그 달의 시작하는 1일의 요일과, 마지막날의 날짜를 리턴해준다.

calendar.monthrange(2021, 9)

(2, 30)

에서 2는 0(월), 1(화), 2(수), 3(목), 4(금), 5(토), 6(일).. 을 각각 가지고 있으므로

수요일로 시작한다는 것을 알 수 있고,

마지막날은 30일..리턴

 

* 요일 알기

calendar.weekday(2021, 9, 4)

5가 리턴 되었으니 토요일 인것을 알 수가 있다.

 

* 그 달을 리스트형식으로 리턴

calendar.monthcalendar(2021,9)

 

위와 같이 다양하게 활용할 수 있다.

calendar 함수와 datetime 함수를 이용한다면 다양한 날짜에 관한 사항들을 활용할 수 있을 것이다.

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

데이터 프레임을 자주 사용하다 보면

각 셀별로 데이터의 길이를 구해서 판단을 해야 하는 경우도 발생하게 된다.

 

예를 들어 아래와 같은 전화번호 컬럼이 있다고 가정해보자.

import pandas as pd
data = [['John', 45, '010-1234-4589'],['Will', 20, '02-1234-1324'],['Ai', 13, '123']]
df = pd.DataFrame(data,columns=['Name','Age', 'Telephone'])
df

 

다양한 방법들이 존재하겠지만,

전화번호 영역에 다른 이상한 것이 끼어있다면 아래와 같이 len( ) 함수를 이용해서 간단하게 처리 할 수 있다.

 

df['Telephone'].apply(len)

len 함수를 사용하게 되면 각 row 별로 리턴해준다.

아래와 같이 조건에 맞게 설정한뒤 다시 데이터프레임으로 저장하면 쓸데없는 값을 쉽게 해결할 수 있다.

df = df[df['Telephone'].apply(len) >= 12]
df

 

간단하지만 많은 부분에서 사용할 수 있을 것라고 생각해본다.

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

안녕하세요.

제목 그대로 크롤링을 하다가 보면 다양한 값들을 읽어와야 하는데요.

 

그중에 특정 텍스트나 속성 값을 불러오는 방법에 대해서 간략히 알아보도록 하겠습니다.

 

[예시]

from bs4 import BeautifulSoup

html_source = '''
    <div class="Top div class 입니다.">
        <div class="Second div class 입니다.">
            <ul class="ul 입니다.">
                <li data-sequence='12345645'>
                <a id="link" href="특정 링크">부자되기 프로젝트!!!!!</a></li>
            </ul>
        </div>
    </div>
'''

soup = BeautifulSoup(html_source, 'html.parser')

a_tag = soup.find_all('a', attrs={"href" : "특정 링크"})

# 태그 불러오기
print('Soup 내용 그대로 불러오기', a_tag)

# 태그내 텍스트 불러오기
print('텍스 내용 불러오기', a_tag[0].text)

# attribute 값 얻어오기
li_tag = soup.find_all('li')
print(li_tag) # 리스트 형태로 반환

attribute = li_tag[0].attrs #리스트의 0 번째 태그
print('attribute 값 얻어오기',attribute)
print('특정 attribute 값 얻오기', attribute['data-sequence'])

 

[결과 값]

Soup 내용 그대로 불러오기 [<a href="특정 링크" id="link">부자되기 프로젝트!!!!!</a>]
텍스 내용 불러오기 부자되기 프로젝트!!!!!
[<li data-sequence="12345645">
<a href="특정 링크" id="link">부자되기 프로젝트!!!!!</a></li>]
attribute 값 얻어오기 {'data-sequence': '12345645'}
특정 attribute 값 얻오기 12345645

soup의 find_all은 보통 리스트형태로 반환됩니다.

리스트로 감싸여 있기 때문에 인덱스를 지정하고 텍스트 불러오기나, attribute 값들을 가지고 오면 됩니다.

 

감사합니다.

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

파이썬 requests 라이브러리를 이용하여 크롤링을 할때

현재 내가 검색해서 보여지는 창의 스크립트가 아닌

다른 내용의 스크립트가 리턴 될 때도 있습니다.

 

그럴때는

requests 와 함께 headers 정보의 user-agent 를 같이 넘겨주게 되면 해결 할 수 있어요.

 

아래는 구글 영화 정보 사이트의 인기차트 내용에 대해서 보는 것인데요.

헤더 정보를 넣는냐 아니냐에 따라서 정보가 달라지는 것을 볼 수 있습니다.

 

[헤더 정보를 넣었을 때]

import requests
from bs4 import BeautifulSoup

url = "https://play.google.com/store/movies/top"
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36 Edg/92.0.902.62'}

res = requests.get(url, headers=headers)

soup = BeautifulSoup(res.text, 'html.parser')

movie_list = soup.select('#fcxH9b > div.WpDbMd > c-wiz > div > c-wiz > div > div > c-wiz > c-wiz > c-wiz > div > div.ZmHEEd > div:nth-child(1) > c-wiz > div > div > div.RZEgze > div > div > div.bQVA0c > div > div > div.b8cIId.ReQCgd.Q9MA7b > a > div')
movie_list
[<div class="WsMG1c nnK0zc" title="A Quiet Place Part II">A Quiet Place Part II</div>]

 

[헤더 정보를 빼고 호출하였을때]

import requests
from bs4 import BeautifulSoup

url = "https://play.google.com/store/movies/top"
res = requests.get(url)

soup = BeautifulSoup(res.text, 'html.parser')

movie_list = soup.select('#fcxH9b > div.WpDbMd > c-wiz > div > c-wiz > div > div > c-wiz > c-wiz > c-wiz > div > div.ZmHEEd > div:nth-child(1) > c-wiz > div > div > div.RZEgze > div > div > div.bQVA0c > div > div > div.b8cIId.ReQCgd.Q9MA7b > a > div')
movie_list
[<div class="WsMG1c nnK0zc" title="F9: The Fast Saga">F9: The Fast Saga</div>,
 <div class="WsMG1c nnK0zc" title="Rick and Morty">Rick and Morty</div>,
 <div class="WsMG1c nnK0zc" title="Gotron Jerrysis Rickvangelion">Gotron Jerrysis Rickvangelion</div>]

 

헤더정보에 대해서는 아래 사이트에 들어가면 본인의 인터넷창에 대한 정보가 나옵니다.

그걸 복사해서 사용하시면 됩니다.

What's My User Agent? (whatmyuseragent.com)

 

What's My User Agent?

Your IP Address 121.53.80.255 Country Name: Korea, Republic of City Name: Latitude: 37.5112 Longitude: 126.9741

whatmyuseragent.com

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

어떤 프로그램을 사용하다가 보면

특정 시간대에 실행하는 경우가 많이 있습니다.

 

windows의 스케쥴링을 이용한다거나 cron을 이용해서 할수도 있지만,

파이썬에서는 간단한 스케쥴 라이브러리가 있습니다.

 

우선 아래와 같이 설치를 하고

pip install schedule

[참고자료]

GitHub - dbader/schedule: Python job scheduling for humans.

 

GitHub - dbader/schedule: Python job scheduling for humans.

Python job scheduling for humans. Contribute to dbader/schedule development by creating an account on GitHub.

github.com

 

라이브러리에 설명된 몇 가지 예시

import schedule
import time
import datetime

def job(message='stuff'):
    print(datetime.datetime.now())
    print("I'm working...")

schedule.every(3).seconds.do(job) # 3초 마다 실행
# schedule.every(10).minutes.do(job) # 10분 마다 실행
# schedule.every().hour.do(job) # 매시간마다 실행
# schedule.every().day.at("10:30").do(job) # 매일 10:30에 실행
# schedule.every(5).to(10).minutes.do(job) # 05:10분에 실행
# schedule.every().monday.do(job) # 월요일마다 실행
# schedule.every().wednesday.at("13:15").do(job) # 수요일마다 13:15에 실행
# schedule.every().minute.at(":17").do(job) # 매시간 17분마다 실행
# schedule.every().hour.do(job, message='things') # 매시간마다 변수와 함께 실행(default는 'stuff')

while True:
    schedule.run_pending()
    time.sleep(1)

※ 3초 마다 실행 확인

이외에도 다양한 예제 파일이 아래 사이트에 있으니 필요한 옵션들을 골라서 사용하면 되구요.

그중 몇 가지 대표적인 기능들을 아래에 적어놨으니

다양하게 조합하셔서 사용하시면 좋을 것 같네요.

schedule/examples.rst at master · dbader/schedule · GitHub

 

GitHub - dbader/schedule: Python job scheduling for humans.

Python job scheduling for humans. Contribute to dbader/schedule development by creating an account on GitHub.

github.com

Run a job every x minute

import schedule
import time

def job():
    print("I'm working...")

# Run job every 3 second/minute/hour/day/week,
# Starting 3 second/minute/hour/day/week from now
schedule.every(3).seconds.do(job)
schedule.every(3).minutes.do(job)
schedule.every(3).hours.do(job)
schedule.every(3).days.do(job)
schedule.every(3).weeks.do(job)

# Run job every minute at the 23rd second
schedule.every().minute.at(":23").do(job)

# Run job every hour at the 42rd minute
schedule.every().hour.at(":42").do(job)

# Run jobs every 5th hour, 20 minutes and 30 seconds in.
# If current time is 02:00, first execution is at 06:20:30
schedule.every(5).hours.at("20:30").do(job)

# Run job every day at specific HH:MM and next HH:MM:SS
schedule.every().day.at("10:30").do(job)
schedule.every().day.at("10:30:42").do(job)

# Run job on a specific day of the week
schedule.every().monday.do(job)
schedule.every().wednesday.at("13:15").do(job)
schedule.every().minute.at(":17").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

 

Cancel a job

To remove a job from the scheduler, use the schedule.cancel_job(job) method

import schedule

def some_task():
    print('Hello world')

job = schedule.every().day.at('22:30').do(some_task)
schedule.cancel_job(job)

 

 

감사합니다.

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. 5. 8. 23:08

tensorflow 깔아보기 Programming/Python2021. 5. 8. 23:08

728x90
반응형

Python 가상 환경은 패키지 설치를 시스템으로부터 분리하는 데 사용됩니다.

Ubuntu/macOSWindowsConda

Python 인터프리터를 선택하고 저장할 .\venv 디렉터리를 만들어 새로운 가상 환경을 만듭니다.

 

python -m venv --system-site-packages .\venv

가상 환경을 활성화합니다.

 

.\venv\Scripts\activate

호스트 시스템 설정에 영향을 주지 않고 가상 환경 내에 패키지를 설치합니다. pip 업그레이드로 시작합니다.

 

pip install --upgrade pip

pip list  # show packages installed within the virtual environment

가상 환경을 나중에 종료하려면 다음 단계를 따르세요.

 

deactivate  # don't exit until you're done using TensorFlow

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

 

변경전

 

변경후

기존에 프로그래밍을 배울 때 변수명을 한글로 배워서 하다보니..

대부분의 한글 변수명이었는데..

차트 그리기 부분에 Area Chart 부분.. y axis 0 을 기준으로 색이 원래 칠해져야 하지만(변경후).

안되었던 부분(변경전)이..

Series 에 보내는 부분의 변수명을 영문으로 바꾸고 나서.. 되었다... 이게 말이되!???

음.. 다른걸 건드렸나?

 

여튼.. 중요한 것은 여러분!

변수명은 한글이 아닌 영문으로!!! 예상하지 못한 에러가 날 수도 있으니 영문으로 추천 드립니다!!!!

 

 

728x90
반응형

'Programming > C#' 카테고리의 다른 글

C# Datetime  (0) 2021.01.24
:
Posted by 패치#노트
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 패치#노트