Ejemplo n.º 1
0
    return sma
     
#calculate 5 days moving average
moving_average_5=moving_average(HongLeong_close,5)  

#To plot the moving average
count = len(moving_average_5)
xaxis = np.arange(count)+5
yaxis = moving_average_5
plt.xlabel('Day $n$')
plt.ylabel('Moving Average')
plt.plot(xaxis,yaxis)
plt.title('Plot of 5-day Moving Average')

print(' ')
print('FTSEKLCI component chosen: HONG LEONG BERHAD')
print(' ')
print('The 5-day moving average plot is as following:')
plt.show()

#5819.KL and ^KLSE is the stock code for Hong Leong Bank Berhad and KLSE respectively
combine=['5819.KL','^KLSE']
#To download the closing data of Hong Leong Bank Berhad and KLCI index
closing = DR(combine, 'yahoo', start, end)['Close']
#To find the correlation of Hong Leong Bank Berhad and KLSE
correlation = closing.corr()

print(' ')
print('The correlation of FTSEKLCI and Hong Leong Bank Berhad is as following:')
print(correlation)
print(' ')
Ejemplo n.º 2
0
import pandas as pd
import pylab as p

start = dt(2012, 6, 1)  # Starting date
end = dt(2015, 5, 31)  # Ending date
data = DR("4197.KL", "yahoo", start, end)  # Use DataReader to read the data of Sime Darby from yahoo!finance
print("3 years of daily data for 4197,Sime Darby")
print(data)

# Plot 5-day moving average for Sime Darby
SD = DR("4197.KL", "yahoo", start, end)["Close"]  # Use DataReader to read the close price
moving_avg = pd.rolling_mean(SD, 5)  # Calculate the moving average
p.plot(moving_avg)
p.xlabel("Days")
p.ylabel("Stock price,$RM$")
p.title("5-days moving average plot for Sime Darby from 1/6/2012 to 31/5/2015")
p.show()

# Downlaod FTSEKLCI daily data
KLCI = DR("^KLSE", "yahoo", start, end)
print("FTSEKLCI Daily Data")
print(KLCI)

# Combine data of Sime Darby and KLSE
combine = ["4197.KL", "^KLSE"]
data1 = DR(combine, "yahoo", start, end)["Close"]

# Calcualte correlation between Sime Darby and KLCI
correlation = data1.corr()
print("Correlation between Sime Darby and FTSEKLCI \n", correlation)
Ejemplo n.º 3
0
#Download Public Bank 5 years stocks price 
data = DR("1295.KL", 'yahoo', start, end)
PB = data['Close'].values
num = len(PB)

# 5-day moving average of Public Bank stock price

mean2 = p.zeros_like(PB)
for i in range(num+1):
 
    if i >=5:
        mean = PB[i-5:i]
        mean2[i-5] = sum(mean)/5
        
#plot the graph
t = p.linspace (0,num-4,num-4);
p.title('5-day moving average')
p.xlabel('Day', fontsize=16)
p.ylabel('Average Stock Price, $RM$ ', fontsize=16)
p.plot(t,mean2[0:-4]); p.show();  # do not need the last 4 value 


#calculate the correlation of Public Bank with FTSEKLCI
Alldata=['^KLSE','1295.KL']
cor = DR(Alldata, 'yahoo', start, end)['Close']
cor1 = cor.corr()
print('The correlation is : ')
print(cor1)

Ejemplo n.º 4
0
from pandas.io.data import DataReader as DR
from datetime import datetime as dt
import pandas as pd
import pylab as p

start = dt(2011, 1, 1)  #start date
end = dt(2015, 1, 1)    #end date
data = DR("3182.KL", 'yahoo', start, end)  #download Genting stock price
genting = DR("3182.KL",'yahoo',start,end)['Close']  #taking the genting closing stock price

#calculate moving average
avg_days = 5
mov_avg = pd.rolling_mean(genting,avg_days)
p.plot(mov_avg)  #plot moving average
p.title('5-day moving average plot for Genting')
p.xlabel('Days')
p.ylabel('Stock price,$RM$')
p.show()

#Download FTSEKLCI daily data for the same duration
KLCI = DR("^KLSE", 'yahoo', start, end)

#Correlation between Genting and FTSEKLCI
combine = ["3182.KL","^KLSE"]
new_data = DR(combine,'yahoo', start, end)['Close']

#Calculate correlation
Correlation = new_data.corr()
print('Correlation between Genting and FTSEKLCI is \n', Correlation)
Ejemplo n.º 5
0
from datetime import datetime as dt

#define function for moving average
def movingaverage (values,window):
    weights = np.repeat(1.0,window)/window
    sma = np.convolve(values,weights,'valid')
    return sma

#download Maxis 5 years stock price    
start = dt(2010, 1, 1)
end = dt(2015, 5, 1)
data = DR("6012.KL", 'yahoo', start, end) 
Close_P = data['Close'].values #take out close price from maxis

# Calculate 5-day moving average of Maxis
MA = movingaverage (Close_P,5)

#plot the moving average graph
num= len(MA)
t = p.linspace (0,num,num); 
p.title('5-day Moving Average for Maxis')
p.xlabel('Days');p.ylabel('Average Stock Price, $RM$ ')
p.plot(t,MA); p.show();

#calculate the correlation of Maxis with FTSEKLCI
Alldata=['^KLSE','6012.KL']
cor = DR(Alldata, 'yahoo', start, end)['Close']
correlation = cor.corr()
print('The correlation is : ')
print(correlation)
Ejemplo n.º 6
0
#Put HL_data into array, and use only the last price
HL_array = p.array(HL_data);
HL_last_price = HL_array[:,-1];
Total_HLLP = HL_last_price.cumsum();

#Calculate 5-days Moving Average
n=5;
matrix = np.zeros((2,(len(Total_HLLP)-n+1)));
matrix[0,:] = Total_HLLP[(n-1):];
matrix[1,1:] = Total_HLLP[:-(n)];
mvg_avg = (matrix[0] - matrix[1]) / n;

#Plot the 5-days Moving Average and Labelling
p.plot(mvg_avg);
p.xlabel('Days'); 
p.ylabel('5-days Average');
p.title('5-days Moving Average of Hong Leong Bank \n [1 July 2011 - 30 June 2014] ' );
p.show();   

# Downlaod and Combining KLSE data with HL_data within the same period
Combine_data = ["5819.KL","^KLSE"]; 
HL_KLSE_data = DR(Combine_data,'yahoo',start,end)['Adj Close'];
#Adj Close is the Adjusted Close Price

# Put HL_KLSE_data into array
HL_KLSE_array = p.array(HL_KLSE_data );

# Calcualte Correlation for both Hong Leong Bank and KLSE
Correlation = HL_KLSE_data.corr();
print('Correlation of Hong Leong Bank and FTSEKLCI \n',Correlation);
Ejemplo n.º 7
0
#define function for moving average
def movingaverage (values,window):
    weights = np.repeat(1.0,window)/window
    sma = np.convolve(values,weights,'valid')
    return sma
    
#download Sime Darby stock price for 5 years
start = dt(2010,1,1)
end = dt(2015,5,1)
data = DR("4197.KL", 'yahoo', start,end)
Close_Price = data['Close'].values

#calculate 5-days moving average of Nestle
MA = movingaverage (Close_Price,5)

#plot moving acverage graph
num= len(MA)
t = p.linspace (0,num,num);
p.title('5-day moving average for Sime Darby')
p.xlabel('Days')
p.ylabel('Average stock Price, $RM$')
p.plot(t,MA)
p.show()

#calculate the correlation of Nestle with FTSEKLCI
alldata=['^KLSE' , '4197.KL']
c = DR(alldata, 'yahoo' ,start,end) ['Close']
correlation = c.corr()
print('The correlation is :')
print (correlation)
Ejemplo n.º 8
0
import matplotlib.pyplot as plt


start = dt(2012,1,1)
end=dt(2015,1,1)
kenchana = DR("5218.KL",'yahoo',start,end)
klse= DR("^KLSE",'yahoo',start,end)


def moving_avg (values, days):
    weight =np.repeat(1.0, days)/days
    sma=np.convolve(values, weight,'valid')
    return sma

closevalue = kenchana['Close'].values #take only the closing value
ma= moving_avg(closevalue, 5)

number= len(ma)
t= p.linspace(0,number,number);
p.title('5day moving average graph for 5218.KL Sapura Kenchana')
p.xlabel('number of days')
p.ylabel('average of stock price (RM)')
p.plot(t,ma)
p.show()


x = ['5218.KL', '^KLSE']
kenchana_klse_closevalue = DR(x, 'yahoo', start, end)['Close']
correlation_kenchana_klci= kenchana_klse_closevalue.corr()
print('the correlation of  5218.Kl Sapura Kenchana with FTSEKLCI is \n ', correlation_kenchana_klci)
Ejemplo n.º 9
0
data = DR("5681.KL", 'yahoo', start, end)

#Define a function for moving average
def moving_avg (values, days):
    weight=np.repeat(1.0, days)/days
    sma=np.convolve(values, weight,'valid')
    return sma

#Calculate 5-day moving average for PDB
closevalue = data['Close'].values #Use the closing value of PDB
ma= moving_avg(closevalue, 5)

#Plot 5-day moving average of PDB
number= len(ma)
t= p.linspace(0,number,number);
p.title('Moving average of 5 days closing price of PDB')
p.xlabel('Number of days, T')
p.ylabel('Average of stock price $')
p.plot(t,ma)
p.show()

#Find the correlation of PDB with FTSEKLCI
data_of_ftseklci= DR("^KLSE",'yahoo',start,end) #download FTSEKLCI data

x = ['5681.KL', '^KLSE']
PDB_klse_closevalue = DR(x, 'yahoo', start, end)['Close']

correlation_PDB_klci= PDB_klse_closevalue.corr()

print('Correlation of PDB with FTSEKLCI is \n ', correlation_PDB_klci)
Ejemplo n.º 10
0
Sum = 0
#finding the number of row
X = data_close.shape[0]

# making a zero array
Average = np.zeros((X + 1 - 5, ))

for i in range(X + 1 - 5):
    for j in range(5):
        Sum = Sum + data_close[j + i]
    Average[i] = Sum / 5
    Sum = 0

Time = p.linspace(0, X + 1 - 5, X + 1 - 5)

p.xlabel('time, $t$', fontsize=16)
p.ylabel('Average Stock Price, S(t)', fontsize=16)
p.title('Moving Average Plot of Genting', fontsize=20)
p.plot(Time, Average)
p.show()

# calculating correlation
Alldata = ['3182.KL', '^KLSE']
closing = DR(Alldata, 'yahoo', start, end)['Close']
correlate = closing.corr()

correlation = correlate['^KLSE'].values
msg = 'The correlation between Genting and FTSE KLCI is %.7f' % correlation[0]

print(correlate)
print(msg)
Ejemplo n.º 11
0
#calculate 5 days moving average
moving_average_5 = moving_average(HongLeong_close, 5)

#To plot the moving average
count = len(moving_average_5)
xaxis = np.arange(count) + 5
yaxis = moving_average_5
plt.xlabel('Day $n$')
plt.ylabel('Moving Average')
plt.plot(xaxis, yaxis)
plt.title('Plot of 5-day Moving Average')

print(' ')
print('FTSEKLCI component chosen: HONG LEONG BERHAD')
print(' ')
print('The 5-day moving average plot is as following:')
plt.show()

#5819.KL and ^KLSE is the stock code for Hong Leong Bank Berhad and KLSE respectively
combine = ['5819.KL', '^KLSE']
#To download the closing data of Hong Leong Bank Berhad and KLCI index
closing = DR(combine, 'yahoo', start, end)['Close']
#To find the correlation of Hong Leong Bank Berhad and KLSE
correlation = closing.corr()

print(' ')
print(
    'The correlation of FTSEKLCI and Hong Leong Bank Berhad is as following:')
print(correlation)
print(' ')
Ejemplo n.º 12
0
Sum=0
#finding the number of row
X=data_close.shape[0]

# making a zero array
Average = np.zeros((X+1-5,))

for i in range (X+1-5):
    for j in range (5):
        Sum=Sum + data_close[j+i];
    Average[i]=Sum/5
    Sum=0
    
Time=p.linspace(0,X+1-5,X+1-5)

p.xlabel('time, $t$',fontsize=16)
p.ylabel('Average Stock Price, S(t)',fontsize=16)
p.title('Moving Average Plot of Genting',fontsize=20)
p.plot (Time,Average);p.show()    

# calculating correlation
Alldata=['3182.KL','^KLSE']
closing=  DR(Alldata, 'yahoo', start, end)['Close']
correlate=closing.corr()

correlation=correlate['^KLSE'].values
msg='The correlation between Genting and FTSE KLCI is %.7f' %correlation [0]

print (correlate)
print (msg)
Ejemplo n.º 13
0
from pandas.io.data import DataReader as DR
from datetime import datetime as dt
import pandas as pd
import pylab as p

#get data from yahoo
start = dt(2012, 5, 1)
end = dt(2015, 5, 1)
genting = DR("3182.KL", 'yahoo',start,end)
klse = DR("^KLSE",'yahoo',start,end)

#find and plot the 5-day moving average
G5DMA = pd.rolling_mean(genting['Close'],5)
p.ylabel('5-day MA')
p.title('GENTING 5-day MA')
G5DMA.plot()
p.show()

#calculate the correlation between genting and FTSEKLCI
data = ["3182.KL","^KLSE"]
dldata = DR(data,'yahoo',start,end)['Close']

correlation=dldata.corr()
print('Correlation= \n',correlation)
Ejemplo n.º 14
0
# COLLECT DATA FROM 1/1/2011 TO 1/5/2015 FOR RHB CAPITAL BERHAD
start = dt(2011, 1, 1)
end = dt(2015, 5, 1)
data = DR("1066.KL", 'yahoo', start, end)

# calculate  rhb moving average
rhb = data['Close']
moving_average = pd.rolling_mean(rhb,5)        

#PLOT RHB MOVING AVERAGE
a = len(moving_average)
x_axis = np.arange(a) + 5
y_axis = moving_average
plt.xlabel('Days $n$')
plt.ylabel('5-day Moving Average')
plt.plot(x_axis,y_axis)
plt.title('RHB CAPITAL BERHAD 5-day Moving Average')
plt.show()

# COLLECT DATA FOR KLCI INDEX FOR SAME DURATION
mask = DR("^KLSE", 'yahoo', start, end)

#collect the closing data of RHB CAPITAL BERHAD and KLCI
combine = ['1066.KL', '^KLSE']
rhb_klse_close_value = DR(combine, 'yahoo', start, end)['Close']

 # calculate correlation between RHB CAPITAL BERHAD and KLCI Index
correlation = rhb_klse_close_value.corr()
print ('Correlation between RHB CAPITAL BERHAD and KLCI Index =')
print(correlation)
Ejemplo n.º 15
0
from datetime import datetime as dt
import pylab as p

#obtaining data

start = dt(2012, 1, 1)
end = dt(2015, 7, 20)
closing_data = DR("1295.KL", 'yahoo', start, end)['Close']
    #Public Bank's closing stock prices from 2012 to 2015 is extracted

#calculating moving average

avg_days = 5
moving_avg = pd.rolling_mean(closing_data,avg_days)

#plotting moving average and stock price
joined_data = pd.concat([moving_avg,closing_data], axis = 1)
    # to merge moving average and closing price into one DataFrame
joined_data[['Moving average','Stock price']] = joined_data[[0,1]]
joined_data[['Moving average','Stock price']].plot(title = '%d-days moving average of stock 1295.KL'%avg_days)
    

#Correlation between prices of 1295.KL and KLCI index

combine=['1295.KL','^KLSE']
closing = DR(combine, 'yahoo', start, end)['Close']
    # a combined dataframe of closing prices is extracted

correlation = p.array(closing.corr())[0,1]
print('\nThe correlation between 1295.KL and KLCI is %f' %correlation)
Ejemplo n.º 16
0
import pylab as p
import pandas as pd

#Downloading daily data of Malayan Banking with the code 1155
from pandas.io.data import DataReader as DR
from datetime import datetime as dt

start = dt(2010,1,1)
end = dt(2015,7,24)
data = DR("1155.KL",'yahoo',start,end)

#Calculating 5-day moving average of Malayan Banking
MB = data['Close'].values
mov_avg = pd.rolling_mean(MB,5)

#Plotting
p.plot(mov_avg)
label = 'Days'; p.xlabel(label)
label = 'Average stock price'; p.ylabel(label)
p.title('5-days moving average of Malayan Banking')
p.show()

#Downloading FTSEKLCI daily data
combine_data = ["1155.KL","^KLSE"]
all_data = DR(combine_data,'yahoo',start,end)['Adj Close']

#Calculating correlation
correlation = all_data.corr()
print ('Correlation = ' +str(correlation))
Ejemplo n.º 17
0
data = DR("1155.KL", 'yahoo', start, end) #download from yahoo

# Pick the data for at least 3 years
data = p.array(data)
closing = data[:,3]
sum = closing.cumsum()
print(closing)

# Take 5-day moving average
average_days = 5

matrix = np.zeros((2,(len(sum)-average_days+1)))
matrix[0,:] = sum[(average_days-1):]
matrix[1,1:] = sum[:-(average_days)]

moving_average = (matrix[0] - matrix[1]) / average_days

# Plot the 5 days moving average of Malayan Banking
p.plot(moving_average)
p.xlabel('Days');
p.ylabel('5 days average');
p.title('5-DAYS MOVING AVERAGE OF MALAYAN BANKING FROM 01/01/2011 TO 31/12/2014');
p.show()

# Correlation of Malayan Banking
complete_data = ['^KLSE','1155.KL']
cor = DR(complete_data, 'yahoo', start, end)['Close']
correlation = cor.corr()

print('THE CORRELATION OF MALAYAN BANKING IS ')
print(correlation)
Ejemplo n.º 18
0
end = dt(2015, 1, 1)
data = DR("1155.KL", 'yahoo', start, end)

#define a function for moving average
def moving_avg (values, days):
    weight =np.repeat(1.0, days)/days
    sma=np.convolve(values, weight,'valid')
    return sma

#calculate 5-day moving average for maybank
closevalue = data['Close'].values #take only the closing value of maybank
ma= moving_avg(closevalue, 5)

#plot the 5-day moving average of maybank
number= len(ma)
t= p.linspace(0,number,number);
p.title('5day moving average graph for Maybank')
p.xlabel('number of days')
p.ylabel('average of stock price (RM)')
p.plot(t,ma)
p.show()

#calculate the correlation of Maybank with FTSEKLCI
data_of_ftseklci= DR("^KLSE",'yahoo',start,end) #download FTSEKLCI data

x = ['1155.KL', '^KLSE']
maybank_klse_closevalue = DR(x, 'yahoo', start, end)['Close']

correlation_mayb_klci= maybank_klse_closevalue.corr()

print('the correlation of Maybank with FTSEKLCI is \n ', correlation_mayb_klci)
Ejemplo n.º 19
0
@author: user
"""
from pandas.io.data import DataReader as DR
from datetime import datetime as dt
import pandas as pd
import pylab as p

#Download daily data for Sime Darby Berhad from 1 July 2012 until 30 June 2015
start = dt(2012, 7, 1);
end = dt(2015, 6, 30);
sime = DR("4197.KL", 'yahoo', start, end);

#Calculate moving average for Sime Darby Berhad from 1 July 2012 until 30 June 2015
sime_close = DR("4197.KL", 'yahoo', start, end)['Close'];
Five_Day_Moving_Average = pd.rolling_mean(sime_close,5);       

#Plot the 5-day moving average plot for Sime Darby Berhad from 1 July 2012 until 30 June 2015
p.plot(Five_Day_Moving_Average);
p.xlabel('Days');
p.ylabel('5-day moving average ($RM$)');
p.title('5-day moving average plot for Sime Darby Berhad from 1 July 2012 until 30 June 2015');
p.show();

#Download daily data for FTSEKLCI from 1 July 2012 until 30 June 2015
klci = DR("^KLSE",'yahoo',start,end);

#Compute the correlation of Sime Darby Berhad with FTSEKLCI
data = ["4197.KL","^KLSE"];
data_close = DR(data,'yahoo',start,end)['Close'];
correlation = data_close.corr();
print('Correlation of Sime Darby Berhad with FTSEKLCI =\n',correlation);
Ejemplo n.º 20
0
sumprice = close_price.cumsum()

avg_day=5

#make a zero matrix with 2 row , from day1 to last 4 days and from 1st day 
#to the fifth day from the last day.
matrix = np.zeros((2,(len(sumprice)-avg_day+1)))
matrix[0,:] = sumprice[(avg_day-1):] #sum value from 5th to last day
matrix[1,1:] = sumprice[:-(avg_day)] #sum value from 1st to the last 5th day

moving_avg = (matrix[0] - matrix[1]) / avg_day

p.plot(moving_avg)
#label
label = 'Days ' ; p.xlabel(label)
label = '5 days average ' ; p.ylabel(label)
p.title('5 days moving average of Digi from 1st June 2012 till 31 May 2015 ' )
p.show()   

#downlaod KLSE data
#combining both data together
combine_data = ["6947.KL","^KLSE"] 
#retrieve information from yahoo with same duration , 
#get only adjusted close price
data2 = DR(combine_data,'yahoo',start,end)['Adj Close']

#compute into a array
combine = p.array(data2)
#calcualte correlation for both Digi and KLSE
correlation=data2.corr()
print('Correlation =\n',correlation)
Ejemplo n.º 21
0
# Download Data From 1/1/2011 TO 1/5/2015 For Public Bank Berhad(pbb)
start = dt(2011, 1, 1)
end = dt(2015, 5, 1)
data = DR("1295.KL", "yahoo", start, end)

# Calculate Moving Average
pbb = data["Close"]
moving_average = pd.rolling_mean(pbb, 5)

# Plot 5-day Moving Average For pbb
MA = len(moving_average)
x_axis = np.arange(MA) + 5
y_axis = moving_average
plt.xlabel("Days $n$")
plt.ylabel("5-day Moving Average")
plt.plot(x_axis, y_axis)
plt.title("Public Bank Berhad 5-day Moving Average")
plt.show()

# Download Data For KLCI Index For Same Duration
KLSE_Data = DR("^KLSE", "yahoo", start, end)

# Download The Closing Data Of Public Bank Berhad and KLCI
pbb_klci = ["1295.KL", "^KLSE"]
pbe_klse_closing = DR(pbb_klci, "yahoo", start, end)["Close"]

# Calculate The Correlation Of Public Bank Berhad and KLCI
correlation = pbe_klse_closing.corr()
print("Correlation between Public Bank Berhad and KLCI Index =")
print(correlation)
returns_fig = sns.PairGrid(closing_df.dropna())

returns_fig.map_upper(plt.scatter, color='purple')

returns_fig.map_lower(sns.kdeplot, cmap='cool_d')

returns_fig.map_diag(plt.hist, bins=30)

# In[29]:

sns.heatmap(tech_rets.corr(), annot=True)

# In[30]:

sns.heatmap(closing_df.corr(), annot=True)

# In[31]:

rets = tech_rets.dropna()

# In[32]:

area = np.pi * 20

plt.scatter(rets.mean(), rets.std(), s=area)

plt.xlabel('Expected Return')
plt.ylabel('Risk')

for label, x, y in zip(rets.columns, rets.mean(), rets.std()):