analyser_hj3415 3.2.1__py3-none-any.whl → 3.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import os
2
- from dataclasses import dataclass, asdict
2
+ from dataclasses import dataclass
3
3
 
4
4
  from utils_hj3415 import tools, setup_logger
5
5
  from db_hj3415 import myredis
@@ -13,6 +13,21 @@ expire_time = tools.to_int(os.getenv('DEFAULT_EXPIRE_TIME_H', 48)) * 3600
13
13
 
14
14
  @dataclass()
15
15
  class GrowthData:
16
+ """
17
+ 기업의 성장 데이터를 저장하는 데이터 클래스.
18
+
19
+ 이 클래스는 기업의 성장 데이터를 관리하며, 매출액 증가율 및 영업이익률 데이터를 포함합니다.
20
+ 또한, 평가 점수와 관련된 날짜 데이터를 관리합니다.
21
+
22
+ 속성:
23
+ code (str): 기업의 종목 코드 (6자리 숫자 문자열).
24
+ name (str): 기업명.
25
+ 매출액증가율_r (float): 최신 매출액 증가율.
26
+ 매출액증가율_dict (dict): 매출액 증가율과 관련된 과거 데이터.
27
+ 영업이익률_c106 (dict): c106 데이터를 기반으로 한 영업이익률 데이터.
28
+ score (list): 평가 점수.
29
+ date (list): 성장 데이터와 관련된 날짜 목록.
30
+ """
16
31
  code: str
17
32
  name: str
18
33
 
@@ -26,6 +41,19 @@ class GrowthData:
26
41
 
27
42
 
28
43
  class Growth:
44
+ """
45
+ 기업의 성장 데이터를 계산하고 관리하는 클래스.
46
+
47
+ 이 클래스는 기업의 매출액 증가율, 영업이익률 등과 같은 성장 지표를 계산하며,
48
+ Redis 캐시를 통해 데이터를 저장하고 재사용할 수 있도록 지원합니다.
49
+
50
+ 속성:
51
+ c101 (myredis.C101): 기업 정보와 데이터를 가져오기 위한 객체.
52
+ c104 (myredis.C104): 매출액 증가율 데이터를 관리하기 위한 객체.
53
+ c106 (myredis.C106): 영업이익률 데이터를 관리하기 위한 객체.
54
+ name (str): 기업명.
55
+ _code (str): 기업 종목 코드.
56
+ """
29
57
  def __init__(self, code: str):
30
58
  assert tools.is_6digit(code), f'Invalid value : {code}'
31
59
  mylogger.debug(f"Growth : 종목코드 ({code})")
@@ -42,10 +70,27 @@ class Growth:
42
70
 
43
71
  @property
44
72
  def code(self) -> str:
73
+ """
74
+ 현재 기업의 종목 코드를 반환합니다.
75
+
76
+ 반환값:
77
+ str: 기업의 종목 코드 (6자리 숫자 문자열).
78
+ """
45
79
  return self._code
46
80
 
47
81
  @code.setter
48
82
  def code(self, code: str):
83
+ """
84
+ 기업의 종목 코드를 변경합니다.
85
+
86
+ 종목 코드 변경 시 관련된 데이터 객체(c101, c104, c106)의 코드도 함께 변경됩니다.
87
+
88
+ 매개변수:
89
+ code (str): 변경할 종목 코드 (6자리 숫자 문자열).
90
+
91
+ 예외:
92
+ AssertionError: 종목 코드가 6자리 숫자 문자열이 아닐 경우 발생.
93
+ """
49
94
  assert tools.is_6digit(code), f'Invalid value : {code}'
50
95
  mylogger.debug(f"Growth : 종목코드 변경({self.code} -> {code})")
51
96
 
@@ -60,6 +105,21 @@ class Growth:
60
105
  return [0,]
61
106
 
62
107
  def _generate_data(self, refresh=False) -> GrowthData:
108
+ """
109
+ 성장 데이터를 계산하여 GrowthData 객체를 생성합니다.
110
+
111
+ 이 함수는 매출액 증가율, 영업이익률 등의 데이터를 계산하고,
112
+ 이를 GrowthData 객체로 정리하여 반환합니다.
113
+
114
+ 매개변수:
115
+ refresh (bool, optional): 데이터를 새로고침할지 여부. 기본값은 False.
116
+
117
+ 반환값:
118
+ GrowthData: 계산된 성장 데이터를 포함하는 객체.
119
+
120
+ 예외:
121
+ ValueError: 날짜 데이터가 없을 경우 기본값으로 빈 날짜 리스트를 설정.
122
+ """
63
123
  self.c104.page = 'c104y'
64
124
  _, 매출액증가율_dict = self.c104.find('매출액증가율', remove_yoy=True, refresh=refresh)
65
125
 
@@ -95,9 +155,20 @@ class Growth:
95
155
 
96
156
  def get(self, refresh = False, verbose = True) -> GrowthData:
97
157
  """
98
- GrowthData 형식의 데이터를 계산하여 리턴하고 레디스 캐시에 저장한다.
99
- :param refresh:
100
- :return:
158
+ GrowthData 객체를 Redis 캐시에서 가져오거나 새로 생성하여 반환합니다.
159
+
160
+ 캐시에서 데이터를 검색하고, 없을 경우 `_generate_data`를 호출하여 데이터를 생성합니다.
161
+ 생성된 데이터는 Redis 캐시에 저장되어 재사용됩니다.
162
+
163
+ 매개변수:
164
+ refresh (bool, optional): 캐시 데이터를 무시하고 새로 계산할지 여부. 기본값은 False.
165
+ verbose (bool, optional): 실행 중 상세 정보를 출력할지 여부. 기본값은 True.
166
+
167
+ 반환값:
168
+ GrowthData: Redis 캐시에서 가져오거나 새로 생성된 GrowthData 객체.
169
+
170
+ 로그:
171
+ - 캐시 검색 상태와 새로 생성된 데이터를 출력합니다.
101
172
  """
102
173
  redis_name = f"{self.code}_growth"
103
174
  mylogger.info(f"{self} GrowthData를 레디스캐시에서 가져오거나 새로 생성합니다.. refresh : {refresh}")
@@ -105,6 +176,6 @@ class Growth:
105
176
  print(f"{self} redisname: '{redis_name}' / refresh : {refresh} / expire_time : {expire_time/3600}h")
106
177
 
107
178
  def fetch_generate_data(refresh_in: bool) -> dict:
108
- return asdict(self._generate_data(refresh_in))
179
+ return self._generate_data(refresh_in) # type: ignore
109
180
 
110
- return GrowthData(**myredis.Base.fetch_and_cache_data(redis_name, refresh, fetch_generate_data, refresh, timer=expire_time))
181
+ return myredis.Base.fetch_and_cache_data(redis_name, refresh, fetch_generate_data, refresh, timer=expire_time)
@@ -1,5 +1,5 @@
1
1
  import os
2
- from dataclasses import dataclass, asdict
2
+ from dataclasses import dataclass
3
3
  from typing import Tuple
4
4
  import math
5
5
 
@@ -15,6 +15,32 @@ expire_time = tools.to_int(os.getenv('DEFAULT_EXPIRE_TIME_H', 48)) * 3600
15
15
 
16
16
  @dataclass
17
17
  class MilData:
18
+ """
19
+ 기업의 주요 재무 데이터를 나타내는 데이터 클래스.
20
+
21
+ 이 클래스는 기업의 다양한 재무 데이터를 포함하며,
22
+ 이를 통해 투자 수익률, 가치 지표, 현금 흐름 등을 분석할 수 있습니다.
23
+
24
+ 속성:
25
+ code (str): 기업의 종목 코드 (6자리 숫자 문자열).
26
+ name (str): 기업명.
27
+ 시가총액억 (float): 기업의 시가총액 (억 단위).
28
+ 주주수익률 (float): 재무활동 현금흐름을 기반으로 계산된 주주 수익률.
29
+ 재무활동현금흐름 (float): 재무활동으로 인한 현금흐름.
30
+ 이익지표 (float): 기업의 이익지표.
31
+ 영업활동현금흐름 (float): 영업활동으로 인한 현금흐름.
32
+ 지배주주당기순이익 (float): 지배주주에게 귀속된 당기순이익.
33
+ roic_r (float): ROIC(투하자본이익률).
34
+ roic_dict (dict): ROIC와 관련된 데이터.
35
+ roe_r (float): ROE(자기자본이익률).
36
+ roe_106 (dict): ROE와 관련된 상세 데이터.
37
+ roa_r (float): ROA(총자산이익률).
38
+ fcf_dict (dict): FCF(자유 현금 흐름) 관련 데이터.
39
+ pfcf_dict (dict): PFCF(주가 대비 자유 현금 흐름 비율) 관련 데이터.
40
+ pcr_dict (dict): PCR(주가 대비 현금 흐름 비율) 관련 데이터.
41
+ score (list): 계산된 평가 점수.
42
+ date (list): 재무 데이터와 관련된 날짜 목록.
43
+ """
18
44
  code: str
19
45
  name: str
20
46
 
@@ -44,6 +70,21 @@ class MilData:
44
70
 
45
71
 
46
72
  class Mil:
73
+ """
74
+ 기업의 재무 데이터를 분석하고 계산하는 클래스.
75
+
76
+ 이 클래스는 주어진 종목 코드에 대해 다양한 재무 데이터를 수집하고,
77
+ 이를 기반으로 주요 재무 지표(예: ROIC, ROE, 이익지표 등)를 계산합니다.
78
+ 또한 Redis 캐시를 활용하여 계산된 데이터를 저장하고 재사용할 수 있습니다.
79
+
80
+ 속성:
81
+ c101 (myredis.C101): 기업 정보 및 최근 데이터 접근 객체.
82
+ c103 (myredis.C103): 재무 상태표 데이터 접근 객체.
83
+ c104 (myredis.C104): 투자 지표 데이터 접근 객체.
84
+ c106 (myredis.C106): ROE 관련 데이터 접근 객체.
85
+ name (str): 기업명.
86
+ _code (str): 기업 종목 코드.
87
+ """
47
88
  def __init__(self, code: str):
48
89
  assert tools.is_6digit(code), f'Invalid value : {code}'
49
90
  mylogger.debug(f"Mil : 종목코드 ({code})")
@@ -78,8 +119,16 @@ class Mil:
78
119
 
79
120
  def get_marketcap억(self, refresh: bool) -> float:
80
121
  """
81
- 시가총액(억원) 반환
82
- :return:
122
+ 기업의 시가총액(억 단위) 반환합니다.
123
+
124
+ 매개변수:
125
+ refresh (bool): 데이터를 새로고침할지 여부.
126
+
127
+ 반환값:
128
+ float: 기업의 시가총액 (억 단위).
129
+
130
+ 로그:
131
+ - 계산된 시가총액 정보를 출력합니다.
83
132
  """
84
133
  c101r = self.c101.get_recent(refresh)
85
134
  시가총액 = tools.to_int(tools.to_float(c101r.get('시가총액', math.nan)) / 100000000)
@@ -87,6 +136,19 @@ class Mil:
87
136
  return 시가총액
88
137
 
89
138
  def _calc주주수익률(self, 시가총액_억: float, refresh: bool) -> Tuple[str, float, float]:
139
+ """
140
+ 주주수익률을 계산합니다.
141
+
142
+ 매개변수:
143
+ 시가총액_억 (float): 기업의 시가총액 (억 단위).
144
+ refresh (bool): 데이터를 새로고침할지 여부.
145
+
146
+ 반환값:
147
+ Tuple[str, float, float]: 최근 날짜, 주주수익률, 재무활동 현금흐름.
148
+
149
+ 예외:
150
+ ZeroDivisionError: 시가총액이 0일 경우 주주수익률을 계산하지 못합니다.
151
+ """
90
152
  self.c103.page = 'c103현금흐름표q'
91
153
  d, 재무활동현금흐름 = self.c103.sum_recent_4q('재무활동으로인한현금흐름', refresh)
92
154
  try:
@@ -97,6 +159,19 @@ class Mil:
97
159
  return d, 주주수익률, 재무활동현금흐름
98
160
 
99
161
  def _calc이익지표(self, 시가총액_억: float, refresh: bool) -> Tuple[str, float, float, float]:
162
+ """
163
+ 이익지표를 계산합니다.
164
+
165
+ 매개변수:
166
+ 시가총액_억 (float): 기업의 시가총액 (억 단위).
167
+ refresh (bool): 데이터를 새로고침할지 여부.
168
+
169
+ 반환값:
170
+ Tuple[str, float, float, float]: 최근 날짜, 이익지표, 영업활동 현금흐름, 지배주주 당기순이익.
171
+
172
+ 예외:
173
+ ZeroDivisionError: 시가총액이 0일 경우 이익지표를 계산하지 못합니다.
174
+ """
100
175
  d1, 지배주주당기순이익 = Tools.calc당기순이익(self.c103, refresh)
101
176
  self.c103.page = 'c103현금흐름표q'
102
177
  d2, 영업활동현금흐름 = self.c103.sum_recent_4q('영업활동으로인한현금흐름', refresh)
@@ -113,6 +188,15 @@ class Mil:
113
188
  return date , 이익지표, 영업활동현금흐름, 지배주주당기순이익
114
189
 
115
190
  def _calc투자수익률(self, refresh: bool) -> tuple:
191
+ """
192
+ ROIC, ROE, ROA 등의 투자 수익률을 계산합니다.
193
+
194
+ 매개변수:
195
+ refresh (bool): 데이터를 새로고침할지 여부.
196
+
197
+ 반환값:
198
+ tuple: 계산된 ROIC, ROE, ROA 및 관련 데이터.
199
+ """
116
200
  self.c104.page = 'c104q'
117
201
  self.c106.page = 'c106q'
118
202
  d1, roic_r = self.c104.sum_recent_4q('ROIC', refresh)
@@ -131,13 +215,16 @@ class Mil:
131
215
 
132
216
  def _calcFCF(self, refresh: bool) -> dict:
133
217
  """
134
- FCF 계산
135
- Returns:
136
- dict: 계산된 fcf 딕셔너리 또는 영업현금흐름 없는 경우 - {}
218
+ 자유 현금 흐름(FCF)을 계산합니다.
219
+
220
+ 매개변수:
221
+ refresh (bool): 데이터를 새로고침할지 여부.
137
222
 
138
- Note:
139
- CAPEX 없는 업종은 영업활동현금흐름을 그대로 사용한다.\n
223
+ 반환값:
224
+ dict: 계산된 FCF 딕셔너리. 영업활동 현금흐름 데이터가 없는 경우 딕셔너리를 반환합니다.
140
225
 
226
+ 참고:
227
+ - CAPEX가 없는 업종의 경우, 영업활동 현금흐름을 그대로 사용합니다.
141
228
  """
142
229
  self.c103.page = 'c103현금흐름표y'
143
230
  _, 영업활동현금흐름_dict = self.c103.find('영업활동으로인한현금흐름', remove_yoy=True, del_unnamed_key=True, refresh=refresh)
@@ -172,13 +259,16 @@ class Mil:
172
259
  return dict(sorted(fcf_dict.items(), reverse=False))
173
260
 
174
261
  def _calcPFCF(self, 시가총액_억: float, fcf_dict: dict) -> dict:
175
- """Price to Free Cash Flow Ratio(주가 대비 자유 현금 흐름 비율)계산
262
+ """
263
+ PFCF(Price to Free Cash Flow Ratio)를 계산합니다.
176
264
 
177
- PFCF = 시가총액 / FCF
265
+ 매개변수:
266
+ 시가총액_억 (float): 기업의 시가총액 (억 단위).
267
+ fcf_dict (dict): 자유 현금 흐름(FCF) 데이터.
178
268
 
179
- Note:
180
- https://www.investopedia.com/terms/p/pricetofreecashflow.asp
181
- """
269
+ 반환값:
270
+ dict: 계산된 PFCF 딕셔너리.
271
+ """
182
272
  if math.isnan(시가총액_억):
183
273
  mylogger.warning(f"{self} - 시가총액이 nan으로 pFCF를 계산할수 없습니다.")
184
274
  return {}
@@ -259,9 +349,20 @@ class Mil:
259
349
 
260
350
  def get(self, refresh = False, verbose = True) -> MilData:
261
351
  """
262
- MilData 형식의 데이터를 계산하여 리턴하고 레디스 캐시에 저장한다.
263
- :param refresh:
264
- :return:
352
+ MilData 객체를 Redis 캐시에서 가져오거나 새로 생성하여 반환합니다.
353
+
354
+ 캐시에서 데이터를 검색하고, 없을 경우 `_generate_data`를 호출하여 데이터를 생성합니다.
355
+ 생성된 데이터는 Redis 캐시에 저장되어 재사용됩니다.
356
+
357
+ 매개변수:
358
+ refresh (bool): 캐시를 무시하고 새로 데이터를 계산할지 여부. 기본값은 False.
359
+ verbose (bool): 실행 중 상세 정보를 출력할지 여부. 기본값은 True.
360
+
361
+ 반환값:
362
+ MilData: Redis 캐시에서 가져오거나 새로 생성된 MilData 객체.
363
+
364
+ 로그:
365
+ - 캐시 검색 상태와 새로 생성된 데이터를 출력합니다.
265
366
  """
266
367
  redis_name = f"{self.code}_mil"
267
368
  mylogger.info(f"{self} MilData를 레디스캐시에서 가져오거나 새로 생성합니다.. refresh : {refresh}")
@@ -269,6 +370,6 @@ class Mil:
269
370
  print(f"{self} redisname: '{redis_name}' / refresh : {refresh} / expire_time : {expire_time/3600}h")
270
371
 
271
372
  def fetch_generate_data(refresh_in: bool) -> dict:
272
- return asdict(self._generate_data(refresh_in))
373
+ return self._generate_data(refresh_in) # type: ignore
273
374
 
274
- return MilData(**myredis.Base.fetch_and_cache_data(redis_name, refresh, fetch_generate_data, refresh, timer=expire_time))
375
+ return myredis.Base.fetch_and_cache_data(redis_name, refresh, fetch_generate_data, refresh, timer=expire_time)
@@ -1,5 +1,5 @@
1
1
  import os
2
- from dataclasses import dataclass, asdict
2
+ from dataclasses import dataclass
3
3
  from typing import Tuple
4
4
  import math
5
5
 
@@ -16,34 +16,31 @@ expire_time = tools.to_int(os.getenv('DEFAULT_EXPIRE_TIME_H', 48)) * 3600
16
16
  @dataclass
17
17
  class RedData:
18
18
  """
19
- A data structure for financial data representation and calculations.
20
-
21
- This class is designed to encapsulate financial details related to a company,
22
- including calculations for business value, property value, debt evaluation, and
23
- associated metrics. It validates specific attributes upon initialization and is
24
- useful for financial data analysis.
25
-
26
- Attributes:
27
- code (str): A 6-digit numeric string representing the company or entity's code.
28
- name (str): The name of the company or entity.
29
- 사업가치 (float): Business value calculated as net income attributable to controlling
30
- shareholders divided by expected return rate.
31
- 지배주주당기순이익 (float): Net income attributable to controlling shareholders.
32
- expect_earn (float): Expected return rate.
33
- 재산가치 (float): Property value calculated as current assets minus 1.2
34
- times current liabilities, plus fixed assets under investment properties.
35
- 유동자산 (float): Current assets of the company.
36
- 유동부채 (float): Current liabilities of the company.
37
- 투자자산 (float): Investment assets within fixed assets.
38
- 투자부동산 (float): Investment real estate property.
39
- 부채평가 (float): Debt evaluation, specifically focusing on non-current liabilities.
40
- 발행주식수 (int): Number of issued shares by the company.
41
- date (list): List of dates relevant to the financial data.
42
- red_price (float): Red price associated with the company or entity.
43
- score (int): Score or rating given to the company or entity.
44
-
45
- Raises:
46
- ValueError: If the 'code' attribute is not a 6-digit numeric string.
19
+ 재무 데이터를 표현하고 계산하기 위한 데이터 구조.
20
+
21
+ 클래스는 기업의 재무 데이터를 관리하며, 사업가치, 재산가치, 부채평가 다양한 재무
22
+ 지표를 포함합니다. 초기화 특정 속성 값을 검증하며, 재무 데이터 분석에 유용하게 활용됩니다.
23
+
24
+ 속성:
25
+ code (str): 기업의 6자리 숫자 코드.
26
+ name (str): 기업명.
27
+ 사업가치 (float): 지배주주 당기순이익 / 기대수익률로 계산된 사업가치.
28
+ 지배주주당기순이익 (float): 지배주주에게 귀속된 당기순이익.
29
+ expect_earn (float): 기대수익률.
30
+ 재산가치 (float): 유동자산 - (유동부채 * 1.2) + 고정자산(투자자산, 투자부동산)으로 계산된 재산가치.
31
+ 유동자산 (float): 기업의 유동자산.
32
+ 유동부채 (float): 기업의 유동부채.
33
+ 투자자산 (float): 투자자산.
34
+ 투자부동산 (float): 투자부동산.
35
+ 부채평가 (float): 비유동부채를 평가한 값.
36
+ 발행주식수 (int): 발행된 주식 수.
37
+ date (list): 재무 데이터와 관련된 날짜 목록.
38
+ 주가 (float): 최근 주가.
39
+ red_price (float): 계산된 레드 가격.
40
+ score (int): 최근 주가와 레드 가격 괴리율로 산출된 점수.
41
+
42
+ 예외:
43
+ ValueError: 'code'가 6자리 숫자 문자열이 아닌 경우 발생.
47
44
  """
48
45
  code: str
49
46
  name: str
@@ -78,17 +75,18 @@ class RedData:
78
75
 
79
76
  class Red:
80
77
  """
81
- Represents a financial analysis object with methods to calculate metrics
82
- and gather data related to a specific code.
83
-
84
- The Red class is designed to interact with specific data sources and provide
85
- tools for financial calculations and analysis. This includes fetching and
86
- processing information related to liabilities, assets, stock prices, and
87
- other financial indicators. The class facilitates both specific calculations
88
- such as 비유동부채(Non-current Liability) and the generation of comprehensive
89
- financial datasets.
90
- """
78
+ 특정 기업의 재무 데이터를 계산하고 분석하기 위한 클래스.
79
+
80
+ 이 클래스는 주어진 종목 코드에 대해 데이터를 가져오고, 사업가치, 재산가치, 부채평가 등 다양한
81
+ 재무 지표를 계산하며, Redis 캐시를 활용하여 데이터 저장 재사용을 관리합니다.
91
82
 
83
+ 속성:
84
+ c101 (myredis.C101): 기업 정보 및 데이터 접근을 위한 객체.
85
+ c103 (myredis.C103): 재무 상태표 데이터 접근을 위한 객체.
86
+ name (str): 기업명.
87
+ recent_price (float): 최근 주가.
88
+ expect_earn (float): 기대수익률. 기본값은 0.06 (6%).
89
+ """
92
90
 
93
91
  def __init__(self, code: str, expect_earn: float = 0.06):
94
92
  assert tools.is_6digit(code), f'Invalid value : {code}'
@@ -121,10 +119,23 @@ class Red:
121
119
  self._code = code
122
120
 
123
121
  def _calc비유동부채(self, refresh: bool) -> Tuple[str, float]:
124
- """유효한 비유동부채 계산
122
+ """
123
+ 비유동부채를 계산합니다.
124
+
125
+ 기본적으로 재무 상태표에서 비유동부채 데이터를 가져오며, 만약 데이터가 누락되었거나 NaN인 경우
126
+ 직접 계산하여 반환합니다.
127
+
128
+ 매개변수:
129
+ refresh (bool): 데이터 새로고침 여부. True일 경우 최신 데이터를 가져옵니다.
125
130
 
126
- 일반적인 경우로 비유동부채를 찾아서 반환한다.\n
127
- 금융기관의 경우는 간접적으로 계산한다.\n
131
+ 반환값:
132
+ Tuple[str, float]: 가장 최근 날짜와 계산된 비유동부채 값.
133
+
134
+ 예외:
135
+ ValueError: 필요한 데이터가 누락된 경우 발생.
136
+
137
+ 로그:
138
+ - 비유동부채 데이터가 없을 경우 경고 메시지를 출력합니다.
128
139
  """
129
140
  mylogger.info(f'In the calc비유동부채... refresh : {refresh}')
130
141
  self.c103.page = 'c103재무상태표q'
@@ -154,11 +165,18 @@ class Red:
154
165
  return d, 비유동부채
155
166
 
156
167
  def _score(self, red_price: int) -> int:
157
- """red price와 최근 주가의 괴리율 파악
168
+ """
169
+ 최근 주가와 레드 가격 간 괴리율을 계산하여 점수를 반환합니다.
170
+
171
+ 매개변수:
172
+ red_price (int): 계산된 레드 가격.
173
+
174
+ 반환값:
175
+ int: 괴리율 기반 점수. 양수는 저평가, 음수는 과대평가를 나타냅니다.
158
176
 
159
- Returns:
160
- int : 주가와 red price 비교한 괴리율
161
- """
177
+ 로그:
178
+ - 최근 주가와 레드 가격, 괴리율, 계산된 점수를 출력합니다.
179
+ """
162
180
  if math.isnan(self.recent_price):
163
181
  return 0
164
182
 
@@ -174,6 +192,24 @@ class Red:
174
192
  return score
175
193
 
176
194
  def _generate_data(self, refresh: bool) -> RedData:
195
+ """
196
+ RedData 객체를 생성하기 위해 재무 데이터를 계산합니다.
197
+
198
+ 내부적으로 사업가치, 재산가치, 비유동부채 등을 계산하며, 계산된 결과를 RedData 객체로 반환합니다.
199
+
200
+ 매개변수:
201
+ refresh (bool): 데이터 새로고침 여부. True일 경우 최신 데이터를 가져옵니다.
202
+
203
+ 반환값:
204
+ RedData: 계산된 재무 데이터를 포함하는 RedData 객체.
205
+
206
+ 예외:
207
+ ZeroDivisionError: 발행 주식 수가 0인 경우 발생.
208
+ ValueError: 필요한 날짜 데이터가 없는 경우 발생.
209
+
210
+ 로그:
211
+ - 각 단계의 계산 결과와 주요 값을 출력합니다.
212
+ """
177
213
  d1, 지배주주당기순이익 = Tools.calc당기순이익(self.c103, refresh)
178
214
  mylogger.debug(f"{self} 지배주주당기순이익: {지배주주당기순이익}")
179
215
  d2, 유동자산 = Tools.calc유동자산(self.c103, refresh)
@@ -230,35 +266,28 @@ class Red:
230
266
 
231
267
  def get(self, refresh = False, verbose = True) -> RedData:
232
268
  """
233
- RedData 형식의 데이터를 계산하여 리턴하고 레디스 캐시에 저장한다.
234
-
235
- redis_name = f"{self.code}_red_data"
236
-
237
- Fetch or create RedData from Redis cache.
269
+ RedData 객체를 Redis 캐시에서 가져오거나, 새로 계산하여 반환합니다.
238
270
 
239
- This function attempts to retrieve the RedData from a Redis cache. If the data is
240
- not available or if a refresh is requested, it generates new data and caches
241
- them back in Redis. The function logs its operations and can provide
242
- verbose output when specified.
271
+ 캐시에서 데이터를 검색하고, 없을 경우 `_generate_data`를 호출하여 새로운 데이터를 생성한 후,
272
+ 캐시에 저장합니다.
243
273
 
244
- Parameters:
245
- refresh : bool, optional
246
- Whether to refresh and generate new data instead of using the cached data.
247
- verbose : bool, optional
248
- Whether to enable verbose logging/display of additional runtime information.
274
+ 매개변수:
275
+ refresh (bool, optional): 캐시 데이터를 무시하고 새로 계산 여부. 기본값은 False.
276
+ verbose (bool, optional): 실행 상세 정보를 출력 여부. 기본값은 True.
249
277
 
250
- Returns:
251
- RedData
252
- The RedData object either retrieved from the cache or newly generated.
278
+ 반환값:
279
+ RedData: Redis 캐시에서 가져오거나 새로 생성된 RedData 객체.
253
280
 
281
+ 로그:
282
+ - 캐시 검색 상태와 새로 계산된 데이터를 출력합니다.
254
283
  """
255
284
  redis_name = f"{self.code}_red_data"
256
285
  mylogger.info(f"{self} RedData를 레디스캐시에서 가져오거나 새로 생성합니다.. refresh : {refresh}")
257
286
  if verbose:
258
287
  print(f"{self} redisname: '{redis_name}' / expect_earn: {self.expect_earn} / refresh : {refresh} / expire_time : {expire_time/3600}h")
259
288
 
260
- def fetch_generate_data(refresh_in: bool) -> dict:
261
- return asdict(self._generate_data(refresh_in))
289
+ def fetch_generate_data(refresh_in: bool) -> RedData:
290
+ return self._generate_data(refresh_in) # type: ignore
262
291
 
263
- return RedData(**myredis.Base.fetch_and_cache_data(redis_name, refresh, fetch_generate_data, refresh, timer=expire_time))
292
+ return myredis.Base.fetch_and_cache_data(redis_name, refresh, fetch_generate_data, refresh, timer=expire_time)
264
293
 
@@ -1,15 +1,3 @@
1
1
  from analyser_hj3415.analyser.tsa.lstm import *
2
2
  from analyser_hj3415.analyser.tsa.prophet import *
3
-
4
- MIs = {
5
- "wti": "CL=F",
6
- "gold": "GC=F",
7
- "silver": "SI=F",
8
- "usdidx": "DX-Y.NYB",
9
- "usdkrw": "KRW=X",
10
- "sp500": "^GSPC",
11
- "kospi": "^KS11",
12
- "nikkei": "^N225",
13
- "china": "^HSI",
14
- "irx": "^IRX",
15
- }
3
+ from analyser_hj3415.analyser.tsa import common
@@ -0,0 +1,33 @@
1
+ import numpy as np
2
+
3
+
4
+ def is_up_by_OLS(data: dict) -> bool:
5
+ if not data:
6
+ # 데이터가 비어있으면 추세를 판단할 수 없음
7
+ return False
8
+
9
+ # 1) 날짜(키) 기준 오름차순 정렬
10
+ sorted_dates = sorted(data.keys())
11
+ values = [data[d] for d in sorted_dates]
12
+
13
+ # 2) x 축을 0,1,2... 형태로 부여 (날짜 간격을 동일하게 가정)
14
+ x = np.arange(len(values), dtype=float)
15
+ y = np.array(values, dtype=float)
16
+
17
+ # 3) 선형 회귀(최소제곱법)로 기울기(slope) 계산
18
+ x_mean = np.mean(x)
19
+ y_mean = np.mean(y)
20
+
21
+ # 분자: sum((xi - x_mean) * (yi - y_mean))
22
+ numerator = np.sum((x - x_mean) * (y - y_mean))
23
+ # 분모: sum((xi - x_mean)^2)
24
+ denominator = np.sum((x - x_mean) ** 2)
25
+
26
+ if denominator == 0:
27
+ # 데이터가 1개 이하인 경우 등
28
+ return False
29
+
30
+ slope = numerator / denominator
31
+
32
+ # 4) 기울기가 양수면 "우상향 추세"로 판별
33
+ return slope > 0