Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Scala for Machine Learning, Second Edition - Second Edition

You're reading from  Scala for Machine Learning, Second Edition - Second Edition

Product type Book
Published in Sep 2017
Publisher Packt
ISBN-13 9781787122383
Pages 740 pages
Edition 2nd Edition
Languages
Toc

Table of Contents (27) Chapters close

Scala for Machine Learning Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface
1. Getting Started 2. Data Pipelines 3. Data Preprocessing 4. Unsupervised Learning 5. Dimension Reduction 6. Naïve Bayes Classifiers 7. Sequential Data Models 8. Monte Carlo Inference 9. Regression and Regularization 10. Multilayer Perceptron 11. Deep Learning 12. Kernel Models and SVM 13. Evolutionary Computing 14. Multiarmed Bandits 15. Reinforcement Learning 16. Parallelism in Scala and Akka 17. Apache Spark MLlib Basic Concepts References Index

Finances 101


The exercises presented throughout the book are related to historical financial data and require the reader to have some basic understanding of financial markets and reports.

Fundamental analysis

Fundamental analysis is a set of techniques to evaluate a security (stock, bond, currency, or commodity) that entails attempting to measure its intrinsic value by examining related to both macro and micro financial and economy reports. Fundamental analysis is usually applied to estimate the optimal price of a stock using a variety of financial ratios.

Numerous financial metrics are used throughout the book. Here are the definitions of the most commonly used metrics [A:16]:

  • Earnings per share (EPS): This is the ratio of net earnings over number of outstanding shares.

  • Price/Earnings Ratio (PE): This is the ratio of market price per share over earnings per share.

  • Price/Sales Ratio (PS): This is the ratio of market price per share over gross sales (or revenue).

  • Price/Book Value Ratio (PB): This is the ratio of market price per share over total balance sheet value per share.

  • Price to Earnings/Growth (PEG): This is the ratio of PE per share over annual growth of earnings per share.

  • Operating Income: This is the difference between operating revenue and operating expenses.

  • Net Sales: This is the difference between revenue or gross sales and cost of goods or cost of sales.

  • Operating Profit Margin: This is the ratio of operating income over net sales

  • Net Profit Margin: This is the ratio of net profit over net sales (or net revenue).

  • Short Interest: This is the quantity of shares sold short.

  • Short Interest Ratio: This is the ratio of short interest over total number of shares floated.

  • Cash per Share: This is the ratio of value of cash per share over market price per share.

  • Pay-out Ratio: This is the percentage of the Primary/Basic Earnings per share, excluding extraordinary items paid to common stockholders in the form of cash dividends.

  • Annual Dividend yield: This is the ratio sum of dividends paid during the previous 12-month rolling period over the current stock price. Regular and extra dividends are included.

  • Dividend Coverage Ratio: This is the ratio of income available to common stockholders excluding extraordinary items for the most recent trailing 12 months to gross dividends paid to common shareholders, expressed as percent.

  • Growth Domestic Product (GDP): This is the aggregate measure of the economic output of a country. It measures the sum of value added in the production of goods and delivery of services.

  • Consumer Price Index (CPI) : This is an indicator that measures the change in the price of an arbitrary basket of goods and services used by the Bureau of Labor Statistics to evaluate inflationary trend.

  • Federal Fund rate: This is the interest rate at which banks trade balances held at the Federal Reserve. The balances are called Federal Funds.

Technical analysis

Technical analysis is a methodology for forecasting the direction of the price of any given security through the study of past market information derived from price and volume. In simpler terms, it is the study of price activity and price patterns in order to identify trade opportunities [A:17]. The price of a stock, commodity, bond, or financial future reflects all the information publicity known about that asset as processed by market participants.

Terminology

  • Bearish or bearish position: A bear position attempts to profit by betting the prices of the security will fall.

  • Bullish or bullish position: A bull position attempts to profit by betting the price of the security will rise.

  • Long position: A long position attempts to profit by betting the price of the security will rise.

  • Neutral position: A neutral position attempts to profit by betting that the price of the security will not change significantly.

  • Oscillator: An oscillator is a technical indicator that measures the price momentum of a security, using some statistical formula.

  • Overbought: A security is overbought when its price rises too fast as measured by one or several trading signals or indicators.

  • Oversold: A security is oversold when its price drops too fast as measured by one or several trading signal or indicator.

  • Relative strength index: The Relative strength index (RSI) is an oscillator that computes the average of the number of trading sessions for which the closing price is higher than the opening price over the average of number of trading sessions for which the closing price is lower than the opening price. The value is normalized over [0, 1] or [0, 100%].

  • Resistance: A resistance level is the upper limit of the price range of a security. The price falls back as soon as it reaches the resistance level.

  • Short position: A short position attempts to profit by betting the price of the security will fall.

  • Support: The support level is the lower limit of the price range of a security over a period. The price bounces back as soon as it reaches the support level.

  • Technical indicator: The technical indicator is a variable derived from the price of a security and possibly its trading volume.

  • Trading range: The trading range for a security over a period is the difference between the highest and lowest price for this period of time.

  • Trading signal: A signal is triggered when a technical indicator reaches a predefined value, upward or downward.

  • Volatility: This is the variance or standard deviation of the price of a security over a period.

Trading data

The raw trading data extracted from Google or Yahoo financials pages consists of the following:

  • adjClose (or close): This is the adjusted or nonadjusted price of a security at the closing of the trading session

  • open: This is the price of the security at the opening of the trading session

  • high: This is the highest price of the security during the trading session

  • low: This is the lowest price of the security during the trading session

    Illustration of a daily open and close price of a stock

We can derive the following metrics from the raw trading data:

  • Price volatility: volatility = 1.0 – high/low

  • Price variation: vPrice = adjClose – open

  • Price difference (or change) between two consecutive sessions: dPrice = adjClose – prevClose = adjClose(t) – adjClose(t-1)

  • Volume difference between two consecutive sessions: dVolume = volume(t)/volume(t-1) – 1.0

  • Volatility difference between two consecutive sessions: dVolatility = volatility(t)/volatility(t-1) – 1.0

  • Relative price variation over the last T trading days: rPrice = price(t)/average(price over T) – 1.0

  • Relative volume variation over the last T trading days: rVolume = volume(t)/average(volume over T) – 1.0

  • Relative volatility variation over the last T trading days: rVolatility = volatility(t)/average(volatility over T) – 1.0

Trading signal and strategy

The purpose is to create a set variable x derived from price and volume, x = f (price, volume) that generates predicates, x op c for which op is a Boolean operator such as > or = that compare the value of x to a predetermined threshold c.

Let's consider one of the most common technical indicators derived from a price: the relative strength index, RSI or the normalized RSI, nRSI for which the formulation is provided next as a reference.

Note

Relative strength Index

RSI for a period of T sessions, with po opening price, pc closing price is as follows:

A trading signal is a predicate using a technical indicator, nRSIT(t) < 0.2. In trading terminology, a signal is emitted for any period t for which the predicate is true:

Visualization of oversold and overbought position using the relative strength index

Traders do not usually rely on a single trading signal to make a rational decision. As an example, if G is the price of gold, I10 is the current rate of the 10-year Treasury bond, and RSIsp500 is the relative strength index of the S&P 500, then we could conclude that the increase of the exchange rate of US$ to the Japanese yen is maximized for the following trading strategy:

{G < $1170 and I10 > 3.9% and RSIsp500 > 0.6 and RSIsp500 < 0.8}

Price patterns

Technical analysis assumes that historical prices contain some recurring albeit noisy patterns that can be discovered using the statistical method. The most common patterns, used in the book are the trend, support, and resistance levels [A:18] as illustrated in the following chart:

Illustration of trend and support resistance levels in technical analysis

Options trading

An option is a contract that gives the buyer the right, but not the obligation, to buy or sell a security at a specific price on or before a certain date [A:19].

The two types of options are calls and puts:

  • A call gives the holder the right to buy a security at a certain price within a specific period. Buyers of calls expect that the price of the security will increase substantially over a strike price before the option expires.

  • A put option gives the holder the right to sell a security at a certain price within a specific period. Buyers of puts expect that the price of the stock will fall below the strike price before the option expires.

Let's consider a call option contact on 100 shares at a strike price of $23 for a total cost of $270 ($2.7 per option). The maximum loss the holder of the call can occur is the loss of premium or $270 when the option expires worthless. However, the profit can be potentially almost unlimited: If the price of the security reaches $36 when the call option expires, the owner will have a profit of ($36 - $23) * 100 - $270 = $1030. The return on investment is 1030/270 = 380 percent. The action of buying the stock at $24, then selling at $36 would have generated a return on investment of 36/24 -1= 50 percent. This example is simple and does not consider the transaction fee or margin cost [A:20]:

Illustration of the pricing of a call option

Financial data sources

There are numerous sources of financial data available to experiment with machine learning and validate models [A:21]:

  • Yahoo finances (stocks, ETFs, and Indices): http://finance.yahoo.com

  • Google finances (stocks, ETFs, and Indices): https://www.google.com/finance

  • NASDAQ (stocks, ETFs, and Indices): http://www.nasdaq.com

  • European Central Bank (European bonds and notes): http://www.ecb.int

  • TrueFx (Forex): http://www.truefx.com

  • Quandl (economics and financials statistics): http://www.quantl.com

  • Dartmouth University (portfolio and simulation): http://mba.tuck.dartmouth.edu

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime