Wednesday, May 11, 2011

R: layout to arrange plots on a page

In R, use layout to specify different arrangement of plots on a page.

注意比较下面各个图的比例。

比如,第一行三个图,第二行四个图:

layout(matrix(c(1,1,1,2,2,2,3,3,4,4,5,5,6,6,7,7),2,8,byrow=T))
for (i in 1:7){
plot(rnorm(100))
}

1,1,1,2,2,2,3,3 表示上面一行3张图,4,4,5,5,6,6,7,7表示下面一行4张图。几个数字的个数表示图尺寸的比例。 上面第一个第二个比第三个图大,上面第三个跟下面4个一样大




layout(matrix(c(1,2,3,0,4,5,6,7),2,4,byrow=T))
for (i in 1:7){
plot(rnorm(100))
}

layout(matrix(c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7),2,12,byrow=T))

for (i in 1:7){
plot(rnorm(100))
}


layout(matrix(c(1,1,1,1,1,1,2,2,2,3,3,3,4,4,5,5,6,6),3,6,byrow=T))

for (i in 1:6){
plot(rnorm(100))
}

SUM within subgroup

/* Within the subgroup of ID, if seq is the same, then calculate the sum of unit for the same seq;*/

/* Else, if seq is different then keep the value of unit */

options formdlim='-';

data test;

input ID seq unit;

cards;

100 1 10

100 2 10

101 1 10

101 1 20

103 1 10

103 2 10

104 1 10

104 1 20

;

run;

/* First is to use DATA STEP */

proc sort data=test;

by id seq;

run;

data want (keep=id seq sumunit);

set test;

by id seq;

if first.id or first.seq then sumunit=unit;

else sumunit+unit;

if last.id or last.seq then output;

run;

proc print data=want;

run;

/* Second is PROC SQL with GROUP BY */

proc sql;

select id, seq, sum(unit) as s

from test

group by id, seq

order by id, seq;

run;

quit;

Wednesday, May 4, 2011

Find the maximum

/******** SAS Data Step ********/
data prior;
input prior @@;
cards;
1 5.2 8 7.2 4.6 2.1 .7 .1 0 0 10 3 20 19
;
run;
data max (keep=max);
set prior end=last;
retain max;
if max<prior then max=prior;
if last then output;
run;
proc print;
run;
/******** Proc Means ********/
proc means data=prior;
output out=s max=maximum;
run;
proc print data=s (keep=maximum);
run;

怎么从yahoo finance下载股票数据(转载加总结)

In R


#################################################
# A DEMO ON HOW TO DOWNLOAD STOCK PRICE ONLINE  #
# AND CREATE A TIME SERIES PLOT WITH R          #
#################################################

library(chron)
library(zoo)

# STOCK TICKER OF Fifth Third Bancorp
stock <- 'FITB'

# DEFINE STARTING DATE
start.date  <- 1
start.month <- 1
start.year  <- 2007

# DEFINE ENDING DATE
end.date  <- 31
end.month <- 12
end.year  <- 2008

# DEFINE URL LINK
link <- paste("http://ichart.finance.yahoo.com/table.csv?s=", stock,
"&a=", as.character(start.month - 1),
"&b=", as.character(start.date),
"&c=", as.character(start.year),
"&d=", as.character(end.month - 1),
"&e=", as.character(end.date),
"&f=", as.character(end.year),
"&g=d&ignore=.csv", sep = '')

# DOWNLOAD STOCK PRICE AS CSV FILE
download.file(link, "d:/r/data.csv")

# READ THE CSV FILE INTO R
data <- read.csv("d:/r/data.csv")

# CONVERT CHARACTER INTO DATE
dt <- dates(as.character(data[, 1]), format = "y-m-d")

# CONVERT DATA FRAME INTO TS OBJECT
ts <- zoo(data[, 2:5], dt)

# CREATE A PLOT FOR OPEN/CLOSE/HIGH/LOW PRICES
plot(ts, main = stock)


another one in R:

library(quantmod)
graphics.off()

#get the C price from yahoo
getSymbols('C',src='yahoo',from = "1994-01-01")
chartSeries(C,subset='last 4 months',TA=NULL,theme=chartTheme('white'))





In Python



#############################################
# READ STOCK PRICE FROM FINANCE.YAHOO.COM   #
#############################################

import urllib
from dateutil.relativedelta import *
from datetime import *

def GetPrice(ticker, start, end):
stock = ticker.upper()

m1 = int(start.split("/")[0])
d1 = int(start.split("/")[1])
y1 = int(start.split("/")[2])
dt1 = date(y1, m1, d1) + relativedelta(months = -1);
a = dt1.month
b = dt1.day
c = dt1.year

m2 = int(end.split("/")[0])
d2 = int(end.split("/")[1])
y2 = int(end.split("/")[2])
dt2 = date(y2, m2, d2) + relativedelta(months = -1);
d = dt2.month
e = dt2.day
f = dt2.year

url = "http://ichart.finance.yahoo.com/table.csv?s=" + stock + \
"&d=" + str(d) + "&e=" + str(e) + "&f=" + str(f) +       \
"&g=d&a=" + str(a) + "&b=" + str(b) + "&c=" + str(c) + "&ignore=.csv"
data = urllib.urlopen(url)
print data.read()

GetPrice("jpm", "08/01/2009", "08/10/2009")




In SAS


%macro getdata(tic);
FILENAME myurl URL "http://ichart.finance.yahoo.com/table.csv?s=&tic";
DATA &tic;
INFILE myurl FIRSTOBS=2 missover dsd;
format date yymmdd10.;
INPUT  Date: yymmdd10. Open    High Low Close    Volume    Adj_Close ;
*if date>=today()-180;

RUN;
%mend;
%getdata(SPY);




Another Python


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

#!/usr/bin/env python
#
#  Copyright (c) 2007-2008, Corey Goldberg (corey@goldb.org)
#
#  license: GNU LGPL
#
#  This library is free software; you can redistribute it and/or
#  modify it under the terms of the GNU Lesser General Public
#  License as published by the Free Software Foundation; either
#  version 2.1 of the License, or (at your option) any later version.


import urllib


"""
This is the "ystockquote" module.

This module provides a Python API for retrieving stock data from Yahoo
Finance.
"""


def __request(symbol, stat):
url = 'http://finance.yahoo.com/d/quotes.csv?s=%s&f=%s' % (symbol, stat)
return urllib.urlopen(url).read().strip().strip('"')


def get_all(symbol):
"""
Get all available quote data for the given ticker symbol.

Returns a dictionary.
"""
values = __request(symbol,
'l1c1va2xj1b4j4dyekjm3m4rr5p5p6s7').split(',')
data = {}
data['price'] = values[0]
data['change'] = values[1]
data['volume'] = values[2]
data['avg_daily_volume'] = values[3]
data['stock_exchange'] = values[4]
data['market_cap'] = values[5]
data['book_value'] = values[6]
data['ebitda'] = values[7]
data['dividend_per_share'] = values[8]
data['dividend_yield'] = values[9]
data['earnings_per_share'] = values[10]
data['52_week_high'] = values[11]
data['52_week_low'] = values[12]
data['50day_moving_avg'] = values[13]
data['200day_moving_avg'] = values[14]
data['price_earnings_ratio'] = values[15]
data['price_earnings_growth_ratio'] = values[16]
data['price_sales_ratio'] = values[17]
data['price_book_ratio'] = values[18]
data['short_ratio'] = values[19]
return data


def get_price(symbol):
return __request(symbol, 'l1')


def get_change(symbol):
return __request(symbol, 'c1')


def get_volume(symbol):
return __request(symbol, 'v')


def get_avg_daily_volume(symbol):
return __request(symbol, 'a2')


def get_stock_exchange(symbol):
return __request(symbol, 'x')


def get_market_cap(symbol):
return __request(symbol, 'j1')


def get_book_value(symbol):
return __request(symbol, 'b4')


def get_ebitda(symbol):
return __request(symbol, 'j4')


def get_dividend_per_share(symbol):
return __request(symbol, 'd')


def get_dividend_yield(symbol):
return __request(symbol, 'y')


def get_earnings_per_share(symbol):
return __request(symbol, 'e')


def get_52_week_high(symbol):
return __request(symbol, 'k')


def get_52_week_low(symbol):
return __request(symbol, 'j')


def get_50day_moving_avg(symbol):
return __request(symbol, 'm3')


def get_200day_moving_avg(symbol):
return __request(symbol, 'm4')


def get_price_earnings_ratio(symbol):
return __request(symbol, 'r')


def get_price_earnings_growth_ratio(symbol):
return __request(symbol, 'r5')


def get_price_sales_ratio(symbol):
return __request(symbol, 'p5')


def get_price_book_ratio(symbol):
return __request(symbol, 'p6')


def get_short_ratio(symbol):
return __request(symbol, 's7')


def get_historical_prices(symbol, start_date, end_date):
"""
Get historical prices for the given ticker symbol.
Date format is 'YYYYMMDD'

Returns a nested list.
"""
url = 'http://ichart.yahoo.com/table.csv?s=%s&' % symbol + \
'd=%s&' % str(int(end_date[4:6]) - 1) + \
'e=%s&' % str(int(end_date[6:8])) + \
'f=%s&' % str(int(end_date[0:4])) + \
'g=d&' + \
'a=%s&' % str(int(start_date[4:6]) - 1) + \
'b=%s&' % str(int(start_date[6:8])) + \
'c=%s&' % str(int(start_date[0:4])) + \
'ignore=.csv'
days = urllib.urlopen(url).readlines()
data = [day[:-2].split(',') for day in days]
return data

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

#Example-

>>> import ystockquote

>>> print ystockquote.get_price('AUY')
10.865

>>> print ystockquote.get_all('PCX')