28/2/2019

새로가 바라보는 세상 - 2차 북미 정상회담 투자자편

2019년 2월 28일 하노이에서 2차 정상회담이 열렸고, 시장의 기대(?) 와 다르게 협상이 결렬되었습니다. 기대가 컸던 만큼. 남북경협주는 폭락했고, 코스피 코스닥은 하락했습니다. 이런먹잇감을 놓칠없는 언론은 먹잇감을 발견한 하이에나 마냥 1차원적인 기사들로 우리를 감정적 바보로 만듭니다.

정상회담 결렬은 예측된 시나리오?

많은 사람이 협상 결렬의 근거로 북한거짓말이 들통남”이라 생각하며, 모자란 거짓말쟁이 북한놈들이라 욕합니다. 이는 유치원생 수준의 정말 단순한 해석입니다. 구글의 위성 지도 서비스만 봐도 알 수 있듯 어느 지역에 어떤 건물이 있는지 알 수. 있습니다. 그런데 미국이 이걸 몰랐다?!!! 웃음이 나올 정도의 어처구니가 없는 생각입니다. 첩보위성 북한 키워드로 검색만 해봐도 알 수 있듯(첩보위성 지오2 추가 배치…북에 촘촘한 거미줄 감시 | JTBC 뉴스), 위성 감시 체제를 갖춘6년이 넘었습니다. 그런데 미국이 북한 상황을 몰랐다?!! 그럴리가요 ㅋㅋ 국가 간의 협상이라는 것은 그렇게 이루어질없습니다. 어느 기업 간의 협약보다비즈니스며, 모든 정보와 상황별 시나리오가 정립되지 않았다면, 애초에 협상자리도 만들지 않았을 겁니다. 즉, 협상결렬은 짜여있던 상황별 시나리오하나를 선택했을 뿐입니다. 그들에게는 놀라울것도 새로울 것도 없는 선택이라 생각합니다.

트럼프는 멍청한 중2병 대통령”일까?

저는 정치에 크게 관심이 없었습니다. 트레이딩을 하기전까지는나름 똑똑한 지성인이라 생각했던년전 지난 미국 대선을 보며 트럼프가 대통령에 당선되는것은 세상이 미치지 않고 불가능일이라 생각했습니다. 대놓고 인종차별주의자에 막말을 서슴치 않는 도덕적으로 결여된 사람이 미국(지구?) 대통령이라니 세상이 미치지 않고는 불가능한 일이라고 생각했었죠. 하지만 우려가 현실이 되었죠. 트럼프가 도덕적으로 결여된 사람인것은 논의의 여지가 없는 명확 팩트입니다. 하지만 그렇다고 해서 그의 능력까지 낮춰보는 것은 객관화된 시각의 결여이며, 모순입니다. 트럼프가 성공한 사업가라는 것은 누구도 부정하지 않습니다. 하지만 우리가 놓치고 있는 하나가 있습니다. 그는 중2병 걸린 감성 팔이꾼이 아닌, 전략적으로 2병 걸린 감성 팔이꾼 의로 포지셔닝한 천재입니다. 잠깐, 대통령이 되고 싶은 트럼프가 되는 상상을 해보겠습니다. 끔찍한 상상이지만 해보겠습니다.

(트럼프가새로) 나는 트럼프다. 돈은만큼 벌었다. 이제는 권력만 얻으면 나는 신이다. 근데 내가 살아오면서 한 짓(망나니짓)을 보았을오바마 형같이 도덕적? 리더는 결코 될 수 없다. (보통 여기서 포기하는게 일반인적인 결론) 아씨 되고 싶은데 나는 내가 갖고 싶은 것, 하고 싶은 것 (3번의 결혼, 불륜, 연예인 등) 모든 것을 했다. 나는 대통령도 될수 있다. (철저한 분석방법을 발견한트럼프는 흥분한 목소리로 외친다) 씨ㅂ ㅏ, F**K 역시 나는 천재 역시 나에게 불가능이란 없어!!! 과거 망령에 사로잡힌 백인 멍청이들(미국 백인 우월주의자)과 내 친구들 (돈밖에 모르는 사업가들) 이 있다면 불가능도 아니지!! 바로 그들에게 이익되는 공략을 세우자. 시대를 역행하는 세금감면, 시대를 역행하는 백인 우월주의 인종차별, 그래서 멕시코 마약새키들 벽까지 세우면 완벽하겠구만!!! 벽 세우면서 인프라 확장하고 하면 부동산도 오르고, 또 부동산은나와바리니까 우리 친구들 돈좀 벌게 해주고 노동자들 일자리 만들고, 오 쉣 ㅆㅂ 완벽해!!! 역시 나는 신이다. 신에게 불가능이란 없다!!

이상의 상상은정신적 건강에 치명적이므로 여기까지 하겠습니다. 후 힘들다… (담배 한대 피고 오겠습니다.)

위의 끔찍한 상상을 정리하자면, 트럼프는 철저히 본인의 가진 장점과 단점을 명확히 파악하고 있으며, 자신의 장점을 극대화 시킬수 있는 컨셉으로 포지셔닝 했습니다. 결국, 트럼프의 주된 정치적 지지층은 복잡하고 이성적인 사고를 하는 부류가 아닙니다. 오히려 꿈과 희망을 파는 감정적인 호소에 열광하는 사람들입니다. 그렇다면 트럼프는 어떤 행동과 쇼맨십을 보여줘야 대통령이 되고, 더 나아가 재선이 될 수 있을까요?! 이미 답은 정해져 있습니다. 절대적으로 심플하고 간결하게 감정에 호소할있어야 하며, 그것에 탁월한 사람이 트럼프입니다. 한마디로 정리하자면 본인의 위치와 가진 리소스를 정확히 이해하고, 극대화할아는 전략적인 비즈니스 맨” 입니다. 협상꾼 트럼프의 11가지 성공 전략 - 미래한국

앞으로의 북미 정상회담 방향은?!

장기전이것입니다. 핵을 가진 북한이 존재 함으로써 미국이 얻는 이익은 명확합니다. 우리나라 무기 수입의 90% 이상을 미국에 의지하고 있으며, 트럼프의 공략하나인 세계 경찰로서의 국방비 지출을 타국에 부담하게 하는것입니다. 또한 북미협상 타결은 트럼프의 언론 플레이를 위한 전략적 카드이기도 합니다. 여론은 언론에 의해서 만들어지며, 여론을 컨트롤 하기 위한 정치적 이슈는 트럼프에게무기입니다. 이러한 무기를 적절한 타이밍에 사용하여, 이익을 극대화하는 것이 그의 목표일 것입니다.

또한, 모두가 알다시피 트럼프는 부동산 투자의 귀재입니다. 부동산 투자란 본질적으로 시간과 인내의 싸움입니다. 이번 협상에서도 알수 있듯 트럼프는 인내심을 갖고 본인이 얻을있는 최대한 이익을 얻기 위해 기다리고 기다릴 것입니다. 김정은과 트럼프의 풍채는 둘 다 헤비급이지만, 협상능력에서는 라이트급과 헤비급 복싱선수의 싸움일 뿐입니다. 김정은과 합의할없었다는 트럼프, 표정에 드러난 속마음은? - YouTube 이런 심리 싸움은 짬밥(경험)을 무시할없다고 생각합니다.

결론, 그래서 뭐 어쩌라고?

결론은 없고, 요지는 있습니다. 이러한사건은 누군가에게는 커다란 고통입니다. 이번 사건은 특히 국내 주식 투자자들에게고통을 주었습니다. 저의 부모님을 비롯해서 말이지요…(엄마 팔아서 미안해 ㅠㅠ 그러니까 내 말 좀 들어줘…) 우리는 인간이기에 감정적일수 밖에 없습니다. 하지만 세상의 현상을 감정적이고, 단편적으로 받아들이는 순간, 인간의 감정을알고 이용하는 트럼프 같은 형님들에게 당할밖에 없습니다. 기관이 매력적인 차트 혹은 뉴스 거리를 만들고, 개미들을 터는 것처럼 말이지요…

PS1. 이 글은 혼자만 생각하고 공유하지 않는 부도덕한 저를 일깨워홍석희님의 자극으로 작성되었습니다.

PS2. 저는 고등학교때부터 국어를 포기한 0개 국어 능력자?입니다. 맞춤법 혹은 부자연스러운 문장은 너그러운 마음으로 지적 해주세요.

trading
31/12/2018

[2018 Mini Pycon] 파이썬 기반서비스의 구성과 이해 - 이새로찬

Download Presentation File

Python Seminar Pycon
2/11/2018

Install Parity to Ubuntu

Install parity

$ bash <(curl https://get.parity.io -L) -r stable
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   170    0   170    0     0    122      0 --:--:--  0:00:01 --:--:--   122
100  3856  100  3856    0     0   2182      0  0:00:01  0:00:01 --:--:-- 1892k
Release selected is: stable
Upgrading parity from 0.0.0 to 2.0.8

systemd

  • systemd unit file - /lib/systemd/system/parity.service
[Unit]
Description=Parity Ethereum Daemon
After=network.target

[Service]
# run as root, set base_path in config.toml
ExecStart=/usr/bin/parity --config /etc/parity/config.toml
# To run as user, comment out above and uncomment below, fill in user and group
# picks up users default config.toml in $HOME/.local/share/io.parity.ethereum/
# User=username
# Group=groupname
# ExecStart=/usr/bin/parity
Restart=on-failure

# Specifies which signal to use when killing a service. Defaults to SIGTERM.
# SIGHUP gives parity time to exit cleanly before SIGKILL (default 90s)
KillSignal=SIGHUP

[Install]
WantedBy=default.target

parity configuration

데이터 경로를 백업볼륨 경로로 선정. 자세한 설정은 해당 링크 참고. Configuring-Parity-Ethereum

  • parity config file - /etc/parity/config.toml
[parity]
base_path = "/var/lib/parity"
db_path = "/var/lib/parity/chains"
keys_path = "/var/lib/parity-data/keys"
...

# log option
[misc]
logging = "info"
log_file = "/var/lib/parity/parity.log"

run parity

parity 를 실행하기 위한 기본적인 셋업은 끝났으며, 정상작동을 확인해본다.

$ sudo systemctl start parity
# 실행 상태 확인
$ sudo systemctl status parity
# 로그 확인
$ sudo tail -f /var/lib/parity/parity.log

logrotate

parity 로그 파일을 logroate사용하여 관리한다.

  • logroate conf file - /etc/logrotate.d/wallet
/data/log/wallet.log { 
    daily
    compress
    rotate 365
    missingok
    notifempty
    dateext
    copytruncate
}
$ sudo logrotate -f /etc/logrotate.d/wallet
$ sudo gzip -d wallet.log-20201010.gz
$ sudo cat wallet.log-20201010

Reference

parity-ethereum github

22/10/2018

Flask gunicorn nginx docker

Best practice of dockerizing flask gunicorn nginx.

PS. If you want to see the sample code. Click this link GitHub Repository

Concept

Starting with the installation of flask application, stack it step by step with Bottom Up.

PS. This following descriptions may not be accurate and in such cases pleas read and understand the code in the repository

main app versions

  • python/3.6.4
  • nginx/1.15.5

Flask Web Application

$ python -m venv venv
$ . venv/bin/activate
$ python -V
$ pip install --upgrade pip
$ pip install Flask
$ pip list
# main.py
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return "HELLO, WORLD!"


@app.route('/ping')
def ping():
    return "PONG"
$ FLASK_APP=main.py flask run
$ curl 127.0.0.1:5000/ping
PONG
$ curl 127.0.0.1:5000/
HELLO, WORLD!

debug or development mode

  • it activates the debugger
  • it activates the automatic reloader
  • it enables the debug mode on the Flask application.
$ export FLASK_ENV=development
$ export FLASK_DEBUG=1
$ export FLASK_APP=main.py
$ flask run

PS. This makes it a major security risk and therefore it must never be used on production machines.

performance test for flaks standalone

$ flask run
$ ab -n 32 -c 16 127.0.0.1:5000/sleep/10
This is ApacheBench, Version 2.3 <$Revision: 1807734 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 127.0.0.1 (be patient).....done


Server Software:        Werkzeug/0.14.1
Server Hostname:        127.0.0.1
Server Port:            5000

Document Path:          /sleep/10
Document Length:        19 bytes

Concurrency Level:      16
Time taken for tests:   20.031 seconds
Complete requests:      32
Failed requests:        0
Total transferred:      5536 bytes
HTML transferred:       608 bytes
Requests per second:    1.60 [#/sec] (mean)
Time per request:       10015.349 [ms] (mean)
Time per request:       625.959 [ms] (mean, across all concurrent requests)
Transfer rate:          0.27 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.2      0       1
Processing: 10006 10012   2.9  10012   10017
Waiting:    10005 10011   2.8  10011   10017
Total:      10006 10012   2.9  10012   10017

Percentage of the requests served within a certain time (ms)
  50%  10012
  66%  10013
  75%  10015
  80%  10015
  90%  10016
  95%  10017
  98%  10017
  99%  10017
 100%  10017 (longest request)

gunicorn

$ pip install gunicron
$ gunicorn -w 3 --threads 3 wsgi:app -b 0.0.0.0:5000
[2018-10-09 19:30:57 +0900] [79365] [INFO] Starting gunicorn 19.9.0
[2018-10-09 19:30:57 +0900] [79365] [INFO] Listening at: http://0.0.0.0:5000 (79365)
[2018-10-09 19:30:57 +0900] [79365] [INFO] Using worker: threads
[2018-10-09 19:30:57 +0900] [79368] [INFO] Booting worker with pid: 79368
[2018-10-09 19:30:57 +0900] [79369] [INFO] Booting worker with pid: 79369
[2018-10-09 19:30:57 +0900] [79370] [INFO] Booting worker with pid: 79370

main configuration

  • bind
  • workers
  • worker_class
  • threads
    • This setting only affects the Gthread worker type.
  • access_logfile
    • - means log to stdout
  • access_logformat
    • default: %(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"
  • error_logfile
    • - means log to stderr
# TCP SOCKET BINDING
$ gunicorn -w 3 --access-logfile - -k gevent wsgi:app -b 0.0.0.0:5000
...
# UNIX SOCKET BINDING
$ gunicorn -w 3 --access-logfile - -k gevent wsgi:app -b unix:/tmp/gunicorn.sock
...

# Check The Socket
$ echo -e "GET /ping HTTP/1.0\r\n\r\n" | nc -q 2 -U /tmp/gunicorn.sock
PONG
$ gunicorn --config gunicorn_config.py wsgi:app

Nginx

mac os var, etc path

/usr/local/etc/nginx/
/usr/local/var/log/nginx

gunicorn-nginx.conf

/usr/local/etc/nginx/servers/gunicorn-nginx.conf

upstream gunicorn-app {
    server unix:/tmp/gunicorn.sock fail_timeout=0;
}


server {
    listen 80;
    server_name 0.0.0.0;

    client_max_body_size 5M;

    access_log /usr/local/var/log/nginx/access.log combined;
    error_log /usr/local/var/log/nginx/error_log.log warn;

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;

        proxy_pass http://gunicorn-app;
    }
}
sudo nginx -c [config_path]
sudo nginx -s stop

Docker

When I dockerize, first setup the tools and environment necessary for dockerizing image. Then, enter console of the container, check the configuration, and run each application to verify normal operation. Afrter verifcation is completed, write CMD or ENTRYPOINT COMMAND.

Dockerfile
FROM python:3.6.6-jessie

MAINTAINER cgex

ENV SRVHOME=/srv/app

WORKDIR $SRVHOME

COPY ./ $SRVHOME

RUN apt-get update &amp;&amp; apt-get install -y \
    nginx \
    supervisor

COPY ./nginx/nginx.conf /etc/nginx/
COPY ./nginx/gunicorn-app.conf /etc/nginx/conf.d/

COPY ./gunicorn_config.py /etc/gunicorn/

COPY supervisord.conf /etc/supervisor/

RUN pip install --upgrade pip
RUN pip install -r requirements.txt

EXPOSE 80
EXPOSE 8080

# for receving stream of log 
RUN ln -sf /dev/stdout /var/log/nginx/access.log \
    &amp;&amp; ln -sf /dev/stderr /var/log/nginx/error.log

CMD ["/usr/bin/supervisord"]

REFERENCES

gunicorn vs uwsgi flask-concurrency-test

12/2/2018

WEB Framework Check Template

글에서 말하는프레임웍은 REST API 중심의프레임웍을 말한다. 해당 글의 작성 목적은프레임웍을 선택 혹은 구축하는데 있어 고려해볼사항들에 대해서 포괄적으로 언급한다. 파이썬 진형의 대표적인프레임웍 장고에서 많은 개념을 참고했다.

주요 고려 항목

  • Authentication
    • OAuth2, JWT
  • Explicit Project Structure
  • Architecture
    • Design Pattern. MVC Pattern
    • 장고의 경우 View, Model, Serializer 와 같은모듈의 명확한 역할 정의. 균일한 데이터 흐름을 갖게 하는게 매우 중요.
  • Middleware
    • Throttling
    • 필요하다면 Device 분기
    • Logging
    • 현재 서버 환경별 Request, Response Handling
      • Beta 환경인 경우. 토큰발행등으로 Beta 서버 추가 인증.
  • Dynamic and Elastic Settings Load. e.g) local, development, alpha, beta, production …
  • DDD or Adaptable MSA
    • 장고의 경우 앱을 Service 중심으로 분류. 서비스간 단일 인터페이스를 통해 의존관계 설립.
  • REST API URL일반화 가능여부.
    • 장고의 경우 function view => class view
      • class view경우 API 별 permission, authentication, throttling 관리가 매우 편해짐.
  • Exception Handling Centralization
  • Test Environment
    • Test Framework
  • Cache Backend & Engine
    • Redis, Memcached …
  • Storage Engines
    • MySQL, MSSQL, PostgreSQL …
  • ORM Engine
  • API Versioning
    • /v1/
  • API Documentation
    • Swagger
  • Web 혹은 Admin 필요시 Template Engine
  • Runtime Debugger
    • django-debbug-toolbar
  • Serialization

ON DEMAND

  • Asynchronous task queue
    • Celery
    • Email, SMS 발송 같은 서비스
  • Support DATA Team
    • DATA HOOK
  • Log Centralization
Web Django
7/2/2018

[Django] contenttypes framework

부제: django.contrib.contenttypes 은 무엇인가?

장고 프로젝트를 생성하고, settings.py 파일을 보면 기본값 설정들이 되어있고, INSTALLED_APPS 하위에 이미 어떤 장고 어플리케이션들이 선언되어있다. 해당 어플리케이션인들이 프로젝트에 판단하기 위해 역할을 알아볼 것이다. 이 포스트에서는 django.contrib.contenttypes대해 살펴볼것이다.

django.contrib.contenttypes

네이밍이 contenttypes 이여서 HTTP Header의 속성 Content-Type 에 관련된 앱인줄 알았다. 하지만 설명을 읽어보니 전혀 상관없었다.

Django includes a contenttypes application that can track all of the models installed in your Django-powered project, providing a high-level, generic interface for working with your models.

설명을 보아하니, 장고 프로젝트안에서 선언된 모델을 추적하며, 높은수준의 사용하기 편한 인터페이스를 제공한단다. 목적은 파악되었다. 아직 필요한지 제거해도 되는지 판단이 서지 않아서 조금알아보겠다.

It’s generally a good idea to have the contenttypes framework installed; several of Django’s other bundled applications require it:

The admin application uses it to log the history of each object added or changed through the admin interface. Django’s authentication framework uses it to tie user permissions to specific models.

몇몇 장고의 번들 어플리케이션을 사용할때 contenttypes framework필요하단다… (몇몇!!!??? 말이여 방구여 그냥 쓰라는 의미로 받아들이자.) 장고 인증 프레임웍과 어드민에 의존 어플리케이션이란다. 더 이상 읽을 필요가 없다. 사용하기로 결정!!

PS. 장고에서 코드를 작성할때, 모델 사용을 참조 형식이 아닌, 문자열 형식으로 선언하고 런타임 환경에서 Lazy Loading 형식으로 구현하는 경우가 많다. 추축이지만 아마 contenttypes framework 때문에 가능한것 같다. 코드를 까서 살펴보면 되지만, 시간이 없다. 조사는 여기까지 그만 짜이찌엔!!

Django Python