learn-algorithmic-trading/courses/sources/chap1_1.py

37 lines
1.4 KiB
Python

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pandas_datareader import data
# Getting data
start_date = '2014-01-01'
end_date = '2018-01-01'
goog_data = data.DataReader('GOOG','yahoo',start_date,end_date)
print(goog_data)
# Preparing the signal
goog_data_signal = pd.DataFrame(index=goog_data.index)
goog_data_signal['price'] = goog_data['Adj Close']
goog_data_signal['daily_difference'] = goog_data_signal['price'].diff()
print(goog_data_signal.head())
goog_data_signal['signal'] = 0.0 # Create a signal based on values of daily_difference
goog_data_signal['signal'] = np.where(goog_data_signal['daily_difference'] > 0, 1.0,0.0) # 0 when we need buy
print(goog_data_signal.head())
# We cannot buy/sell limiteless, we can only buy/sell the amount of position we have
goog_data_signal['positions'] = goog_data_signal['signal'].diff()
print(goog_data_signal.head())
# Signal visualization
fig = plt.figure()
ax1 = fig.add_subplot(111,ylabel='Google price in $')
goog_data_signal['price'].plot(ax=ax1, color='r', lw=2.)
ax1.plot(goog_data_signal.loc[goog_data_signal.positions == 1.0].index, \
goog_data_signal.price[goog_data_signal.positions == 1.0],
'^', markersize=5, color='m')
ax1.plot(goog_data_signal.loc[goog_data_signal.positions == -1.0].index, \
goog_data_signal.price[goog_data_signal.positions == -1.0],
'v', markersize=5, color='k')
plt.show()