기본 콘텐츠로 건너뛰기

令和5年5月3日気になるニュース

yahooニュース 産経新聞、首相「腹を割って意見交換」 7、8日に訪韓し尹大統領と会談  岸田文雄首相は1日(日本時間2日)、7~8日の日程で韓国を訪問し、尹錫悦(ユン・ソンニョル)大統領と会談する方向で調整(ちょうせい)していると明らかにした。訪問先(ほうもんさき)のガーナで記者団の取材に答えた。首相は尹氏が3月に来日(らいにち)した際(さい)、首脳同士が相互(そうご)に訪問する「シャトル外交」の再開(さいかい)で合意(ごうい)しており、その第1弾(いちだん)となる。 続いて、日本政府は4月28日に韓国を輸出手続き簡略化などの優遇措置の対象国となる「グループA(旧ホワイト国)」に再指定(さいしてい)する方針を発表したが、首相の訪韓(ほうかん)で成果(せいか)を示(しめ)せるかが焦点(しょうてん)になると書いていました。 日韓関係が改善されているようでうれしい記事でした。

Moving Average

In statistics, a moving average is a calculation used to analyze data points by creating a series of averages of different subsets of the full data set. In finance, a moving average (MA) is a stock indicator that is commonly used in technical analysis.

Let find Moving Average Line followed by previous market stock prices.

Module Import

from urllib.request import *
from bs4 import *
import requests
import re
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

in previous analysis (ref. https://tomtomplace.blogspot.com/2022/05/web-crawling.html), we've already get object variable 'pList', which is closing market stock price of Samsung electronic, and now we used to its data, we are going to make moving average price using Queue ADT.

Queue ADT

Queue is a linear data structure in which the insertion and deletion operations are performed at two different ends. In a queue data structure, adding and removing elements are performed at two different positions. The insertion is performed at one end and deletion is performed at another end. (ref. btechsmartclass) We can find 5 days moving average price using following method :

numMA_5 = 5
  mList_5 = []
  Q_5 = []
  mSum_5 = pList[0] * numMA_5
  for i in range(numMA_5) :
      Q_5.append(pList[0])
  for M in pList :
      mSum_5 = mSum_5 - Q_5.pop(0)
      mSum_5 += M
      mList_5.append(mSum_5/numMA_5)
      Q_5.append(M)

numMA_5 is a number how much interval days we want to set, mList_5 is such container saving average price analyzed, and Q_5 is temporary container to make average price. As using similar method, we can make 20 days moving average price and its of 60 days to use following codes :
def makeMA(pList):
  numMA_5 = 5
  mList_5 = []
  Q_5 = []
  mSum_5 = pList[0] * numMA_5

  numMA_20 = 20
  mList_20 = []
  Q_20 = []
  mSum_20 = pList[0] * numMA_20

  numMA_60 = 60
  mList_60 = []
  Q_60 = []
  mSum_60 = pList[0] * numMA_60

  for i in range(numMA_5) :
      Q_5.append(pList[0])
  for i in range(numMA_20) :
      Q_20.append(pList[0])
  for i in range(numMA_60) :
      Q_60.append(pList[0])

  for M in pList :
      mSum_5 = mSum_5 - Q_5.pop(0)
      mSum_5 += M
      mList_5.append(mSum_5/numMA_5)
      Q_5.append(M)

      mSum_20 = mSum_20 - Q_20.pop(0)
      mSum_20 += M
      mList_20.append(mSum_20/numMA_20)
      Q_20.append(M)

      mSum_60 = mSum_60 - Q_60.pop(0)
      mSum_60 += M
      mList_60.append(mSum_60/numMA_60)
      Q_60.append(M)

  drawGraph(pList,mList_5,mList_20,mList_60)

  return mList_5, mList_20, mList_60
makeMA() is the function which makes moving average price whose interval is 5, 20, 60 days.

Visualization

To visualize our analyzed data, we need to make the function who draw a graph. From the above code, the function named drawGraph is chain-function which is make MA price graph.

def drawGraph(pList,mList_5,mList_20,mList_60):
graph = pd.Series(pList, index=range(len(pList)))
  graph_m5 = pd.Series(mList_5, index=range(len(pList)))
  graph_m20 = pd.Series(mList_20, index=range(len(pList)))
  graph_m60 = pd.Series(mList_60, index=range(len(pList)))
  plt.style.use('seaborn')
  plt.plot(graph, label = 'stock price')
  plt.plot(graph_m5, label = '5MA')
  plt.plot(graph_m20, label = '20MA')
  plt.plot(graph_m60, label = '60MA')
  plt.legend(loc = 'upper left')
  plt.xlabel('Days')
  plt.ylabel('Price')
  plt.grid(True)
  plt.show()

The bottom image is following result.


댓글

댓글 쓰기

이 블로그의 인기 게시물

Portfolio Analysis, Mean Variance Frontier

  포트폴리오 이론에서의 기대수익률     포트폴리오 기대수익률은 개별 자산의 기대수익률의 가중치를 고려하여 만든 포트폴리오의 기대수익률이다 mean - variance space     자산 투자에 있어서 기대수익률을 위해서는 투자의 리스크를 감수해야 한다. 즉, 위험 한 단위가 증가할 때 기대수익률 또한 증가한다. Indifference Curve     Risk Averse의 성향이 많은 개인 투자자는 위험에 대해 기피하는 경향이 있다. 따라서, 위험 한 단위가 증가할 때마다 기대수익률을 더 많이 받으려고 하는 경향을 보인다. 따라서 무차별 곡선은 우상향하며, 기울기는 체증한다. 반면, Risk lover의 Indifference Cuve의 기울기는 체감한다. Portfolio Risk     포트폴리오의 리스크는 각 자산의 기대수익률간의 편차로 계산한다.  Example     2000년 1월부터 2020년 12월까지 기간동안 고려한 자산은 다음과 같다 스페인 국채 10년물  KOSPI 주가지수 S&P 주가지수 원유 선물 천연가스 선물 금 선물 구리 선물 import numpy as np import pandas as pd import matplotlib.pyplot as plt % matplotlib inline csv data의 변수명은 다음과 같이 정의한다 data : 수익률 데이터 cycle : 경기순환 사이클 데이터  import한 데이터는 다음과 같이 세가지 형식으로 분류한다 df = pd . concat ([ data . iloc [:, 1 :], cycle . iloc [:, 1 :]], axis = 1 ) # 전체 데이터 df_up = df [ df . cycle == 1 ] # 경기 확장기의 데이터 df_down = df [ df . cycle == 0 ] ...

AFML Chapter 3. Bollinger Band, Rolling Volatility

  이벤트 기반의 표본 추출 포트폴리오 매니저는 시장 구조적 변화, 추출된 신호 혹은 미시 구조적 현상 등 어떤 사건이 발생한 후에 사후 판단하여 베팅을 한다. 이러한 이벤트들은 대개 변동성 확대, 스프레드의 이탈, 거시경제지표 등과 연계되어 있을 수 있다. 프라도 교수는 이벤트를 중대한 것으로 특징지을 수 있고, 머신러닝을 활용해 이벤트가 발생한 부분을 Labeling하여 학습시키면 충분히 예측할 수 있는 학습기를 만들수 있다고 한다. (후에 기술하겠지만, Meta Labeling 기법의 가장 중요한 아이디어라고 할 수 있다) Cumulative Sum filter는 품질 통제 기법으로서 측정값이 목표값의 평균으로부터 얼마나 벗어났는지 확인하는 필터이다. 즉, 시장흐름의 기대값을 벗어나면 이벤트가 발생되었다고 보는 것이다. 물론, 여기서 기대값을 정하는 것은 사용자의 영역이므로 Hyper Parameter라고 볼 수 있다. CUSUM Filter Locally stationary process에서 발생한 관측값을 생각해 보자. 누적 합계는 다음과 같이 정의한다. $$ S_t = \max \{0, S_{t-1} + y_t - E_{t-1}[y_t]\}$$ 여기서 경계 조건은 $ S_0 = 0 $이다. 이 절차는 특정 임계값에 대해 $ S_t \leq h $를 만족하는 첫 번째 시간 $t$에서의 행동을 추천할 것이다.$y_t \geq E_{t-1}[y_t] - S_{t-1}$일 때마다 $S_t=0$이다. 0 floor는 $S_t$가 음수가 되지 못하도록 하방 편차를 무시할 것을 의미한다. 그 이유는 필터가 모든 재설정 레벨 0으로부터 위로 발산하는 시퀀스를 식별하도록 설정됐기 때문이다. 특히 임계값은 다음의 경우에 활성화된다 $$ S_t \leq h \Leftrightarrow \exists \tau \in [1,t] \Big| \sum_{i=\tau} ^t (y_i - E_{I-1} [y_t]) \leq h$$ 이러한 개념은 upper bound와 lo...

Monetary Demand and Supply, Leisure

We assume that the person's money demand behavior satisfies following statement $\frac{M_t}{P_t} = L(y_t,R_t)$ where M means demand of nominal money, P means price index, R means prevailing rate of interest on some relevant assets. Variable y makes function L increase and variable R makes function L decrease. A Formal Model consider a hypothetical household that seeks at time $t$ to maximize the multiperiod utility function : $u(c_t,l_t) + \beta u(c_{t+1},l_{t+1}) + \beta u(c_{t+2},l_{t+2}) + ...$ here the $c_t$ and $l_t$ are the household's consumption of goods and leisure, respectively during the period $t$. Given above assumptions, the household's budget constraint for period $t$ alone can be written as following statement $P_ty + M_{t-1} + (1 + R_{t-1})B_{t-1} = P_tc_t + M_t + B_t$ Where B means Bond price. In this assumption, the left side means the total resources available, and the right side means the total expenditure available from the household. To take account ...