2026-04-15

data_for_stocktrek

 {

    "Asset": {

"Quantity": 29, "Ticker": "395160" },

"Cash": {

"Amount": 3912649}

}

2019-10-19

주식 매매하는 법ㅡ제시 리버모어

전설의 제시 리버모어가 쓴 책이다.

제 2장 p100에서 p180까지가 How to Trade in Stocks 본문이다.

나는 이 장만 읽었다.
추세추종 매매를 하고, 손실은 제한한다는 간단한 내용이다.
가격 기록을 직접 해야만 그 과정에서 많은 깨달음을 얻는다.

사업의 관점에서 트레이딩을 해야한다.
본문 중의 심리적시간 같은것은 이해하기 어렵다. 모호한것인지 아직은 내공이 부족한지 나중에 그 부분만 다시 한번 읽어 봐야겠다.

추세가 형성되고 가격이 돌파될때  피라미딩 매수를 한다. ㅡ 실제 따라하기에는 엄청난 심리적 부담이 있고 추세가 실패하는 경우가 더 많아 손절이 누적 될수록 자신감 상실 및 계좌손실을 감수해야 한다. 대체로 열번의 매매에 여덟번은 실패추세일 것이다.

아무리 어렵다해도 이 방향이 옳은 길이란 것을 이후의 니콜라스 다바스의 박스매매로 확인할 수 있다.




오늘날의 관점에서 캔들챠트를  볼때 일봉에서 상승추세라 판단 했는데, 주봉이 하락 추세라면 혹은 60분봉, 30분봉 심지어 1분봉들의 추세는 어떻게 해석해야 할까?

리버모어의 시대에는 단순히 일봉으로 생각되는 가격의 움직임만을 보고 추세가 형성되었다고 생각하는 종목을 선택해서 매매한 것으로 생각되는데, 그렇다면 100개의 종목중에서 소수의 비율의 종목만이 추세를 형성 했을 것이고, 그것들을 잘 찾아내어 매매를 성공한 것은 아닐까?

단순한 price channel 돌파 시스템을 작성해서 백테스팅을 해봐도 타임스팬에 따라 수익과 손실이 다양하게 나온다. 
일봉 수익, 주봉 손실,.. 그냥 운일 뿐일까?

진정한 추세는 무엇이고 그것을 알 수 있는 방법은 정말 무엇일까?

책을 읽고
점점 더 깊이 무지의 세상으로 빠져 들어만 간다.




2019-03-03

VBA - Database and ODBC

VBA - Database and ODBC
*---
---*

VBA - ADODB
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
With conn
.ConnectionString = cnn_str("OracleODBC32") ''OracleODBC32
.CursorLocation = adUseClient
.Open
End With

VBA - ODBC with Connection Strings
*---
---*

VBA - Excel SQL Solution















2019-02-20

VBA - Oracle ODBC connection string


ODBC로 Oracle 데이터베이스 연결하는 경우, VBA ConnectionString 구성.

1. 윈도우즈 DSN을 설정하고 사용하는 경우.
(ODBC관리자에서 사용자 또는 시스템 데이터소스가 설정되어 있어야 한다. 여기서는 dsnOra로 설정됨)
'' ODBC using Data Source Name 
Dim connStr As String
connStr = "DSN=dsnOra;UID=HR;PASSWORD=1111;"
...



2. Oracle ODBC직접 설정 연결,
'' Direct connetion to Oracle ODBC 
Dim connStr As String
connStr = ("DRIVER="Oracle in OraDb11g_home1;" & _
"SERVER=ORCL;" & _
"DBQ=ORCL;" & _
"Uid=HR;" & _
"Pwd=1111;" )
...









2019-02-18

VBA - RegExp 사용하기

VBA로 Regular Expression을 사용하여 문자열을 찾는 함수를 만들어 봅니다.

------------------------------------------------------------
Function myRegEx(testStr As String, pattern As String)
    Dim re As Object
    ''Tools/Add- Microsoft VBScript Regular Expression 5.5
    Set re = CreateObject("VBScript.RegExp")

    With re
       ''.Pattern = "^[\w-\.]{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,3}$"
       .Pattern = pattern
       .IgnoreCase = True
       .Global = False
    End With

    ' Test method returns TRUE if a match is found
    If re.test(testStr) Then
       Debug.Print testStr & " is a valid e-mail address"
    Else
       Debug.Print testStr & " is NOT a valid e-mail address"
    End If

    myRegEx = re.test(testStr)
End Function
------------------------------------------------------------

VBA Editor에서 도구/참조를 열어서
Microsoft VBScript Regular Expression 5.5를 추가해 주어야 합니다.














Regular Expression 문법은 아래와 같은 사이트를 참조합니다.
https://regexr.com/

아래와 같이 만든 함수 myRegEx를 테스트 할 수 있습니다.
Sub regExp_test()
        If myRegEx(빈도항목값.Value, "^[\w-\.]{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,3}$") Then
            Debug.Print "문자열이 EMail형식이 맞습니다.!"
        End If   
End Sub






2019-02-13

VBA - HttpRequest로 웹페이지 가져오기

VBA코드로 웹페이지를 가져오고, HTML DOM Parsing을 하는 예제 입니다.

Public Sub parsehtml()
    ''Add Tools/Reference first- Microsoft HTML Object Library
    Dim http As Object, html As New HTMLDocument, topics As Object, titleElem As Object, detailsElem As Object, topic As HTMLHtmlElement
    Dim i As Integer
    
    Set http = CreateObject("MSXML2.XMLHTTP")
    
    http.Open "GET", "https://news.ycombinator.com/", False
    http.Send
    html.body.innerHTML = http.responseText
    Set topics = html.getElementsByClassName("athing")
    i = 2
    For Each topic In topics
        Set titleElem = topic.getElementsByTagName("td")(2)
        Sheets(1).Cells(i, 1).Value = titleElem.getElementsByTagName("a")(0).innerText
        Sheets(1).Cells(i, 2).Value = titleElem.getElementsByTagName("a")(0).href
        Set detailsElem = topic.NextSibling.getElementsByTagName("td")(1)
        Sheets(1).Cells(i, 3).Value = detailsElem.getElementsByTagName("span")(0).innerText
        Sheets(1).Cells(i, 4).Value = detailsElem.getElementsByTagName("a")(0).innerText
        i = i + 1
    Next
End Sub

፠도구/참조에 마이크로소프트 HTML Object Library를 추가해야 합니다.







 

VBA - HttpRequest: Get Data from google sheet

1. Google sheet에 표와 같은 데이터가 있다.

타임스탬프금칙어표준어담당자성명
2018. 10. 24 오전 10:41:29stainless steel스테인리스강최치원
2018. 11. 13 오전 9:58:14스테인리스스틸연결유니언스테인리스유니언박나래
2018. 11. 13 오전 10:07:24스테인리스스틸앵글밸브스테인리스앵글밸브박나래
2018-09-05 17:51:00특수아크릴(인장강동특수아크릴(인장강도최치원
2018. 11. 13 오전 9:58:42스테인리스스틸유니언스테인리스유니언박나래
2018. 11. 20 오후 5:39:45알루미늄 - D.C알루미늄다이캐스팅김치국

2. 구글시트 데이터를 엑셀에서 읽어와서 작업 및 가공을 하려 한다.

3. 코드
Function webservice()
    ''First, Add a reference to MSXML (Tools > references)
    Dim req As Object
    Dim sheetUrl As String
    sheetUrl = "https://docs.google.com/spreadsheets/d/e/(Your-Google-Sheet-ID)/pub?gid=(Your-gid)&single=true&output=csv"
    
    Set req = CreateObject("MSXML2.XMLHTTP")
    With req
        .Open "GET", sheetUrl, False
        .Send
    End With
    Dim response As String
    response = req.ResponseText
    ''Debug.Print response
    Dim table() As String
    table() = Split(response, vbCrLf)
    Debug.Print LBound(table) & ":" & UBound(table) ''0~128..count=129
    ''
'    Dim 타임스탬프, 금칙어, 표준어, 담당자 As String
'    Dim row() As String
'    For Each wordrow In table
'        ''Debug.Print wordrow
'        row() = Split(wordrow, ",")
'        타임스탬프 = row(0)
'        금칙어 = row(1)
'        표준어 = row(2)
'        담당자 = row(3)
'    Next
    Set req = Nothing
    webservice = table
End Function

※ MSXML을 도구/참조에 등록해야 XMLHTTP Request를 사용할 수 있습니다.





 

2019-01-31

VBA - SHA256 해쉬 문자열 만들기

참조 링크:
https://en.m.wikibooks.org/wiki/Visual_Basic_for_Applications/String_Hashing_in_VBA


도구 추가:
Mscorlib 4.0 64bit

소스:
Function SHA256(sIn As String, Optional bB64 As Boolean = 0) As String
    'prerequisite
    'Set a reference to mscorlib 4.0 64-bit
    Dim oT As Object, oSHA256 As Object
    Dim TextToHash() As Byte, bytes() As Byte
    Set oT = CreateObject("System.Text.UTF8Encoding")
    Set oSHA256 = CreateObject("System.Security.Cryptography.SHA256Managed")
    TextToHash = oT.GetBytes_4(sIn)
    bytes = oSHA256.ComputeHash_2((TextToHash))
    If bB64 = True Then
       SHA256 = ConvToBase64String(bytes)
    Else
       SHA256 = ConvToHexString(bytes)
    End If
    Set oT = Nothing
    Set oSHA256 = Nothing
End Function
Function ConvToHexString(vIn As Variant) As Variant
    Dim oD As Object
    Set oD = CreateObject("MSXML2.DOMDocument")
      With oD
        .LoadXML ""
        .DocumentElement.DataType = "bin.Hex"
        .DocumentElement.nodeTypedValue = vIn
      End With
    ConvToHexString = Replace(oD.DocumentElement.Text, vbLf, "")
    Set oD = Nothing
End Function
결과:
Base64: MDkBFbBmlo/AYoaEwOl7KAUEnj5dfJ/+1pxVFjKkkuc=
44 characters in length
Hex: 30390115b066968fc0628684c0e97b2805049e3e5d7c9ffed69c551632a492e7
64 characters in length






 


2019-01-15

VBA - Excel Objects

VBA - Excel Objects



VBA로 프로그램을 작성할 때, 기본이 되는 엑셀 개체들이 있다.
Application Objects
    Dim appName As String
    appName = Application.ActiveWorkbook.Name
    Debug.Print appName     ''VBA_dedicated.xlsx
Workbook Objects
    ''Workbook object
    Dim wb As Workbook
    Set wb = Workbooks.Open(appPath & "\" & "VBA_dedicated.xlsx") ''workbook.fullname
Worksheet Objects
    ''Worksheet object
    Dim ws As Worksheet
    Set ws = Worksheets(1)
    ws.Visible = False
Range Objects
    ''Range
    Dim rng As Range
    Set rng = Worksheets("Sheet1").Range("A1:A4")
    rng.Value = 5









2019-01-14

VBA - Function and Sub Procedure

VBA - User Defined Functions


1. Function 정의
Function getArea(Length As Double, Optional Width As Variant)
    Dim findArea As Double

    If IsMissing(Width) Then
       findArea = Length * Length    ''Square
    Else
       findArea = Length * Width     ''Area
    End If
    ''return: VBA has no return statement, instead using Function Name to return
    getArea = findArea
End Function

2. Function 호출

  • Sub procedure에서 호출
  • Excel 시트의 셀에서 직접 호출



VBA에서 함수(Function)는 Return문이 없다.
함수이름(getArea = '값')에 결과값을 대입하여 리턴하는 것에 주의해야 한다.


3. Sub Procedures
Sub Procedures 도 함수와 유사하지만, 몇 가지 다른 점이 있다.
  • Sub procedures는 Return값이 없다.
  • Sub procedures는 Sub 와 End Sub 문으로 구성된다.
Sub show_myArea()
    Dim 길이 As Double
    Dim  As Double
    Dim 면적 As Double
    길이 = 4
    폭 = 5
    ''Call function in sub procedure
    면적 = getArea(길이, 폭)
    
    Debug.Print 면적
    '' f(4,5) = 길이 * 폭 = 4 * 5 = 20
End Sub











2019-01-09

Madonna

Madonna

La Isla Bonita

Like A Prayer


Express Yourself


Madonna Like a Virgin

Material Girl


Vogue



2019-01-04

VBA - Basics

VBA - Basics
1. Module
모듈은 코드를 작성하는 영역으로 매크로 기록을 처음으로 작성하는 경우 Module이 만들어 진다. 워크북에서 VBA Editor창을 열고 삽입 메뉴에서 모듈을 선택하여 생성할 수 있다.


2. Procedure
프로시져는 한번에 실행될 명령의 모음이다. 엑셀에게 특정한 작업을 수행하도록 지시한다.
단순한 프로시져부터 복잡한 프로시져까지 만들 수 있지만, 복잡한 것은 작게 나누어 작성하여 유지보수를 쉽게 하는 것이 좋다.
함수의 코드는 Sub 과 End Sub 사이에 위치한다.
https://gist.github.com/SeongilRyu/6c541219ca325bef40cb9401c37b0edb



3. Function
펑션, 함수는 재사용 가능한 코드의 모음이다., 프로그램의 어디에서든지 호출 가능하며 리턴되는 값이 있다. 
기본으로 엑셀에 포함된 함수외에, VBA로 사용자 정의 함수를 만들 수 있다.
함수의 코드는 Function 과 End Function 사이에 위치한다.
https://gist.github.com/SeongilRyu/ec60bd70f8e9b3dc0aa3d106b5c070d4


4. Comments
Single Quote(') 또는 'Rem' 시작하는 문장은 Comments이다. 명령로직의 설명 문서와 프로그램 작성자의 의도를 알 수 있게 한다.
' This line is comment.  
' Written by : Author VBA Tutorial 
REM 이 줄은 코멘트입니다.  
Rem 작성자 : VBA 강좌

5. MessageBox and InputBox
Message box는 메세지 창에 메세지를 표시한다.
Sub show_Message() 
   '메세지박스 표시 ("Hello VBA.!")     

   MsgBox "Hello VBA.!" 

End Sub
Input box는 사용자의 입력을 받을 수 있다.
두 개의 Inputbox가 있으며, Application.InputBox는 셀의 값을 참조로 받을 수 있다.
Sub show_Inputbox() 
   '사용자 입력 박스로 입력을 받는다.
   Dim 가로 As Integer
   Dim 세로 As Integer
   Dim 면적 As Integer
   가로 = InputBox("가로 입력 ", "숫자를 입력하시오")
   세로 = Application.InputBox("세로 입력 ", "숫자를 입력/셀선택 하시오")
   면적 = 가로 * 세로
   MsgBox 면적

End Sub















6. 변수(Variables)
Variable 은 값을 담을 수 있는 메모리 이름이다. 스크립트가 실행되는 중에 값은 변경될 수 있다.
Sub show_variables()
''변수(Variable)
''Type별 변수 정의

    Dim var_bool As Boolean
    Dim var_byte As Byte
    Dim var_int As Integer
    Dim var_long As Long
    Dim var_single As Single
    Dim var_double As Double
    ''
    Dim var_string As String
    Dim var_date As Date
    Dim var_variant As Variant
    ''
    var_bool = False
    var_byte = 255
    var_int = 32767
    var_long = 2147483647#
    var_single = 3.402823E+38
    var_double = 1.79769313486232E+307
    
    var_string = "1 to 65,400 characters"
    var_date = DateValue("30 / 10 / 2020")
    var_object = "Some Object"
    var_variant = "Number or String"
    
    Debug.Print var_bool & vbCrLf & _
                var_byte & vbCrLf & _
                var_int & vbCrLf & _
                var_long & vbCrLf & _
                var_single & vbCrLf & _
                var_double & vbCrLf & _
                var_string & vbCrLf & _
                var_date & vbCrLf & _
                var_variant & vbCrLf

End Sub
Constants
값이 변할 수 있는 변수와는 다르게 항상 고정된 값을 가지는 상수이다.
Const MyInteger As Integer = 24 
Const 나의정수 As Integer = 24


7. 연산자(Operators)
VBA는 수치, 논리, 관계 연산자를 제공하고, 문자열을 연결하는 Concatenation 연산자가 있다.
Operator Description Example
+ Adds the two operands 10 + 5 will give 15
- Subtracts the second operand from the first 10 - 5 will give -5
* Multiplies both the operands 10 * 5 will give 50
/ Divides the numerator by the denominator 5 / 10 will give 2
% Modulus operator and the remainder after an integer division 5 % 10 will give 0
^ Exponentiation operator 5 ^ 10 will give 100000
= Checks if the value of the two operands are equal or not. If yes, then the condition is true. (10 = 20) is False.
<> Checks if the value of the two operands are equal or not. If the values are not equal, then the condition is true. (10 <> 20) is True.
> Checks if the value of the left operand is greater than the value of the right operand. If yes, then the condition is true. (10 > 20) is False.
< Checks if the value of the left operand is less than the value of the right operand. If yes, then the condition is true. (10 < 20) is True.
>= Checks if the value of the left operand is greater than or equal to the value of the right operand. If yes, then the condition is true. (10 >= 20) is False.
<= Checks if the value of the left operand is less than or equal to the value of the right operand. If yes, then the condition is true. (10 <= 20) is True.
AND Called Logical AND operator. If both the conditions are True, then the Expression is true. 10<>0 AND 0<>0 is False.
OR Called Logical OR Operator. If any of the two conditions are True, then the condition is true. 10<>0 OR 0<>0 is true.
NOT Called Logical NOT Operator. Used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make false. NOT(10<>0 OR 0<>0) is false.
XOR Called Logical Exclusion. It is the combination of NOT and OR Operator. If one, and only one, of the expressions evaluates to be True, the result is True. (10<>0 XOR 0<>0) is true.
& Concatenates two Values "Microsoft" & "VBA" will give MicrosoftVBA


8. 조건(Decision)
조건문 if, if-else, if-elseif, nested if,  Switch문으로 프로그램의 흐름을 제어한다.
Sub show_conditions()
''1. if-statement
   If 234 > 34 Then
      MsgBox "234 is Greater than 34"
   End If
   
''2. if-else
    Dim X, Y As Integer
    X = 234
    Y = 432
   If X > Y Then
      MsgBox "X is Greater than Y"
   Else
      MsgBox "Y is Greater than X"
   End If

''3. if-elseif
   X = 234
   Y = 234
   If X > Y Then
      MsgBox "X is Greater than Y"
   ElseIf Y > X Then
      MsgBox "Y is Greater than X"
   Else
      MsgBox "X and Y are EQUAL"
   End If
   
''4. 중첩 if
   Dim a As Integer
   a = 23
   If a > 0 Then
      MsgBox "a가 양수인 경우"
      If a = 1 Then
         MsgBox "The Number is 1"
      Else
         MsgBox "The Number is NOT 1"
      End If
   End If

''5. switch
   Dim MyVar As Integer
   MyVar = 1
   Select Case MyVar
      Case 1
         MsgBox "첫번째 수"
      Case 2
         MsgBox "중간 수"
      Case 3
         MsgBox "마지막 수"
      Case Else
         MsgBox "Unknown Number"
   End Select
End Sub


8. 반복(Loop)
VBA 에서 for-loop, for-each-loop, do-while-loop등을 사용한다.
Sub show_loops()
'''1. for-loop
   Dim a As Integer
   a = 8
   
   For i = 0 To a Step 2
      MsgBox "The value is i is : " & i
   Next
   
'''2. for-each-loop
    Dim fruits As Variant
    ''fruits는 배열
    fruits = Array("apple", "orange", "cherries")
 
   'iterating using For each loop.
    For Each Item In fruits
       Debug.Print Item & Chr(10)
    Next
   
''3. do-while-loop
    Dim x As Integer
    x = 3
   Do While x < 5
      x = x + 1
      MsgBox "The value of x is : " & x
   Loop
End Sub

9. 문자열(String) 함수
Strings은 일련의 문자열이다. 알파벳, 숫자, 특수문자로 구성된다. 변수에 담기는 스트링은 겹따옴표( " ")로 표현한다.


10. 날짜와 시간(Date and Time) 함수
VBA에서는 날짜와 시간 함수를 사용하여 시스템 날짜를 가져오거나 다른 포맷으로 표현할 수 있다.

11. 배열(Array)
변수는 하나의 값을 가진다. 때로는 여러개의 값을 가질 수 있는 하나의 변수가 필요하다.
일련의 값들을 저장하기 위해 Array변수를 사용한다.

Array변수를 선언하고 값을 지정한다.

Multi-dimensional array
다차원 배열도 선언할 수 있고 값을 지정할 수 있다.


ReDim

초기에는 배열의 크기를 지정하지 않고 나중에 사용될 때 크기를 지정할때 ReDim을 사용한다.
=gist=

=gist-end=

Array Methods

LBound와 UBound
배열의 최소 첨자와 최대 첨자를 확인한다.
Dim arr(5)
arr(0) = 10
arr(1) = 20
arr(2) = 30
arr(3) = 40
arr(4) = 50
Debug.Print LBound(arr) & "~" & UBound(arr)  '' 0~4

Split, Join, Filter
Sub array_split()
'Split function: 구분자로 분리될 수 있는 문자열을 분리하여 배열로 만든다.
   ' 구분자(delimiter) comma ','
   Dim a as Variant
   
   a = Split("Red,Blue,Yellow",",")
   
For i = 0 to UBound(a)
  msgbox("Value" & i & " is :"  & a(i))
   Next
End Sub

Sub array_join() 
'Join function: Split 함수의 반대 개념.
' 배열 항목들을 구분하여 문자열을 만든다.
   a = array("Red","Blue","Yellow")

   ' Join using $
   b = join(a,"$")
   msgbox("The Join result after using delimiter is : " & b)
''Red$Blue$Yellow
End Sub

Sub array_filter()
'Filter function: 필터 조건에 맞는 항목만 선택된 배열을 만든다.
   Dim a,b,c,d as Variant
   a = array("Red","Blue","Yellow")
   b = Filter(a,"B")
   c = Filter(a,"e")
   d = Filter(a,"Y")
  
   For each x in b
      msgbox("The Filter result 1: " & x)
   Next
  
   For each y in c
      msgbox("The Filter result 2: " & y)
   Next
  
   For each z in d
      msgbox("The Filter result 3: " & z)
   Next
End Sub
IsArray, Erase
Sub array_erase()
' IsArray function: 배열인지 아닌지 확인(True, False)
   Dim a,b as Variant
   a = array("Red","Blue","Yellow")
   b = "12345"
  
  If IsArray(a) = True then
    Erase a          ' 각 배열의 항목이 초기화 된다.
    ' Dynamic Array인 경우 사용된 메모리가 Free된다.
  End If
   
End Sub






'