<jupyter_start><jupyter_text><jupyter_code>import pandas as pd

fb = pd.read_csv('/content/facebook.csv',index_col = 0)
print(fb)
ms = pd.read_csv('/content/microsoft.csv',parse_dates=False,index_col = 0 )
print(ms)
print(ms.iloc[0, 0])
print(fb.iloc[0, 0])
ms.head()
fb.head()
print(ms.shape)
print(fb.shape)
print(fb.describe())
print(ms.describe())
# select all the price information of Facebook in 2016.
fb_2015=fb.loc['2015-01-01':'2015-12-31']
# print the price of Facebook on '2015-03-16'
print(fb_2015.loc['2015-03-16'])
# select all the price information of Microsoft in 2016
ms_2016 = ms.loc['2016-01-01':'2016-12-31']
# print the price of Microsoft on '2016-03-16'
print(ms_2016.loc['2016-03-16'])
# print the opening price of the first row
print(fb.iloc[0, 0])
# print the opening price of the last row
print(ms.iloc[-1, 0])
# Plot the stock data using plot() method
fb[['Open', 'Low']]
import matplotlib.pyplot as plt
# plot only the Close price of 2016 of Microsoft, 1 line 
ms.loc['2016-01-01':'2016-12-31','Close'].plot()
# Create a new column in the DataFrame (1) - Price difference
# Create a new column PriceDiff in the DataFrame fb
fb['PriceDiff'] = fb['Close'].shift(-1) - fb['Close']
#Your turn to create PriceDiff in the DataFrame ms
ms['PriceDiff'] = ms['Close'].shift(-1) - ms['Close']
# Run this code to display the price difference of Microsoft on 2015-01-05
print(ms['PriceDiff'].loc['2015-01-05'])
# Create a new column in the DataFrame (2) - Daily return

# Daily Return is calcuated as PriceDiff/Close
#Create a new column Return in the DataFrame fb
fb['Return'] = fb['PriceDiff'] /fb['Close']
fb.head()
#Your turn to create a new column Return in the DataFrame MS
ms['Return'] = ms['PriceDiff'] /ms['Close']
#Run this code to print the return on 2015-01-05
print(ms['Return'].loc['2015-01-05'])
#Create a new column Direction. 
#The List Comprehension means : if the price difference is larger than 0, denote as 1, otherwise, denote as 0,
#for every record in the DataFrame - fb

fb['Direction'] = [1 if fb['PriceDiff'].loc[ei] > 0 else 0 for ei in fb.index ]
# Your turn to create a new column Direction for MS

ms['Direction'] = [1 if ms['PriceDiff'].loc[ei] > 0 else 0 for ei in ms.index ]
# Run the following code to show the price difference on 2015-01-05
print('Price difference on {} is {}. direction is {}'.format('2015-01-05', ms['PriceDiff'].loc['2015-01-05'], ms['Direction'].loc['2015-01-05']))
### Create a new column in the DataFrame using Rolling Window calculation (.rolling()) - Moving average

fb['ma50'] = fb['Close'].rolling(50).mean()

#plot the moving average
plt.figure(figsize=(10, 8))
fb['ma50'].loc['2015-01-01':'2015-12-31'].plot(label='MA50')
fb['Close'].loc['2015-01-01':'2015-12-31'].plot(label='Close')
plt.legend()
plt.show()
# You can use .rolling() to calculate any numbers of days' Moving Average. This is your turn to calculate "60 days"
# moving average of Microsoft, rename it as "ma60". And follow the codes above in plotting a graph

ms['ma60'] = ms['Close'].rolling(60).mean()

#plot the moving average
plt.figure(figsize=(10, 8))
ms['ma60'].loc['2015-01-01':'2015-12-31'].plot(label='MA60')
ms['Close'].loc['2015-01-01':'2015-12-31'].plot(label='Close')
plt.legend()
plt.show()
### 1. Munging los datos de acciones y agregue dos columnas: MA10 y MA50
fb = pd.read_csv('facebook.csv',index_col = 0)
fb['MA10'] = fb['Close'].rolling(10).mean()
fb['MA50'] = fb['Close'].rolling(50).mean()
fb = fb.dropna()
fb.head()
## 2. Agregue la columna "Acciones=shares" para tomar decisiones basadas en la estrategia
#Añadir una nueva columna "Acciones", si MA10> MA50, denotar como 1 (una acción larga de acciones), de lo contrario, denotar como 0 (no hacer nada)
fb['Shares'] = [1 if fb.loc[ei, 'MA10']>fb.loc[ei, 'MA50'] else 0 for ei in fb.index]
#Agregue una nueva columna "Beneficio" usando la Comprensión de lista, para cualquier fila en fb, si shares = 1,
# el beneficio se calcula como el precio de cierre de
# Tomorrow: el precio de cierre de hoy. De lo contrario, la ganancia es 0.

# Trace un gráfico para mostrar la ganancia / pérdida

fb['Close1'] = fb['Close'].shift(-1)
fb['Profit'] = [fb.loc[ei, 'Close1'] - fb.loc[ei, 'Close'] if fb.loc[ei, 'Shares']==1 else 0 for ei in fb.index]
fb['Profit'].plot()
plt.axhline(y=0, color='red')

### 3. Use .cumsum() to display our model's performance if we follow the strategy
#Use .cumsum() to calculate the accumulated wealth over the period

fb['wealth'] = fb['Profit'].cumsum()
fb.tail()

# trazar la riqueza para mostrar el crecimiento de las ganancias durante el período

fb['wealth'].plot()
plt.title('Total money you win is {}'.format(fb.loc[fb.index[-2], 'wealth']))
ms[‘diff’].shift(-1) – ms[‘Close’]<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.16319663512092533, 'fraction_numerical': 0.06813880126182965, 'mean_word_length': 4.959899749373434, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '417590', 'license': 'MIT', 'n_tokens_mistral': 1890, 'n_tokens_neox': 1628, 'n_words': 554, 'path': 'Estadistical,_predicion_y_series_de_tiempo.ipynb', 'repo_name': 'WuilsonEstacio/github-para-estadistica', 'size': '4755'}