Develop an investment algorithm in Python 2

Until last time

Last time simply displayed the stock price of 9984 (Softbank). This time, let's calculate the moving average of the stock price.

What is a moving average?

Wikipedia: Moving Average

There are various types of moving averages, but in the case of a simple moving average, if $ p_t $ is the price $ t $ days ago, the n-day moving average will be the average of the closing prices for the past n days.

SMA_t = \frac{p_t + p_{t-1} + \ldots + p_{t - \left( n - 1 \right)}}{n};t \geq n - 1

The moving average is one of the most basic indicators in the technical analysis of stock prices and is used to judge the conditions such as golden cross and dead cross. The golden cross is the opposite of the dead cross, as the 5-day moving average is "good to buy" when it exceeds the 25-day moving average.

[Wikipedia: Moving Average](https://ja.wikipedia.org/wiki/Moving Average)

This time, let's calculate the moving average with the closing price after adjusting the stock price.

code

Suddenly, it's a code.

    def _mavg_signal(data):
        m5 = data["close_price_adj"].fillna(method='ffill').rolling(window=5, center=False).mean()
        m25 = data["close_price_adj"].fillna(method='ffill').rolling(window=25, center=False).mean()
        return {
            "mavg_5:price": m5,
            "mavg_25:price": m25,
        }

    #Signal registration
    ctx.regist_signal("mavg_signal", _mavg_signal)

In ʻinitialize (), register the function _mavg_signalwithctx.regist_signal ()`.

In _mavg_signal (), two types of calculation are performed: 5-day moving average and 25-day moving average. The parameter data is of type pandas.Panel and has a three-dimensional structure. The three-dimensional structure is

axis-0 (items): Data items (close_price, volume, etc.) axis-1 (major): Date (datetime.datetime type) axis-2 (minor): Brand name (symbol object type) Quoted from https://quantx.io/handbook/ja/#initialize

It seems that it has a structure like this. It's hard to imagine, but it may be easier to understand if you think like Excel (3D with "rows, columns, sheets"?) The actual internal image is written in handbook, but after deciding the data item of axis-0 and dropping it to 2D, pandas The moving average is calculated by the function of .DataFrame and returned as the value of dict as the return value.

Try to run

スクリーンショット 2017-06-15 10.38.18.png

It came out! mavg_5 is the 5-day moving average and mavg_25 is the 25-day moving average. The 5-day moving average is not much different from the closing price (close_price_adj), so it's hard to see.

Can you really calculate?

I wonder if I can really calculate, so I will check the actual calculation result on the tab called RawData on the chart.

スクリーンショット 2017-06-15 11.08.43.png

The value of the 5-day moving average of 2014-01-10 is $ \ frac {8880 + 8920 + 8990 + 8920 + 9020} 5 = 8946 $, so it seems that it can be calculated! Mavg_5: price is 5 Since it is a daily moving average, it is blank because it cannot be calculated until the 4th day after the back test is started.

Chart axis

In _mavg_signal (), which calculates the moving average,

        return {
            "mavg_5:price": m5,
            "mavg_25:price": m25,
        }

I returned the dict. The value of dict is pandas.DataFrame which is the calculation result of moving average.

The key is the axis name of the chart, but the point is : price, which specifies the scale in the chart. : price is a predefined scale, which is the stock price scale of the stock. By making the axes of mavg_5 and mavg_25 the same, it is possible to compare on the chart for the first time.

as a trial,

        return {
            "mavg_5:mavg_5": m5,
            "mavg_25:mavg_25": m25,
        }

With that feeling, when I try to execute it,

スクリーンショット 2017-06-15 10.48.22.png

Since the scale of the vertical axis of each moving average value is different, the degree of overlap of the charts has changed slightly (difficult to understand). Therefore, it is difficult to judge the golden cross or dead cross from this chart, so let's align the axes.

Summary

This is the code for this time.

def initialize(ctx):
    ctx.configure(
      target="jp.stock.daily",
      channels={
        "jp.stock": {
          "symbols": [ "jp.stock.9984" ],
          "columns": [ "close_price_adj" ]
        }
      }
    )

    def _mavg_signal(data):
        m5 = data["close_price_adj"].fillna(method='ffill').rolling(window=5, center=False).mean()
        m25 = data["close_price_adj"].fillna(method='ffill').rolling(window=25, center=False).mean()
        return {
            "mavg_5:price": m5,
            "mavg_25:price": m25,
        }

    #Signal registration
    ctx.regist_signal("mavg_signal", _mavg_signal)

def handle_signals(ctx, date, current):
    '''
    current: pd.DataFrame
    '''
    pass

Next time, I will try to calculate and display more complicated indicators.

Reference information

2018/1/11 postscript Official version URL:

Recommended Posts

Develop an investment algorithm in Python 2
Let's develop an investment algorithm with Python 1
Genetic algorithm in python
Algorithm in Python (Bellman-Ford)
Algorithm in Python (Dijkstra's algorithm)
Algorithm in Python (primality test)
Reproduce Euclidean algorithm in Python
Algorithm in Python (binary search)
Implement Dijkstra's Algorithm in python
How to develop in Python
Algorithm in Python (breadth-first search, bfs)
Sorting algorithm and implementation in Python
Write an HTTP / 2 server in Python
Python algorithm
Write A * (A-star) algorithm in Python
Algorithm in Python (depth-first search, dfs)
Implementing a simple algorithm in Python 2
Algorithm (segment tree) in Python (practice)
Python in is also an operator
Run a simple algorithm in Python
An alternative to `pause` in Python
Ant book in python: Sec.2-5 Dijkstra's algorithm
Algorithm in Python (ABC 146 C Binary Search
Develop slack bot in python using chat.postMessage
Write a simple greedy algorithm in Python
Alignment algorithm by insertion method in Python
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Python memorandum (algorithm)
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv