2014년 9월 24일 수요일

2014년 8월 17일 일요일

keygen

http://pincopall.altervista.org/cratut/ThunderPwr-CDtoMP3115-tutorial7.htm

load dll asm

.file "loaddllex.cpp" .intel_syntax noprefix .def ___main; .scl 2; .type 32; .endef .section .rdata,"dr" LC0: .ascii "C:\\work\\dummy.dll\0" .text .globl _main .def _main; .scl 2; .type 32; .endef _main: LFB6: lea ecx, [esp+4] LCFI0: and esp, -16 push DWORD PTR [ecx-4] push ebp LCFI1: mov ebp, esp push ecx LCFI2: sub esp, 36 call ___main mov DWORD PTR [esp], OFFSET FLAT:LC0 call _LoadLibraryA@4 sub esp, 4 mov DWORD PTR [ebp-12], eax mov eax, 0 mov ecx, DWORD PTR [ebp-4] LCFI3: leave LCFI4: lea esp, [ecx-4] LCFI5: ret LFE6: .section .eh_frame,"w" Lframe1: .long LECIE1-LSCIE1 LSCIE1: .long 0 .byte 0x3 .ascii "\0" .uleb128 0x1 .sleb128 -4 .uleb128 0x8 .byte 0xc .uleb128 0x4 .uleb128 0x4 .byte 0x88 .uleb128 0x1 .align 4 LECIE1: LSFDE1: .long LEFDE1-LASFDE1 LASFDE1: .long LASFDE1-Lframe1 .long LFB6 .long LFE6-LFB6 .byte 0x4 .long LCFI0-LFB6 .byte 0xc .uleb128 0x1 .uleb128 0 .byte 0x4 .long LCFI1-LCFI0 .byte 0x10 .byte 0x5 .uleb128 0x2 .byte 0x75 .sleb128 0 .byte 0x4 .long LCFI2-LCFI1 .byte 0xf .uleb128 0x3 .byte 0x75 .sleb128 -4 .byte 0x6 .byte 0x4 .long LCFI3-LCFI2 .byte 0xc .uleb128 0x1 .uleb128 0 .byte 0x4 .long LCFI4-LCFI3 .byte 0xc5 .byte 0x4 .long LCFI5-LCFI4 .byte 0xc .uleb128 0x4 .uleb128 0x4 .align 4 LEFDE1: .ident "GCC: (GNU) 4.8.1" .def _LoadLibraryA@4; .scl 2; .type 32; .endef

2014년 8월 16일 토요일

k-mean clustering

require(graphics) beta1<-c(-0.130811881,-0.124113184,-0.111084035,-0.346505179,0.146765992,-0.203682819) beta2<-c(0.19744896,0.158675025,0.098311959,0.644843941,-0.197478252,0.278922585) beta1<-c(-0.130811881, -0.124113184, -0.111084035, -0.346505179, 0.146765992, -0.201818799, 0.109229194, -0.203682819, -0.124113184, -0.065281704, -0.089614531) beta2<-c(0.19744896, 0.158675025, 0.098311959, 0.644843941, -0.197478252, 0.100779252, -0.204082744, 0.278922585, 0.158675025, 0.099221018, 0.136914875) x <- cbind(beta1, beta2) colnames(x) <- c("x", "y") (cl <- kmeans(x, 2)) plot(x, col = cl$cluster) points(cl$centers, col = 1:2, pch = 8, cex = 2) # sum of squares ss <- function(x) sum(scale(x, scale = FALSE)^2) ## cluster centers "fitted" to each obs.: fitted.x <- fitted(cl); head(fitted.x) resid.x <- x - fitted(cl) ## Equalities : ---------------------------------- cbind(cl[c("betweenss", "tot.withinss", "totss")], # the same two columns c(ss(fitted.x), ss(resid.x), ss(x))) stopifnot(all.equal(cl$ totss, ss(x)), all.equal(cl$ tot.withinss, ss(resid.x)), ## these three are the same: all.equal(cl$ betweenss, ss(fitted.x)), all.equal(cl$ betweenss, cl$totss - cl$tot.withinss), ## and hence also all.equal(ss(x), ss(fitted.x) + ss(resid.x)) ) kmeans(x,1)$withinss # trivial one-cluster, (its W.SS == ss(x)) ## random starts do help here with too many clusters ## (and are often recommended anyway!): (cl <- kmeans(x, 5, nstart = 25)) plot(x, col = cl$cluster) points(cl$centers, col = 1:5, pch = 8)

2014년 7월 28일 월요일

2014년 7월 27일 일요일

텍스트 파일 병합 펄 스크립트

$name = "name.txt"; $formular = "formular.txt"; $A = "A.txt"; $B = "B.txt"; $C = "C.txt"; open $fh_name, '<', $name or die "Cannot open $name: $!"; open $fh_formular, '<', $formular or die "Cannot open $formular: $!"; open $fh_A, '<', $A or die "Cannot open $A: $!"; open $fh_B, '<', $B or die "Cannot open $B: $!"; open $fh_C, '<', $C or die "Cannot open $C: $!"; open $table, '>table.txt'; my $n = @{[<$fh_name>]}; seek $fh_name,0,0; for ($i=1; $i<= $n; $i++){ $l_name = <$fh_name>; chomp($l_name); $l_formular = <$fh_formular>; chomp($l_formular); $l_A = <$fh_A>; chomp($l_A); $l_B = <$fh_B>; chomp($l_B); $l_C = <$fh_C>; chomp($l_C); print $table "$l_name\t$l_formular\t$l_A\t$l_B\t$l_C\n"; }

2014년 7월 23일 수요일

이클립스 프로젝트 SWT 예제

1.[File]-[New]-[Java Project]


[New]-[Class]

소스코드 입력

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

/**
 * @author Steven Holzner
 * 
 */
public class SWTButtonExampleDemo {

  public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setSize(300, 200);
    shell.setText("Button Example");
    shell.setLayout(new RowLayout());

    final Button button = new Button(shell, SWT.PUSH);
    button.setText("Click Me");

    final Text text = new Text(shell, SWT.SHADOW_IN);

    button.addSelectionListener(new SelectionListener() {

      public void widgetSelected(SelectionEvent event) {
        text.setText("No worries!");
      }

      public void widgetDefaultSelected(SelectionEvent event) {
        text.setText("No worries!");
      }
    });
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch())
        display.sleep();
    }
    display.dispose();
  }
}



2. [Project]-[Java Build Path]-[Libraries]-[Add External JARs]

2014년 7월 8일 화요일

[c#] 엑셀 파일 읽기

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Excel = Microsoft.Office.Interop.Excel;

namespace ReadExcel
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\\C.xlsx");
            Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
            Excel.Range xlRange = xlWorksheet.UsedRange;

            int rowCount = xlRange.Rows.Count;
            int colCount = xlRange.Columns.Count;

            for (int i = 1; i <= rowCount; i++)
            {
                for (int j = 1; j <= colCount; j++)
                {
                    MessageBox.Show(xlRange.Cells[i, j].Value2.ToString());
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }

    }
}

클릭하면 div를 보여주는 jquery 소스

<button>Toggle</button>
<div id="select" style="display: none">
<p>Such interesting text, eh?</p>
</div>
<div>this is second para</div>
</body>

<script>
$( "button" ).click(function() {
$('#select').toggle( "slow" );
});
</script>

2014년 6월 28일 토요일

[c#]1분 간격으로 이벤트 실행

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Timers;

namespace sendgmail
{
    public partial class Form1 : Form
    {
        static System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
       
        public Form1()
        {
            InitializeComponent();

            timer.Tick += new EventHandler(timer_Tick); // Everytime timer ticks, timer_Tick will be called
            timer.Interval = 60 * 1000;
            timer.Enabled = true;                       // Enable the timer
            timer.Start();    

  
        }

        // 쓰레드풀의 작업쓰레드가 지정된 시간 간격으로
        // 아래 이벤트 핸들러 실행
        private void timer_Tick(object sender, EventArgs e)
        {
            // MessageBox.Show("timer success");

        }

    }
}

2014년 6월 26일 목요일

윈도우환경에서 autoconf 사용

mingw32를 다운받고 installer에서 msys를 선택한 후 설치한다.

명령프롬프트에서 bash 입력

./configure 명령을 사용할 수 있다.

2014년 6월 25일 수요일

서브버전 사용법

서브버전 클라이언트를 설치
http://sourceforge.net/projects/win32svn/


명령프롬프트에서

svn checkout [주소]

2014년 6월 3일 화요일

get naver kin

use LWP::UserAgent;
use autodie qw/ open close /;
use WWW::Mechanize;
use LWP::Simple qw($ua get);
use Encode;

$filename="naverkin-phy.txt";
if(-e $filename)
    {
        unlink($filename);
    }

$ua->agent('My agent/1.0');

# create WWW::Mechanize object
# autocheck 1 checks each request to ensure it was successful
my $mech = WWW::Mechanize->new();

$mech->get("http://kin.naver.com/qna/list.nhn?m=noanswer&dirId=1114&page=1");
#$no=197187698;


$list_cont = $mech->content();

$list_cont=encode("euc-kr", $list_cont);
#print $list_cont;

@link = split(/docId=(\d{9})/, $list_cont);


for ($i=1; $i<=$#link; $i++){
    if ($i%2 == 1){
     push(@no, $link[$i]);
    }
}

@no = sort {$a <=> $b} @no;  # 1,2,3 순으로 정렬; Ascending
 
for ($i=1; $i<=$#no; $i++){

print $no[$i]." article is extracted...\n";

# paste from url of webbrowser manually later modify
$mech->get("http://kin.naver.com/qna/detail.nhn?d1id=11&dirId=1114&docId=$no[$i]");

$cont = $mech->content();
$cont=encode("euc-kr", $cont);

#@temp = split(/og:url/, $cont);
#@temp = split(/science&no=/, $temp[1]);
#@temp = split(/&page/, $temp[1]);


@temp = split(/tit_cont/, $cont);
@temp = split(/recom_q/, $temp[1]);
@temp = split(/img/, $temp[0]);
@temp = split(/dl/, $temp[0]);

$subject = $temp[0];
$subject =~ s/">//g;
$subject =~ s/h3>//g;
$subject =~ s/<//g;
$subject =~ s/\///g;
$subject =~ s/^\s+//g;
$subject =~ s/\s+$//g;

$subject = "subject: ".$subject;


@temp = split(/tit_cont/, $cont);
@temp = split(/recom_q/, $temp[1]);
@temp = split(/<dl>/, $temp[0]);
@temp = split(/<\/dl>/, $temp[1]);
@temp = split(/<dt>/, $temp[0]);
@temp = split(/<\/dt>/, $temp[1]);

$name = $temp[0];

$name =~ s/^\s+//g;
$name =~ s/\s+$//g;
$name = "name: ".$name;


@temp = split(/본문/, $cont);
@temp = split(/게시중단 안내/, $temp[3]);
$out = $temp[1];
$out =~ s/!<--$//;
$out =~ s/<\/div>//;
$out =~ s/\!<--//;
$memo = $out;

#print $memo;

$memo = "memo: ".$memo;

@temp = split(/본문/, $cont);
@temp = split(/게시중단 안내/, $temp[3]);
@img_url = split(/src="/,$temp[1]);
@img_url = split(/\?type/,$img_url[1]);
#print $img_url[0];

$img_url[0]=~ m/jpg|png|JPG|PNG/;

if ($img_url[0]){
$img_type = $&;
$mech->mirror($img_url[0], $no.".".$img_type);
}

$attached = "file:".$no.".".$img_type;

open MYFILE, ">>", "naverkin-phy.txt" or die ;
 print MYFILE "$no[$i]";
 print MYFILE "------------------------------------------------------------------------------\n";
 print MYFILE "$name\n";
 print MYFILE "$subject\n";
 print MYFILE "$memo\n";
 print MYFILE "$attached\n";

}

get bgm from bgmstore

use LWP::UserAgent;
use autodie qw/ open close /;
use WWW::Mechanize;
use LWP::Simple qw($ua get);
use Encode;

$ua->agent('My agent/1.0');

# create WWW::Mechanize object
# autocheck 1 checks each request to ensure it was successful
my $mech = WWW::Mechanize->new();

if (-e "bgmstore.txt"){
    unlink("bgmstore.txt");
    }
   
$mech->get("http://bgmstore.net/?q_type=category&q=%EC%9C%A0%EB%A8%B8");
@link = $mech->find_all_links( url_regex => qr/view/);

for $new_link (@link){
$url = $new_link->url_abs();

$no++;

if ($no % 2 == 0 ){
print $url;

$mech->get($url);
$cont = $mech->content();

print $no." article is extracted...\n";
@files=();

$cont=encode("euc-kr", $cont);

@temp = split(/titleBox/, $cont);
@temp = split(/<span/, $temp[1]);
$subject = $temp[0];
$subject =~ s/clearfix">//;

print $subject;
$name = "땡초";

@mp3 = $mech->find_all_links( url_regex => qr/mp3/);

print $mp3[0]->url_abs();
$filename = $subject;
$filename =~ s/,//g;
$filename =~ s/\?//g;
$filename =~ s/\s+//g;
print $filename;

$mech->mirror($mp3[0]->url_abs(), $filename.".mp3");


$name = "name: ".$name;
$subject = "subject: ".$subject;
$memo = "memo: ".$memo;

open MYFILE, ">>", "bgmstore.txt" or die ;
 print MYFILE "$no";
 print MYFILE "------------------------------------------------------------------------------\n";
 print MYFILE "$name\n";
 print MYFILE "$subject\n";
 print MYFILE "$memo\n";
 }
}

2014년 5월 30일 금요일

우분투에서 루트 권한으로 명령 실행

우분투에서 루트 권한으로 명령을 실행하기 위해서는 root password가 설정되어 있어야 한다.

sudo passwd root

이후 sudo 명령을 사용할 수 있다

윈도우에 git 클라이언트 설치

다운로드
http://git-scm.com/download/win

path에 설치폴더의 바이너리 경로를 등록

명령프롬프트에서 실행하면 된다

perl mechanize example

use LWP::UserAgent;
use autodie qw/ open close /;
use WWW::Mechanize;
use LWP::Simple qw($ua get);
use Encode;


$ua->agent('My agent/1.0');

# create WWW::Mechanize object
# autocheck 1 checks each request to ensure it was successful
my $mech = WWW::Mechanize->new();

$filename = "ilbe.txt";
if(-e $filename)
    {
        unlink($filename);
    }
   
$mech->get("http://www.ilbe.com/ilbe");

@link = $mech->find_all_links( url_regex => qr/\d{10}/);

for $new_link (@link){

$url = $new_link->url_abs();

$no = $url;
$no =~ m/\d{10}/;

$no = $&;

$mech->get($url);
$cont = $mech->content();

print $no." article is extracted...\n";
@files=();

# paste from url of webbrowser manually later modify

#@temp = split(/og:url/, $cont);
#@temp = split(/science&no=/, $temp[1]);
#@temp = split(/&page/, $temp[1]);


#$no = $temp[0];

$cont=encode("euc-kr", $cont);

@temp = split(/author/, $cont);
@temp = split(/<\/div>/, $temp[1]);
@temp = split(/<\/div>/, $temp[0]);
@temp = split(/margin-right:3px;/, $temp[0]);
$name = $temp[1];
$name =~ s/"//;
$name =~ s/\/>//;
$name =~ s/^\s+//;
@temp = split(/<\/span>/, $name);
$name =~ s/\s+$//;
$name = $temp[0];
#print $name;

@temp = split(/기사 제목/, $cont);
@temp = split(/-->/, $temp[1]);
@temp = split(/<!--/, $temp[1]);

$subject = $temp[0];

print $subject;


@temp = split(/기사 본문/, $cont);
@temp = split(/serverLog/, $temp[1]);

$memo = $temp[0];
$memo =~ s/-->//;
$memo =~ s/^\s+//;

#print $memo;



@img = $mech->find_all_links( text_regex => qr/png/i );

$i = 0;
for my $img_url (@img) {
    $i++;
    print $img_url->url_abs;
    $mech->mirror($img_url->url_abs, $no."-".$i.".png");
    push (@files, $no."-".$i.".png");
   
}

@img = $mech->find_all_links( text_regex => qr/jpg/i );
for my $img_url (@img) {
    $i++;
    print $img_url->url_abs;
    $mech->mirror($img_url->url_abs, $no."-".$i.".jpg");
    push (@files, $no."-".$i.".jpg");
   
    #Opens FROM_DIR, ao I can read from it
   
       
}

$attached = "file:";
for ($i=0; $i<=$#files; $i++){
$attached = $attached.$files[$i]." ";

}

$name = "name: ".$name;
$subject = "subject: ".$subject;
$memo = "memo: ".$memo;


open MYFILE, ">>$filename" or die ;
 print MYFILE "$no";
 print MYFILE "------------------------------------------------------------------------------\n";
 print MYFILE "$name\n";
 print MYFILE "$subject\n";
 print MYFILE "$memo\n";
 print MYFILE "$attached\n";
}

2014년 5월 23일 금요일

펄 모듈 설치 모듈이 서브 타입으로 되어 있을 때

모듈이름이
WWW::Mechanize::Firefox

다 써주어야 한다.

cpan install WWW::Mechanize::Firefox

대소문자도 구분하니까 유의

2014년 5월 8일 목요일

하위 폴더의 모든 파일에서 특정 문자열을 검색하는 펄스크립트

use strict;
use warnings;
use Cwd;

use File::Find;

my $search_pattern=$ARGV[0];
my $file_pattern  =$ARGV[1];

if (@ARGV <2){
print "Useage: $0 [string to search] [file type]\n";
exit 1;
}

find(\&d, cwd);

sub d {

  my $file = $File::Find::name;

  $file =~ s,/,\\,g;

  return unless -f $file;
  return unless $file =~ /$file_pattern/;

  open F, $file or print "couldn't open $file\n" && return;

  while (<F>) {
    if (my ($found) = m/($search_pattern)/o) {
      print "found $found in $file\n";
      last;
    }
  }

  close F;
}

2014년 4월 12일 토요일

마르코브

library(stringr)

setwd("C:/rdata")
source("DTMC.R")

###here kospi data
dat <- read.csv('port3.csv', header=TRUE, na="")

odat<-dat[c(1:nrow(dat)),]

attach(odat)

x<-odat[order(일자),]


price <- as.numeric(str_replace_all(x$리홈쿠첸, ",", ""))


d <- diff(price)

up2up <-0
up2down <-0
down2up <-0
down2down <-0

for (i in 2:length(d)){
    if (d[i-1]> 0 && d[i]>0){
    up2up <- up2up+1
    }
    if (d[i-1]> 0 && d[i]<0){
    up2down <- up2down +1
    }
    if (d[i-1]< 0 && d[i]>0){
    down2up <- down2up+1
    }
    if (d[i-1]< 0 && d[i]<0){
    down2down <- down2down+1
    }

}

u2u <- up2up/(up2up+up2down)
u2d <- up2down/(up2up+up2down)
d2u <- down2up/(down2up+down2down)
d2d <- down2down/(down2up+down2down)

mattrans <- matrix(c(u2u, d2u, u2d, d2d),nrow=2,ncol=2)

colnames(mattrans) <- c("U","D")
row.names(mattrans) <- c("U","D")
rm(temp)
rm(sim)
temp<-0
sim <-data.frame(vector())

#now set states
state<- c(1,2,3,4,5)
nstate<-c(8000,9000,10000,11000,12000)

#current state
temp[1]<- 5

for (i in 1:100){
ins<- simula(mattrans,10)
 for (j in 2:20){
if (ins[j] == "U"){
    temp[j] <- temp[j-1]+1
}
else { temp[j] <- temp[j-1]-1}
}

sim <-rbind(sim, temp)
}

p1<-sum(rowSums(sim <=1))/(10*100)

p2<-sum(rowSums(sim == 2))/(10*100)

p3<-sum(rowSums(sim == 3))/(10*100)
p4<-sum(rowSums(sim == 4))/(10*100)
p5<-sum(rowSums(sim >= 5))/(10*100)

p <- c(p1,p2,p3,p4,p5)

cat("tansition matex is:\n")
matrix(mattrans, nrow = 2,ncol = 2)

f <- data.frame(nstate, p)
colnames(f)<-c("주가", "확률")

f[order(-f[,1]),]

cat("current state is:",temp[1], sep="\n")

2014년 4월 11일 금요일

markov chain for stock price

## NAME:  markovchain.py
##
## USAGE:  From shell prompt: python -i markovchain.py
##         or within interactive python environment, scrape and paste
## REQUIRED ARGUMENTS: none
##
## OPTIONS: none
## DESCRIPTION: Simulation of the cash management model as a Markov chain
## DIAGNOSTICS: None
## CONFIGURATION AND ENVIRONMENT: None
## DEPENDENCIES: None
## INCOMPATIBILITIES: None known
## PROVENANCE: Tue Aug 28, 2012  5:38 AM
## BUGS AND LIMITATIONS:  None Known
## FEATURES AND POTENTIAL IMPROVEMENTS:
## For the innermost for-loop, you can simply use
## newState = scipy.random.choice(1, 1, prob=T[state,])
## That shows more clearly what's going on
## On the other hand, if other languages don't have a function comparable to sample, then
## the current formulation is easier to adapt and make the algorithms similar.

## AUTHOR:  Steve Dunbar
## VERSION: 1.0 Tue Aug 28, 2012  5:38 AM
##          1.1 added some ouput formatting Mon Nov 12, 2012  6:03 AM
## KEYWORDS:   Markov chain, simulation, reflecting boundary
#! /usr/bin/env python

import scipy

n = 6;   # Top boundary, number of states 0..n is n+1
s = 4;   # Start and Reset state number 1 <= s <= n-1
p = 0.8;
steps = 1000;

T = scipy.diag( p*scipy.ones( n ), 1) + scipy.diag( (1-p)*scipy.ones( n ), -1);
T[0,1] = 0; T[0,s] = 1;
T[n,n-1] = 0; T[n,s] = 1;

# vector to hold the count of visits to each state during a cycle
count = scipy.zeros(n+1, float);
# Initialize the cyclelength
numberCycles = 0;
# Start in the state s
state = s;
# Make steps through the markov chain
for i in range(1, steps+1):
    x = 0;
    u = scipy.random.random(1);
    newState = state;
    for j in range(n+1):
    x = x + T[state, j];
    if (x >= u):
        newState = j;
        break;
    ## newState = scipy.random.choice(1, 1, prob=T[state,])
    state = newState;
    count[state] = count[state] + 1;
   
    if (state == n or state == 0):
        numberCycles = numberCycles + 1;
        avgVisits = count/numberCycles;
        avgCycleLength = i/numberCycles;

Wsk = avgVisits

print Wsk

theoreticalWsk = 2*(  s*(1-scipy.arange(0,n+1,dtype=float)/n) - scipy.maximum(s-scipy.arange(0,n+1), scipy.zeros(n+1, int) ) )

prob = [0] * (n+1)    # initialize probility as list data type
for i in range(1, n+1):
    prob[i] = Wsk[i]/sum(Wsk);

price = [2000, 2900, 3500, 4500, 5100, 5300, 5500]   # this is list not array
print "each price state in a cycle:\n", price
print "Average number of visits to each state in a cycle:\n ",  [round(n, 2) for n in prob]


2014년 3월 30일 일요일

계절성 분석

library(tseries)
library(quadprog)
getwd()
setwd('c:/rdata')

###here kospi data
dat <- read.csv('hite.csv', header=TRUE)

odat<-dat[c(1:nrow(dat)),]

attach(odat)

x<-odat[order(일자),]

x$newday <- as.Date(x$일자, "%Y-%m-%d")

price <- as.numeric(gsub( ",", "", as.vector(x$종가)))


par(mfrow=c(3,1))

par(mar=c(3,3,1,2))

plot(price, type='l')

time<-c(1:30)

lm1 <-lm(price[1:30]~time)

err <- price[1:30] - (lm1$coeff[2]*time+lm1$coeff[1])


time<-c(31:40)

lm1 <-lm(price[31:40]~time)

err <- c(err, (price[31:40] - (lm1$coeff[2]*time+lm1$coeff[1])))

time<-c(41:50)

lm1 <-lm(price[41:50]~time)

err <- c(err, (price[41:50] - (lm1$coeff[2]*time+lm1$coeff[1])))


plot(x$newday[1:50], err, type='l', col='red',
    panel.first=grid(col = "gray", lty = "dotted"), pch=20)
points(x$newday[1:50], err, pch = 20, col = "red")
axis.Date(side = 1, x$newday[1:50])

2014년 3월 28일 금요일

베타중립포트폴리오

library(tseries)
library(quadprog)
getwd()
setwd('c:/rdata')

###here kospi data
dat <- read.csv('port3.csv', header=TRUE)

odat<-dat[c(1:nrow(dat)),]

attach(odat)

x<-odat[order(일자),]

ret <- 0
ret2<-0
ret3<-0


kospi <- as.numeric(as.vector(x$코스피))
kosdaq <- as.numeric(as.vector(x$코스닥))


beta <- 0
beta2 <-0

price <- as.numeric(as.vector(x$sk하이닉스))
for (i in 1:length(price)) {
ret[i] <- (price[i]-price[1])/price[1]
ret2[i] <- (kospi[i]-kospi[1])/kospi[1]
ret3[i] <- (kosdaq[i]-kosdaq[1])/kosdaq[1]
}

beta[1] <- cov(ret, ret2)/sd(ret2)^2
beta2[1] <- cov(ret, ret3)/sd(ret3)^2



price <- as.numeric(as.vector(x$하이트진로))
for (i in 1:length(price)) {
ret[i] <- (price[i]-price[1])/price[1]
}


beta[2] <- cov(ret, ret2)/sd(ret2)^2
beta2[2] <- cov(ret, ret3)/sd(ret3)^2


price <- as.numeric(as.vector(x$lg전자))
for (i in 1:length(price)) {
ret[i] <- (price[i]-price[1])/price[1]
}


beta[3] <- cov(ret, ret2)/sd(ret2)^2
beta2[3] <- cov(ret, ret3)/sd(ret3)^2

price <- as.numeric(gsub( ",", "", as.vector(x$삼성중공업)))



for (i in 1:length(price)) {
ret[i] <- (price[i]-price[1])/price[1]
}



beta[4] <- cov(ret, ret2)/sd(ret2)^2
beta2[4] <- cov(ret, ret3)/sd(ret3)^2

price <- as.numeric(as.vector(x$삼성전기))


for (i in 1:length(price)) {
ret[i] <- (price[i]-price[1])/price[1]
}

beta[5] <- cov(ret, ret2)/sd(ret2)^2
beta2[5] <- cov(ret, ret3)/sd(ret3)^2



####### 베타중립 포트폴리오 구성 몬테카를로 시뮬레이션 이용 ##########

objbeta <- 0
nwsum <- 1
w<-0
nw <-0

d <- ncol(x)

n<-5

for (r in 1:1000){
w <- runif(n, 1, 100)

sw <- w/sum(w)

for (i in 1:n){
wsum <- sw[i]*beta[i]
}

if (abs(wsum) < nwsum) {
nwsum <- wsum
nw <- sw
cat("objective function", nwsum, sep="\n")
}
}

names = c('sk하이닉스', '하이트진로', 'lg전자', '삼성중공업', '삼성전기')

names
cat("optimized value of beta is:", nwsum, "under weights of stocks as following", sep="\n")
names
round(nw,2)



####

plot(x=beta, y=beta2, xlim=c(-3,3), ylim=c(-3,3), pch=20, col='red',
 panel.first=grid(col = "gray", lty = "dotted"),

xlab="beta with kospi", ylab="beta with kosdaq")

text(x=beta, y=beta2, labels = names, adj=c(0,1))

####






2014년 3월 22일 토요일

5초 후 자동으로 사라짐

<!DOCTYPE html>

<html>

<title>Web Page Design</title>

<head>

<style type="text/css">


#box {  
    height: 300px;  
    position: absolute;
    top: 0;
    left: 0;  
    width: 500px;
    opacity: 0;  
    transition: opacity 3s ease;
}

</style>

<body onload="document.getElementById('box').style.opacity='1'">
<div id="box"></div>



<script>
    ni = document.getElementById('box');

  var newdiv = document.createElement('div');

   newdiv.setAttribute('id','box2');

  newdiv.innerHTML = 'This is test';
  ni.appendChild(newdiv);

var myVar=setTimeout(function(){Notifr()},5000);

function Notifr()
{
    document.getElementById('box2').remove();
}


</script>


</body>
</html>

css 서서히 나타나는 효과

<!DOCTYPE html>
<html>
<title>Web Page Design</title>
<head>
<style type="text/css">
body{
opacity:0;
-moz-transition: opacity 2s;
-webkit-transition: opacity 2s; /* Safari */
}

</style>
</head>
<body onload="document.body.style.opacity='1'">
this string is to test
</body>
</html>


-------------------
 div id를 이용


<!DOCTYPE html>
<html>
<title>Web Page Design</title>
<head>
<style type="text/css">

#box {   
    height: 300px;   
    position: absolute;
    top: 0;
    left: 0;   
    width: 500px;
    opacity: 0;   
    transition: opacity 3s ease;
}
</style>
<body onload="document.getElementById('box').style.opacity='1'">
<div id="box">
       This is test</div>
</body>
</html>

2014년 3월 16일 일요일

prediction of kospi with arma(2,2)

library(quantmod)

library(fGarch)

URL <- "http://ichart.finance.yahoo.com/table.csv?s=^KS11"

dat <- read.csv(URL)

dat$Date <- as.Date(dat$Date, "%Y-%m-%d")

odat<-dat[c(1:100),]

attach(odat)

x<-odat[order(Date),]

fit <- arima(diff(log(x$Close)), order=c(2,0,2))

sim <- diff(log(abs(x$Close)))[99]
sim <- c(sim, diff(log(abs(x$Close)))[98])
err <- rnorm(30, 0, sd(diff(log(x$Close[length(x$Close)-10:length(x$Close)]))))

upcount = 1
downcount = 1

ye <-x$Close[100]

td<-x$Date[100]
group<-rep(i, length(ye))

pred<-data.frame(td, ye, group)

// 시뮬레이션 회수
n<-100

for (i in 1:n){

for (t in 3:100) {

    sim[t] <- fit$coef[1]*sim[t-1] + fit$coef[2]*sim[t-2]
        +fit$coef[3]*err[t-1]
        +fit$coef[4]*err[t-2]

}


err <- rnorm(100, 0, 15)

// 20일간 주가를 예측함
for (j in 2:20) {

td[j] <- x$Date[length(x$Date)] + j

ye[j] <- exp(sim[j-1])*ye[j-1]+err[j-1]

pred<- rbind(pred, data.frame(td=td[j], ye=ye[j], group=i))

}


if (ye[20] > x$Close[100]){
        upcount = upcount+1}
else downcount = downcount +1

}

// 상승확률과 하락확률
cat("Probabilty of upward is", upcount/n)
cat("Probabilty of downward is", downcount/n)


library(ggplot2)
ggplot(pred, aes(x=td, y=ye, colour=group, group=group))+geom_line()




2014년 3월 13일 목요일

arma(2,2)

library(quantmod)

library(fGarch)

URL <- "http://ichart.finance.yahoo.com/table.csv?s=^KS11"

dat <- read.csv(URL)

dat$Date <- as.Date(dat$Date, "%Y-%m-%d")

odat<-dat[c(1:100),]

attach(odat)

x<-odat[order(Date),]

fit <- arima(diff(log(x$Close)), order=c(2,0,2))

#fore <- predict(fit, n.ahead=10, doplot=F)

sim <- diff(log(abs(x$Close)))[99]
sim <- c(sim, diff(log(abs(x$Close)))[98])
err <- rnorm(30, 0, sd(diff(log(x$Close[length(x$Close)-10:length(x$Close)]))))


for (t in 3:30) {

    sim[t] <- fit$coef[1]*sim[t-1] + fit$coef[2]*sim[t-2]
        +fit$coef[3]*err[t-1]
        +fit$coef[4]*err[t-2]

}

dev.new()

par(mfrow=c(3,1))

par(mar=c(3,3,1,2))

x$newday <- as.Date(x$Date, "%m/%d/%Y")

plot(x$newday, x$Close, type='l', col='red', xlim=c(x$newday[1],x$newday[length(x$newday)]+20),

    panel.first=grid(col = "gray", lty = "dotted"), pch=20)

points(x$newday, x$Close, pch = 20, col = "red")

ye <- x$Close[100]

td<-x$newday[length(x$newday)]+1

err <- rnorm(30, 0, sd(diff(x$Close[length(x$Close)-50:length(x$Close)])))

for (j in 2:30) {

td[j] <- x$newday[length(x$newday)] + j

ye[j] <- exp(sim[j])*ye[j-1]+err[j-1]

}

td<-as.Date(td)

ye

points(td, ye, col='red', pch=20, type='b')

##########################################################

library(forecast)

afit <- auto.arima(x$Close)

fore <- forecast(afit, h=15)

plot(fore)





2014년 3월 12일 수요일

ar2kospi

library(quantmod)

library(fGarch)

URL <- "http://ichart.finance.yahoo.com/table.csv?s=^KS11"

dat <- read.csv(URL)

dat$Date <- as.Date(dat$Date, "%Y-%m-%d")

odat<-dat[c(1:100),]

attach(odat)

x<-odat[order(Date),]

fit <- arima(diff(log(x$Close)), order=c(2,0,0))

sim <- diff(log(abs(x$Close)))[98]

sim <- c(sim, diff(log(abs(x$Close)))[99])

for (t in 3:20) {

    sim[t] <- fit$coef[2]*sim[t-2]+ fit$coef[1]*sim[t-1]

}


dev.new()

par(mfrow=c(3,1))

par(mar=c(3,3,1,2))

plot(x$Close, type='l', xlim=c(0, 120), xaxt='n',

    panel.first=grid(col = "gray", lty = "dotted"), pch=20)

t <- c(101:120)

points(x$Close, pch = 20, col = "red")

ye <- x$Close[100]

err <- rnorm(20, 0, sqrt(sd(x$Close[length(x$Close)-50:length(x$Close)])))

for (j in 2:20) {

ye[j] <- exp(sim[j-1])*ye[j-1]+err[j]

}

ye

points(t, ye, col='red', pch=20, type='b')

##########################################################

library(forecast)

fit <- auto.arima(x$Close[1:80])
#library(dataframes2xls)
#write.xls(forecast(fit, h=20), "c:/mydata.xls")

write.table(x, "c:/kospi.txt")

plot(forecast(fit, h=20))




2014년 3월 7일 금요일

[perl] 이미지가로 500px 작으면 삭제

use strict;
#use warnings;
use Cwd;

use File::Find;
use Image::Size;

if (@ARGV <1){
print "Useage: $0 [string to search] [file type]\n";
exit 1;
}
 opendir (DIR, $ARGV[0]) or die $!;
   
    my @list;
chdir($ARGV[0]);   
  while (my $file = readdir(DIR)) {

   my ($width, $height ) = imgsize($file);
       
   #print $width;
    if ($width < 500) {
    push(@list,$file);
    }

    }
   
unlink @list;

2014년 3월 4일 화요일

arma(1,1) kospi

library(quantmod)
library(fGarch)

URL <- "http://ichart.finance.yahoo.com/table.csv?s=^KS11"
dat <- read.csv(URL)
dat$Date <- as.Date(dat$Date, "%Y-%m-%d")

odat<-dat[c(1:100),]

attach(odat)

x<-odat[order(Date),]

fit <- arima(diff(x$Close), order=c(1,0,2))

err <- rnorm(30, 0, sd(diff(x$Close)))

sim <- diff(x$Close)[99]

for (t in 2:30) {
    sim[t] <- fit$coef[1]*sim[t-1] + fit$coef[2]*err[t-1]*0.5
            + fit$coef[3]*err[t-2]*0.5
}

par(mfrow=c(3,1))
par(mar=c(3,3,1,2))

x$newday <- as.Date(x$Date, "%m/%d/%Y")
plot(x$newday, x$Close, type='l', col='red',
    panel.first=grid(col = "gray", lty = "dotted"), pch=20)
points(x$newday, x$Close, pch = 20, col = "red")

ye <- x$Close[100]
td<-x$newday[length(x$newday)]+1
for (j in 2:30) {
td[j] <- x$newday[length(x$newday)] + j

ye[j] <- sim[j-1]+ye[j-1]
}

td<-as.Date(td)
points(td, ye, col='red', pch=20, type='b')

plot(diff(x$Close), type='l', col=heat.colors(32)[15],panel.first=grid(col = "gray", lty = "dotted"))
##########################################################

library(forecast)

fit <- auto.arima(x$Close)
fore <- forecast(fit, h=10)
plot(fore)

ye

2014년 3월 2일 일요일

코스닥 주기 68일

URL <- "http://ichart.finance.yahoo.com/table.csv?s=^KQ11"

dat <- read.csv(URL)

dat$Date <- as.Date(dat$Date, "%Y-%m-%d")

odat<-dat[c(1:170),]

attach(odat)

x<-odat[order(Date),]


ret <- 0

for (i in 1:length(x$Close)) {

ret[i] <- (x$Close[i]-x$Close[1])/x$Close[1]*100

}


par(mfrow=c(2,1))
par(mar=c(3,3,1,2))

sample.t<-seq(1:length(ret))

sample.v<- ret
plot(sample.t, sample.v, type='l')
lines(sample.t, sample.v, lwd=2, col=heat.colors(32)[15])



## FFT stuff goes in here
##
x<- sample.v

per <- abs(fft(x-mean(x)))^2/length(x)  # Mod() and abs() same here
# if you want a nice picture:
freq = (1:length(x)-1)/length(x)
plot(freq, per, xlim=c(0,.2), type='o', lwd=2, col=heat.colors(32)[15])
text(freq, per, round(freq,digits=3), cex=0.6, pos=4, col=heat.colors(32)[15])



2014년 3월 1일 토요일

qone8 악성코드 제거

파이어폭스 주소창에
about:config

명령으로 고급환경설정으로 들어감

qone8 검색 후
초기화

2014년 2월 24일 월요일

kosdaq arma

library(quantmod)
library(fGarch)

URL <- "http://ichart.finance.yahoo.com/table.csv?s=^KQ11"
dat <- read.csv(URL)
dat$Date <- as.Date(dat$Date, "%Y-%m-%d")

odat<-dat[c(1:100),]

attach(odat)

x<-odat[order(Date),]

#kospiGarch <- garchFit(~arma(1, 2) + garch(1, 1), data=as.ts(x$Close))

fit <- arima(diff(log(x$Close)), order=c(1,0,1))

#fore <- predict(fit, n.ahead=10, doplot=F)

err <- rnorm(30, 0, sd(diff(log(x$Close))))

sim <- diff(log(abs(x$Close)))[99]

for (t in 2:30) {
    sim[t] <- fit$coef[1]*sim[t-1] + fit$coef[2]*err[t-1]
}

dev.new()

par(mfrow=c(3,1))
par(mar=c(3,3,1,2))

x$newday <- as.Date(x$Date, "%m/%d/%Y")
plot(x$newday, x$Close, type='l', col='red',
    panel.first=grid(col = "gray", lty = "dotted"), pch=20)
points(x$newday, x$Close, pch = 20, col = "red")

ye <- x$Close[100]
td<-x$newday[length(x$newday)]+1
for (j in 2:30) {
td[j] <- x$newday[length(x$newday)] + j

ye[j] <- exp(sim[j-1])*ye[j-1]
}

td<-as.Date(td)
ye
points(td, ye, col='red', pch=20, type='b')


##########################################################

library(forecast)

fit <- arima(x$Close, order=c(1,1,10))
fore <- forecast(fit, h=15)
plot(fore)

fore


변동성 garch(1)

library(tseries)
library(quadprog)
getwd()
setwd('c:/rdata')

###here kospi data
dat <- read.csv('port.csv', header=TRUE)
#dat$Date <- as.Date(dat$Date, "%Y-%m-%d")

odat<-dat[c(1:nrow(dat)),]
apply(na.omit(odat),2,max)
attach(odat)

x<-odat[order(일자),]

apply(na.omit(x),2,max)


price <- as.numeric(x$안랩)
ret <- 0

for (i in 1:length(price)) {
ret[i] <- (price[i]-price[1])/price[1]*100
}

chg <-0
for (i in 2:length(price)) {
chg[i] <- (price[i]-price[i-1])/price[i-1]*100
}


#garch

  mod.fit<-garch(x = ret - mean(ret), order = c(0,1), trace = TRUE) #Fit ARCH(1)
  summary(mod.fit)                      #Summarizes fit
  names(mod.fit)
  mod.fit$coef
#  plot(mod.fit)

 coef(mod.fit) # see above and compare with coefficient alpha0 and alpha1 caculated by arch model


par(mfrow=c(3,1))
par(mar=c(3,3,1,2))


plot(mod.fit$fitted.values[,1], type='l', xaxt='n',
    panel.first=grid(col = "gray", lty = "dotted"), pch=20)
title(main = "변동성", sub = NULL, xlab = NULL, ylab = NULL,
      line = NA, outer = FALSE)
plot(chg, type='l', xaxt='n'
)
points(chg, pch = 20, col = "red")
title(main = "일등락율%", sub = NULL, xlab = NULL, ylab = NULL,
      line = NA, outer = FALSE)

plot(ret, type='l', xaxt='n'
)
points(ret, pch = 20, col = "red")
title(main = "수익률%", sub = NULL, xlab = NULL, ylab = NULL,
      line = NA, outer = FALSE)



2014년 2월 23일 일요일

최소분산포트폴리오

# Copyright 2013 LBB. All rights reserved.
# Author: Gray Fox
# Description: PortOpt-3Fund.R
#              Optimize 3-Fund Portfolio
# Date: 07-March-2013

## source and library statements
library(tseries)
getwd()
setwd('c:/rdata')
## CHANGE THE PATH TO YOUR LOCAL DIRECTORY
source("portfolio_noshorts.r")
options(digits=4, width=70)

## constants
shorts=FALSE
library(tseries)
library(quadprog)
getwd()
setwd('c:/rdata')

###here kospi data
dat <- read.csv('port.csv', header=TRUE)
#dat$Date <- as.Date(dat$Date, "%Y-%m-%d")

odat<-dat[c(1:nrow(dat)),]

attach(odat)

x<-odat[order(Date),]

#x<-odat

price1 <- as.numeric(x$로만손)
price2 <- as.numeric(x$KB금융)
price3 <- as.numeric(x$동서)
#price4 <- as.numeric(x$동서)

ret1 <- 0
ret2 <- 0
ret3 <- 0
#ret4 <- 0

for (i in 1:length(price1)) {
ret1[i] <- (price1[i]-price1[1])/price1[1]
ret2[i] <- (price2[i]-price2[1])/price2[1]
ret3[i] <- (price3[i]-price3[1])/price3[1]
#ret4[i] <- (price3[i]-price3[1])/price3[1]

}

Returns.z <- cbind(ret1, ret2, ret3)


## constants
shorts=FALSE
r.free.a <- 0.025  # T-bill Rate
r.free <- r.free.a/12
start_date <- "2013-11-13"
end_date <- "2014-02-21"


#Prices.z <- merge(price1, price2, price3)
colnames(Returns.z) = c("로만손", "KB금융", "동서")

# Plot 1. Monthly cc returns vs time
plot(Returns.z, plot.type="single", lty=1:3, col=1:3, lwd=2)
legend(x="bottomleft", legend=colnames(Returns.z), lty=1:3, col=1:3, lwd=2)
abline(h=0)
title("Monthly cc returns")

## Plot 2. Pairwise scatterplot
#pairs(coredata(Returns.z), col="blue", pch=16)

## Compute estimates of CER model parameters
muhat.vals <- apply(Returns.z, 2, mean)
sigma2hat.vals <- apply(Returns.z, 2, var)
sigmahat.vals <- apply(Returns.z, 2, sd)
cov.mat <- var(Returns.z)
cor.mat <- cor(Returns.z)


###############################################################################
## GMVP
gmin.port <- globalMin.portfolio(muhat.vals, cov.mat, shorts=FALSE)
summary(gmin.port)
gmin.SR = (12*gmin.port$er - r.free.a) / (sqrt(12)*gmin.port$sd)
print("GMVP Sharpe Ratio"); print(gmin.SR)
## Plot 3. GMVP weights
plot(gmin.port, col="blue")

## Tangency portfolio
tan.port <- tangency.portfolio(muhat.vals, cov.mat, risk.free=r.free, shorts=shorts)
summary(tan.port)
tp.SR.m = (tan.port$er - r.free) / (tan.port$sd)
tp.SR = (12*tan.port$er - r.free.a) / (sqrt(12)*tan.port$sd)
print("TP Sharpe Ratio"); print(tp.SR)
## Plot 4. Tangency portfolio weights
plot(tan.port, col="blue")

## Efficient Frontier
ef <- efficient.frontier(muhat.vals, cov.mat, nport=21, alpha.min=-10, alpha.max=10, shorts=shorts)

## Plot 6. Efficient Frontier allowing short sales
plot(ef, plot.assets=T, col="blue", pch=16, cex=1)
points(tan.port$sd, tan.port$er, col="green", pch=16, cex=1)
text(tan.port$sd, tan.port$er, labels="TP", pos=2)
abline(a=r.free, b=tp.SR.m, col="green", lwd=2)  ## CAL

print("Done")


2014년 2월 7일 금요일

git 사용법

git bash를 연다

사용자 이름 및 이메일주소 등록

git --global username

git --global email

// git 초기화

git init

// 저장소에 파일 추가



git add *.c
git add README

2014년 2월 2일 일요일

자바스크립트 div 노드 추가

$(document).ready(function(){
var container = document.getElementById('container');
var outerdiv = document.createElement('div');
container.appendChild(outerdiv);

for (var i = 0; i < 10; i++) {
  var innerdiv = document.createElement('div');
   
  innerdiv.innerHTML = "this is";
  innerdiv.appendChild(document.createTextNode(i));
 
  outerdiv.appendChild(innerdiv);

}
  
       
  } 
  );


------------------


<body>
  <div id="container">
    </div>
 
</body>

2014년 1월 24일 금요일

css table

.td1_th {border-width:1px;border-color:#e1e1e1;border-style:solid;background-color:#ffffff;}

2014년 1월 23일 목요일

javascript

var div = document.getElementById("container");
var rect = div.getBoundingClientRect();

document.getElementById("banner").innerHTML = ("<div style='position:absolute;top: "+rect.left+"px'> <img src='http://hmwatch.woobi.co.kr/sci/images/icm.png' />");

2014년 1월 12일 일요일

ar1 of kospi

with prediction
library(quantmod)
library(fGarch)

URL <- "http://ichart.finance.yahoo.com/table.csv?s=^KS11"
dat <- read.csv(URL)
dat$Date <- as.Date(dat$Date, "%Y-%m-%d")

odat<-dat[c(1:100),]

attach(odat)

x<-odat[order(Date),]

#kospiGarch <- garchFit(~arma(1, 2) + garch(1, 1), data=as.ts(x$Close))

fit <- arima(diff(log(x$Close)), order=c(1,0,0))

#fore <- predict(fit, n.ahead=10, doplot=F)

err <- rnorm(20, 0, .002)

sim <- diff(log(abs(x$Close)))[99]

for (t in 2:20) {
    sim[t] <- fit$coef[2]+ fit$coef[1]*sim[t-1] + err[t]
}

dev.new()

par(mfrow=c(3,1))
par(mar=c(3,3,1,2))

plot(x$Close, type='l', xlim=c(0, 120), xaxt='n',
    panel.first=grid(col = "gray", lty = "dotted"), pch=20)
t <- c(101:120)
points(x$Close, pch = 20, col = "red")

ye <- x$Close[100]
for (j in 2:20) {
ye[j] <- exp(sim[j-1])*ye[j-1]
}

ye
points(t, ye, col='red', pch=20, type='b')


##########################################################

library(forecast)

fit <- auto.arima(x$Close)
plot(forecast(fit, h=20))

2014년 1월 5일 일요일

arch(1) model

require(tseries)

URL <- "http://ichart.finance.yahoo.com/table.csv?s=^KS11"
dat <- read.csv(URL)
dat$Date <- as.Date(dat$Date, "%Y-%m-%d")

odat<-dat[c(1:100),]

N<-99

attach(odat)

x<-odat[order(Date),]


price <- x[[2]]
ret <- 0

for (i in 1:length(price)) {
ret[i] <- (price[i]-price[1])/price[1]
}

par(mfrow=c(3,1))
par(mar=c(3,3,1,2))
x=c(1:length(ret))
plot(price, type='l', xaxt='n')

y<-diff(price)
plot(x = y, ylab = expression(y[t]), xlab = "t", type = "l", col = "red", 
     panel.first=grid(col = "gray", lty = "dotted"))
  points(x = y, pch = 20, col = "blue")
 

x.arch <- garch(ret-mean(ret), order = c(0,1), trace=TRUE)  # Fit ARCH(1)

#summary(x.arch)                     # Diagnostic tests
vol <- x.arch$fitted.values[,1]

plot(x, ret, type='l', col='lightgray', ylim=c(-0.01,0.08), xaxt='n')
points(x=x, y=vol, col='red', type='l')

abline(h=0, col="lightgray")


파이를 무한자리수까지 계산하는 파이썬 코드

교양수학책을 읽다보면 파이나 e 같은 무한소수의 자리수를 10조자리까지 계산했다느니 뭐니 하는 얘기를 자주 접하게 된다. 그래서 지금 펜티엄코어2로 돌리면 시간이 어느 정도 걸리나 한번 테스트해보려고 했다.

그런데 막상 c로 알고리즘을 만드려니까 자리수 계산하려면 배열에 동적메모리 할당해서 넣어야 하는데 막상 구현하려니 머리가 멍해짐. 웹페이지 검색해보니 코드와 함께 우리말로 설명이 된 웹페이지는 찾을 수가 없었다.

구글에서 infinite precision pi로 검색하다가 c#으로 된 페이지를 겨우 찾았는데 읽다가 졸려서 아침에 보려고 나뒀는데 실수로 검색창을 닫아버려서 다시 검색하다가 발견한 페이지.


http://rosettacode.org/wiki/Pi

c로 하려니까 gmp.h 헤더파일 인클루드하라고 에러 나와서 귀찾아서 파이선으로 돌림.





파이선 코드
 ------------
def calcPi():
    q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
    while True:
        if 4*q+r-t < n*t:
            yield n
            nr = 10*(r-n*t)
            n  = ((10*(3*q+r))//t)-10*n
            q  *= 10
            r  = nr
        else:
            nr = (2*q+r)*l
            nn = (q*(7*k)+2+(r*l))//(t*l)
            q  *= k
            t  *= l
            l  += 2
            k += 1
            n  = nn
            r  = nr

import sys
pi_digits = calcPi()
i = 0
for d in pi_digits:
    sys.stdout.write(str(d))
    i += 1
    if i == 40: print(""); i = 0