레이블이 프로그래밍인 게시물을 표시합니다. 모든 게시물 표시
레이블이 프로그래밍인 게시물을 표시합니다. 모든 게시물 표시

2014년 1월 28일 화요일

Python - A benefit of the module "Readability"

Main purpose : Comparison between two modules "Readability" and "BeautifulSoup"

Source = Chris Reeves'

I am going to introduce a new module "Readability" . Mainly, it is used to pull out the contents in HTML body. Some people may insist that users might be able to do with BeautifulSoup. So, let's compare those two.

import nltk
import urllib
import readability
from bs4 import BeautifulSoup
from readability.readability import Document
import mechanize

url = "http://www.nytimes.com/2014/01/27/us/politics/2014-elections-likely-to-keep-capitals-split.html?ref=us"

br = mechanize.Browser()
htmltext = br.open(url).read()

soup = BeautifulSoup(htmltext)
for tag in soup.find_all('p',attrs = {"itemprop":"articleBody"}):
        print tag.contents[0]

This is the code reading up HTML body contents using BeatifulSoup. You might also know, this code would bring only the half of (above the big pictures on articles) Body contents. When a bot met some Java Script, a bot commanded by BeautifulSoup might think the article is ended, so the program is terminated. It is why I recommend to use "readability" to pull out the HTML Body contents.


import urllib
import readability
from bs4 import BeautifulSoup
from readability.readability import Document
import mechanize

url = "http://www.nytimes.com/2014/01/27/us/politics/2014-elections-likely-to-keep-capitals-split.html?ref=us"

br = mechanize.Browser()
htmltext = br.open(url).read()

# The bestway to access HTML file is to use mechanize because it can avoid.
br = mechanize.Browser()
br.set_handle_robots(False)
br.addheaders = [('User-agent','Firefox')] # It says that I am not a robot, but a Firefox web browser

html = br.open(url).read()

readable_article = Document(html).summary()
readable_title = Document(html).short_title()
soup = BeautifulSoup(readable_article)

final_article = soup.text
print final_article
print readable_title

This is the code using readability, and there are a few things to remember.

br.set_handle_robots(False)
br.addheaders = [('User-agent','Firefox')] # It says that I am not a robot, but a Firefox web browser
# Avoid that you are not a robot 

Python Tutorial Part 3 - Keyword Extractor

Main Purpose : Build up own a keyword scrapper

Source : Chris Reeves' Python turorial

In this tutorial, we are going to learn how to build up keyword extractor.



Main,py

import gethtml
import articletext

url = "http://www.nytimes.com/2014/01/27/sports/committing-to-play-for-a-college-then-starting-9th-grade.html?hp"
# we will extract the keyword from this news article

article = gethtml.getHtmlText(url)
print articletext.getkeywords(article)                                         


gethtml.py

import mechanize

def getHtmlText(url):
        br = mechanize.Browser()
        htmltext = br.open(url).read()
        return htmltext

def getHtmlFile(url):
        br = mechanize.Browser()
        htmlfile = br.open(url)
        return htmlfile                                


articletext.py

from bs4 import BeautifulSoup
import gethtml

def getArticleText(webtext):
        articletext = ""
        soup = BeautifulSoup(webtext)
        for tag in soup.find_all('p',attrs = {"itemprop":"articleBody"}):
                articletext += tag.contents[0]
        return articletext

def getkeywords(articletext):
        common = open("common.txt").read().split("\n")
        word_dict = dict()
        word_list = articletext.lower().split()
        for word in word_list:
                if word not in common and word.isalnum():
                        if word not in word_dict:
                                word_dict[word] = 1
                        if word in word_dict:
                                word_dict[word] += 1
        top_words = sorted(word_dict.items(), key = lambda(k,v):(v,k),reverse = True)[0:25]
        top25 = []
        for w in top_words:
                top25.append(w[0])
        return top25

The most important key file is "articletext.py". The algorithm of this file group is followed as

  1. Call up "getHtmlText" in gethtml.py
  2. In gethtml.py, read up the HTML text in getHtmlText and return htmltext. So, the variable 'article' in Main.py now contains the HTML text.
  3. Call up "articlekeyword" function in articletext.py
  4. articlekeyword function in articletext.py takes a parameter as an "articletext". To separate the article into words list, the parameter "articletext" must be a list.
    1. So, we create a new function getArticleText taking a parameter as a HTML text, which we delievered in Main.py. The parameter was now moved to the new function getArticleText.
    2. for tag in soup.find_all('p',attrs = {"itemprops":"articleBody"} # You can check through Chrome
      
      Check only the body of text by words in such a method. Return such a word list
  5. We are going to find the words occurred in highest frequency. To avoid that words such as "the","a" are picked, we downloaded "the most used words top 500", and avoided words in this list.
  6. Construct the dictionary. Using dictionary, we can access the data not by its index, but by its "keywords". word_dict["keyword"] = "input-value" is the classical method to construct the dictionary. In this codes, "word_dict" is the dictionary contains the frequency of words in the article.
  7. Using lambda function, we sorted in order of high frequency.
    lambda "parameter" : "expressin"
    lambda x,y : x+y
    map(function, list)
    map(lambda x: x ** 2, range(5)) # [0, 1, 4, 9, 16]  
    
    "Sorted" is a function used for preserving the original target. Thus, you can sort any forms (dic, list, tuple) with sorted method.

Python Tutorial Part 2 - Page Scraper

Main Purpose : Build up own Web scraper

Source : Chris Reeves' Python turorial

From this post, we will use some useful modules specified to deal with HTML file, such as BeautifulSoup or Mechanize. This is also from Chris Reeves' Python turorial


Part 1. Page explorer - Beautiful Soup and Mechanize

import urllib
import urlparse
import mechanize
from bs4 import BeautifulSoup

url = raw_input("Input URL you want to scrape: ")
print urlparse.urlparse(url).hostname
1. br = mechanize.Browser()

2. urls = [url]
visited = [url]

2. while len(urls) > 0:
3.      try:
1.             br.open(urls[0])
2.             urls.pop(0)
4.             for link in br.links():
                        newurl = urlparse.urljoin(link.base_url,link.url)
                        b1 = urlparse.urlparse(newurl).hostname
                        b2 = urlparse.urlparse(newurl).path
                        newurl =  "http://"+b1+b2

5.                     if newurl not in visited and urlparse.urlparse(url).hostname in newurl:
                                visited.append(newurl)
                                urls.append(newurl)
                                print newurl
3.      except:
                urls.pop(0)

This is the classic page explorer program, and here the algorithm is.

  1. Open up one stack and one box containing historical records of spider's behavior
  2. Start the while roop with a condition of empty stack. (Starting with a base URL in the stack, we will find every sub-URL of base URL and put in what we found into the stack. Every time the spider visits a certain page, that page is removed in the stack. The workflow follows the ㄹ method, which works in horizontal first.
  3. Once the program read the HTML, then delete it by using urls.pop(0)
  4. It is also one of classical method to find all sub URL.
    "http://" + urlparse.urlparse(url).hostname + urlparse.urlpasre(url).path
    
  5. If such an URL is not in visited box and hostname is in our new subURL, keep working.

Here are some important codes that we have to remember.

1.

br = mechanize.Browser() ## br is commanded to work in similar way as a Web Browser. 
br.open(url) ## open an web site and bring HTML as a file 

2.

while len(urls) > 0: 
       urls = [url]
       # After read 
       urls.pop()

3. Try- Except. If some error occurs, then follow the command written after except. If the website we are crawling has some error-hyper link, we can deal with that as an error, and just keep going on to the next task.

4.

for link in br.links () ## br.links() examines every sub-link to find subURL. A 'link' is the key to move in br.links()
     link.base_url  ## link.base_url is the base URL. It stands for the horizontal position the robot is exploring now. 
     link.url ## link.url is to find every sub-URL. 
     newurl = urlparse.urljoin(link.base_url,link.url)
     b1 = urlparse.urlparse(newurl).hostname
     b2 = urlparse.urlparse(newurl).path ## it is more clever method to find subURL without JavaScript Trap. 
     newurl = "http://"+b1+b2

5.

if newurl not in visited and urlparse.urlparse(url).hostname in newurl: ## 1) Not in historical data, 2) same tree
     visited.append(newurl)
     urls.append(newurl)
     print newurl



Part 2. Use BeautifulSoup

# Another elements of url not with / this form 
import urllib
from bs4 import BeautifulSoup
import urlparse

url = "http://nytimes.com"
htmltext = urllib.urlopen(url)
soup = BeautifulSoup(htmltext)

1. for tag in soup.find_all('a',href = True):
        raw = tag['href']
2.        b1 = urlparse.urlparse(tag['href']).hostname
        b2 = urlparse.urlparse(tag['href']).path # * 
        print str(b1) + str(b2)

#* Spider trap:
        # We don't use the method used in last tutorial
        # because sometimes WEB gives certain ID to users and Spider web might be confused it as all different website
        # That is why it is good to use urlparse.path

1.

 
for tag in soup.find_all('a',href = True)

It finds every sources containing "a href".

2.

 
urlparse.urlparse(tag['href'])
The result of 1. is not a string. With this method, we can convert the result into the string.



Part 3. Find the smartest way to make sub-url

import urllib
from bs4 import BeautifulSoup
import urlparse
import mechanize
# Simulate the browser

url  = "http://sparkbrowser.com"
count = 0

# The smartest method ==> No hashtop such tha sparkbrowser.com#top 

br = mechanize.Browser()
#Just copy how the Browser acts 
br.open(url)
for link in br.links():
	newurl = urlparse.urljoin(link.base_url,link.url)
	b1 = urlparse.urlparse(newurl).path
	b2 = urlparse.urlparse(newurl).hostname
	print "http://"+b2+b1
	count += 1
print count
		# IN this way, we don't include Javascript such as #top 
		# Best way



# Method_3. NOT WORK Use urlparse.urlparse(tag['href']).path or hostname
'''
htmlfile = urllib.urlopen(url)
soup = BeautifulSoup(htmlfile)

for tag in soup.find_all('a',href=True):
	b1 = urlparse.urlparse(tag['href']).hostname
	b2 = urlparse.urlparse(tag['href']).path
	print "http://"+str(b1)+str(b2)
'''

# Method_1. Use BeautifulSoup 
'''
htmlfile = urllib.urlopen(url)
soup = BeautifulSoup(htmlfile)

for tag in soup.find_all('a',href=True):
	print tag['href']
'''


# Method_2. Use mechanize 
'''
br = mechanize.Browser()
br.open(url)

for link in br.links():
	newurl = urlparse.urljoin(link.base_url,link.url)
	print newurl
	count += 1
print count
'''

The best way is already introduced in Part 1. The second best way is to use a BeautifulSoup, but it cannot filter some Java script trap.

Python Tutorial Part 1 - Program scrapping Stock Price

Main Purpose : Build up own the stock price scraper

Source : Chris Reeves' Python turorial

Recently, I found a good tutorial to have interest in Python: Chris Reeves' Python turorial I want to abridge what I have learned from this tutorial. The main purpose of this tutorial is to build my own Web Spider
(Web bot, Web crawler, or whatever so called)

First 10 of tutorials deal with constructing up a program scrapping stock prices of companies registered in NASDAQ list. In this post (part 1), I am going to review the Python codes for study.

Part 1. Stock Price - A single company, say, Apple

This is the code for scrapping the last price of APPLE from Yahoo Finance - Apple
 
1. import urllib
    import re

htmlfile = urllib.urlopen("http://finance.yahoo.com/q?s=AAPL&ql=1")
2. htmltext = htmlfile.read()

regex = '(.+?)'
pattern = re.compile(regex)

3. price = re.findall(pattern,htmltext)

print price   

A main algorithm for this code is to read HTML file, and scrape the HTML source standing up the last price.

1. Import the module "urllib" and "re". A "urllib" is a module to read up HTML, and "re" module is a module to use Regular Expression, which is useful to deal with character strings.
2.

 
htmlfile = urllib.urlopen(url)
htmltext = urllib.urlopen(url).read()
 
is to read a HTML of the website. In this code, we read the HTML as a text, not a file, to use a certain keyword with 'Re' module (It is useful to read HTML as a file to use BeautifulSoup method, which we will deal with later)
3. This is the useful link for learning a Regular Expression (it is written in Korean, because I am a Korean. You can find some well written tutorials easily.)
 '(.+?)' 
'()', in ReGex, is to used in grouping ReGex. For example, Set (Value) is matched with "Set" and "Set Value". A dot (.) is matched with anything, and "+" means "more than one", equivalently 'not empty'. In totally, (.+?) will be matched any string up to .
pattern = re.compile(regex)
find = re.findall(target, htmltext)
A "re.compile(regex)" compiles and "re.findall(target,htmltext)" convert the regex language into the word we can understand.


Part 2. Stock Price - Multiple companies

This is the code for scrapping every code registered in NASDAQ. Preliminarily, we have to download the list of the code of companies listed in NASDAQ. You can easily download it by googling.

import urllib
import re

symbolfile = open("stocklist.txt")
1. symbolslist = symbolfile.read()
2. uppernewsymbolslist = symbolslist.split("\n")
3. newsymbolslist = [x.lower() for x in uppernewsymbolslist]
i = 0

while i (.+?)'
        pattern = re.compile(regex)
        price = re.findall(pattern,htmltext)
        print "the price of",uppernewsymbolslist[i],"is", price
        i += 1
1.
file = open("directory of file/filename")
file_read_text = file.read()
This is how we let Python to read the file.
2. A 'split()' let python to save the text into the list.
3.
 newsymbolslist = [x.lower() for x in uppernewsymbolslist]
It is pretty interesting that this command is actually working. It is why Python is such a strong language. It resembles how we talk. It does mean that "Lower x, which is an element of the list "uppernewsymbolist."



Part 3. Quicker Method to scrape the price of multiple companies

import urllib
import re
import json

NASfile = open("stocklist.txt")
NASread = NASfile.read()
NASlist = NASread.split("\n")

i = 0
while i < len(NASlist):
        url = "http://www.bloomberg.com/markets/watchlist/recent-ticker/"+NASlist[i]+":US"
        htmltext = urllib.urlopen(url)

1.         data = json.load(htmltext) #it takes only a file, it must occur an error!  
# It is file distinguished by a Hash Map, which will work as a key

        print data["disp_name"],":", data["last_price"] #works like an array, but it works with a key, not an index.
        i+= 1

You can find a Json file easily by separating any websites by "developer tool" in Chrome. In most cases, it is likely that a Json file include the data in the website. If you scrape more than 200 companies' stock price with a method in part 2, it might take more than 10 minutes to complete. If you would scrape it through "Bloomberg", which contains lots of heavy flash files, it might go worse. However,
if you could just scrape the price through Json files, just simple text files, it might take a few seconds to complete a task. This is the code how we do in such a way.

1. The biggest benefit that 'Json' module has is that it contains data in the form of list. The distinguished point from list is that you can call data not by an index, but by a keyword.
In this code, we defined a json file by the variable 'data'. You can call json file by calling its key in a form of 'data["key"]'.
It is important to keep in mind that the object of json function is a file, not a text.



Part 4. Printing out a result

import urllib
import json

#Open up the stocklist.txt
NASfile = open("stocklist.txt")
NASload = NASfile.read()
NASlist = NASload.split("\n")

for symbol in NASlist:
        1. myfile = open("/home/hansjung/Python/stockprogram/"+symbol+".txt","w+")
        myfile.close()

        htmltext = urllib.urlopen("http://www.bloomberg.com/markets/chart/data/1D/"+symbol+":US")
        data = json.load(htmltext) #When we use Json, we don't use .read()
        datapoints = data["data_values"]

        2. myfile = open("/home/hansjung/Python/stockprogram/"+symbol+".txt","a")

        for point in datapoints:
        3.        myfile.write(str(symbol+","+str(point[0])+","+str(point[1])))
        4.        myfile.close()

The basic algorithm for printing in a file (writing up in a file) is in following.

  1. (Open) Create a file printed your result (Close)
  2. (Open) Append your result into the file
  3. Write your result (Close)



Part 5. Quicker method - Using Multi-thread

1. from threading import Thread
import urllib
import re

2. def th(ur):
        base = "http://finance.yahoo.com/q?s="+ur
        regex = '(.+?)'
        pattern = re.compile(regex)
        htmltext = urllib.urlopen(base).read()
        results = re.findall(pattern,htmltext)
        print "the price of",str(ur),"is",str(results[0])

stocklist = open("stocklist.txt").read()
stocklist = stocklist.split("\n")
print stocklist

3. threadlist = []

4. for u in stocklist:
        t = Thread(target=th, args=(u,))
        t.start()
        threadlist.append(t)

5. for b in threadlist :
        b.join()

A multi-thread is able to your program to work in multi-tasking. Basically, computer programs are built up in following a certain sequence. In contrast, a computer program can work in multi-tasking by a multi-thread method. The basic algorithm for this computer program is following.

  1. Define the task to be processed in multi-tasking as a function
  2. Open the list 'threadlist' that stores up results
  3. Point your function in number 1 and setting up an parameter, and call up to start a task.
  4. Store up results into the list built in 2.

Actually, it is difficult to use this method, because almost all programmers are used to programming in sequence based. If we are able to use multi-thread properly, our work might be way more efficient.

1. Call the module. From A import B means that, from A folder, import B module file.
2. Define your task that you want to deal with in multi-thread.
3. Open up 'threadlist' (I don't know why we need this, but it is must be done)
4. Define a multi-thread and start it, then save up the result into the threadlist. 5. Prettify your result.

2014년 1월 23일 목요일

Interesting tutorials about how to build the web crawler by Python

www.youtube.com/creeveshft
I found an impressive video list recently. It gives you lectures about how to build programs through Python. Unlike to other tutorials, this tutorials are really helpful because
  • It gives a lecture with an video
  • Short so to be able to keep concentration
  • Useful - Unlike other tutorials starting from "Hello, world", it gives you how to construct a "real" program applicable in real life.

Statistical Data Mining - FInd the Mr / Miss Right

Amy Webb, the speaker on that video, gave a speech about how she met her husband through online dating.

How she had done is similar to the way that a mathematician used. This is a link about how a mathematician found her girl friend. Link
The fabulous a data mining can give to the data miner is that once you have desire to know or find out something, you can gather, process and modify data to achieve your goal through data mining.

2014년 1월 18일 토요일

What is 'R'?

2014년 1월~2월, 학부 졸업과 석사 입학의 징검다리에 있는 입장이다. 이 시간동안 어차피 공부도 잘 되지 않고, 무엇을 배워두면 참 좋을까 고민하던 차에, 번뜩 생각난 아이디어. "R을 배워보자!"

2013년 방학 등 시간이 날때마다 틈틈히 C++, Python, MATLAB 및 프로그래밍 언어는 아니지만 HTML, LaTex를 익혀온 까닭에, 프로그래밍은 이제 자신이 있다. 이 새로운 언어가 나의 연구에 얼마만큼 편의를 제공해 줄 수 있을지 기대가 된다.

이 언어에 어떻게 접근해야 할까? 내가 구한 몇 가지 튜토리얼들의 목차를 정리하면 다음과 같다. (R 다운로드, 설치 등 당연한 정보들은 건너뛴다.)

R cookbook

  1. 변수 설정해보기
    • 변수설정하기 (vector 등)
    • 함수정의하기
  2. R에서 제공하는 기본기능들
    • Command history 보기
    • Script 돌려보기
  3. 입출력
    • 직접 데이터 입력하기
    • 입력된 데이터 반올림하기
    • 파일로 직접 출력해보기
    • CSV 파일 읽어오기
    • HTML 등 웹페이지에서 직접 데이터 긁어오기
  4. 데이터구조
    • 데이터를 벡터로 바꾸기
    • Matrix 다루기
    • String data 다루기
  5. 확률 & 통계
    • Combination, Permutation 계산
    • Random generating
    • Calc. Prob.
    • Quantile
    • Quantile
    • 회귀분석 및 ANOVA
    • 시계열분석


R을 이용한 통계프로그래밍

  1. 기본 입출력 명령어
  2. R object
    1. 데이터의 종류
    2. 벡터
    3. array & matrix
    4. list
    5. data frame - 우리가 생각하는 표
  3. 데이터 읽어오기
  4. R 프로그래밍
  5. R과 확률통계

2014년 1월 15일 수요일

Python 을 배우기 시작했습니다.

2014.01.15 일부로 Python 을 배우기 시작했다. 느낀 점을 정리해본다.

처음배우는 언어 및 학문에 진입하는 방법

역시 가장 좋은 법은 "Jumping into" 이다. 가장 쉬운 예로 영어를 배우는 과정을 생각해보면 된다. 수능을 보기까지 10년간 매일 꾸준히 문법, reading 공부하는 것보다 차라리 미국을 가는 등의 방식으로 그 언어에 뛰어드는 것이 가장 효과적으로 배우는 방식이다.

Python도 마찬가지였다. 어제 Tutorial을 다운받아서 이것만 읽어보려니까 재미가 없었다. 생각해보니 그랬다. C++을 처음 배울 때도, 프로그래밍은 하지도 않고 TCPL만 읽다가 때려친 적이 한 두번이 아니었다. 프로그래머 친구의 도움을 받아서, 매일 매일 알고리즘 문제를 풀자, C++에도 재미가 붙었고, 실력도 금방 늘었다.

Python을 배울 때도 그렇게 해 보았다. Tutorial 필요하다 싶은 부분까지 해보고, 내가 풀어왔던 수많은 알고리즘 문제를 Python 으로 Conversing 해보았더니, 정말 빠르게 언어에 친숙해지는 느낌이 들었다. Python 언어를 설치하고 딱 하루 지났을 뿐인데, 벌써 Try-cat.ch 문제 easy 부분은 거의 다 풀었다. 이렇게 언어에 익숙해지는거구나 싶다. 이제 자신감이 붙는다.

Python vs C++

솔직히 Python을 배워보니 '이 언어는 진리구나' 싶다. 배우기가 정말로 쉽다. 코드는 내가 C++ 로 짰던 코드의 1/4 분량밖에 나오지 않는다. 가독성도 훌륭하다.

단, 프로그래밍 공부를 C++로 먼저 시작한 것은 참 다행이구나 싶다. Python은 '학습용 C++' 처럼 느껴지기 때문에, 쉽게 배운 측면도 있을 것이다. 이 언어는 웹언어, Data analysis 까지 확장할 수 있단다. 더 배우고 싶어서 흥분된다.

2014년 1월 12일 일요일

금융공학도를 위한 프로그래밍 언어 (주관)

이 글은 저자의 개인적인 생각이 섞여있습니다. 저자는 프로그래밍 초짜 중에 초짜입니다. 감안하고 읽으시기 바랍니다.

글을 쓰기에 앞서, 저자의 base 언어는 C++ 이다. WIlmott forum 에서 말하기를, 금융공학에서 가장 많이 쓰이는 언어는 C++이라고 하기에, C++을 먼저 배운 것이다. (1학년 때, JAVA로 프로그래밍을 처음 배웠지만, 모조리 까먹었다.)
다음은, 업계에서 쓰이는 Top Five 언어이다. Top Five 언어

링크된 홈페이지에서 소개하는 언어는 많이 쓰는 순서대로 Python, C/C++,Java, Javascript, Ruby 이다. 저자는, 이 언어들 중 일부와, 금융공학을 하는데 필요한 프로그래밍 언어, 혹은 프로그래밍 패키지를 섞어 중요도 별로 소개한다. (저자 주관) 공대 대학원에서도 똑같은 순위가 적용된다.

MATLAB

쓰임새
공대 대학원이든, 금융공학 분야에 속해있는 사람이든 가장 많이 쓰는 언어이다. 행렬을 활용하여 모든 계산을 처리하기 때문에, 연산이 상당히 빠르고 편리하다. 또한, 원하는 프로그램을 아주 쉽게 짤 수 있기 때문에, 모델링에도 매우 편리한 이점이 있다.
장점
한 마디로 이야기해서, 현재 인류가 "계산" 이라고 부르는 모든 행위를 다 할 수 있다. 그렇기 때문에, 시뮬레이션에 가장 특화되어 있다.
단점
느리다.... 다양한 기능을 패키지로 포함하기 때문이지만 그럼에도 불구하고 엄청나게 느리다. 컴퓨터에 성능이 좋으면 상관없지만, 넷북을 쓰게 되면 실행하는데만 2분이 넘게 걸린다.
그리고 유료다. 보통 유료도 아니고, 엄청, 무지막지하게 비싼 유료다. 학교나 큰 회사에 속해 있다면 라이센스를 취득하고 있겠지만, 그것이 아니라면 그림의 떡에 불과하다. 단, MATLAB의 기본만 구현해 놓은 Octave 라는 프로그램이 있는데 이는 무료이며, 속도도 괜찮게 나온다. 다만, MATLAB의 고급기능은 구현이 안 되어있다.

Python

쓰임새
공학 (컴공 제외)에서는 주로 간단한 알고리즘을 테스트하기 위한 용도로 쓰인다. 라이브러리가 막강하고, 코드가 짧고 간결하게 나오기 떄문에 (C++에서 20줄 걸릴 것이 한 줄), 많이 애용된다.
장점
  1. 쉽다. 아주 쉽기 때문에, 많은 대학교에서 입문용 프로그래밍 언어로 쓰이고 있다. 코드가 아주 간결하게 나오는 특징이 있어서, "가장 짧은 코드 짜기" 대회가 있으면 언제나 파이썬이 1등이다.
  2. 기능이 막강하다. 라이브러리를 활용하여, C/C++과 Java를 데려올 수 있다. (커버가 된다는 얘기)
  3. 속도에서 밀리지 않는다. C++보다는 느리지만, 그래도 우리가 감식할 수 있는 수준은 아니다. MATLAB 보다는 월등히 빠르다.

단점
없다. 금융공학에서는 현재 C++ 이 가장 많은 인기를 독차지하고 있지만, 이는 기존의 언어가 가지는 Market share 효과인 것으로 보인다. 즉, 빠른 시일내에 Python으로 대체될 전망.

C/C++

쓰임새
거의 모든 프로그래밍 언어의 어머니. 절차지향언어, 객체지향언어의 시발점. 파이썬을 빠른 설계가 가능한 스위스 나이프로 비유한다면, C++은 그냥 공구상자 그 자체.
금융공학 외에 게임 프로그래밍, 시스템 프로그래밍에 많이 쓰인다. 한 마디로, 가장 Technical 한 부분에 쓰인다는 이야기.
C++ 대신에 Java를 배워도 아주 무방해보인다.
장점
    매우 빠르다. 프로그래밍 언어에서는 Java를 제외하고, 따라갈 수가 없을 정도로 빠르다. Python 에 비해 3배 정도 빠르다. (그래봤자, 우리가 느낄 수 있는 수준은 아니다.)
    프로그래밍을 하기 위해서는 Java 나 C++ 중에 하나는 배워야 할 것이다. 거의 모든 언어가 C++ 을 기초로 하기 때문에, 꼭 배워야 한다.
    금융공학에서는 가장 Dominant 한 언어이다. Quantlib 이라는 라이브러리가 개발되어 있어서, 상당히 편리하게 모형화를 할 수 있다.

단점
조오금 어렵다. 많은 부분에서 파이썬으로 대체되고 있는 실정이다.

R

쓰임새
통계 무료패키지. SPSS, SAS, Minitab 만큼이나 강력하면서도 거의 유일한 통계패키지이다.
장점
  • MATLAB 은 모델링에 특화된 툴이라면, R은 통계계산에 특화된 툴이다. 더 빠르고 안정적으로 계산이 가능하다. 금융공학에서 쓰이는 거의 모든 수학은 통계인 것을 감안하면, 그냥 배워야 한다.
  • 배우기 쉬움에도 불구하고, 은근히 전문가를 찾기가 어려운 언어다. 따라서, 잘 다룰 수 있으면 어딜가든 환영받는다.
  • 공짜이고, 아주 빠르다. C++ 을 기반으로 작동하는 듯.

Javasctipt

쓰임새 & 설명
HTML, CSS를 선수로 배운 후에, 배워야 하는 언어이다. HTML을 기반으로 작동하며, 오늘날 거의 모든 홈페이지가 자바스크립트 기반으로 쓰여있다. 웹언어에서는 독보적인 위치의 언어.

2013년 12월 2일 월요일

구글 블로거에 LaTex 사용하기!

레이아웃 - 템플릿에 보면 Html 코드가 있을 것입니다. 
여기에 <Head> ~~ </Head>  사이에 다음의 스크립트를 복사해 붙여넣으시면 됩니다.

<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js">
MathJax.Hub.Config({
extensions: ["tex2jax.js","TeX/AMSmath.js","TeX/AMSsymbols.js"],
jax: ["input/TeX", "output/HTML-CSS"],
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
},
"HTML-CSS": { availableFonts: ["TeX"] }
});
</script>

드디어 수식을 마음껏 편집할 수 있게 되었습니다!