2012年10月16日 星期二
落漆的 System.MissingMethodException
System.MissingMethodException: Method not found: 'Boolean System.Threading.WaitHandle.WaitOne(Int32)'.
那當初幹麻讓我 compile 過?!
因此問題出在 .NET Framework 版本,真的很鳥。
Upgrade to 3.5 SP1,解決。
真掉漆。
2012年10月15日 星期一
《西遊記》前五十回
怪越打越強。
王下七武海鷹眼說,王者最厲害的功夫不是武力,而是化敵為友的能力,這個才可怕。魯夫連打都不用打,女帝就變自己人了 ((羞))。孫悟空也是。以現在的術語來說,就是 CALL OUT KING,唐三藏是談判籌碼,豬八戒是個丑角搞笑用的,沙悟淨是萬年留守人員。當然啦,孫悟空對唐三藏也是有情有義。就是個搞笑小說,害我笑到快岔氣了。
略過不題。說點三大法人交易記錄。TWSE 對我很好心,每次抓檔都不用故意等幾秒鐘,因此我一下就抓完了。
Schema:
create table if not exists TradingSummary
(
creation_dt datetime default current_timestamp,
trading_date datetime not null,
item text not null,
buy real,
sell real,
diff real,
unique (trading_date, item) on conflict ignore
);
Source codes:
import csv
import logging
import os
import sqlite3
from ..common import logger
class Sourcing():
def __init__(self):
self.LOGGER = logging.getLogger()
self.URL_TEMPLATE = '''http://www.twse.com.tw/ch/trading/fund/BFI82U/BFI82U_print.php?begin_date=%s&end_date=&report_type=day&language=ch&save=csv'''
self.DATES = []
self.CSV_DIR = '''./dataset/trading_summary/csv/'''
self.DB_FILE = './db/stocktotal.db'
self.SQL_INSERT = '''insert or ignore into
TradingSummary(trading_date, item, buy, sell, diff) values(?, ?, ?, ?, ?)'''
def source(self, begin_date, end_date):
self.init_dates(begin_date, end_date)
#self.source_url_to_csv(self.CSV_DIR)
self.source_csv_to_sqlite(self.CSV_DIR, self.DB_FILE, self.SQL_INSERT)
def init_dates(self, begin_date, end_date):
from datetime import date
from datetime import datetime
from datetime import timedelta
begin = datetime.strptime(begin_date, '%Y-%m-%d')
end = datetime.strptime(end_date, '%Y-%m-%d')
self.DATES = [begin + timedelta(n) for n in range(int((end - begin).days + 1))]
def source_url_to_csv(self, dest_dir):
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
for date in self.DATES:
url = self.URL_TEMPLATE % date.strftime('%Y%m%d')
dest_file = os.path.join(dest_dir, date.strftime('%Y-%m-%d'))
self.__wget(url, dest_file)
def source_csv_to_sqlite(self, src_dir, dest_db, sql_insert):
assert os.path.isfile(dest_db)
for date in self.DATES:
src_file = os.path.join(src_dir, date.strftime('%Y-%m-%d'))
self.source_csv_to_sqlite_single(src_file, dest_db, sql_insert)
def source_csv_to_sqlite_single(self, src_file, dest_db, sql_insert):
self.LOGGER.debug('''%s => %s''' % (src_file, dest_db))
csv_reader = csv.reader(open(src_file, 'r'))
rows = [_ for _ in csv_reader]
if len(rows) is 1:
self.LOGGER.info('''%s => No record''' % src_file)
return
elif len(rows) is not 6:
self.LOGGER.info('''%s => Error''' % src_file)
return
conn = sqlite3.connect(dest_db)
cursor = conn.cursor()
for n in range(2, 6):
r = self.__build_db_record(src_file, rows[n])
cursor.execute(self.SQL_INSERT, r)
self.LOGGER.debug(r)
conn.commit()
cursor.close()
conn.close()
def __wget(self, url, dest_file):
wget = os.path.abspath('./src/thirdparty/wget/wget.exe')
assert os.path.isfile(wget)
wget_cmdline = '''%s -N \"%s\" --waitretry=3 -O \"%s\"''' % (wget, url, dest_file)
os.system(wget_cmdline)
def __build_db_record(self, src_file, row):
trading_date = os.path.basename(src_file)
item = row[0]
buy = row[1].replace(',','')
sell = row[2].replace(',','')
diff = row[3].replace(',','')
return [trading_date, item, buy, sell, diff]
2012年10月14日 星期日
Stocktotal Database 之二
接著,想查最近各家股票的自有資本比率 = 股東權益/資產。
研究許久,用 inner join 兜出想要的 SQL statement:
然後再重做一次,把資料清掉,再重新塞一千多萬筆資料。喵的,哪有那麼多時間,直接下:
因此當初用 text 存數字就是他媽的錯誤設計。改 schema 吧。
該用 int 或者是 real 呢?因為損益表有類似 something per share 的概念,因此有小數,只好全用 real。接著就是改 schema。Firefox plugin 的 SQLite Manager 有提供快速更改 column data type 的功能 ((!!))
((
Stocktotal 總算恢復正常了。
現在我想找近十年自由現金流量為正的公司中,最近一次自有資本比率超過五成的有那些?
ET: 3186ms,時間很漂亮 ((index => 用空間換時間))。38 家公司如下:
然後我發現還欠許多資料,每月營收、股東權利變動表、股價、市場總本益比、三大法人進出等等。
研究許久,用 inner join 兜出想要的 SQL statement:
select然後碰到麻煩了,當初 schema 存 item number 的 data type 是 text,結果發現 field 值若為 '17,458,850.00',SQLite 會把它 cast 為 17 ((int)),這不是我們要的。倘若值為 '17458850.00',那麼 SQLite 會把它正確轉成 17458850。這樣一來,原先 sourcing_base.py 就要略為修改
E.stock_code,
E.activity_date,
E.number as Equity,
A.number as Assets,
E.number / A.number as Ratio
from BalanceSheet as E
inner join
BalanceSheet as A
on E.stock_code = A.stock_code
and E.activity_date = A.activity_date
and E.item = '股東權益總計'
and A.item = '資產總計'
and E.report_type = 'C'
and A.report_type = 'C'
and E.activity_date = '2012-06-30'
cursor.execute(self.SQL_INSERT, (..., row[1].replace(',', '')))
update BalanceSheet set number = replace(number, ',', '');重新做上述 SQL command,好慢,只好建 index:
create index IX_BALANCE_SHEET_ITEM on BalanceSheet(item);好多了。此外,會計對負數表示法有兩種,同樣是負一,可以寫 -1,也可以寫 (1)。
因此當初用 text 存數字就是他媽的錯誤設計。改 schema 吧。
該用 int 或者是 real 呢?因為損益表有類似 something per share 的概念,因此有小數,只好全用 real。接著就是改 schema。Firefox plugin 的 SQLite Manager 有提供快速更改 column data type 的功能 ((!!))
ALTER TABLE "main"."BalanceSheet" RENAME TO "oXHFcGcd04oXHFcGcd04_BalanceSheet";很開心的按下去,結果悲劇了:index 掉了。喵的。只好重建:
CREATE TABLE "main"."BalanceSheet" (
"creation_dt" datetime DEFAULT (current_timestamp) ,
"stock_code" text NOT NULL ,
"report_type" character(1) NOT NULL ,
"report_date" datetime NOT NULL ,
"activity_date" datetime NOT NULL ,
"item" text NOT NULL ,
"number" real,
"revision" int DEFAULT (0) );
INSERT INTO "main"."BalanceSheet" SELECT ... FROM "main"."oXHFcGcd04oXHFcGcd04_BalanceSheet";
DROP TABLE "main"."oXHFcGcd04oXHFcGcd04_BalanceSheet";
create index IX_BALANCE_SHEET_ITEM on BalanceSheet(item);前面 index 很好理解,後面 unique index 就不好理解了。但也沒什麼,當初 create table 有設 unique 限制,SQLite 會建立相對應的 unique index。((其實也不難想像,如果 unique 不建立 index,那每次 insert 資料,都對 table scan 一次,怎麼可能這樣做呢?))
create unique index UX_BALANCE_SHEET_RECORD on
BalanceSheet(stock_code, report_type, report_date, activity_date, item, revision);
((
將來可以先把 index SQL command 先撈出來: SELECT sql FROM sqlite_master where type = 'index' and tbl_name = 'BalanceSheet'))
Stocktotal 總算恢復正常了。
現在我想找近十年自由現金流量為正的公司中,最近一次自有資本比率超過五成的有那些?
select * from
(
select
E.stock_code,
E.activity_date,
E.number as Equity,
A.number as Assets,
E.number / A.number as Ratio
from BalanceSheet as E
inner join
BalanceSheet as A
on E.stock_code = A.stock_code
and E.activity_date = A.activity_date
and E.item = '股東權益總計'
and A.item = '資產總計'
and E.report_type = 'C'
and A.report_type = 'C'
and E.activity_date = '2012-06-30'
and E.stock_code in
(
select stock_code from
(
select stock_code, activity_date, sum(number) as sum from CashFlowStmt
where report_type = 'C'
and strftime('%m-%d', activity_date) = '12-31'
and strftime('%Y', activity_date) > '2001'
and item in ('Operating', 'Financing')
group by activity_date, stock_code
)
where sum > 0
group by stock_code
having count(*) >= 10
)
) where Ratio > 0.5
ET: 3186ms,時間很漂亮 ((index => 用空間換時間))。38 家公司如下:
1301, 1303, 1319, 1434, 1460, 1525, 1730, 1734, 1802, 1905,
2106, 2323, 2325, 2330, 2340, 2367, 2387, 2428, 2460, 2474,
2478, 2492, 3031, 3060, 3311, 5706, 6155, 6202, 6271, 6283,
8103, 8210, 9905, 9917, 9925, 9938, 9939, 9943
然後我發現還欠許多資料,每月營收、股東權利變動表、股價、市場總本益比、三大法人進出等等。
2012年10月13日 星期六
Stocktotal Database 之一
Schema:
drop table if exists BalanceSheet;
drop table if exists IncomeStmt;
drop table if exists CashFlowStmt;
drop table if exists StockCode;
create table if not exists BalanceSheet
(
creation_dt datetime default current_timestamp,
stock_code text not null,
report_type character(1) not null,
report_date datetime not null,
activity_date datetime not null,
item text not null,
number text,
revision int default 0,
unique (stock_code, report_type, report_date, activity_date, item, revision) on conflict ignore
);
create table if not exists IncomeStmt
(
creation_dt datetime default current_timestamp,
stock_code text not null,
report_type character(1) not null,
report_date datetime not null,
activity_date datetime not null,
item text not null,
number text,
revision int default 0,
unique (stock_code, report_type, report_date, activity_date, item, revision) on conflict ignore
);
create table if not exists CashFlowStmt
(
creation_dt datetime default current_timestamp,
stock_code text not null,
report_type character(1) not null,
report_date datetime not null,
activity_date datetime not null,
item text not null,
number text,
revision int default 0,
unique (stock_code, report_type, report_date, activity_date, item, revision) on conflict ignore
);
create table if not exists StockCode
(
creation_dt datetime default current_timestamp,
code text unique,
name text unique,
isin_code text unique,
listing_date datetime,
market_category text,
industry_category text,
cfi_code text
);
還沒為查詢建 index。因為 SQLite 沒有 stored procedures 可以用,所以也沒有建立 stored procedures 之必要。((將來考慮用 PostgreSQL 之類的 open source database solution))
研究:
SQLite 會不會爆掉?想太多!
select count(*) from BalanceSheet -- 7518726
select count(*) from IncomeStmt -- 3561990
select count(*) from CashFlowStmt -- 276730
參考:http://www.sqlite.org/limits.html
Maximum Number Of Rows In A Table
The theoretical maximum number of rows in a table is 2^64. This limit is unreachable since the maximum database size of 14 terabytes will be reached first. A 14 terabytes database can hold no more than approximately 1e+13 rows, and then only if there are no indices and if each row contains very little data.
有意思的查詢:近十年,哪些股票自由現金流量表 (free cash flow) 皆為正?
select stock_code, count(*) as positive_fcf_count from
(
select stock_code, activity_date, sum(number) as sum from CashFlowStmt
where report_type = 'C'
and strftime('%m-%d', activity_date) = '12-31'
and strftime('%Y', activity_date) > '2001'
and item in ('Operating', 'Financing')
group by activity_date, stock_code
)
where sum > 0
group by stock_code
having positive_fcf_count >= 10
特別留意 SQLite 對 date/time 的處理方式,請參考 http://www.sqlite.org/lang_datefunc.html。許多 MSSQL 常用的 date/time functions,SQLite 也有其對應 functions。個人認為更直覺。
答案:共 92 家。((未驗算,1301果然在榜單))
2012年10月11日 星期四
Git - About Version Control
Local Version Control Systems
Many people’s version-control method of choice is to copy files into another directory (perhaps a time-stamped directory, if they’re clever). This approach is very common because it is so simple, but it is also incredibly error prone.
((常常絞在一起))
Centralized Version Control Systems
The next major issue that people encounter is that they need to collaborate with developers on other systems. To deal with this problem, Centralized Version Control Systems (CVCSs) were developed.
((Perforce 屬於這個很難用的系列))
Distributed Version Control Systems
This is where Distributed Version Control Systems (DVCSs) step in. In a DVCS (such as Git, Mercurial, Bazaar or Darcs), clients don’t just check out the latest snapshot of the files: they fully mirror the repository.
((這個比較像實際應用,也因此個人想架一套 Git 來存 source codes 跟 dataset))
2012年9月30日 星期日
龜山島。401高地。環島。
時間:2012-09-22
很早之前,林教授發信寄給宗偉,華倚,思賢,小根,幫協會出一個活動。
四個人思考許久,決定走輕鬆路線,龜山島401高地。
開活動很簡單,辦活動好麻煩,必須處理許多事項,還好我們有四個人,工作分配下去,倒也輕鬆如意。小根負責保險。其實每個人都應該保意外險,例如同事B,每年都會保一次。這次共有九員參加,還包含大咖大哥哩。
話說上回爬山拉傷鵝足肌,有點不想去龜山島,打算專心養傷。但,401高地不好申請,而且才爬一點點應該沒差吧!走上401高地必須陡上1706階樓梯,第一千階有休息處,我為自己定了一個目標,好走歹走也要屏住一口氣走到第一千階 ((志氣變小,但好漢不提當年勇?!過去的就過去了,只有當下的我才是真實的))。或許太久沒爬山了,有點撐,但雙腳並無不適,島上悶熱的空氣,逼出許多汗滴,身體應能負擔,只要心理有跟上就夠了。
((摸之前告誡不舒服就別上去,哈,明知山有虎,偏往虎山行))
大咖拼第一位搶拍照,思賢,Ben Lo,跟我搶第二位,咚咚咚一下就搶到第一千階,三人賴在涼亭等後面隊友,後面隊友果然夠爭氣,讓我們休夠久,孱弱的島上海風,倒也吹的我昏昏欲睡。最後一段只剩七百多階,撐上去就能看見龜山島全貌,好興奮。下山倒吃不少苦頭,因為害怕再次拉傷鵝足肌,大腿肌撐得很辛苦,下山略有鐵腿。
復出第一站,成功吧?
PS. 美中不足處 Ben Lo 被虎頭蜂叮到。
2012年9月23日 星期日
海力士 (日式料理)
2012-09-23
自以為豚馬最好吃,至今仍這麼認為。
但實在太遠,有時懶惰就不想去,因此有必要尋找永和還不錯的店。在此推薦「海力士」。
今天試過綜合生魚片(小)(NT150)、鰻魚飯(NT270),還不錯,吃的很開心,若要挑缺點當然是不夠精緻,服務也不算特佳,這方面很嚴格的。
雖然如此,還是得面對交通不便的問題,有得吃就吃吧!
自以為豚馬最好吃,至今仍這麼認為。
但實在太遠,有時懶惰就不想去,因此有必要尋找永和還不錯的店。在此推薦「海力士」。
海力士日式料理
地址:新北市永和區福和路127號
電話:(02)3233-8488
今天試過綜合生魚片(小)(NT150)、鰻魚飯(NT270),還不錯,吃的很開心,若要挑缺點當然是不夠精緻,服務也不算特佳,這方面很嚴格的。
雖然如此,還是得面對交通不便的問題,有得吃就吃吧!
訂閱:
文章 (Atom)