Pebble Coding

ソフトウェアエンジニアによるIT技術、数学の備忘録

米国株式投資する上で参考になる本

米国株式投資をする上で人に勧めるならこれという書籍を紹介します。

億万長者をめざすバフェットの銘柄選択術

超有名人ウォーレンバフェット氏がどのように銘柄を選んでいるかが解説されています。
基本的な事柄を学べます。
バフェット氏は逆張り投資家で、ROEの高い安定した大型バリュー株を安いときに買えと言っています。

バカでも稼げる 「米国株」高配当投資

なぜ米国株投資なのかを説明しています。言葉使いが雑ですが、理屈はまともです。
リバランスの考え方は参考になります。
どうやって資産を築いたかは書かれていません。資産額は5000万円ほどだそうです。

バカでも稼げる 「米国株」高配当投資

バカでも稼げる 「米国株」高配当投資

お金が増える 米国株超楽ちん投資術

こちらもなぜ米国株なのかを説明しています。
インデックス投資をおすすめしています。
資産は日本株で築いたようですが、今は米国株押しのようです。
資産が2000万を超えていたり、めんどくさい投資をしたくない人をターゲットにしているので、あまりマス向けではなさそうです。

お金が増える 米国株超楽ちん投資術

お金が増える 米国株超楽ちん投資術

  • 作者:たぱぞう
  • 発売日: 2019/10/18
  • メディア: 単行本

米国会社四季報

最初は米国株の主要銘柄に馴染みがなさすぎると思いますので、これを軸に覚えていきましょう。
ETFも全て載っています。

FIRE 最強の早期リタイア術を流し読みした

FIRE 最強の早期リタイア術を流し読みしてみました。

いわゆる投資で一髪当ててリタイアした系の人の自叙伝です。

わりとどうでもいい話が多いです。
大雑把に言うと、リーマンショック時に大きくS&P500などのインデックス投資10万ドル程度から開始して、
節約生活しつつフルインベストメントして10年でリタイアした話です。
ポートフォリオは債権4割、株6割。
カナダで働いているらしく、株はカナダ、アメリカ、全世界に三等分だったようです。
共働きでソフトウェアエンジニアなので、年収は高めです。

参考になったのは、リバランスの考え方です。
株の暴落などによって、資産の配分比率が変わったら、最も資産比率が高くなっており、利益が出ている資産を売って、最も資産比率が低くなっている損失が出ている資産を買い増す現代金融理論のテクニックです。

あとは、先進国で暮らすよりも物価の安い東南アジアを旅して生活する方が、生活費が抑えられるということが書いてありました。
なので、東南アジアを旅行先に加えれば、全世界旅行するのと地元で生活するのは生活費が同じになるらしいです。

macOS環境にてバイナリをdisassembleする

~$ cat main.c
#include <stdio.h>
int main(int argc, char** argv) {
    int a = 2;
    int b = 3;
    int c = a + b;
    return 0;
}
~$ cc main.c
~$ otool -tvV a.out
a.out:
(__TEXT,__text) section
_main:
0000000100000f80	pushq	%rbp
0000000100000f81	movq	%rsp, %rbp
0000000100000f84	xorl	%eax, %eax
0000000100000f86	movl	$0x0, -0x4(%rbp)
0000000100000f8d	movl	%edi, -0x8(%rbp)
0000000100000f90	movq	%rsi, -0x10(%rbp)
0000000100000f94	movl	$0x2, -0x14(%rbp)  ; 値2をローカル変数領域Aにセットする
0000000100000f9b	movl	$0x3, -0x18(%rbp)  ; 値3をローカル変数領域Bにセットする
0000000100000fa2	movl	-0x14(%rbp), %edi  ; 値2が入ったローカル変数領域の値を%ediレジスタにセットする
0000000100000fa5	addl	-0x18(%rbp), %edi  ; %ediレジスタの値にローカル変数領域Bの値を加算する
0000000100000fa8	movl	%edi, -0x1c(%rbp)
0000000100000fab	popq	%rbp
0000000100000fac	retq


# std::vector 実装をdisassembleする

~$ cat main.cpp
#include <stdio.h>
#include <vector>

int main(int argc, char** argv) {
    std::vector<int16_t> data;
    data.reserve(256);
    for (int i = 0; i < 256; ++i) {
        data.push_back(3);
    }
    return 0;
}


~$ otool -tvV /Users/pebble8888/Library/Developer/Xcode/DerivedData/a-caxuagxwgdeqtmaqpognnfhilejt/Build/Products/Release/a 
/Users/pebble8888/Library/Developer/Xcode/DerivedData/a-caxuagxwgdeqtmaqpognnfhilejt/Build/Products/Release/a:
(__TEXT,__text) section
_main:
0000000100000eee	pushq	%rbp
0000000100000eef	movq	%rsp, %rbp
0000000100000ef2	pushq	%rbx
0000000100000ef3	pushq	%rax
0000000100000ef4	movl	$0x2000, %edi
0000000100000ef9	callq	0x100000f54 ## symbol stub for: _malloc
0000000100000efe	movq	%rax, %rbx
0000000100000f01	movdqa	0x87(%rip), %xmm0
0000000100000f09	xorl	%eax, %eax
0000000100000f0b	movdqa	0x8d(%rip), %xmm1
0000000100000f13	movdqu	%xmm0, (%rbx,%rax,2)  ; ループ開始位置1
0000000100000f18	addq	$0x8, %rax  ; 
0000000100000f1c	paddw	%xmm1, %xmm0
0000000100000f20	cmpq	$0x1000, %rax
0000000100000f26	jne	0x100000f13 ; ループ開始位置へジャンプする
0000000100000f28	movswl	0x1000(%rbx), %esi
0000000100000f2f	leaq	0x7a(%rip), %rdi ## literal pool for: "data %d"
0000000100000f36	xorl	%eax, %eax
0000000100000f38	callq	0x100000f5a ## symbol stub for: _printf
0000000100000f3d	movq	%rbx, %rdi
0000000100000f40	callq	0x100000f4e ## symbol stub for: _free
0000000100000f45	xorl	%eax, %eax
0000000100000f47	addq	$0x8, %rsp
0000000100000f4b	popq	%rbx
0000000100000f4c	popq	%rbp
0000000100000f4d	retq

movdqa : アライメントが揃っている128Bit転送
movdqu : アライメントが揃っていない128Bit転送
paddw : packed add word

C++11 ムーブセマンティクス

C++11 のムーブセマンティクスがよく分からないので実験してみる。

class Bean {
public:
    Bean()
    :color(0)
    ,shape(0)
    {
        std::cout << "constructor\n";
    }
    
    Bean(const Bean& other)
    : color(other.color)
    , shape(other.shape)
    {
        std::cout << "Bean copy constructer\n";
    }

    Bean(Bean&& other) noexcept
    : color(std::exchange(other.color, 0))
    , shape(std::exchange(other.shape, 0))
    {
        std::cout << "Bean move constructer\n";
    }
    
    int color;
    int shape;
};

class Bag {
public:
    Bag()
    {
    }
    std::vector<Bean> beans;
};


int main(int argc, const char * argv[]) {
    printf("1--\n");
    {
        auto bag = Bag();
        Bean bean; // constructor
        bag.beans.push_back(bean); // copy
    }
    printf("2--\n");
    {
        auto bag = Bag();
        Bean bean; // constructer
        bag.beans.emplace_back(bean); // copy
    }
    printf("3--\n");
    {
        auto bag = Bag();
        bag.beans.emplace_back(); // move
    }
    printf("4--\n");
    {
        auto bag = Bag();
        Bean bean; // constructor
        bag.beans.emplace_back(std::move(bean)); // move
    }
    printf("5--\n");
    {
        auto bag = Bag();
        Bean bean; // constructor
        bag.beans.push_back(std::move(bean)); // move
    }
    printf("6--\n");
    {
        auto bag = Bag();
        bag.beans.push_back(Bean()); // constructor + move
    }
    printf("7--\n");
    {
        auto bag = Bag();
        bag.beans.emplace_back(Bean()); // constructor + move
    }
    
    // 1, 2がcopyが走っていて最悪なケース
    // 4, 5, 6, 7 は生成処理が1回、moveが1回
    // 3 は生成処理が1回で最も効率的なケース
    

この例では要素の型が説明のためintになっているが、一般に巨大なクラスだと考えておく。

1--
constructor
copy
2--
constructor
copy
3--
constructor
4--
constructor
move
5--
constructor
move
6--
constructor
move
7--
constructor
move

次にcopy operatorとmove operatorの動作をみてみよう。

    Bean& operator=(const Bean& other)
    {
        std::cout << "Bean copy operator\n";
        if (this != &other) {
            color = other.color;
            shape = other.shape;
        }
        return *this;
    }
    Bean& operator=(Bean&& other) noexcept
    {
        std::cout << "Bean move operator\n";
        if (this != &other) {
            color = other.color;
            shape = other.shape;
        }
        return *this;
    }



    {
        Bean bean1;
        Bean bean2;
        bean2 = bean1;
    }
    printf("--\n");
    {
        Bean bean1;
        Bean bean2;
        bean2 = std::move(bean1);
    }
Bean copy operator
--
Bean move operator

こちらは意図通り、左辺値を渡した時はcopy、右辺値を渡した時はmoveとなった。

macOS10.15 Catalinaでdockerでpandas環境で米国のファイナンス情報を取得する

Docker Desktop on Macをインストールする。

Install Docker Desktop on Mac | Docker Documentation

python3.7が入ったDocker イメージをpullする。

$ docker pull python:3.7

起動する。

$ docker run -it --name pytest python:3.7 /bin/bash

yfinanceをインストールする。

root@2a63671a0430:/home# pip3 install yfinance

lxmlをインストールする。

root@2a63671a0430:/home# pip3 install lxml

root@2a63671a0430:/home# python3  
>>> import yfinance as yf
>>> msft = yf.Ticker("MSFT")
>>> msft.info
{'zip': '98052',
 'sector': 'Technology',
 'fullTimeEmployees': 144000,
 'longBusinessSummary': "Microsoft Corporation develops, licenses, and supports software, services, devices, and solutions worldwide. The company's Productivity and Business Processes segment offers Office, Exchange, SharePoint, Microsoft Teams, Office 365 Security and Compliance, and Skype for Business, as well as related Client Access Licenses (CAL); and Skype, Outlook.com, and OneDrive. It also provides LinkedIn that includes Talent and marketing solutions, and subscriptions; and Dynamics 365, a set of cloud-based and on-premises business solutions for small and medium businesses, large organizations, and divisions of enterprises. The company's Intelligent Cloud segment licenses SQL and Windows Servers, Visual Studio, System Center, and related CALs; GitHub that provides a collaboration platform and code hosting service for developers; and Azure, a cloud platform. It also provides support services and Microsoft consulting services to assist customers in developing, deploying, and managing Microsoft server and desktop solutions; and training and certification to developers and IT professionals on various Microsoft products. The company's More Personal Computing segment offers Windows OEM licensing and other non-volume licensing of the Windows operating system; Windows Commercial comprising volume licensing of the Windows operating system, Windows cloud services, and other Windows commercial offerings; patent licensing; Windows Internet of Things; and MSN advertising. It also provides Microsoft Surface, PC accessories, and other intelligent devices; Gaming, including Xbox hardware, and Xbox software and services; video games and third-party video game royalties; and Search, including Bing and Microsoft advertising. The company sells its products through distributors and resellers; and directly through digital marketplaces, online stores, and retail stores. It has strategic partnerships with Humana Inc. and Nokia. The company was founded in 1975 and is headquartered in Redmond, Washington.", 
'city': 'Redmond',
 'phone': '425-882-8080',
 'state': 'WA', 
'country': 'United States',
 'companyOfficers': [],
 'website': 'http://www.microsoft.com',
 'maxAge': 1,
 'address1': 'One Microsoft Way', 
'fax': '425-706-7329', 
'industry': 'Software—Infrastructure',
 'previousClose': 184.42,
 'regularMarketOpen': 183.17, 
'twoHundredDayAverage': 150.7186, 
'trailingAnnualDividendYield': 0.010519467,
 'payoutRatio': 0.32930002, 
'volume24Hr': None, 
'regularMarketDayHigh': 183.5,
 'navPrice': None,
 'averageDailyVolume10Day': 33274840, 
'totalAssets': None,
 'regularMarketPreviousClose': 184.42,
 'fiftyDayAverage': 172.45728, 
'trailingAnnualDividendRate': 1.94, 
'open': 183.17,
 'averageVolume10days': 33274840, 
'expireDate': None,
 'yield': None, 
'algorithm': None,
 'dividendRate': 2.04,
 'exDividendDate': 1582070400, 
'beta': 1.154593,
 'circulatingSupply': None,
 'startDate': None, 
'regularMarketDayLow': 177.25,
 'priceHint': 2,
 'currency': 'USD', 
'trailingPE': 31.107819,
 'regularMarketVolume': 48600385,
 'lastMarket': None, 
'maxSupply': None,
 'openInterest': None,
 'marketCap': 1358364409856,
 'volumeAllCurrencies': None,
 'strikePrice': None, 
'averageVolume': 26463705,
 'priceToSalesTrailing12Months': 10.118246,
 'dayLow': 177.25, 
'ask': 172.35,
 'ytdReturn': None,
 'askSize': 2200,
 'volume': 48600385,
 'fiftyTwoWeekHigh': 190.7,
 'forwardPE': 28.347618,
 'fromCurrency': None, 
'fiveYearAvgDividendYield': 2.02,
 'fiftyTwoWeekLow': 108.8, 
'bid': 172.8, 
'tradeable': True,
 'dividendYield': 0.0111,
 'bidSize': 1400, 
'dayHigh': 183.5, 
'exchange': 'NMS', 
'shortName': 'Microsoft Corporation',
 'longName': 'Microsoft Corporation', 
'exchangeTimezoneName': 'America/New_York',
 'exchangeTimezoneShortName': 'EST',
 'isEsgPopulated': False,
 'gmtOffSetMilliseconds': '-18000000', 
'quoteType': 'EQUITY',
 'symbol': 'MSFT',
 'messageBoardId': 'finmb_21835',
 'market': 'us_market',
 'annualHoldingsTurnover': None,
 'enterpriseToRevenue': 9.768,
 'beta3Year': None, 
'profitMargins': 0.33016,
 'enterpriseToEbitda': 21.403, 
'52WeekChange': 0.65265703, 
'morningStarRiskRating': None, 
'forwardEps': 6.3,
 'revenueQuarterlyGrowth': None,
 'sharesOutstanding': 7606049792, 
'fundInceptionDate': None, 
'annualReportExpenseRatio': None,
 'bookValue': 14.467,
 'sharesShort': 56674560,
 'sharesPercentSharesOut': 0.0075,
 'fundFamily': None,
 'lastFiscalYearEnd': 1561852800,
 'heldPercentInstitutions': 0.75201, 
'netIncomeToCommon': 44323000320, 
'trailingEps': 5.741,
 'lastDividendValue': None, 
'SandP52WeekChange': 0.20640099,
 'priceToBook': 12.344646, 
'heldPercentInsiders': 0.014249999, 
'nextFiscalYearEnd': 1625011200, 
'mostRecentQuarter': 1577750400,
 'shortRatio': 2.16,
 'sharesShortPreviousMonthDate': 1577750400, 
'floatShares': 7494542361, 
'enterpriseValue': 1311279939584,
 'threeYearAverageReturn': None,
 'lastSplitDate': 1045526400,
 'lastSplitFactor': '2:1', 
'legalType': None,
 'morningStarOverallRating': None, 
'earningsQuarterlyGrowth': 0.383,
 'dateShortInterest': 1580428800, 
'pegRatio': 2.2,
 'lastCapGain': None,
 'shortPercentOfFloat': 0.0075,
 'sharesShortPriorMonth': 62706418,
 'category': None,
 'fiveYearAverageReturn': None,
 'regularMarketPrice': 183.17,
 'logo_url': 'https://logo.clearbit.com/microsoft.com'}

これは使えそうだ。
試していませんがpandasイメージの方もうまくいくかも知れません。

参考:
DockerでPython3.6の環境構築!matplotlibインストールで詰まった話とかも - Qiita

https://hub.docker.com/r/amancevice/pandas
Reliably download historical market data from Yahoo! Finance with Python | Ran Aroussi (Official Website)