コード例 #1
0
def main(symbol):

    t1 = datetime.now()
    t2 = t1 - timedelta(days=PAST_DAYS)

    df  = DataReader(symbol,  FIN_SERVICE_PROVIDER , t2, t1)
    print df.head()
    print '...' * 20
    print df.tail()

    return df
    shock = np.zeros(days)
    drift = np.zeros(days)

    for x in range(1, days):
        shock[x] = np.random.normal(loc=mu * dt, scale=sigma * np.sqrt(dt))

        drift[x] = mu * dt

        price[x] = price[x - 1] + (price[x - 1] * (drift[x] + shock[x]))

    return price


# In[18]:

AAPL.head()

# In[19]:

# Running the Monte Carlo simulation a hundred times

start_price = 113.790001

for run in range(100):
    plt.plot(stock_monte_carlo(start_price, days, mu, sigma))

plt.xlabel('Days')
plt.ylabel('Price')
plt.title('Monte Carlo Simulation for Apple')

# In[ ]:
    shock = np.zeros(days)
    drift = np.zeros(days)
    
    for x in range(1,days):
        shock[x] = np.random.normal(loc=mu*dt,scale=sigma*np.sqrt(dt))
        
        drift[x] = mu * dt
        
        price[x] = price[x-1] + (price[x-1]* (drift[x] + shock[x]))
        
    return price


# In[18]:

AAPL.head()


# In[19]:

# Running the Monte Carlo simulation a hundred times

start_price = 113.790001

for run in range(100):
    plt.plot(stock_monte_carlo(start_price,days,mu,sigma))
    
plt.xlabel('Days')
plt.ylabel('Price')
plt.title('Monte Carlo Simulation for Apple')
    shock = np.zeros(days)
    drift = np.zeros(days)
    
    for x in range(1,days):
        shock[x] = np.random.normal(loc=mu*dt,scale=sigma*np.sqrt(dt))
        
        drift[x] = mu * dt
        
        price[x] = price[x-1] + (price[x-1]* (drift[x] + shock[x]))
        
    return price


# In[19]:

TSLA.head()


# In[20]:

# Running the Monte Carlo simulation a hundred times

start_price = 226.899994

for run in range(100):
    plt.plot(stock_monte_carlo(start_price,days,mu,sigma))
    
plt.xlabel('Days')
plt.ylabel('Price')
plt.title('Monte Carlo Simulation for Tesla Motors')
コード例 #5
0
ファイル: demo.py プロジェクト: rnandan273/python
import pandas as pd
from datetime import datetime
from datetime import *
from pandas.io.data import DataReader
#TECHM.NS,HCLTECH.NS

#axis = DataReader("AXISBANK.NS","yahoo",datetime(2013,3,1),datetime(2014,3,31))
nifty = DataReader("^NSEI","yahoo",datetime(2013,5,1),datetime(2013,5,25))
bn=DataReader("^NSEBANK","yahoo",datetime(2013,5,1),datetime(2013,5,25))
#print spx.head()
#print ss0.head()

#print axis.tail()
print nifty.tail()['Close'],bn.tail()['Close']
print nifty.head()['Close'],bn.head()['Close']

#axis_daily= axis.tail().diff()['Close']
#nifty_daily=nifty.tail().diff()['Close']
#axis_daily= axis.diff()['Close']
nifty_daily=nifty.diff()['Close']
bn_daily=bn.diff()['Close']
#daily_return = (axis_daily*250 ) - (50*nifty_daily)
daily_return = (bn_daily*25)- (50*nifty_daily)
nifty_daily_return =50*(nifty_daily)
bn_daily_return =25*(bn_daily)

print -nifty_daily_return.sum()+bn_daily_return.sum()

both = pd.DataFrame(data = {'nifty': 50*nifty.diff()['Adj Close'], 'bn': 25*bn.diff()['Adj Close']})
print both.plot()
コード例 #6
0
ファイル: CorrelationAnalysis.py プロジェクト: dubu/financePy
top10_codes = [
    '005930.KS','005380.KS','012330.KS','005490.KS','000660.KS',
    '035420.KS','005935.KS','000270.KS','055550.KS','015760.KS' ]

top5_codes = [
    '005930.KS','005380.KS','012330.KS','005490.KS','000660.KS' ]


start = datetime(2014, 1, 1)
end  = datetime(2014, 12, 31)

df = DataReader(top10_codes, 'yahoo', start=start, end=end)
df = df['Adj Close']

print(df.head())

df = df[top10_codes]
# df = df[top5_codes]
# print(df.head())

code_names = {
    '005930.KS':'Samsung Elec', '005380.KS':'Hyundai Motor',
    '012330.KS':'Hyundai Mobis', '005490.KS':'POSCO',
    '000660.KS':'SK Hynix','035420.KS':'Naver',
    '005935.KS':'Samsung Elec(Prep)', '000270.KS':'Kia Motor',
    '055550.KS':'Shinhan', '015760.KS':'Korea Elc Pwr' }

df = df.rename(columns=code_names)

# print(df.head())
コード例 #7
0
ファイル: CorrelationAnalysis.py プロジェクト: dubu/financePy
from pandas.io.data import DataReader

top10_codes = [
    '005930.KS', '005380.KS', '012330.KS', '005490.KS', '000660.KS',
    '035420.KS', '005935.KS', '000270.KS', '055550.KS', '015760.KS'
]

top5_codes = ['005930.KS', '005380.KS', '012330.KS', '005490.KS', '000660.KS']

start = datetime(2014, 1, 1)
end = datetime(2014, 12, 31)

df = DataReader(top10_codes, 'yahoo', start=start, end=end)
df = df['Adj Close']

print(df.head())

df = df[top10_codes]
# df = df[top5_codes]
# print(df.head())

code_names = {
    '005930.KS': 'Samsung Elec',
    '005380.KS': 'Hyundai Motor',
    '012330.KS': 'Hyundai Mobis',
    '005490.KS': 'POSCO',
    '000660.KS': 'SK Hynix',
    '035420.KS': 'Naver',
    '005935.KS': 'Samsung Elec(Prep)',
    '000270.KS': 'Kia Motor',
    '055550.KS': 'Shinhan',
コード例 #8
0
# logicals
temps_df.Missoula > 82  #
temps_df[temps_df.Missoula > 82]  # only subsetted rows

#####
# loading CSVs
#####

df = pd.read_csv("data/test1.csv")
df.date

df = pd.read_csv("data/test1.csv", parse_dates=["date"])
type(df.date[0])

df.index  # numeric

# reimport
df = pd.read_csv("data/test1.csv", parse_dates=["date"], index_col="date")

# load data from the web
from pandas.io.data import DataReader
from datetime import date
from dateutil.relativedelta import relativedelta

goog = DataReader("GOOG", "yahoo", date.today() + relativedelta(months=-3))
goog.head()
goog.tail()

goog.plot(y="Adj Close")
コード例 #9
0
# coding: utf-8
# iPython Demo

get_ipython().magic(u'pylab inline')

import pandas as pd
from pandas.io.data import DataReader
import matplotlib.pyplot as plt

df = DataReader("TSLA", "yahoo", " 20141130", "20151201")
df.head()

plt.plot(df.index, df['Close'])
plt.show()
    shock = np.zeros(days)
    drift = np.zeros(days)

    for x in range(1, days):
        shock[x] = np.random.normal(loc=mu * dt, scale=sigma * np.sqrt(dt))

        drift[x] = mu * dt

        price[x] = price[x - 1] + (price[x - 1] * (drift[x] + shock[x]))

    return price


# In[19]:

XOM.head()

# In[20]:

# Running the Monte Carlo simulation a hundred times

start_price = 93.330002

for run in range(100):
    plt.plot(stock_monte_carlo(start_price, days, mu, sigma))

plt.xlabel('Days')
plt.ylabel('Price')
plt.title('Monte Carlo Simulation for ExxonMobil')

# In[21]:
コード例 #11
0
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 15 10:40:13 2017

@author: Tom
"""
from pandas.io.data import DataReader

Tickers = [
    "HK3188"
];
        
for ticker in Tickers:
    try:
        data = DataReader(ticker, 'yahoo')
        print(data.head())
    except Exception as e:
        print("{} failed. {}\n".format(ticker, e))        
コード例 #12
0
import datetime
import pandas as pd
from pandas.io.data import DataReader
from matplotlib import pyplot as plt

start = datetime.datetime(2014, 1, 1)
end = datetime.datetime(2014, 12, 31)

#삼성전자
df = DataReader("005930.KS", "yahoo", start, end)

df['MA_5'] = pd.stats.moments.rolling_mean(df['Adj Close'], 5)
df['MA_20'] = pd.stats.moments.rolling_mean(df['Adj Close'], 20)
df['diff'] = df['MA_5'] - df['MA_20']

print(df.head(100))

#골든크로스 데드크로스
prev_key = prev_val = 0

for key, val in df['diff'][1:].iteritems():
    if val == 0:
        continue
    if val * prev_val < 0 and val > prev_val:
        print '[golden]', key, val
    if val * prev_val < 0 and val < prev_val:
        print '[dead]', key, val
    prev_key, prev_val = key, val

#골든크로 데드크로스 차트 표시
ax = df[['Adj Close', 'MA_5', 'MA_20']].plot(figsize(16, 6))
コード例 #13
0
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 28 17:10:45 2016

@author: gopal_a
"""

from pandas.io.data import DataReader
ticker = "SPY"
source = 'yahoo'
start = '01/01/2012'
end = '03/22/2014'
spy = DataReader(ticker, source, start, end)
print spy.head()
print spy.tail()
spy.to_csv('D:\\SPY.csv')
コード例 #14
0
    shock = np.zeros(days)
    drift = np.zeros(days)
    
    for x in range(1,days):
        shock[x] = np.random.normal(loc=mu*dt,scale=sigma*np.sqrt(dt))
        
        drift[x] = mu * dt
        
        price[x] = price[x-1] + (price[x-1]* (drift[x] + shock[x]))
        
    return price


# In[18]:

MSFT.head()


# In[19]:

# Running the Monte Carlo simulation a hundred times

start_price = 47.700001

for run in range(100):
    plt.plot(stock_monte_carlo(start_price,days,mu,sigma))
    
plt.xlabel('Days')
plt.ylabel('Price')
plt.title('Monte Carlo Simulation for Microsoft')
    shock = np.zeros(days)
    drift = np.zeros(days)

    for x in range(1, days):
        shock[x] = np.random.normal(loc=mu * dt, scale=sigma * np.sqrt(dt))

        drift[x] = mu * dt

        price[x] = price[x - 1] + (price[x - 1] * (drift[x] + shock[x]))

    return price


# In[20]:

GOOG.head()

# In[21]:

# Running the Monte Carlo simulation a hundred times

start_price = 532.192446

for run in range(100):
    plt.plot(stock_monte_carlo(start_price, days, mu, sigma))

plt.xlabel('Days')
plt.ylabel('Price')
plt.title('Monte Carlo Simulation for Google')

# In[22]:
    shock = np.zeros(days)
    drift = np.zeros(days)

    for x in range(1, days):
        shock[x] = np.random.normal(loc=mu * dt, scale=sigma * np.sqrt(dt))

        drift[x] = mu * dt

        price[x] = price[x - 1] + (price[x - 1] * (drift[x] + shock[x]))

    return price


# In[19]:

TSLA.head()

# In[20]:

# Running the Monte Carlo simulation a hundred times

start_price = 226.899994

for run in range(100):
    plt.plot(stock_monte_carlo(start_price, days, mu, sigma))

plt.xlabel('Days')
plt.ylabel('Price')
plt.title('Monte Carlo Simulation for Tesla Motors')

# In[21]:
コード例 #17
0

# In[21]:

###AAPL['Daily Return'].hist(bins=100) Removed, overlayed graphs better


# In[22]:

#New dataframe from ayhoo finance with just the adj closing
closing_df = DataReader(tech_list, 'yahoo',start,end)['Adj Close']


# In[23]:

closing_df.head()


# In[24]:

tech_returns = closing_df.pct_change()


# In[29]:

sns.jointplot('GOOG','MSFT', tech_returns,kind='scatter', color='green')


# In[31]:

sns.pairplot(tech_returns.dropna())
コード例 #18
0
import datetime
import pandas as pd
from pandas.io.data import DataReader
from matplotlib import pyplot as plt

start = datetime.datetime(2014, 1, 1)
end = datetime.datetime(2014, 12, 31)

#삼성전자
df = DataReader("005930.KS", "yahoo", start, end)

df['MA_5'] = pd.stats.moments.rolling_mean(df['Adj Close'], 5)
df['MA_20'] = pd.stats.moments.rolling_mean(df['Adj Close'], 20)
df['diff'] = df['MA_5'] - df['MA_20']

print(df.head(100))

#골든크로스 데드크로스
prev_key = prev_val = 0

for key, val in df['diff'][1:].iteritems():
    if val == 0:
        continue
    if val * prev_val < 0 and val > prev_val:
        print '[golden]', key, val
    if val * prev_val < 0 and val < prev_val:
        print '[dead]', key, val
    prev_key, prev_val = key, val

#골든크로 데드크로스 차트 표시
ax = df[['Adj Close', 'MA_5', 'MA_20']].plot(figsize(16,6))
コード例 #19
0
ファイル: fetch2.py プロジェクト: doktor01/compfi
def get_data():
    """symbols are specified on command line
    mitre, folio, smm are allowed abbreviations
    period defaults to 400 calendar days
    """
    
    start       = get_starting_date()
    print       "\ttoday is %s" % datetime.datetime.today().date()
   
    print       "\tstart date is %s\n" % start
    
    series      = {}
    
    not_found   = []
    for index, symbol in enumerate(symbols, 1):
        print "\t%6d. fetching %s" % (index, symbol.upper()),
        try:
            data    = DataReader(symbol.upper(),"yahoo", start)
            print "\t", type(data), data.shape
            print data.head()
            print "first five adj close values:", data["Adj Close"][:5]
            
            x       = data["Adj Close"]
            print "\n\t x starts with ", x[:5]
            
            z = pd.DataFrame(index = data.index, \
                data = x.values, columns = [symbol])
            
            print "\n\tz\n", z.head()
        
            series[symbol] = z
            print series[symbol]
            Symbol(symbol)
            Symbol.dict[symbol].adjclose = series[symbol]
            print
        except urllib2.HTTPError:
            print "\tnot found"    
            not_found.append(symbol)
            
    for symbol in not_found:
        symbols.remove(symbol)
        print "\tnot found:", symbol
        
    df      = series[symbols[0]]
    print "head and tail for", symbols[0]
    print df.head()
    print df.tail()
    print df.shape
    print "\n", "_" * 40, "\n"
    
  
    
    #-------------------------
    for symbol in symbols[1:]:
        new = series[symbol]
        
        df = pd.merge(left = df, 
            right       = new, 
            left_index  = True, 
            right_index = True,
            how         = "outer")
    print "\njoined df"
    print df.head()
    print df.tail()
    print df.shape
    print "_" * 30
    
    print "\ntotal returns"
    for symbol_name in Symbol.dict:
        symbol              = Symbol.dict[symbol_name]
        series              = df[symbol_name].dropna()
      
        total_return        = series[-1] - series[0]
        total_return_pct    = 100.0 * total_return / series[0] 
        print               "%10s" % symbol.symbol,
        print "total return = %10.2f " % total_return,
        print "total return = %10.2f" % total_return_pct, "%"
        
        symbol.total_return     = total_return
        symbol.total_return_pct = total_return_pct
        
        symbol.trading_days = series.shape[0]
        print "%10s has %6d trading days" % \
            (symbol_name, series.shape[0]) 
        
        calendar_days = (
            series.index[-1] - series.index[0]).days + 1
        print "%10s has %6d calendar days" % (symbol_name, calendar_days)
        symbol.calendar_days =   calendar_days
        
        years = calendar_days / 365.25
        
        arr = (1.0 + total_return_pct / 100) ** ( 1.0 / years) - 1.0
        
        symbol.first_day        = series.index[0]
        symbol.last_day         = series.index[-1]
        symbol.calendar_days    = (symbol.last_day - symbol.first_day).days + 1
       
        symbol.arr              = arr
        symbol.years            = years
        symbol.max_draw_down    = max_draw_down_f(symbol, series)
        symbol.series           = series 
       
        
    print
    return df
    shock = np.zeros(days)
    drift = np.zeros(days)
    
    for x in range(1,days):
        shock[x] = np.random.normal(loc=mu*dt,scale=sigma*np.sqrt(dt))
        
        drift[x] = mu * dt
        
        price[x] = price[x-1] + (price[x-1]* (drift[x] + shock[x]))
        
    return price


# In[20]:

GOOG.head()


# In[21]:

# Running the Monte Carlo simulation a hundred times

start_price = 532.192446

for run in range(100):
    plt.plot(stock_monte_carlo(start_price,days,mu,sigma))
    
plt.xlabel('Days')
plt.ylabel('Price')
plt.title('Monte Carlo Simulation for Google')
コード例 #21
0
ファイル: ImportDataPandas.py プロジェクト: GBelzoni/BigGits
                data = psql.read_frame(sqltxt, con)
                sqlDropTxt = 'DROP TABLE "main"."{}"'.format(tb)
                #print sqlDropTxt
                psql.execute(sqlDropTxt, con)
                con.commit()
                psql.write_frame( data, tb, con)
                con.commit()
        
        con.close()

start = datetime(2007,1,1)
end = datetime.date(datetime.now())

data = DataReader("^GSPC", "yahoo", start, end)
data = data.reset_index()
data.Date = [unicode(d) for d in data.Date]
data.Date[0]

data.head()

con = sqlite3.connect("/home/phcostello/Documents/Data/FinanceData.sqlite")
try:
    psql.write_frame( data, "SP500", con)
    con.commit()
except Exception as e:
    print "Problems with {}".format(series[0]), e
con.close()



コード例 #22
0
ファイル: US_Forex_Pairs.py プロジェクト: phroiland/FOREX
currencyfig2.savefig('currencyfig2.png')
	
currency.loc[:, ('Daily Return')] = currency[[0]].pct_change()
	
currencyfig3 = currency[[4]].plot(figsize=(10,4), legend=True, linestyle='--', marker='o')
currencyfig3 = currencyfig3.get_figure()
currencyfig3.savefig('currencyfig3.png')
	
currencyfig4 = sns.distplot(currency[['Daily Return']].dropna(), color='purple')
currencyfig4 = currencyfig4.get_figure()
currencyfig4.savefig('currencyfig4.png')


closing_df = DataReader(fred_currencies, 'fred', start, end)
print '\nDaily Close Snapshot'
print '\n', closing_df.head()

fred_ret = closing_df.pct_change()
print '\nDaily Return Snapshot\n'
print '\n', fred_ret.head()

print "\nSee how currency pairs correlate...\n"

currency1 = raw_input("Enter Currency 1: ")
if currency1 == 'DEXUSEU':
	currency1 = fred_ret[['DEXUSEU']].dropna()
	currency1.rename(columns = {'DEXUSEU':'Return'}, inplace = True)
elif currency1 == 'DEXUSAL':
	currency1 = fred_ret[['DEXUSAL']].dropna()
	currency1.rename(columns = {'DEXUSAL':'Return'}, inplace = True)
elif currency1 == 'DEXUSUK':
コード例 #23
0
    shock = np.zeros(days)
    drift = np.zeros(days)
    
    for x in range(1,days):
        shock[x] = np.random.normal(loc=mu*dt,scale=sigma*np.sqrt(dt))
        
        drift[x] = mu * dt
        
        price[x] = price[x-1] + (price[x-1]* (drift[x] + shock[x]))
        
    return price


# In[18]:

AMZN.head()


# In[19]:

# Running the Monte Carlo simulation a hundred times

start_price = 307.850006

for run in range(100):
    plt.plot(stock_monte_carlo(start_price,days,mu,sigma))
    
plt.xlabel('Days')
plt.ylabel('Price')
plt.title('Monte Carlo Simulation for Amazon')
                          legend=True,
                          linestyle='--',
                          marker='o')

# In[3]:

sns.distplot(MSFT['Daily Return'].dropna(), bins=100, color='purple')

# In[55]:

# Closing prices
closing_df = DataReader(['AAPL', 'GOOG', 'MSFT', 'AMZN'], 'yahoo', start,
                        end)['Adj Close']

# In[57]:

closing_df.head()

# In[8]:

# Make a new tech returns DataFrame
tech_rets = closing_df.pct_change()
# Using joinplot to compare the daily returns of Google and Microsoft
sns.jointplot('GOOG', 'MSFT', tech_rets, kind='scatter')

# In[7]:

sns.pairplot(tech_rets.dropna())

# In[ ]:
コード例 #25
0
plt.show()

AAPL['Daily Return'] = AAPL['Adj Close'].pct_change()
AAPL['Daily Return'].plot(figsize=(10, 4), legend=True, linestyle='--', marker='o')
plt.show()

sns.distplot(AAPL['Daily Return'].dropna(), bins=100, color='purple')
plt.show()

AAPL['Daily Return'].hist(bins=100)
plt.show()

closing_df = DataReader(tech_list, 'yahoo', start, end)['Adj Close']

print(closing_df.head())

tech_rets = closing_df.pct_change()
print(tech_rets.head())

sns.jointplot('GOOG', 'GOOG', tech_rets, kind = 'scatter', color='seagreen')
plt.show()

sns.jointplot('GOOG', 'MSFT', tech_rets, kind='scatter')
plt.show()

sns.pairplot(tech_rets.dropna())
plt.show()

returns_fig = sns.PairGrid(tech_rets.dropna())
returns_fig.map_upper(plt.scatter, color='purple')
コード例 #26
0
ファイル: US_Forex_Pairs.py プロジェクト: phroiland/FOREX
currencyfig3 = currency[[4]].plot(figsize=(10, 4),
                                  legend=True,
                                  linestyle='--',
                                  marker='o')
currencyfig3 = currencyfig3.get_figure()
currencyfig3.savefig('currencyfig3.png')

currencyfig4 = sns.distplot(currency[['Daily Return']].dropna(),
                            color='purple')
currencyfig4 = currencyfig4.get_figure()
currencyfig4.savefig('currencyfig4.png')

closing_df = DataReader(fred_currencies, 'fred', start, end)
print '\nDaily Close Snapshot'
print '\n', closing_df.head()

fred_ret = closing_df.pct_change()
print '\nDaily Return Snapshot\n'
print '\n', fred_ret.head()

print "\nSee how currency pairs correlate...\n"

currency1 = raw_input("Enter Currency 1: ")
if currency1 == 'DEXUSEU':
    currency1 = fred_ret[['DEXUSEU']].dropna()
    currency1.rename(columns={'DEXUSEU': 'Return'}, inplace=True)
elif currency1 == 'DEXUSAL':
    currency1 = fred_ret[['DEXUSAL']].dropna()
    currency1.rename(columns={'DEXUSAL': 'Return'}, inplace=True)
elif currency1 == 'DEXUSUK':