Skip to content

Instantly share code, notes, and snippets.

View quantra-go-algo's full-sized avatar

Algorithmic Trading quantra-go-algo

View GitHub Profile
#importing libraries
import statsmodels.api as stat
import statsmodels.tsa.stattools as ts
import quandl
#fetching financial data for two securities from Quandl
data1 = quandl.get("CHRIS/MCX_AL1", start_date="2016-11-01", api_key= 'U_PJwA55r5u8Lz_uFJ6L')
data2 = quandl.get("CHRIS/MCX_PB1", start_date="2014-04-01", api_key= 'U_PJwA55r5u8Lz_uFJ6L')
#printing the first 5 rows of our fetched data
# Importing libraries
import statsmodels.api as stat
import statsmodels.tsa.stattools as ts
import quandl
# Fetching financial data for two securities from Quandl
data1 = quandl.get("CHRIS/MCX_AL1", start_date="2014-04-01", api_key= '')
data2 = quandl.get("CHRIS/MCX_PB1", start_date="2014-04-01", api_key= '')
# Printing the first 5 rows of our fetched data
# Creating a time series with duplicated indices
datesdup = [datetime(2018, 1, 1), datetime(2018, 1, 2), datetime(2018, 1, 2), datetime(2018, 1, 2), datetime(2018, 1, 3)]
dup_ts = pd.Series(np.random.randn(5), index=datesdup)
dup_ts
# Creating a time series with random numbers
import numpy as np
from random import random
dates = [datetime(2011, 1, 2), datetime(2011, 1, 5), datetime(2011, 1, 7), datetime(2011, 1, 8), datetime(2011, 1, 10), datetime(2011, 1, 12)]
ts = pd.Series(np.random.randn(6), index=dates)
ts
# Converting datetime to string
my_date1 = datetime(2018,2,14)
str(my_date1)
# Converting a string to datetime
datestr = '2018-02-14'
datetime.strptime(datestr, '%Y-%m-%d')
# Importing pandas
import pandas as pd
# Using pandas to parse dates
datestrs = ['1/14/2018', '2/14/2018']
# ‘to_datetime’ method in pandas are used to convert date strings to dates
pd.to_datetime(datestrs)
# Computes the forecasted values
stock['forecast'] = intercept + slope*stock['t']
# Computes the error
stock['error'] = stock['Adj Close'] - stock['forecast']
mean_error=stock['error'].mean()
print ('The mean error is: ', mean_error)
stock = yf.download('MRF.BO','2012-01-01', '2017-12-31')
# Populates the time period number in stock under head t
stock['t'] = range (1,len(stock)+1)
# Computes t squared, tXD(t) and n
stock['sqr t']=stock['t']**2
stock['tXD']=stock['t']*stock['Adj Close']
n=len(stock)
from matplotlib import pyplot
from statsmodels.graphics.tsaplots import plot_acf
import yfinance as yf
tesla = yf.download('TSLA','2019-01-27', '2020-02-11')
plot_acf(tesla['Close'], lags=20)
pyplot.show()
from statsmodels.graphics.tsaplots import plot_pacf
plot_pacf(tesla['Close'], lags=20)
pyplot.show()