金融数据分析(九)模拟计算以MACD指标买入卖出信号进行股票交易而产生的收益

案例(三)简单金融数据分析

项目三:计算一年内以MACD指标买入卖出信号进行股票交易而产生的收益

设计一个程序,计算一年内以MACD指标买入卖出信号进行股票交易而产生收益。MACD交易信号为:快线从下往上穿越慢线是当天买入信号,快线从上往下穿越慢线是当天卖出。假设买入和卖出价格为发出交易信号当天的收盘价格。

# -*- coding: utf-8 -*-
"""
Created on Sun Sept 20 9:04:59 2020

@author: mly
"""
import numpy as np
import datetime
import pandas_datareader.data as web

start = datetime.datetime(2018, 6, 1)
end = datetime.datetime.today()
stock_name = '601318.ss'
df = web.DataReader(stock_name, 'yahoo', start, end)


def df_EMA(prices, N):
    ema = []
    k = len(prices)
    if k > 0:
        for i in range(k):
            if i == 0:
                ema.append(prices[i])
            else:
                ema.append((2 * prices[i] + (N - 1) * ema[i - 1]) / (N + 1))
    return (ema)


def df_MACD(df, short=12, long=26, M=9):
    fast = df_EMA(df['Adj Close'].values, short)
    slow = df_EMA(df['Adj Close'].values, long)
    if len(fast) > 0:  # & len(slow)>0:
        df['Fast'] = np.round(np.array(fast), 2)
        df['Slow'] = np.round(np.array(slow), 2)
        df['DIF'] = df['Fast'] - df['Slow']
        df['DEA'] = np.round(np.array(df_EMA(df['DIF'].values, M)), 2)
        df['MACD'] = 2 * (df['DIF'] - df['DEA'])
        df['tim'] = df['Close'] / df['Open']
        return (df)
    else:
        print('no data,no MACD')


times0 = 1
marker = 0
df_MACD(df, 12, 26, 9)
for i in df.itertuples(index=True, name='df'):
    if getattr(i, 'DIF') > 0 and marker == 0:
        times0 = times0 * getattr(i, 'tim')
        marker = 1
    elif getattr(i, 'DIF') > 0 and marker == 1:
        times0 = times0 * getattr(i, 'tim')
        marker = 1
    elif getattr(i, 'DIF') == 0 and marker == 1:
        times0 = times0 * getattr(i, 'tim')
        marker = 0
    elif getattr(i, 'DIF') < 0 and marker == 1:
        times0 = times0 * getattr(i, 'tim')
        marker = 0
    else:
        continue

print(times0)

运行结果:

在这里插入图片描述
看来历史上如果按照这个方法买股票,至少不会亏qwq,233333333…

©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页